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