]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - js/util.js
Merge remote branch 'gitorious/0.9.x' 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                         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                 if (typeof this.files == "object") {
461                     // Some newer browsers will let us fetch the files for preview.
462                     for (var i = 0; i < this.files.length; i++) {
463                         SN.U.PreviewAttach(this.files[i]);
464                     }
465                 }
466             });
467         },
468
469         /**
470          * For browsers with FileAPI support: make a thumbnail if possible,
471          * and append it into the attachment display widget.
472          *
473          * Known good:
474          * - Firefox 3.6.6, 4.0b7
475          * - Chrome 8.0.552.210
476          *
477          * Known ok metadata, can't get contents:
478          * - Safari 5.0.2
479          *
480          * Known fail:
481          * - Opera 10.63, 11 beta (no input.files interface)
482          *
483          * @param {File} file
484          *
485          * @todo use configured thumbnail size
486          * @todo detect pixel size?
487          * @todo should we render a thumbnail to a canvas and then use the smaller image?
488          */
489         PreviewAttach: function(file) {
490             var tooltip = file.type + ' ' + Math.round(file.size / 1024) + 'KB';
491             var preview = true;
492
493             var blobAsDataURL;
494             if (typeof window.createObjectURL != "undefined") {
495                 /**
496                  * createObjectURL lets us reference the file directly from an <img>
497                  * This produces a compact URL with an opaque reference to the file,
498                  * which we can reference immediately.
499                  *
500                  * - Firefox 3.6.6: no
501                  * - Firefox 4.0b7: no
502                  * - Safari 5.0.2: no
503                  * - Chrome 8.0.552.210: works!
504                  */
505                 blobAsDataURL = function(blob, callback) {
506                     callback(window.createObjectURL(blob));
507                 }
508             } else if (typeof window.FileReader != "undefined") {
509                 /**
510                  * FileAPI's FileReader can build a data URL from a blob's contents,
511                  * but it must read the file and build it asynchronously. This means
512                  * we'll be passing a giant data URL around, which may be inefficient.
513                  *
514                  * - Firefox 3.6.6: works!
515                  * - Firefox 4.0b7: works!
516                  * - Safari 5.0.2: no
517                  * - Chrome 8.0.552.210: works!
518                  */
519                 blobAsDataURL = function(blob, callback) {
520                     var reader = new FileReader();
521                     reader.onload = function(event) {
522                         callback(reader.result);
523                     }
524                     reader.readAsDataURL(blob);
525                 }
526             } else {
527                 preview = false;
528             }
529
530             var imageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/svg+xml'];
531             if ($.inArray(file.type, imageTypes) == -1) {
532                 // We probably don't know how to show the file.
533                 preview = false;
534             }
535
536             var maxSize = 8 * 1024 * 1024;
537             if (file.size > maxSize) {
538                 // Don't kill the browser trying to load some giant image.
539                 preview = false;
540             }
541
542             if (preview) {
543                 blobAsDataURL(file, function(url) {
544                     var img = $('<img>')
545                         .attr('title', tooltip)
546                         .attr('alt', tooltip)
547                         .attr('src', url)
548                         .attr('style', 'height: 120px');
549                     $('#'+SN.C.S.NoticeDataAttachSelected).append(img);
550                 });
551             } else {
552                 var img = $('<div></div>').text(tooltip);
553                 $('#'+SN.C.S.NoticeDataAttachSelected).append(img);
554             }
555         },
556
557         NoticeLocationAttach: function() {
558             var NLat = $('#'+SN.C.S.NoticeLat).val();
559             var NLon = $('#'+SN.C.S.NoticeLon).val();
560             var NLNS = $('#'+SN.C.S.NoticeLocationNs).val();
561             var NLID = $('#'+SN.C.S.NoticeLocationId).val();
562             var NLN = $('#'+SN.C.S.NoticeGeoName).text();
563             var NDGe = $('#'+SN.C.S.NoticeDataGeo);
564
565             function removeNoticeDataGeo() {
566                 $('label[for='+SN.C.S.NoticeDataGeo+']')
567                     .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()))
568                     .removeClass('checked');
569
570                 $('#'+SN.C.S.NoticeLat).val('');
571                 $('#'+SN.C.S.NoticeLon).val('');
572                 $('#'+SN.C.S.NoticeLocationNs).val('');
573                 $('#'+SN.C.S.NoticeLocationId).val('');
574                 $('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
575
576                 $.cookie(SN.C.S.NoticeDataGeoCookie, 'disabled', { path: '/' });
577             }
578
579             function getJSONgeocodeURL(geocodeURL, data) {
580                 $.getJSON(geocodeURL, data, function(location) {
581                     var lns, lid;
582
583                     if (typeof(location.location_ns) != 'undefined') {
584                         $('#'+SN.C.S.NoticeLocationNs).val(location.location_ns);
585                         lns = location.location_ns;
586                     }
587
588                     if (typeof(location.location_id) != 'undefined') {
589                         $('#'+SN.C.S.NoticeLocationId).val(location.location_id);
590                         lid = location.location_id;
591                     }
592
593                     if (typeof(location.name) == 'undefined') {
594                         NLN_text = data.lat + ';' + data.lon;
595                     }
596                     else {
597                         NLN_text = location.name;
598                     }
599
600                     $('label[for='+SN.C.S.NoticeDataGeo+']')
601                         .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + NLN_text + ')');
602
603                     $('#'+SN.C.S.NoticeLat).val(data.lat);
604                     $('#'+SN.C.S.NoticeLon).val(data.lon);
605                     $('#'+SN.C.S.NoticeLocationNs).val(lns);
606                     $('#'+SN.C.S.NoticeLocationId).val(lid);
607                     $('#'+SN.C.S.NoticeDataGeo).attr('checked', true);
608
609                     var cookieValue = {
610                         NLat: data.lat,
611                         NLon: data.lon,
612                         NLNS: lns,
613                         NLID: lid,
614                         NLN: NLN_text,
615                         NLNU: location.url,
616                         NDG: true
617                     };
618
619                     $.cookie(SN.C.S.NoticeDataGeoCookie, JSON.stringify(cookieValue), { path: '/' });
620                 });
621             }
622
623             if (NDGe.length > 0) {
624                 if ($.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
625                     NDGe.attr('checked', false);
626                 }
627                 else {
628                     NDGe.attr('checked', true);
629                 }
630
631                 var NGW = $('#notice_data-geo_wrap');
632                 var geocodeURL = NGW.attr('title');
633                 NGW.removeAttr('title');
634
635                 $('label[for='+SN.C.S.NoticeDataGeo+']')
636                     .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()));
637
638                 NDGe.change(function() {
639                     if ($('#'+SN.C.S.NoticeDataGeo).attr('checked') === true || $.cookie(SN.C.S.NoticeDataGeoCookie) === null) {
640                         $('label[for='+SN.C.S.NoticeDataGeo+']')
641                             .attr('title', NoticeDataGeo_text.ShareDisable)
642                             .addClass('checked');
643
644                         if ($.cookie(SN.C.S.NoticeDataGeoCookie) === null || $.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
645                             if (navigator.geolocation) {
646                                 navigator.geolocation.getCurrentPosition(
647                                     function(position) {
648                                         $('#'+SN.C.S.NoticeLat).val(position.coords.latitude);
649                                         $('#'+SN.C.S.NoticeLon).val(position.coords.longitude);
650
651                                         var data = {
652                                             lat: position.coords.latitude,
653                                             lon: position.coords.longitude,
654                                             token: $('#token').val()
655                                         };
656
657                                         getJSONgeocodeURL(geocodeURL, data);
658                                     },
659
660                                     function(error) {
661                                         switch(error.code) {
662                                             case error.PERMISSION_DENIED:
663                                                 removeNoticeDataGeo();
664                                                 break;
665                                             case error.TIMEOUT:
666                                                 $('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
667                                                 break;
668                                         }
669                                     },
670
671                                     {
672                                         timeout: 10000
673                                     }
674                                 );
675                             }
676                             else {
677                                 if (NLat.length > 0 && NLon.length > 0) {
678                                     var data = {
679                                         lat: NLat,
680                                         lon: NLon,
681                                         token: $('#token').val()
682                                     };
683
684                                     getJSONgeocodeURL(geocodeURL, data);
685                                 }
686                                 else {
687                                     removeNoticeDataGeo();
688                                     $('#'+SN.C.S.NoticeDataGeo).remove();
689                                     $('label[for='+SN.C.S.NoticeDataGeo+']').remove();
690                                 }
691                             }
692                         }
693                         else {
694                             var cookieValue = JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));
695
696                             $('#'+SN.C.S.NoticeLat).val(cookieValue.NLat);
697                             $('#'+SN.C.S.NoticeLon).val(cookieValue.NLon);
698                             $('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS);
699                             $('#'+SN.C.S.NoticeLocationId).val(cookieValue.NLID);
700                             $('#'+SN.C.S.NoticeDataGeo).attr('checked', cookieValue.NDG);
701
702                             $('label[for='+SN.C.S.NoticeDataGeo+']')
703                                 .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + cookieValue.NLN + ')')
704                                 .addClass('checked');
705                         }
706                     }
707                     else {
708                         removeNoticeDataGeo();
709                     }
710                 }).change();
711             }
712         },
713
714         NewDirectMessage: function() {
715             NDM = $('.entity_send-a-message a');
716             NDM.attr({'href':NDM.attr('href')+'&ajax=1'});
717             NDM.bind('click', function() {
718                 var NDMF = $('.entity_send-a-message form');
719                 if (NDMF.length === 0) {
720                     $(this).addClass(SN.C.S.Processing);
721                     $.get(NDM.attr('href'), null, function(data) {
722                         $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
723                         NDMF = $('.entity_send-a-message .form_notice');
724                         SN.U.FormNoticeXHR(NDMF);
725                         SN.U.FormNoticeEnhancements(NDMF);
726                         NDMF.append('<button class="close">&#215;</button>');
727                         $('.entity_send-a-message button').click(function(){
728                             NDMF.hide();
729                             return false;
730                         });
731                         NDM.removeClass(SN.C.S.Processing);
732                     });
733                 }
734                 else {
735                     NDMF.show();
736                     $('.entity_send-a-message textarea').focus();
737                 }
738                 return false;
739             });
740         },
741
742         GetFullYear: function(year, month, day) {
743             var date = new Date();
744             date.setFullYear(year, month, day);
745
746             return date;
747         },
748
749         StatusNetInstance: {
750             Set: function(value) {
751                 var SNI = SN.U.StatusNetInstance.Get();
752                 if (SNI !== null) {
753                     value = $.extend(SNI, value);
754                 }
755
756                 $.cookie(
757                     SN.C.S.StatusNetInstance,
758                     JSON.stringify(value),
759                     {
760                         path: '/',
761                         expires: SN.U.GetFullYear(2029, 0, 1)
762                     });
763             },
764
765             Get: function() {
766                 var cookieValue = $.cookie(SN.C.S.StatusNetInstance);
767                 if (cookieValue !== null) {
768                     return JSON.parse(cookieValue);
769                 }
770                 return null;
771             },
772
773             Delete: function() {
774                 $.cookie(SN.C.S.StatusNetInstance, null);
775             }
776         },
777
778         /**
779          * Check if the current page is a timeline where the current user's
780          * posts should be displayed immediately on success.
781          *
782          * @fixme this should be done in a saner way, with machine-readable
783          * info about what page we're looking at.
784          */
785         belongsOnTimeline: function(notice) {
786             var action = $("body").attr('id');
787             if (action == 'public') {
788                 return true;
789             }
790
791             var profileLink = $('#nav_profile a').attr('href');
792             if (profileLink) {
793                 var authorUrl = $(notice).find('.entry-title .author a.url').attr('href');
794                 if (authorUrl == profileLink) {
795                     if (action == 'all' || action == 'showstream') {
796                         // Posts always show on your own friends and profile streams.
797                         return true;
798                     }
799                 }
800             }
801
802             // @fixme tag, group, reply timelines should be feasible as well.
803             // Mismatch between id-based and name-based user/group links currently complicates
804             // the lookup, since all our inline mentions contain the absolute links but the
805             // UI links currently on the page use malleable names.
806
807             return false;
808         }
809     },
810
811     Init: {
812         NoticeForm: function() {
813             if ($('body.user_in').length > 0) {
814                 SN.U.NoticeLocationAttach();
815
816                 $('.'+SN.C.S.FormNotice).each(function() {
817                     SN.U.FormNoticeXHR($(this));
818                     SN.U.FormNoticeEnhancements($(this));
819                 });
820
821                 SN.U.NoticeDataAttach();
822             }
823         },
824
825         Notices: function() {
826             if ($('body.user_in').length > 0) {
827                 SN.U.NoticeFavor();
828                 SN.U.NoticeRepeat();
829                 SN.U.NoticeReply();
830             }
831
832             SN.U.NoticeAttachments();
833         },
834
835         EntityActions: function() {
836             if ($('body.user_in').length > 0) {
837                 $('.form_user_subscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
838                 $('.form_user_unsubscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
839                 $('.form_group_join').live('click', function() { SN.U.FormXHR($(this)); return false; });
840                 $('.form_group_leave').live('click', function() { SN.U.FormXHR($(this)); return false; });
841                 $('.form_user_nudge').live('click', function() { SN.U.FormXHR($(this)); return false; });
842
843                 SN.U.NewDirectMessage();
844             }
845         },
846
847         Login: function() {
848             if (SN.U.StatusNetInstance.Get() !== null) {
849                 var nickname = SN.U.StatusNetInstance.Get().Nickname;
850                 if (nickname !== null) {
851                     $('#form_login #nickname').val(nickname);
852                 }
853             }
854
855             $('#form_login').bind('submit', function() {
856                 SN.U.StatusNetInstance.Set({Nickname: $('#form_login #nickname').val()});
857                 return true;
858             });
859         }
860     }
861 };
862
863 $(document).ready(function(){
864     if ($('.'+SN.C.S.FormNotice).length > 0) {
865         SN.Init.NoticeForm();
866     }
867     if ($('#content .notices').length > 0) {
868         SN.Init.Notices();
869     }
870     if ($('#content .entity_actions').length > 0) {
871         SN.Init.EntityActions();
872     }
873     if ($('#form_login').length > 0) {
874         SN.Init.Login();
875     }
876 });
877
878 // Formerly in xbImportNode.js
879
880 /* is this stuff defined? */
881 if (!document.ELEMENT_NODE) {
882         document.ELEMENT_NODE = 1;
883         document.ATTRIBUTE_NODE = 2;
884         document.TEXT_NODE = 3;
885         document.CDATA_SECTION_NODE = 4;
886         document.ENTITY_REFERENCE_NODE = 5;
887         document.ENTITY_NODE = 6;
888         document.PROCESSING_INSTRUCTION_NODE = 7;
889         document.COMMENT_NODE = 8;
890         document.DOCUMENT_NODE = 9;
891         document.DOCUMENT_TYPE_NODE = 10;
892         document.DOCUMENT_FRAGMENT_NODE = 11;
893         document.NOTATION_NODE = 12;
894 }
895
896 document._importNode = function(node, allChildren) {
897         /* find the node type to import */
898         switch (node.nodeType) {
899                 case document.ELEMENT_NODE:
900                         /* create a new element */
901                         var newNode = document.createElement(node.nodeName);
902                         /* does the node have any attributes to add? */
903                         if (node.attributes && node.attributes.length > 0)
904                                 /* add all of the attributes */
905                                 for (var i = 0, il = node.attributes.length; i < il;) {
906                                         if (node.attributes[i].nodeName == 'class') {
907                                                 newNode.className = node.getAttribute(node.attributes[i++].nodeName);
908                                         } else {
909                                                 newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i++].nodeName));
910                                         }
911                                 }
912                         /* are we going after children too, and does the node have any? */
913                         if (allChildren && node.childNodes && node.childNodes.length > 0)
914                                 /* recursively get all of the child nodes */
915                                 for (var i = 0, il = node.childNodes.length; i < il;)
916                                         newNode.appendChild(document._importNode(node.childNodes[i++], allChildren));
917                         return newNode;
918                         break;
919                 case document.TEXT_NODE:
920                 case document.CDATA_SECTION_NODE:
921                 case document.COMMENT_NODE:
922                         return document.createTextNode(node.nodeValue);
923                         break;
924         }
925 };
926
927 // A shim to implement the W3C Geolocation API Specification using Gears or the Ajax API
928 if (typeof navigator.geolocation == "undefined" || navigator.geolocation.shim ) { (function(){
929
930 // -- BEGIN GEARS_INIT
931 (function() {
932   // We are already defined. Hooray!
933   if (window.google && google.gears) {
934     return;
935   }
936
937   var factory = null;
938
939   // Firefox
940   if (typeof GearsFactory != 'undefined') {
941     factory = new GearsFactory();
942   } else {
943     // IE
944     try {
945       factory = new ActiveXObject('Gears.Factory');
946       // privateSetGlobalObject is only required and supported on WinCE.
947       if (factory.getBuildInfo().indexOf('ie_mobile') != -1) {
948         factory.privateSetGlobalObject(this);
949       }
950     } catch (e) {
951       // Safari
952       if ((typeof navigator.mimeTypes != 'undefined') && navigator.mimeTypes["application/x-googlegears"]) {
953         factory = document.createElement("object");
954         factory.style.display = "none";
955         factory.width = 0;
956         factory.height = 0;
957         factory.type = "application/x-googlegears";
958         document.documentElement.appendChild(factory);
959       }
960     }
961   }
962
963   // *Do not* define any objects if Gears is not installed. This mimics the
964   // behavior of Gears defining the objects in the future.
965   if (!factory) {
966     return;
967   }
968
969   // Now set up the objects, being careful not to overwrite anything.
970   //
971   // Note: In Internet Explorer for Windows Mobile, you can't add properties to
972   // the window object. However, global objects are automatically added as
973   // properties of the window object in all browsers.
974   if (!window.google) {
975     google = {};
976   }
977
978   if (!google.gears) {
979     google.gears = {factory: factory};
980   }
981 })();
982 // -- END GEARS_INIT
983
984 var GearsGeoLocation = (function() {
985     // -- PRIVATE
986     var geo = google.gears.factory.create('beta.geolocation');
987
988     var wrapSuccess = function(callback, self) { // wrap it for lastPosition love
989         return function(position) {
990             callback(position);
991             self.lastPosition = position;
992         };
993     };
994
995     // -- PUBLIC
996     return {
997         shim: true,
998
999         type: "Gears",
1000
1001         lastPosition: null,
1002
1003         getCurrentPosition: function(successCallback, errorCallback, options) {
1004             var self = this;
1005             var sc = wrapSuccess(successCallback, self);
1006             geo.getCurrentPosition(sc, errorCallback, options);
1007         },
1008
1009         watchPosition: function(successCallback, errorCallback, options) {
1010             geo.watchPosition(successCallback, errorCallback, options);
1011         },
1012
1013         clearWatch: function(watchId) {
1014             geo.clearWatch(watchId);
1015         },
1016
1017         getPermission: function(siteName, imageUrl, extraMessage) {
1018             geo.getPermission(siteName, imageUrl, extraMessage);
1019         }
1020
1021     };
1022 });
1023
1024 var AjaxGeoLocation = (function() {
1025     // -- PRIVATE
1026     var loading = false;
1027     var loadGoogleLoader = function() {
1028         if (!hasGoogleLoader() && !loading) {
1029             loading = true;
1030             var s = document.createElement('script');
1031             s.src = (document.location.protocol == "https:"?"https://":"http://") + 'www.google.com/jsapi?callback=_google_loader_apiLoaded';
1032             s.type = "text/javascript";
1033             document.getElementsByTagName('body')[0].appendChild(s);
1034         }
1035     };
1036
1037     var queue = [];
1038     var addLocationQueue = function(callback) {
1039         queue.push(callback);
1040     };
1041
1042     var runLocationQueue = function() {
1043         if (hasGoogleLoader()) {
1044             while (queue.length > 0) {
1045                 var call = queue.pop();
1046                 call();
1047             }
1048         }
1049     };
1050
1051     window['_google_loader_apiLoaded'] = function() {
1052         runLocationQueue();
1053     };
1054
1055     var hasGoogleLoader = function() {
1056         return (window['google'] && google['loader']);
1057     };
1058
1059     var checkGoogleLoader = function(callback) {
1060         if (hasGoogleLoader()) { return true; }
1061
1062         addLocationQueue(callback);
1063
1064         loadGoogleLoader();
1065
1066         return false;
1067     };
1068
1069     loadGoogleLoader(); // start to load as soon as possible just in case
1070
1071     // -- PUBLIC
1072     return {
1073         shim: true,
1074
1075         type: "ClientLocation",
1076
1077         lastPosition: null,
1078
1079         getCurrentPosition: function(successCallback, errorCallback, options) {
1080             var self = this;
1081             if (!checkGoogleLoader(function() {
1082                 self.getCurrentPosition(successCallback, errorCallback, options);
1083             })) { return; }
1084
1085             if (google.loader.ClientLocation) {
1086                 var cl = google.loader.ClientLocation;
1087
1088                 var position = {
1089                     coords: {
1090                         latitude: cl.latitude,
1091                         longitude: cl.longitude,
1092                         altitude: null,
1093                         accuracy: 43000, // same as Gears accuracy over wifi?
1094                         altitudeAccuracy: null,
1095                         heading: null,
1096                         speed: null
1097                     },
1098                     // extra info that is outside of the bounds of the core API
1099                     address: {
1100                         city: cl.address.city,
1101                         country: cl.address.country,
1102                         country_code: cl.address.country_code,
1103                         region: cl.address.region
1104                     },
1105                     timestamp: new Date()
1106                 };
1107
1108                 successCallback(position);
1109
1110                 this.lastPosition = position;
1111             } else if (errorCallback === "function")  {
1112                 errorCallback({ code: 3, message: "Using the Google ClientLocation API and it is not able to calculate a location."});
1113             }
1114         },
1115
1116         watchPosition: function(successCallback, errorCallback, options) {
1117             this.getCurrentPosition(successCallback, errorCallback, options);
1118
1119             var self = this;
1120             var watchId = setInterval(function() {
1121                 self.getCurrentPosition(successCallback, errorCallback, options);
1122             }, 10000);
1123
1124             return watchId;
1125         },
1126
1127         clearWatch: function(watchId) {
1128             clearInterval(watchId);
1129         },
1130
1131         getPermission: function(siteName, imageUrl, extraMessage) {
1132             // for now just say yes :)
1133             return true;
1134         }
1135
1136     };
1137 });
1138
1139 // If you have Gears installed use that, else use Ajax ClientLocation
1140 navigator.geolocation = (window.google && google.gears) ? GearsGeoLocation() : AjaxGeoLocation();
1141
1142 })();
1143 }