]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - js/util.js
035c59da00c8e5e2ecb601629c63f72c9a554c6b
[quix0rs-gnu-social.git] / js / util.js
1 /*
2  * StatusNet - a distributed open-source microblogging tool
3  * Copyright (C) 2008, StatusNet, Inc.
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  *
18  * @category  UI interaction
19  * @package   StatusNet
20  * @author    Sarven Capadisli <csarven@status.net>
21  * @author    Evan Prodromou <evan@status.net>
22  * @copyright 2009 StatusNet, Inc.
23  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
24  * @link      http://status.net/
25  */
26
27 var SN = { // StatusNet
28     C: { // Config
29         I: { // Init
30             CounterBlackout: false,
31             MaxLength: 140,
32             PatternUsername: /^[0-9a-zA-Z\-_.]*$/,
33             HTTP20x30x: [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307]
34         },
35
36         S: { // Selector
37             Disabled: 'disabled',
38             Warning: 'warning',
39             Error: 'error',
40             Success: 'success',
41             Processing: 'processing',
42             CommandResult: 'command_result',
43             FormNotice: 'form_notice',
44             NoticeDataText: 'notice_data-text',
45             NoticeTextCount: 'notice_text-count',
46             NoticeInReplyTo: 'notice_in-reply-to',
47             NoticeDataAttach: 'notice_data-attach',
48             NoticeDataAttachSelected: 'notice_data-attach_selected',
49             NoticeActionSubmit: 'notice_action-submit',
50             NoticeLat: 'notice_data-lat',
51             NoticeLon: 'notice_data-lon',
52             NoticeLocationId: 'notice_data-location_id',
53             NoticeLocationNs: 'notice_data-location_ns',
54             NoticeGeoName: 'notice_data-geo_name',
55             NoticeDataGeo: 'notice_data-geo',
56             NoticeDataGeoCookie: 'NoticeDataGeo',
57             NoticeDataGeoSelected: 'notice_data-geo_selected',
58             StatusNetInstance:'StatusNetInstance'
59         }
60     },
61
62     messages: {},
63     msg: function(key) {
64         if (typeof SN.messages[key] == "undefined") {
65             return '[' + key + ']';
66         } else {
67             return SN.messages[key];
68         }
69     },
70
71     U: { // Utils
72         FormNoticeEnhancements: function(form) {
73             if (jQuery.data(form[0], 'ElementData') === undefined) {
74                 MaxLength = form.find('#'+SN.C.S.NoticeTextCount).text();
75                 if (typeof(MaxLength) == 'undefined') {
76                      MaxLength = SN.C.I.MaxLength;
77                 }
78                 jQuery.data(form[0], 'ElementData', {MaxLength:MaxLength});
79
80                 SN.U.Counter(form);
81
82                 NDT = form.find('#'+SN.C.S.NoticeDataText);
83
84                 NDT.bind('keyup', function(e) {
85                     SN.U.Counter(form);
86                 });
87
88                 var delayedUpdate= function(e) {
89                     // Cut and paste events fire *before* the operation,
90                     // so we need to trigger an update in a little bit.
91                     // This would be so much easier if the 'change' event
92                     // actually fired every time the value changed. :P
93                     window.setTimeout(function() {
94                         SN.U.Counter(form);
95                     }, 50);
96                 };
97                 // Note there's still no event for mouse-triggered 'delete'.
98                 NDT.bind('cut', delayedUpdate)
99                    .bind('paste', delayedUpdate);
100
101                 NDT.bind('keydown', function(e) {
102                     SN.U.SubmitOnReturn(e, form);
103                 });
104             }
105             else {
106                 form.find('#'+SN.C.S.NoticeTextCount).text(jQuery.data(form[0], 'ElementData').MaxLength);
107             }
108
109             if ($('body')[0].id != 'conversation' && window.location.hash.length === 0 && $(window).scrollTop() == 0) {
110                 form.find('textarea').focus();
111             }
112         },
113
114         SubmitOnReturn: function(event, el) {
115             if (event.keyCode == 13 || event.keyCode == 10) {
116                 el.submit();
117                 event.preventDefault();
118                 event.stopPropagation();
119                 $('#'+el[0].id+' #'+SN.C.S.NoticeDataText).blur();
120                 $('body').focus();
121                 return false;
122             }
123             return true;
124         },
125
126         Counter: function(form) {
127             SN.C.I.FormNoticeCurrent = form;
128
129             var MaxLength = jQuery.data(form[0], 'ElementData').MaxLength;
130
131             if (MaxLength <= 0) {
132                 return;
133             }
134
135             var remaining = MaxLength - SN.U.CharacterCount(form);
136             var counter = form.find('#'+SN.C.S.NoticeTextCount);
137
138             if (remaining.toString() != counter.text()) {
139                 if (!SN.C.I.CounterBlackout || remaining === 0) {
140                     if (counter.text() != String(remaining)) {
141                         counter.text(remaining);
142                     }
143                     if (remaining < 0) {
144                         form.addClass(SN.C.S.Warning);
145                     } else {
146                         form.removeClass(SN.C.S.Warning);
147                     }
148                     // Skip updates for the next 500ms.
149                     // On slower hardware, updating on every keypress is unpleasant.
150                     if (!SN.C.I.CounterBlackout) {
151                         SN.C.I.CounterBlackout = true;
152                         SN.C.I.FormNoticeCurrent = form;
153                         window.setTimeout("SN.U.ClearCounterBlackout(SN.C.I.FormNoticeCurrent);", 500);
154                     }
155                 }
156             }
157         },
158
159         CharacterCount: function(form) {
160             return form.find('#'+SN.C.S.NoticeDataText).val().length;
161         },
162
163         ClearCounterBlackout: function(form) {
164             // Allow keyup events to poke the counter again
165             SN.C.I.CounterBlackout = false;
166             // Check if the string changed since we last looked
167             SN.U.Counter(form);
168         },
169
170         FormXHR: function(form) {
171             $.ajax({
172                 type: 'POST',
173                 dataType: 'xml',
174                 url: form.attr('action'),
175                 data: form.serialize() + '&ajax=1',
176                 beforeSend: function(xhr) {
177                     form
178                         .addClass(SN.C.S.Processing)
179                         .find('.submit')
180                             .addClass(SN.C.S.Disabled)
181                             .attr(SN.C.S.Disabled, SN.C.S.Disabled);
182                 },
183                 error: function (xhr, textStatus, errorThrown) {
184                     alert(errorThrown || textStatus);
185                 },
186                 success: function(data, textStatus) {
187                     if (typeof($('form', data)[0]) != 'undefined') {
188                         form_new = document._importNode($('form', data)[0], true);
189                         form.replaceWith(form_new);
190                     }
191                     else {
192                         form.replaceWith(document._importNode($('p', data)[0], true));
193                     }
194                 }
195             });
196         },
197
198         FormNoticeXHR: function(form) {
199             SN.C.I.NoticeDataGeo = {};
200             form.append('<input type="hidden" name="ajax" value="1"/>');
201             form.ajaxForm({
202                 dataType: 'xml',
203                 timeout: '60000',
204                 beforeSend: function(formData) {
205                     if (form.find('#'+SN.C.S.NoticeDataText)[0].value.length === 0) {
206                         form.addClass(SN.C.S.Warning);
207                         return false;
208                     }
209                     form
210                         .addClass(SN.C.S.Processing)
211                         .find('#'+SN.C.S.NoticeActionSubmit)
212                             .addClass(SN.C.S.Disabled)
213                             .attr(SN.C.S.Disabled, SN.C.S.Disabled);
214
215                     SN.C.I.NoticeDataGeo.NLat = $('#'+SN.C.S.NoticeLat).val();
216                     SN.C.I.NoticeDataGeo.NLon = $('#'+SN.C.S.NoticeLon).val();
217                     SN.C.I.NoticeDataGeo.NLNS = $('#'+SN.C.S.NoticeLocationNs).val();
218                     SN.C.I.NoticeDataGeo.NLID = $('#'+SN.C.S.NoticeLocationId).val();
219                     SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked');
220
221                     cookieValue = $.cookie(SN.C.S.NoticeDataGeoCookie);
222
223                     if (cookieValue !== null && cookieValue != 'disabled') {
224                         cookieValue = JSON.parse(cookieValue);
225                         SN.C.I.NoticeDataGeo.NLat = $('#'+SN.C.S.NoticeLat).val(cookieValue.NLat).val();
226                         SN.C.I.NoticeDataGeo.NLon = $('#'+SN.C.S.NoticeLon).val(cookieValue.NLon).val();
227                         if ($('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS)) {
228                             SN.C.I.NoticeDataGeo.NLNS = $('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS).val();
229                             SN.C.I.NoticeDataGeo.NLID = $('#'+SN.C.S.NoticeLocationId).val(cookieValue.NLID).val();
230                         }
231                     }
232                     if (cookieValue == 'disabled') {
233                         SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked', false).attr('checked');
234                     }
235                     else {
236                         SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked', true).attr('checked');
237                     }
238
239                     return true;
240                 },
241                 error: function (xhr, textStatus, errorThrown) {
242                     form
243                         .removeClass(SN.C.S.Processing)
244                         .find('#'+SN.C.S.NoticeActionSubmit)
245                             .removeClass(SN.C.S.Disabled)
246                             .removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
247                     form.find('.form_response').remove();
248                     if (textStatus == 'timeout') {
249                         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>');
250                     }
251                     else {
252                         var response = SN.U.GetResponseXML(xhr);
253                         if ($('.'+SN.C.S.Error, response).length > 0) {
254                             form.append(document._importNode($('.'+SN.C.S.Error, response)[0], true));
255                         }
256                         else {
257                             if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
258                                 form
259                                     .resetForm()
260                                     .find('#'+SN.C.S.NoticeDataAttachSelected).remove();
261                                 SN.U.FormNoticeEnhancements(form);
262                             }
263                             else {
264                                 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>');
265                             }
266                         }
267                     }
268                 },
269                 success: function(data, textStatus) {
270                     form.find('.form_response').remove();
271                     var result;
272                     if ($('#'+SN.C.S.Error, data).length > 0) {
273                         result = document._importNode($('p', data)[0], true);
274                         result = result.textContent || result.innerHTML;
275                         form.append('<p class="form_response error">'+result+'</p>');
276                     }
277                     else {
278                         if($('body')[0].id == 'bookmarklet') {
279                             self.close();
280                         }
281
282                         if ($('#'+SN.C.S.CommandResult, data).length > 0) {
283                             result = document._importNode($('p', data)[0], true);
284                             result = result.textContent || result.innerHTML;
285                             form.append('<p class="form_response success">'+result+'</p>');
286                         }
287                         else {
288                             // New notice post was successful. If on our timeline, show it!
289                             var notice = document._importNode($('li', data)[0], true);
290                             var notices = $('#notices_primary .notices');
291                             if (notices.length > 0 && SN.U.belongsOnTimeline(notice)) {
292                                 if ($('#'+notice.id).length === 0) {
293                                     var notice_irt_value = $('#'+SN.C.S.NoticeInReplyTo).val();
294                                     var notice_irt = '#notices_primary #notice-'+notice_irt_value;
295                                     if($('body')[0].id == 'conversation') {
296                                         if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
297                                             $(notice_irt).append('<ul class="notices"></ul>');
298                                         }
299                                         $($(notice_irt+' .notices')[0]).append(notice);
300                                     }
301                                     else {
302                                         notices.prepend(notice);
303                                     }
304                                     $('#'+notice.id)
305                                         .css({display:'none'})
306                                         .fadeIn(2500);
307                                     SN.U.NoticeWithAttachment($('#'+notice.id));
308                                     SN.U.NoticeReplyTo($('#'+notice.id));
309                                 }
310                             }
311                             else {
312                                 // Not on a timeline that this belongs on?
313                                 // Just show a success message.
314                                 result = document._importNode($('title', data)[0], true);
315                                 result_title = result.textContent || result.innerHTML;
316                                 form.append('<p class="form_response success">'+result_title+'</p>');
317                             }
318                         }
319                         form.resetForm();
320                         form.find('#'+SN.C.S.NoticeInReplyTo).val('');
321                         form.find('#'+SN.C.S.NoticeDataAttachSelected).remove();
322                         SN.U.FormNoticeEnhancements(form);
323                     }
324                 },
325                 complete: function(xhr, textStatus) {
326                     form
327                         .removeClass(SN.C.S.Processing)
328                         .find('#'+SN.C.S.NoticeActionSubmit)
329                             .removeAttr(SN.C.S.Disabled)
330                             .removeClass(SN.C.S.Disabled);
331
332                     $('#'+SN.C.S.NoticeLat).val(SN.C.I.NoticeDataGeo.NLat);
333                     $('#'+SN.C.S.NoticeLon).val(SN.C.I.NoticeDataGeo.NLon);
334                     if ($('#'+SN.C.S.NoticeLocationNs)) {
335                         $('#'+SN.C.S.NoticeLocationNs).val(SN.C.I.NoticeDataGeo.NLNS);
336                         $('#'+SN.C.S.NoticeLocationId).val(SN.C.I.NoticeDataGeo.NLID);
337                     }
338                     $('#'+SN.C.S.NoticeDataGeo).attr('checked', SN.C.I.NoticeDataGeo.NDG);
339                 }
340             });
341         },
342
343         GetResponseXML: function(xhr) {
344             // Work around unavailable responseXML when document.domain
345             // has been modified by Meteor or other tools.
346             try {
347                 return xhr.responseXML;
348             } catch (e) {
349                 return (new DOMParser()).parseFromString(xhr.responseText, "text/xml");
350             }
351         },
352
353         NoticeReply: function() {
354             if ($('#'+SN.C.S.NoticeDataText).length > 0 && $('#content .notice_reply').length > 0) {
355                 $('#content .notice').each(function() { SN.U.NoticeReplyTo($(this)); });
356             }
357         },
358
359         NoticeReplyTo: function(notice) {
360             notice.find('.notice_reply').live('click', function() {
361                 var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
362                 SN.U.NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
363                 return false;
364             });
365         },
366
367         NoticeReplySet: function(nick,id) {
368             if (nick.match(SN.C.I.PatternUsername)) {
369                 var text = $('#'+SN.C.S.NoticeDataText);
370                 if (text.length > 0) {
371                     replyto = '@' + nick + ' ';
372                     text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
373                     $('#'+SN.C.S.FormNotice+' #'+SN.C.S.NoticeInReplyTo).val(id);
374
375                     text[0].focus();
376                     if (text[0].setSelectionRange) {
377                         var len = text.val().length;
378                         text[0].setSelectionRange(len,len);
379                     }
380                 }
381             }
382         },
383
384         NoticeFavor: function() {
385             $('.form_favor').live('click', function() { SN.U.FormXHR($(this)); return false; });
386             $('.form_disfavor').live('click', function() { SN.U.FormXHR($(this)); return false; });
387         },
388
389         NoticeRepeat: function() {
390             $('.form_repeat').live('click', function(e) {
391                 e.preventDefault();
392
393                 SN.U.NoticeRepeatConfirmation($(this));
394                 return false;
395             });
396         },
397
398         NoticeRepeatConfirmation: function(form) {
399             var submit_i = form.find('.submit');
400
401             var submit = submit_i.clone();
402             submit
403                 .addClass('submit_dialogbox')
404                 .removeClass('submit');
405             form.append(submit);
406             submit.bind('click', function() { SN.U.FormXHR(form); return false; });
407
408             submit_i.hide();
409
410             form
411                 .addClass('dialogbox')
412                 .append('<button class="close">&#215;</button>')
413                 .closest('.notice-options')
414                     .addClass('opaque');
415
416             form.find('button.close').click(function(){
417                 $(this).remove();
418
419                 form
420                     .removeClass('dialogbox')
421                     .closest('.notice-options')
422                         .removeClass('opaque');
423
424                 form.find('.submit_dialogbox').remove();
425                 form.find('.submit').show();
426
427                 return false;
428             });
429         },
430
431         NoticeAttachments: function() {
432             $('.notice a.attachment').each(function() {
433                 SN.U.NoticeWithAttachment($(this).closest('.notice'));
434             });
435         },
436
437         NoticeWithAttachment: function(notice) {
438             if (notice.find('.attachment').length === 0) {
439                 return;
440             }
441
442             var attachment_more = notice.find('.attachment.more');
443             if (attachment_more.length > 0) {
444                 $(attachment_more[0]).click(function() {
445                     var m = $(this);
446                     m.addClass(SN.C.S.Processing);
447                     $.get(m.attr('href')+'/ajax', null, function(data) {
448                         m.parent('.entry-content').html($(data).find('#attachment_view .entry-content').html());
449                     });
450
451                     return false;
452                 }).attr('title', SN.msg('showmore_tooltip'));
453             }
454         },
455
456         NoticeDataAttach: function() {
457             NDA = $('#'+SN.C.S.NoticeDataAttach);
458             NDA.change(function() {
459                 S = '<div id="'+SN.C.S.NoticeDataAttachSelected+'" class="'+SN.C.S.Success+'"><code>'+$(this).val()+'</code> <button class="close">&#215;</button></div>';
460                 NDAS = $('#'+SN.C.S.NoticeDataAttachSelected);
461                 if (NDAS.length > 0) {
462                     NDAS.replaceWith(S);
463                 }
464                 else {
465                     $('#'+SN.C.S.FormNotice).append(S);
466                 }
467                 $('#'+SN.C.S.NoticeDataAttachSelected+' button').click(function(){
468                     $('#'+SN.C.S.NoticeDataAttachSelected).remove();
469                     NDA.val('');
470
471                     return false;
472                 });
473                 if (typeof this.files == "object") {
474                     // Some newer browsers will let us fetch the files for preview.
475                     for (var i = 0; i < this.files.length; i++) {
476                         SN.U.PreviewAttach(this.files[i]);
477                     }
478                 }
479             });
480         },
481
482         /**
483          * For browsers with FileAPI support: make a thumbnail if possible,
484          * and append it into the attachment display widget.
485          *
486          * Known good:
487          * - Firefox 3.6.6, 4.0b7
488          * - Chrome 8.0.552.210
489          *
490          * Known ok metadata, can't get contents:
491          * - Safari 5.0.2
492          *
493          * Known fail:
494          * - Opera 10.63, 11 beta (no input.files interface)
495          *
496          * @param {File} file
497          *
498          * @todo use configured thumbnail size
499          * @todo detect pixel size?
500          * @todo should we render a thumbnail to a canvas and then use the smaller image?
501          */
502         PreviewAttach: function(file) {
503             var tooltip = file.type + ' ' + Math.round(file.size / 1024) + 'KB';
504             var preview = true;
505
506             var blobAsDataURL;
507             if (typeof window.createObjectURL != "undefined") {
508                 /**
509                  * createObjectURL lets us reference the file directly from an <img>
510                  * This produces a compact URL with an opaque reference to the file,
511                  * which we can reference immediately.
512                  *
513                  * - Firefox 3.6.6: no
514                  * - Firefox 4.0b7: no
515                  * - Safari 5.0.2: no
516                  * - Chrome 8.0.552.210: works!
517                  */
518                 blobAsDataURL = function(blob, callback) {
519                     callback(window.createObjectURL(blob));
520                 }
521             } else if (typeof window.FileReader != "undefined") {
522                 /**
523                  * FileAPI's FileReader can build a data URL from a blob's contents,
524                  * but it must read the file and build it asynchronously. This means
525                  * we'll be passing a giant data URL around, which may be inefficient.
526                  *
527                  * - Firefox 3.6.6: works!
528                  * - Firefox 4.0b7: works!
529                  * - Safari 5.0.2: no
530                  * - Chrome 8.0.552.210: works!
531                  */
532                 blobAsDataURL = function(blob, callback) {
533                     var reader = new FileReader();
534                     reader.onload = function(event) {
535                         callback(reader.result);
536                     }
537                     reader.readAsDataURL(blob);
538                 }
539             } else {
540                 preview = false;
541             }
542
543             var imageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/svg+xml'];
544             if ($.inArray(file.type, imageTypes) == -1) {
545                 // We probably don't know how to show the file.
546                 preview = false;
547             }
548
549             var maxSize = 8 * 1024 * 1024;
550             if (file.size > maxSize) {
551                 // Don't kill the browser trying to load some giant image.
552                 preview = false;
553             }
554
555             if (preview) {
556                 blobAsDataURL(file, function(url) {
557                     var img = $('<img>')
558                         .attr('title', tooltip)
559                         .attr('alt', tooltip)
560                         .attr('src', url)
561                         .attr('style', 'height: 120px');
562                     $('#'+SN.C.S.NoticeDataAttachSelected).append(img);
563                 });
564             } else {
565                 var img = $('<div></div>').text(tooltip);
566                 $('#'+SN.C.S.NoticeDataAttachSelected).append(img);
567             }
568         },
569
570         NoticeLocationAttach: function() {
571             var NLat = $('#'+SN.C.S.NoticeLat).val();
572             var NLon = $('#'+SN.C.S.NoticeLon).val();
573             var NLNS = $('#'+SN.C.S.NoticeLocationNs).val();
574             var NLID = $('#'+SN.C.S.NoticeLocationId).val();
575             var NLN = $('#'+SN.C.S.NoticeGeoName).text();
576             var NDGe = $('#'+SN.C.S.NoticeDataGeo);
577
578             function removeNoticeDataGeo() {
579                 $('label[for='+SN.C.S.NoticeDataGeo+']')
580                     .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()))
581                     .removeClass('checked');
582
583                 $('#'+SN.C.S.NoticeLat).val('');
584                 $('#'+SN.C.S.NoticeLon).val('');
585                 $('#'+SN.C.S.NoticeLocationNs).val('');
586                 $('#'+SN.C.S.NoticeLocationId).val('');
587                 $('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
588
589                 $.cookie(SN.C.S.NoticeDataGeoCookie, 'disabled', { path: '/' });
590             }
591
592             function getJSONgeocodeURL(geocodeURL, data) {
593                 $.getJSON(geocodeURL, data, function(location) {
594                     var lns, lid;
595
596                     if (typeof(location.location_ns) != 'undefined') {
597                         $('#'+SN.C.S.NoticeLocationNs).val(location.location_ns);
598                         lns = location.location_ns;
599                     }
600
601                     if (typeof(location.location_id) != 'undefined') {
602                         $('#'+SN.C.S.NoticeLocationId).val(location.location_id);
603                         lid = location.location_id;
604                     }
605
606                     if (typeof(location.name) == 'undefined') {
607                         NLN_text = data.lat + ';' + data.lon;
608                     }
609                     else {
610                         NLN_text = location.name;
611                     }
612
613                     $('label[for='+SN.C.S.NoticeDataGeo+']')
614                         .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + NLN_text + ')');
615
616                     $('#'+SN.C.S.NoticeLat).val(data.lat);
617                     $('#'+SN.C.S.NoticeLon).val(data.lon);
618                     $('#'+SN.C.S.NoticeLocationNs).val(lns);
619                     $('#'+SN.C.S.NoticeLocationId).val(lid);
620                     $('#'+SN.C.S.NoticeDataGeo).attr('checked', true);
621
622                     var cookieValue = {
623                         NLat: data.lat,
624                         NLon: data.lon,
625                         NLNS: lns,
626                         NLID: lid,
627                         NLN: NLN_text,
628                         NLNU: location.url,
629                         NDG: true
630                     };
631
632                     $.cookie(SN.C.S.NoticeDataGeoCookie, JSON.stringify(cookieValue), { path: '/' });
633                 });
634             }
635
636             if (NDGe.length > 0) {
637                 if ($.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
638                     NDGe.attr('checked', false);
639                 }
640                 else {
641                     NDGe.attr('checked', true);
642                 }
643
644                 var NGW = $('#notice_data-geo_wrap');
645                 var geocodeURL = NGW.attr('title');
646                 NGW.removeAttr('title');
647
648                 $('label[for='+SN.C.S.NoticeDataGeo+']')
649                     .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()));
650
651                 NDGe.change(function() {
652                     if ($('#'+SN.C.S.NoticeDataGeo).attr('checked') === true || $.cookie(SN.C.S.NoticeDataGeoCookie) === null) {
653                         $('label[for='+SN.C.S.NoticeDataGeo+']')
654                             .attr('title', NoticeDataGeo_text.ShareDisable)
655                             .addClass('checked');
656
657                         if ($.cookie(SN.C.S.NoticeDataGeoCookie) === null || $.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
658                             if (navigator.geolocation) {
659                                 navigator.geolocation.getCurrentPosition(
660                                     function(position) {
661                                         $('#'+SN.C.S.NoticeLat).val(position.coords.latitude);
662                                         $('#'+SN.C.S.NoticeLon).val(position.coords.longitude);
663
664                                         var data = {
665                                             lat: position.coords.latitude,
666                                             lon: position.coords.longitude,
667                                             token: $('#token').val()
668                                         };
669
670                                         getJSONgeocodeURL(geocodeURL, data);
671                                     },
672
673                                     function(error) {
674                                         switch(error.code) {
675                                             case error.PERMISSION_DENIED:
676                                                 removeNoticeDataGeo();
677                                                 break;
678                                             case error.TIMEOUT:
679                                                 $('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
680                                                 break;
681                                         }
682                                     },
683
684                                     {
685                                         timeout: 10000
686                                     }
687                                 );
688                             }
689                             else {
690                                 if (NLat.length > 0 && NLon.length > 0) {
691                                     var data = {
692                                         lat: NLat,
693                                         lon: NLon,
694                                         token: $('#token').val()
695                                     };
696
697                                     getJSONgeocodeURL(geocodeURL, data);
698                                 }
699                                 else {
700                                     removeNoticeDataGeo();
701                                     $('#'+SN.C.S.NoticeDataGeo).remove();
702                                     $('label[for='+SN.C.S.NoticeDataGeo+']').remove();
703                                 }
704                             }
705                         }
706                         else {
707                             var cookieValue = JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));
708
709                             $('#'+SN.C.S.NoticeLat).val(cookieValue.NLat);
710                             $('#'+SN.C.S.NoticeLon).val(cookieValue.NLon);
711                             $('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS);
712                             $('#'+SN.C.S.NoticeLocationId).val(cookieValue.NLID);
713                             $('#'+SN.C.S.NoticeDataGeo).attr('checked', cookieValue.NDG);
714
715                             $('label[for='+SN.C.S.NoticeDataGeo+']')
716                                 .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + cookieValue.NLN + ')')
717                                 .addClass('checked');
718                         }
719                     }
720                     else {
721                         removeNoticeDataGeo();
722                     }
723                 }).change();
724             }
725         },
726
727         NewDirectMessage: function() {
728             NDM = $('.entity_send-a-message a');
729             NDM.attr({'href':NDM.attr('href')+'&ajax=1'});
730             NDM.bind('click', function() {
731                 var NDMF = $('.entity_send-a-message form');
732                 if (NDMF.length === 0) {
733                     $(this).addClass(SN.C.S.Processing);
734                     $.get(NDM.attr('href'), null, function(data) {
735                         $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
736                         NDMF = $('.entity_send-a-message .form_notice');
737                         SN.U.FormNoticeXHR(NDMF);
738                         SN.U.FormNoticeEnhancements(NDMF);
739                         NDMF.append('<button class="close">&#215;</button>');
740                         $('.entity_send-a-message button').click(function(){
741                             NDMF.hide();
742                             return false;
743                         });
744                         NDM.removeClass(SN.C.S.Processing);
745                     });
746                 }
747                 else {
748                     NDMF.show();
749                     $('.entity_send-a-message textarea').focus();
750                 }
751                 return false;
752             });
753         },
754
755         GetFullYear: function(year, month, day) {
756             var date = new Date();
757             date.setFullYear(year, month, day);
758
759             return date;
760         },
761
762         StatusNetInstance: {
763             Set: function(value) {
764                 var SNI = SN.U.StatusNetInstance.Get();
765                 if (SNI !== null) {
766                     value = $.extend(SNI, value);
767                 }
768
769                 $.cookie(
770                     SN.C.S.StatusNetInstance,
771                     JSON.stringify(value),
772                     {
773                         path: '/',
774                         expires: SN.U.GetFullYear(2029, 0, 1)
775                     });
776             },
777
778             Get: function() {
779                 var cookieValue = $.cookie(SN.C.S.StatusNetInstance);
780                 if (cookieValue !== null) {
781                     return JSON.parse(cookieValue);
782                 }
783                 return null;
784             },
785
786             Delete: function() {
787                 $.cookie(SN.C.S.StatusNetInstance, null);
788             }
789         },
790
791         /**
792          * Check if the current page is a timeline where the current user's
793          * posts should be displayed immediately on success.
794          *
795          * @fixme this should be done in a saner way, with machine-readable
796          * info about what page we're looking at.
797          */
798         belongsOnTimeline: function(notice) {
799             var action = $("body").attr('id');
800             if (action == 'public') {
801                 return true;
802             }
803
804             var profileLink = $('#nav_profile a').attr('href');
805             if (profileLink) {
806                 var authorUrl = $(notice).find('.entry-title .author a.url').attr('href');
807                 if (authorUrl == profileLink) {
808                     if (action == 'all' || action == 'showstream') {
809                         // Posts always show on your own friends and profile streams.
810                         return true;
811                     }
812                 }
813             }
814
815             // @fixme tag, group, reply timelines should be feasible as well.
816             // Mismatch between id-based and name-based user/group links currently complicates
817             // the lookup, since all our inline mentions contain the absolute links but the
818             // UI links currently on the page use malleable names.
819
820             return false;
821         }
822     },
823
824     Init: {
825         NoticeForm: function() {
826             if ($('body.user_in').length > 0) {
827                 SN.U.NoticeLocationAttach();
828
829                 $('.'+SN.C.S.FormNotice).each(function() {
830                     SN.U.FormNoticeXHR($(this));
831                     SN.U.FormNoticeEnhancements($(this));
832                 });
833
834                 SN.U.NoticeDataAttach();
835             }
836         },
837
838         Notices: function() {
839             if ($('body.user_in').length > 0) {
840                 SN.U.NoticeFavor();
841                 SN.U.NoticeRepeat();
842                 SN.U.NoticeReply();
843             }
844
845             SN.U.NoticeAttachments();
846         },
847
848         EntityActions: function() {
849             if ($('body.user_in').length > 0) {
850                 $('.form_user_subscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
851                 $('.form_user_unsubscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
852                 $('.form_group_join').live('click', function() { SN.U.FormXHR($(this)); return false; });
853                 $('.form_group_leave').live('click', function() { SN.U.FormXHR($(this)); return false; });
854                 $('.form_user_nudge').live('click', function() { SN.U.FormXHR($(this)); return false; });
855
856                 SN.U.NewDirectMessage();
857             }
858         },
859
860         Login: function() {
861             if (SN.U.StatusNetInstance.Get() !== null) {
862                 var nickname = SN.U.StatusNetInstance.Get().Nickname;
863                 if (nickname !== null) {
864                     $('#form_login #nickname').val(nickname);
865                 }
866             }
867
868             $('#form_login').bind('submit', function() {
869                 SN.U.StatusNetInstance.Set({Nickname: $('#form_login #nickname').val()});
870                 return true;
871             });
872         }
873     }
874 };
875
876 $(document).ready(function(){
877     if ($('.'+SN.C.S.FormNotice).length > 0) {
878         SN.Init.NoticeForm();
879     }
880     if ($('#content .notices').length > 0) {
881         SN.Init.Notices();
882     }
883     if ($('#content .entity_actions').length > 0) {
884         SN.Init.EntityActions();
885     }
886     if ($('#form_login').length > 0) {
887         SN.Init.Login();
888     }
889 });
890
891 // Formerly in xbImportNode.js
892
893 /* is this stuff defined? */
894 if (!document.ELEMENT_NODE) {
895         document.ELEMENT_NODE = 1;
896         document.ATTRIBUTE_NODE = 2;
897         document.TEXT_NODE = 3;
898         document.CDATA_SECTION_NODE = 4;
899         document.ENTITY_REFERENCE_NODE = 5;
900         document.ENTITY_NODE = 6;
901         document.PROCESSING_INSTRUCTION_NODE = 7;
902         document.COMMENT_NODE = 8;
903         document.DOCUMENT_NODE = 9;
904         document.DOCUMENT_TYPE_NODE = 10;
905         document.DOCUMENT_FRAGMENT_NODE = 11;
906         document.NOTATION_NODE = 12;
907 }
908
909 document._importNode = function(node, allChildren) {
910         /* find the node type to import */
911         switch (node.nodeType) {
912                 case document.ELEMENT_NODE:
913                         /* create a new element */
914                         var newNode = document.createElement(node.nodeName);
915                         /* does the node have any attributes to add? */
916                         if (node.attributes && node.attributes.length > 0)
917                                 /* add all of the attributes */
918                                 for (var i = 0, il = node.attributes.length; i < il;) {
919                                         if (node.attributes[i].nodeName == 'class') {
920                                                 newNode.className = node.getAttribute(node.attributes[i++].nodeName);
921                                         } else {
922                                                 newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i++].nodeName));
923                                         }
924                                 }
925                         /* are we going after children too, and does the node have any? */
926                         if (allChildren && node.childNodes && node.childNodes.length > 0)
927                                 /* recursively get all of the child nodes */
928                                 for (var i = 0, il = node.childNodes.length; i < il;)
929                                         newNode.appendChild(document._importNode(node.childNodes[i++], allChildren));
930                         return newNode;
931                         break;
932                 case document.TEXT_NODE:
933                 case document.CDATA_SECTION_NODE:
934                 case document.COMMENT_NODE:
935                         return document.createTextNode(node.nodeValue);
936                         break;
937         }
938 };
939
940 // A shim to implement the W3C Geolocation API Specification using Gears or the Ajax API
941 if (typeof navigator.geolocation == "undefined" || navigator.geolocation.shim ) { (function(){
942
943 // -- BEGIN GEARS_INIT
944 (function() {
945   // We are already defined. Hooray!
946   if (window.google && google.gears) {
947     return;
948   }
949
950   var factory = null;
951
952   // Firefox
953   if (typeof GearsFactory != 'undefined') {
954     factory = new GearsFactory();
955   } else {
956     // IE
957     try {
958       factory = new ActiveXObject('Gears.Factory');
959       // privateSetGlobalObject is only required and supported on WinCE.
960       if (factory.getBuildInfo().indexOf('ie_mobile') != -1) {
961         factory.privateSetGlobalObject(this);
962       }
963     } catch (e) {
964       // Safari
965       if ((typeof navigator.mimeTypes != 'undefined') && navigator.mimeTypes["application/x-googlegears"]) {
966         factory = document.createElement("object");
967         factory.style.display = "none";
968         factory.width = 0;
969         factory.height = 0;
970         factory.type = "application/x-googlegears";
971         document.documentElement.appendChild(factory);
972       }
973     }
974   }
975
976   // *Do not* define any objects if Gears is not installed. This mimics the
977   // behavior of Gears defining the objects in the future.
978   if (!factory) {
979     return;
980   }
981
982   // Now set up the objects, being careful not to overwrite anything.
983   //
984   // Note: In Internet Explorer for Windows Mobile, you can't add properties to
985   // the window object. However, global objects are automatically added as
986   // properties of the window object in all browsers.
987   if (!window.google) {
988     google = {};
989   }
990
991   if (!google.gears) {
992     google.gears = {factory: factory};
993   }
994 })();
995 // -- END GEARS_INIT
996
997 var GearsGeoLocation = (function() {
998     // -- PRIVATE
999     var geo = google.gears.factory.create('beta.geolocation');
1000
1001     var wrapSuccess = function(callback, self) { // wrap it for lastPosition love
1002         return function(position) {
1003             callback(position);
1004             self.lastPosition = position;
1005         };
1006     };
1007
1008     // -- PUBLIC
1009     return {
1010         shim: true,
1011
1012         type: "Gears",
1013
1014         lastPosition: null,
1015
1016         getCurrentPosition: function(successCallback, errorCallback, options) {
1017             var self = this;
1018             var sc = wrapSuccess(successCallback, self);
1019             geo.getCurrentPosition(sc, errorCallback, options);
1020         },
1021
1022         watchPosition: function(successCallback, errorCallback, options) {
1023             geo.watchPosition(successCallback, errorCallback, options);
1024         },
1025
1026         clearWatch: function(watchId) {
1027             geo.clearWatch(watchId);
1028         },
1029
1030         getPermission: function(siteName, imageUrl, extraMessage) {
1031             geo.getPermission(siteName, imageUrl, extraMessage);
1032         }
1033
1034     };
1035 });
1036
1037 var AjaxGeoLocation = (function() {
1038     // -- PRIVATE
1039     var loading = false;
1040     var loadGoogleLoader = function() {
1041         if (!hasGoogleLoader() && !loading) {
1042             loading = true;
1043             var s = document.createElement('script');
1044             s.src = (document.location.protocol == "https:"?"https://":"http://") + 'www.google.com/jsapi?callback=_google_loader_apiLoaded';
1045             s.type = "text/javascript";
1046             document.getElementsByTagName('body')[0].appendChild(s);
1047         }
1048     };
1049
1050     var queue = [];
1051     var addLocationQueue = function(callback) {
1052         queue.push(callback);
1053     };
1054
1055     var runLocationQueue = function() {
1056         if (hasGoogleLoader()) {
1057             while (queue.length > 0) {
1058                 var call = queue.pop();
1059                 call();
1060             }
1061         }
1062     };
1063
1064     window['_google_loader_apiLoaded'] = function() {
1065         runLocationQueue();
1066     };
1067
1068     var hasGoogleLoader = function() {
1069         return (window['google'] && google['loader']);
1070     };
1071
1072     var checkGoogleLoader = function(callback) {
1073         if (hasGoogleLoader()) { return true; }
1074
1075         addLocationQueue(callback);
1076
1077         loadGoogleLoader();
1078
1079         return false;
1080     };
1081
1082     loadGoogleLoader(); // start to load as soon as possible just in case
1083
1084     // -- PUBLIC
1085     return {
1086         shim: true,
1087
1088         type: "ClientLocation",
1089
1090         lastPosition: null,
1091
1092         getCurrentPosition: function(successCallback, errorCallback, options) {
1093             var self = this;
1094             if (!checkGoogleLoader(function() {
1095                 self.getCurrentPosition(successCallback, errorCallback, options);
1096             })) { return; }
1097
1098             if (google.loader.ClientLocation) {
1099                 var cl = google.loader.ClientLocation;
1100
1101                 var position = {
1102                     coords: {
1103                         latitude: cl.latitude,
1104                         longitude: cl.longitude,
1105                         altitude: null,
1106                         accuracy: 43000, // same as Gears accuracy over wifi?
1107                         altitudeAccuracy: null,
1108                         heading: null,
1109                         speed: null
1110                     },
1111                     // extra info that is outside of the bounds of the core API
1112                     address: {
1113                         city: cl.address.city,
1114                         country: cl.address.country,
1115                         country_code: cl.address.country_code,
1116                         region: cl.address.region
1117                     },
1118                     timestamp: new Date()
1119                 };
1120
1121                 successCallback(position);
1122
1123                 this.lastPosition = position;
1124             } else if (errorCallback === "function")  {
1125                 errorCallback({ code: 3, message: "Using the Google ClientLocation API and it is not able to calculate a location."});
1126             }
1127         },
1128
1129         watchPosition: function(successCallback, errorCallback, options) {
1130             this.getCurrentPosition(successCallback, errorCallback, options);
1131
1132             var self = this;
1133             var watchId = setInterval(function() {
1134                 self.getCurrentPosition(successCallback, errorCallback, options);
1135             }, 10000);
1136
1137             return watchId;
1138         },
1139
1140         clearWatch: function(watchId) {
1141             clearInterval(watchId);
1142         },
1143
1144         getPermission: function(siteName, imageUrl, extraMessage) {
1145             // for now just say yes :)
1146             return true;
1147         }
1148
1149     };
1150 });
1151
1152 // If you have Gears installed use that, else use Ajax ClientLocation
1153 navigator.geolocation = (window.google && google.gears) ? GearsGeoLocation() : AjaxGeoLocation();
1154
1155 })();
1156 }