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