]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - js/util.js
2c79c1db668050faaa301b07a0b33f879c107e87
[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  * @author    Brion Vibber <brion@status.net>
23  * @copyright 2009,2010 StatusNet, Inc.
24  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
25  * @link      http://status.net/
26  */
27
28 var SN = { // StatusNet
29     C: { // Config
30         I: { // Init
31             CounterBlackout: false,
32             MaxLength: 140,
33             PatternUsername: /^[0-9a-zA-Z\-_.]*$/,
34             HTTP20x30x: [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307]
35         },
36
37         /**
38          * @fixme are these worth the trouble? They seem to mostly just duplicate
39          * themselves while slightly obscuring the actual selector, so it's hard
40          * to pop over to the HTML and find something.
41          *
42          * In theory, minification could reduce them to shorter variable names,
43          * but at present that doesn't happen with yui-compressor.
44          */
45         S: { // Selector
46             Disabled: 'disabled',
47             Warning: 'warning',
48             Error: 'error',
49             Success: 'success',
50             Processing: 'processing',
51             CommandResult: 'command_result',
52             FormNotice: 'form_notice',
53             NoticeDataText: 'notice_data-text',
54             NoticeTextCount: 'notice_text-count',
55             NoticeInReplyTo: 'notice_in-reply-to',
56             NoticeDataAttach: 'notice_data-attach',
57             NoticeDataAttachSelected: 'notice_data-attach_selected',
58             NoticeActionSubmit: 'notice_action-submit',
59             NoticeLat: 'notice_data-lat',
60             NoticeLon: 'notice_data-lon',
61             NoticeLocationId: 'notice_data-location_id',
62             NoticeLocationNs: 'notice_data-location_ns',
63             NoticeGeoName: 'notice_data-geo_name',
64             NoticeDataGeo: 'notice_data-geo',
65             NoticeDataGeoCookie: 'NoticeDataGeo',
66             NoticeDataGeoSelected: 'notice_data-geo_selected',
67             StatusNetInstance:'StatusNetInstance'
68         }
69     },
70
71     /**
72      * Map of localized message strings exported to script from the PHP
73      * side via Action::getScriptMessages().
74      *
75      * Retrieve them via SN.msg(); this array is an implementation detail.
76      *
77      * @access private
78      */
79     messages: {},
80
81     /**
82      * Grabs a localized string that's been previously exported to us
83      * from server-side code via Action::getScriptMessages().
84      *
85      * @example alert(SN.msg('coolplugin-failed'));
86      *
87      * @param {String} key: string key name to pull from message index
88      * @return matching localized message string
89      */
90     msg: function(key) {
91         if (typeof SN.messages[key] == "undefined") {
92             return '[' + key + ']';
93         } else {
94             return SN.messages[key];
95         }
96     },
97
98     U: { // Utils
99         /**
100          * Setup function -- DOES NOT trigger actions immediately.
101          *
102          * Sets up event handlers on the new notice form.
103          *
104          * @param {jQuery} form: jQuery object whose first matching element is the form
105          * @access private
106          */
107         FormNoticeEnhancements: function(form) {
108             if (jQuery.data(form[0], 'ElementData') === undefined) {
109                 MaxLength = form.find('#'+SN.C.S.NoticeTextCount).text();
110                 if (typeof(MaxLength) == 'undefined') {
111                      MaxLength = SN.C.I.MaxLength;
112                 }
113                 jQuery.data(form[0], 'ElementData', {MaxLength:MaxLength});
114
115                 SN.U.Counter(form);
116
117                 NDT = form.find('#'+SN.C.S.NoticeDataText);
118
119                 NDT.bind('keyup', function(e) {
120                     SN.U.Counter(form);
121                 });
122
123                 var delayedUpdate= function(e) {
124                     // Cut and paste events fire *before* the operation,
125                     // so we need to trigger an update in a little bit.
126                     // This would be so much easier if the 'change' event
127                     // actually fired every time the value changed. :P
128                     window.setTimeout(function() {
129                         SN.U.Counter(form);
130                     }, 50);
131                 };
132                 // Note there's still no event for mouse-triggered 'delete'.
133                 NDT.bind('cut', delayedUpdate)
134                    .bind('paste', delayedUpdate);
135
136                 NDT.bind('keydown', function(e) {
137                     SN.U.SubmitOnReturn(e, form);
138                 });
139             }
140             else {
141                 form.find('#'+SN.C.S.NoticeTextCount).text(jQuery.data(form[0], 'ElementData').MaxLength);
142             }
143
144             if ($('body')[0].id != 'conversation' && window.location.hash.length === 0 && $(window).scrollTop() == 0) {
145                 form.find('textarea').focus();
146             }
147         },
148
149         /**
150          * To be called from keydown event handler on the notice import form.
151          * Checks if return or enter key was pressed, and if so attempts to
152          * submit the form and cancel standard processing of the enter key.
153          *
154          * @param {Event} event
155          * @param {jQuery} el: jQuery object whose first element is the notice posting form
156          *
157          * @return {boolean} whether to cancel the event? Does this actually pass through?
158          * @access private
159          */
160         SubmitOnReturn: function(event, el) {
161             if (event.keyCode == 13 || event.keyCode == 10) {
162                 el.submit();
163                 event.preventDefault();
164                 event.stopPropagation();
165                 $('#'+el[0].id+' #'+SN.C.S.NoticeDataText).blur();
166                 $('body').focus();
167                 return false;
168             }
169             return true;
170         },
171
172         /**
173          * To be called from event handlers on the notice import form.
174          * Triggers an update of the remaining-characters counter.
175          *
176          * Additional counter updates will be suppressed during the
177          * next half-second to avoid flooding the layout engine with
178          * updates, followed by another automatic check.
179          *
180          * The maximum length is pulled from data established by
181          * FormNoticeEnhancements.
182          *
183          * @param {jQuery} form: jQuery object whose first element is the notice posting form
184          * @access private
185          */
186         Counter: function(form) {
187             SN.C.I.FormNoticeCurrent = form;
188
189             var MaxLength = jQuery.data(form[0], 'ElementData').MaxLength;
190
191             if (MaxLength <= 0) {
192                 return;
193             }
194
195             var remaining = MaxLength - SN.U.CharacterCount(form);
196             var counter = form.find('#'+SN.C.S.NoticeTextCount);
197
198             if (remaining.toString() != counter.text()) {
199                 if (!SN.C.I.CounterBlackout || remaining === 0) {
200                     if (counter.text() != String(remaining)) {
201                         counter.text(remaining);
202                     }
203                     if (remaining < 0) {
204                         form.addClass(SN.C.S.Warning);
205                     } else {
206                         form.removeClass(SN.C.S.Warning);
207                     }
208                     // Skip updates for the next 500ms.
209                     // On slower hardware, updating on every keypress is unpleasant.
210                     if (!SN.C.I.CounterBlackout) {
211                         SN.C.I.CounterBlackout = true;
212                         SN.C.I.FormNoticeCurrent = form;
213                         window.setTimeout("SN.U.ClearCounterBlackout(SN.C.I.FormNoticeCurrent);", 500);
214                     }
215                 }
216             }
217         },
218
219         /**
220          * Pull the count of characters in the current edit field.
221          * Plugins replacing the edit control may need to override this.
222          *
223          * @param {jQuery} form: jQuery object whose first element is the notice posting form
224          * @return number of chars
225          */
226         CharacterCount: function(form) {
227             return form.find('#'+SN.C.S.NoticeDataText).val().length;
228         },
229
230         /**
231          * Called internally after the counter update blackout period expires;
232          * runs another update to make sure we didn't miss anything.
233          *
234          * @param {jQuery} form: jQuery object whose first element is the notice posting form
235          * @access private
236          */
237         ClearCounterBlackout: function(form) {
238             // Allow keyup events to poke the counter again
239             SN.C.I.CounterBlackout = false;
240             // Check if the string changed since we last looked
241             SN.U.Counter(form);
242         },
243
244         /**
245          * Grabs form data and submits it asynchronously, with 'ajax=1'
246          * parameter added to the rest.
247          *
248          * If a successful response includes another form, that form
249          * will be extracted and copied in, replacing the original form.
250          * If there's no form, the first paragraph will be used.
251          *
252          * @fixme can sometimes explode confusingly if returnd data is bogus
253          * @fixme error handling is pretty vague
254          * @fixme can't submit file uploads
255          *
256          * @param {jQuery} form: jQuery object whose first element is a form
257          *
258          * @access public
259          */
260         FormXHR: function(form) {
261             $.ajax({
262                 type: 'POST',
263                 dataType: 'xml',
264                 url: form.attr('action'),
265                 data: form.serialize() + '&ajax=1',
266                 beforeSend: function(xhr) {
267                     form
268                         .addClass(SN.C.S.Processing)
269                         .find('.submit')
270                             .addClass(SN.C.S.Disabled)
271                             .attr(SN.C.S.Disabled, SN.C.S.Disabled);
272                 },
273                 error: function (xhr, textStatus, errorThrown) {
274                     alert(errorThrown || textStatus);
275                 },
276                 success: function(data, textStatus) {
277                     if (typeof($('form', data)[0]) != 'undefined') {
278                         form_new = document._importNode($('form', data)[0], true);
279                         form.replaceWith(form_new);
280                     }
281                     else {
282                         form.replaceWith(document._importNode($('p', data)[0], true));
283                     }
284                 }
285             });
286         },
287
288         /**
289          * Setup function -- DOES NOT trigger actions immediately.
290          *
291          * Sets up event handlers for special-cased async submission of the
292          * notice-posting form, including some pre-post validation.
293          *
294          * Unlike FormXHR() this does NOT submit the form immediately!
295          * It sets up event handlers so that any method of submitting the
296          * form (click on submit button, enter, submit() etc) will trigger
297          * it properly.
298          *
299          * Also unlike FormXHR(), this system will use a hidden iframe
300          * automatically to handle file uploads via <input type="file">
301          * controls.
302          *
303          * @fixme tl;dr
304          * @fixme vast swaths of duplicate code and really long variable names clutter this function up real bad
305          * @fixme error handling is unreliable
306          * @fixme cookieValue is a global variable, but probably shouldn't be
307          * @fixme saving the location cache cookies should be split out
308          * @fixme some error messages are hardcoded english: needs i18n
309          * @fixme special-case for bookmarklet is confusing and uses a global var "self". Is this ok?
310          *
311          * @param {jQuery} form: jQuery object whose first element is a form
312          *
313          * @access public
314          */
315         FormNoticeXHR: function(form) {
316             SN.C.I.NoticeDataGeo = {};
317             form.append('<input type="hidden" name="ajax" value="1"/>');
318
319             /**
320              * Show a response feedback bit under the new-notice dialog.
321              *
322              * @param {String} cls: CSS class name to use ('error' or 'success')
323              * @param {String} text
324              * @access private
325              */
326             var showFeedback = function(cls, text) {
327                 form.append(
328                     $('<p class="form_response"></p>')
329                         .addClass(cls)
330                         .text(text)
331                 );
332             };
333
334             /**
335              * Hide the previous response feedback, if any.
336              */
337             var removeFeedback = function() {
338                 form.find('.form_response').remove();
339             };
340
341             form.ajaxForm({
342                 dataType: 'xml',
343                 timeout: '60000',
344                 beforeSend: function(formData) {
345                     if (form.find('#'+SN.C.S.NoticeDataText)[0].value.length === 0) {
346                         form.addClass(SN.C.S.Warning);
347                         return false;
348                     }
349                     form
350                         .addClass(SN.C.S.Processing)
351                         .find('#'+SN.C.S.NoticeActionSubmit)
352                             .addClass(SN.C.S.Disabled)
353                             .attr(SN.C.S.Disabled, SN.C.S.Disabled);
354
355                     SN.C.I.NoticeDataGeo.NLat = $('#'+SN.C.S.NoticeLat).val();
356                     SN.C.I.NoticeDataGeo.NLon = $('#'+SN.C.S.NoticeLon).val();
357                     SN.C.I.NoticeDataGeo.NLNS = $('#'+SN.C.S.NoticeLocationNs).val();
358                     SN.C.I.NoticeDataGeo.NLID = $('#'+SN.C.S.NoticeLocationId).val();
359                     SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked');
360
361                     cookieValue = $.cookie(SN.C.S.NoticeDataGeoCookie);
362
363                     if (cookieValue !== null && cookieValue != 'disabled') {
364                         cookieValue = JSON.parse(cookieValue);
365                         SN.C.I.NoticeDataGeo.NLat = $('#'+SN.C.S.NoticeLat).val(cookieValue.NLat).val();
366                         SN.C.I.NoticeDataGeo.NLon = $('#'+SN.C.S.NoticeLon).val(cookieValue.NLon).val();
367                         if ($('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS)) {
368                             SN.C.I.NoticeDataGeo.NLNS = $('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS).val();
369                             SN.C.I.NoticeDataGeo.NLID = $('#'+SN.C.S.NoticeLocationId).val(cookieValue.NLID).val();
370                         }
371                     }
372                     if (cookieValue == 'disabled') {
373                         SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked', false).attr('checked');
374                     }
375                     else {
376                         SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked', true).attr('checked');
377                     }
378
379                     return true;
380                 },
381                 error: function (xhr, textStatus, errorThrown) {
382                     form
383                         .removeClass(SN.C.S.Processing)
384                         .find('#'+SN.C.S.NoticeActionSubmit)
385                             .removeClass(SN.C.S.Disabled)
386                             .removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
387                     removeFeedback();
388                     if (textStatus == 'timeout') {
389                         // @fixme i18n
390                         showFeedback('error', 'Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists.');
391                     }
392                     else {
393                         var response = SN.U.GetResponseXML(xhr);
394                         if ($('.'+SN.C.S.Error, response).length > 0) {
395                             form.append(document._importNode($('.'+SN.C.S.Error, response)[0], true));
396                         }
397                         else {
398                             if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
399                                 form
400                                     .resetForm()
401                                     .find('#'+SN.C.S.NoticeDataAttachSelected).remove();
402                                 SN.U.FormNoticeEnhancements(form);
403                             }
404                             else {
405                                 // @fixme i18n
406                                 showFeedback('error', '(Sorry! We had trouble sending your notice ('+xhr.status+' '+xhr.statusText+'). Please report the problem to the site administrator if this happens again.');
407                             }
408                         }
409                     }
410                 },
411                 success: function(data, textStatus) {
412                     removeFeedback();
413                     var errorResult = $('#'+SN.C.S.Error, data);
414                     if (errorResult.length > 0) {
415                         showFeedback('error', errorResult.text());
416                     }
417                     else {
418                         if($('body')[0].id == 'bookmarklet') {
419                             // @fixme self is not referenced anywhere?
420                             self.close();
421                         }
422
423                         var commandResult = $('#'+SN.C.S.CommandResult, data);
424                         if (commandResult.length > 0) {
425                             showFeedback('success', commandResult.text());
426                         }
427                         else {
428                             // New notice post was successful. If on our timeline, show it!
429                             var notice = document._importNode($('li', data)[0], true);
430                             var notices = $('#notices_primary .notices');
431                             if (notices.length > 0 && SN.U.belongsOnTimeline(notice)) {
432                                 if ($('#'+notice.id).length === 0) {
433                                     var notice_irt_value = $('#'+SN.C.S.NoticeInReplyTo).val();
434                                     var notice_irt = '#notices_primary #notice-'+notice_irt_value;
435                                     if($('body')[0].id == 'conversation') {
436                                         if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
437                                             $(notice_irt).append('<ul class="notices"></ul>');
438                                         }
439                                         $($(notice_irt+' .notices')[0]).append(notice);
440                                     }
441                                     else {
442                                         notices.prepend(notice);
443                                     }
444                                     $('#'+notice.id)
445                                         .css({display:'none'})
446                                         .fadeIn(2500);
447                                     SN.U.NoticeWithAttachment($('#'+notice.id));
448                                     SN.U.NoticeReplyTo($('#'+notice.id));
449                                 }
450                             }
451                             else {
452                                 // Not on a timeline that this belongs on?
453                                 // Just show a success message.
454                                 showFeedback('success', $('title', data).text());
455                             }
456                         }
457                         form.resetForm();
458                         form.find('#'+SN.C.S.NoticeInReplyTo).val('');
459                         form.find('#'+SN.C.S.NoticeDataAttachSelected).remove();
460                         SN.U.FormNoticeEnhancements(form);
461                     }
462                 },
463                 complete: function(xhr, textStatus) {
464                     form
465                         .removeClass(SN.C.S.Processing)
466                         .find('#'+SN.C.S.NoticeActionSubmit)
467                             .removeAttr(SN.C.S.Disabled)
468                             .removeClass(SN.C.S.Disabled);
469
470                     $('#'+SN.C.S.NoticeLat).val(SN.C.I.NoticeDataGeo.NLat);
471                     $('#'+SN.C.S.NoticeLon).val(SN.C.I.NoticeDataGeo.NLon);
472                     if ($('#'+SN.C.S.NoticeLocationNs)) {
473                         $('#'+SN.C.S.NoticeLocationNs).val(SN.C.I.NoticeDataGeo.NLNS);
474                         $('#'+SN.C.S.NoticeLocationId).val(SN.C.I.NoticeDataGeo.NLID);
475                     }
476                     $('#'+SN.C.S.NoticeDataGeo).attr('checked', SN.C.I.NoticeDataGeo.NDG);
477                 }
478             });
479         },
480
481         /**
482          * Fetch an XML DOM from an XHR's response data.
483          *
484          * Works around unavailable responseXML when document.domain
485          * has been modified by Meteor or other tools, in some but not
486          * all browsers.
487          *
488          * @param {XMLHTTPRequest} xhr
489          * @return DOMDocument
490          */
491         GetResponseXML: function(xhr) {
492             try {
493                 return xhr.responseXML;
494             } catch (e) {
495                 return (new DOMParser()).parseFromString(xhr.responseText, "text/xml");
496             }
497         },
498
499         /**
500          * Setup function -- DOES NOT trigger actions immediately.
501          *
502          * Sets up event handlers on all visible notice's reply buttons to
503          * tweak the new-notice form with needed variables and focus it
504          * when pushed.
505          *
506          * (This replaces the default reply button behavior to submit
507          * directly to a form which comes back with a specialized page
508          * with the form data prefilled.)
509          *
510          * @access private
511          */
512         NoticeReply: function() {
513             if ($('#'+SN.C.S.NoticeDataText).length > 0 && $('#content .notice_reply').length > 0) {
514                 $('#content .notice').each(function() { SN.U.NoticeReplyTo($(this)); });
515             }
516         },
517
518         /**
519          * Setup function -- DOES NOT trigger actions immediately.
520          *
521          * Sets up event handlers on the given notice's reply button to
522          * tweak the new-notice form with needed variables and focus it
523          * when pushed.
524          *
525          * (This replaces the default reply button behavior to submit
526          * directly to a form which comes back with a specialized page
527          * with the form data prefilled.)
528          *
529          * @param {jQuery} notice: jQuery object containing one or more notices
530          * @access private
531          */
532         NoticeReplyTo: function(notice) {
533             notice.find('.notice_reply').live('click', function() {
534                 var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
535                 SN.U.NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
536                 return false;
537             });
538         },
539
540         /**
541          * Updates the new notice posting form with bits for replying to the
542          * given user. Adds replyto parameter to the form, and a "@foo" to the
543          * text area.
544          *
545          * @fixme replyto is a global variable, but probably shouldn't be
546          *
547          * @param {String} nick
548          * @param {String} id
549          */
550         NoticeReplySet: function(nick,id) {
551             if (nick.match(SN.C.I.PatternUsername)) {
552                 var text = $('#'+SN.C.S.NoticeDataText);
553                 if (text.length > 0) {
554                     replyto = '@' + nick + ' ';
555                     text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
556                     $('#'+SN.C.S.FormNotice+' #'+SN.C.S.NoticeInReplyTo).val(id);
557
558                     text[0].focus();
559                     if (text[0].setSelectionRange) {
560                         var len = text.val().length;
561                         text[0].setSelectionRange(len,len);
562                     }
563                 }
564             }
565         },
566
567         /**
568          * Setup function -- DOES NOT apply immediately.
569          *
570          * Sets up event handlers for favor/disfavor forms to submit via XHR.
571          * Uses 'live' rather than 'bind', so applies to future as well as present items.
572          */
573         NoticeFavor: function() {
574             $('.form_favor').live('click', function() { SN.U.FormXHR($(this)); return false; });
575             $('.form_disfavor').live('click', function() { SN.U.FormXHR($(this)); return false; });
576         },
577
578         /**
579          * Setup function -- DOES NOT trigger actions immediately.
580          *
581          * Sets up event handlers for repeat forms to toss up a confirmation
582          * popout before submitting.
583          *
584          * Uses 'live' rather than 'bind', so applies to future as well as present items.
585          */
586         NoticeRepeat: function() {
587             $('.form_repeat').live('click', function(e) {
588                 e.preventDefault();
589
590                 SN.U.NoticeRepeatConfirmation($(this));
591                 return false;
592             });
593         },
594
595         /**
596          * Shows a confirmation dialog box variant of the repeat button form.
597          * This seems to use a technique where the repeat form contains
598          * _both_ a standalone button _and_ text and buttons for a dialog.
599          * The dialog will close after its copy of the form is submitted,
600          * or if you click its 'close' button.
601          *
602          * The dialog is created by duplicating the original form and changing
603          * its style; while clever, this is hard to generalize and probably
604          * duplicates a lot of unnecessary HTML output.
605          *
606          * @fixme create confirmation dialogs through a generalized interface
607          * that can be reused instead of hardcoded text and styles.
608          *
609          * @param {jQuery} form
610          */
611         NoticeRepeatConfirmation: function(form) {
612             var submit_i = form.find('.submit');
613
614             var submit = submit_i.clone();
615             submit
616                 .addClass('submit_dialogbox')
617                 .removeClass('submit');
618             form.append(submit);
619             submit.bind('click', function() { SN.U.FormXHR(form); return false; });
620
621             submit_i.hide();
622
623             form
624                 .addClass('dialogbox')
625                 .append('<button class="close">&#215;</button>')
626                 .closest('.notice-options')
627                     .addClass('opaque');
628
629             form.find('button.close').click(function(){
630                 $(this).remove();
631
632                 form
633                     .removeClass('dialogbox')
634                     .closest('.notice-options')
635                         .removeClass('opaque');
636
637                 form.find('.submit_dialogbox').remove();
638                 form.find('.submit').show();
639
640                 return false;
641             });
642         },
643
644         /**
645          * Setup function -- DOES NOT trigger actions immediately.
646          *
647          * Goes through all notices currently displayed and sets up attachment
648          * handling if needed.
649          */
650         NoticeAttachments: function() {
651             $('.notice a.attachment').each(function() {
652                 SN.U.NoticeWithAttachment($(this).closest('.notice'));
653             });
654         },
655
656         /**
657          * Setup function -- DOES NOT trigger actions immediately.
658          *
659          * Sets up special attachment link handling if needed. Currently this
660          * consists only of making the "more" button used for OStatus message
661          * cropping turn into an auto-expansion button that loads the full
662          * text from an attachment file.
663          *
664          * @param {jQuery} notice
665          */
666         NoticeWithAttachment: function(notice) {
667             if (notice.find('.attachment').length === 0) {
668                 return;
669             }
670
671             var attachment_more = notice.find('.attachment.more');
672             if (attachment_more.length > 0) {
673                 $(attachment_more[0]).click(function() {
674                     var m = $(this);
675                     m.addClass(SN.C.S.Processing);
676                     $.get(m.attr('href')+'/ajax', null, function(data) {
677                         m.parent('.entry-content').html($(data).find('#attachment_view .entry-content').html());
678                     });
679
680                     return false;
681                 }).attr('title', SN.msg('showmore_tooltip'));
682             }
683         },
684
685         /**
686          * Setup function -- DOES NOT trigger actions immediately.
687          *
688          * Sets up event handlers for the file-attachment widget in the
689          * new notice form. When a file is selected, a box will be added
690          * below the text input showing the filename and, if supported
691          * by the browser, a thumbnail preview.
692          *
693          * This preview box will also allow removing the attachment
694          * prior to posting.
695          */
696         NoticeDataAttach: function() {
697             NDA = $('#'+SN.C.S.NoticeDataAttach);
698             NDA.change(function() {
699                 S = '<div id="'+SN.C.S.NoticeDataAttachSelected+'" class="'+SN.C.S.Success+'"><code>'+$(this).val()+'</code> <button class="close">&#215;</button></div>';
700                 NDAS = $('#'+SN.C.S.NoticeDataAttachSelected);
701                 if (NDAS.length > 0) {
702                     NDAS.replaceWith(S);
703                 }
704                 else {
705                     $('#'+SN.C.S.FormNotice).append(S);
706                 }
707                 $('#'+SN.C.S.NoticeDataAttachSelected+' button').click(function(){
708                     $('#'+SN.C.S.NoticeDataAttachSelected).remove();
709                     NDA.val('');
710
711                     return false;
712                 });
713                 if (typeof this.files == "object") {
714                     // Some newer browsers will let us fetch the files for preview.
715                     for (var i = 0; i < this.files.length; i++) {
716                         SN.U.PreviewAttach(this.files[i]);
717                     }
718                 }
719             });
720         },
721
722         /**
723          * For browsers with FileAPI support: make a thumbnail if possible,
724          * and append it into the attachment display widget.
725          *
726          * Known good:
727          * - Firefox 3.6.6, 4.0b7
728          * - Chrome 8.0.552.210
729          *
730          * Known ok metadata, can't get contents:
731          * - Safari 5.0.2
732          *
733          * Known fail:
734          * - Opera 10.63, 11 beta (no input.files interface)
735          *
736          * @param {File} file
737          *
738          * @todo use configured thumbnail size
739          * @todo detect pixel size?
740          * @todo should we render a thumbnail to a canvas and then use the smaller image?
741          */
742         PreviewAttach: function(file) {
743             var tooltip = file.type + ' ' + Math.round(file.size / 1024) + 'KB';
744             var preview = true;
745
746             var blobAsDataURL;
747             if (typeof window.createObjectURL != "undefined") {
748                 /**
749                  * createObjectURL lets us reference the file directly from an <img>
750                  * This produces a compact URL with an opaque reference to the file,
751                  * which we can reference immediately.
752                  *
753                  * - Firefox 3.6.6: no
754                  * - Firefox 4.0b7: no
755                  * - Safari 5.0.2: no
756                  * - Chrome 8.0.552.210: works!
757                  */
758                 blobAsDataURL = function(blob, callback) {
759                     callback(window.createObjectURL(blob));
760                 }
761             } else if (typeof window.FileReader != "undefined") {
762                 /**
763                  * FileAPI's FileReader can build a data URL from a blob's contents,
764                  * but it must read the file and build it asynchronously. This means
765                  * we'll be passing a giant data URL around, which may be inefficient.
766                  *
767                  * - Firefox 3.6.6: works!
768                  * - Firefox 4.0b7: works!
769                  * - Safari 5.0.2: no
770                  * - Chrome 8.0.552.210: works!
771                  */
772                 blobAsDataURL = function(blob, callback) {
773                     var reader = new FileReader();
774                     reader.onload = function(event) {
775                         callback(reader.result);
776                     }
777                     reader.readAsDataURL(blob);
778                 }
779             } else {
780                 preview = false;
781             }
782
783             var imageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/svg+xml'];
784             if ($.inArray(file.type, imageTypes) == -1) {
785                 // We probably don't know how to show the file.
786                 preview = false;
787             }
788
789             var maxSize = 8 * 1024 * 1024;
790             if (file.size > maxSize) {
791                 // Don't kill the browser trying to load some giant image.
792                 preview = false;
793             }
794
795             if (preview) {
796                 blobAsDataURL(file, function(url) {
797                     var img = $('<img>')
798                         .attr('title', tooltip)
799                         .attr('alt', tooltip)
800                         .attr('src', url)
801                         .attr('style', 'height: 120px');
802                     $('#'+SN.C.S.NoticeDataAttachSelected).append(img);
803                 });
804             } else {
805                 var img = $('<div></div>').text(tooltip);
806                 $('#'+SN.C.S.NoticeDataAttachSelected).append(img);
807             }
808         },
809
810         /**
811          * Setup function -- DOES NOT trigger actions immediately.
812          *
813          * Initializes state for the location-lookup features in the
814          * new-notice form. Seems to set up some event handlers for
815          * triggering lookups and using the new values.
816          *
817          * @fixme tl;dr
818          * @fixme there's not good visual state update here, so users have a
819          *        hard time figuring out if it's working or fixing if it's wrong.
820          *
821          */
822         NoticeLocationAttach: function() {
823             var NLat = $('#'+SN.C.S.NoticeLat).val();
824             var NLon = $('#'+SN.C.S.NoticeLon).val();
825             var NLNS = $('#'+SN.C.S.NoticeLocationNs).val();
826             var NLID = $('#'+SN.C.S.NoticeLocationId).val();
827             var NLN = $('#'+SN.C.S.NoticeGeoName).text();
828             var NDGe = $('#'+SN.C.S.NoticeDataGeo);
829
830             function removeNoticeDataGeo() {
831                 $('label[for='+SN.C.S.NoticeDataGeo+']')
832                     .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()))
833                     .removeClass('checked');
834
835                 $('#'+SN.C.S.NoticeLat).val('');
836                 $('#'+SN.C.S.NoticeLon).val('');
837                 $('#'+SN.C.S.NoticeLocationNs).val('');
838                 $('#'+SN.C.S.NoticeLocationId).val('');
839                 $('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
840
841                 $.cookie(SN.C.S.NoticeDataGeoCookie, 'disabled', { path: '/' });
842             }
843
844             function getJSONgeocodeURL(geocodeURL, data) {
845                 $.getJSON(geocodeURL, data, function(location) {
846                     var lns, lid;
847
848                     if (typeof(location.location_ns) != 'undefined') {
849                         $('#'+SN.C.S.NoticeLocationNs).val(location.location_ns);
850                         lns = location.location_ns;
851                     }
852
853                     if (typeof(location.location_id) != 'undefined') {
854                         $('#'+SN.C.S.NoticeLocationId).val(location.location_id);
855                         lid = location.location_id;
856                     }
857
858                     if (typeof(location.name) == 'undefined') {
859                         NLN_text = data.lat + ';' + data.lon;
860                     }
861                     else {
862                         NLN_text = location.name;
863                     }
864
865                     $('label[for='+SN.C.S.NoticeDataGeo+']')
866                         .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + NLN_text + ')');
867
868                     $('#'+SN.C.S.NoticeLat).val(data.lat);
869                     $('#'+SN.C.S.NoticeLon).val(data.lon);
870                     $('#'+SN.C.S.NoticeLocationNs).val(lns);
871                     $('#'+SN.C.S.NoticeLocationId).val(lid);
872                     $('#'+SN.C.S.NoticeDataGeo).attr('checked', true);
873
874                     var cookieValue = {
875                         NLat: data.lat,
876                         NLon: data.lon,
877                         NLNS: lns,
878                         NLID: lid,
879                         NLN: NLN_text,
880                         NLNU: location.url,
881                         NDG: true
882                     };
883
884                     $.cookie(SN.C.S.NoticeDataGeoCookie, JSON.stringify(cookieValue), { path: '/' });
885                 });
886             }
887
888             if (NDGe.length > 0) {
889                 if ($.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
890                     NDGe.attr('checked', false);
891                 }
892                 else {
893                     NDGe.attr('checked', true);
894                 }
895
896                 var NGW = $('#notice_data-geo_wrap');
897                 var geocodeURL = NGW.attr('title');
898                 NGW.removeAttr('title');
899
900                 $('label[for='+SN.C.S.NoticeDataGeo+']')
901                     .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()));
902
903                 NDGe.change(function() {
904                     if ($('#'+SN.C.S.NoticeDataGeo).attr('checked') === true || $.cookie(SN.C.S.NoticeDataGeoCookie) === null) {
905                         $('label[for='+SN.C.S.NoticeDataGeo+']')
906                             .attr('title', NoticeDataGeo_text.ShareDisable)
907                             .addClass('checked');
908
909                         if ($.cookie(SN.C.S.NoticeDataGeoCookie) === null || $.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
910                             if (navigator.geolocation) {
911                                 navigator.geolocation.getCurrentPosition(
912                                     function(position) {
913                                         $('#'+SN.C.S.NoticeLat).val(position.coords.latitude);
914                                         $('#'+SN.C.S.NoticeLon).val(position.coords.longitude);
915
916                                         var data = {
917                                             lat: position.coords.latitude,
918                                             lon: position.coords.longitude,
919                                             token: $('#token').val()
920                                         };
921
922                                         getJSONgeocodeURL(geocodeURL, data);
923                                     },
924
925                                     function(error) {
926                                         switch(error.code) {
927                                             case error.PERMISSION_DENIED:
928                                                 removeNoticeDataGeo();
929                                                 break;
930                                             case error.TIMEOUT:
931                                                 $('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
932                                                 break;
933                                         }
934                                     },
935
936                                     {
937                                         timeout: 10000
938                                     }
939                                 );
940                             }
941                             else {
942                                 if (NLat.length > 0 && NLon.length > 0) {
943                                     var data = {
944                                         lat: NLat,
945                                         lon: NLon,
946                                         token: $('#token').val()
947                                     };
948
949                                     getJSONgeocodeURL(geocodeURL, data);
950                                 }
951                                 else {
952                                     removeNoticeDataGeo();
953                                     $('#'+SN.C.S.NoticeDataGeo).remove();
954                                     $('label[for='+SN.C.S.NoticeDataGeo+']').remove();
955                                 }
956                             }
957                         }
958                         else {
959                             var cookieValue = JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));
960
961                             $('#'+SN.C.S.NoticeLat).val(cookieValue.NLat);
962                             $('#'+SN.C.S.NoticeLon).val(cookieValue.NLon);
963                             $('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS);
964                             $('#'+SN.C.S.NoticeLocationId).val(cookieValue.NLID);
965                             $('#'+SN.C.S.NoticeDataGeo).attr('checked', cookieValue.NDG);
966
967                             $('label[for='+SN.C.S.NoticeDataGeo+']')
968                                 .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + cookieValue.NLN + ')')
969                                 .addClass('checked');
970                         }
971                     }
972                     else {
973                         removeNoticeDataGeo();
974                     }
975                 }).change();
976             }
977         },
978
979         /**
980          * Setup function -- DOES NOT trigger actions immediately.
981          *
982          * Initializes event handlers for the "Send direct message" link on
983          * profile pages, setting it up to display a dialog box when clicked.
984          *
985          * Unlike the repeat confirmation form, this appears to fetch
986          * the form _from the original link target_, so the form itself
987          * doesn't need to be in the current document.
988          *
989          * @fixme breaks ability to open link in new window?
990          */
991         NewDirectMessage: function() {
992             NDM = $('.entity_send-a-message a');
993             NDM.attr({'href':NDM.attr('href')+'&ajax=1'});
994             NDM.bind('click', function() {
995                 var NDMF = $('.entity_send-a-message form');
996                 if (NDMF.length === 0) {
997                     $(this).addClass(SN.C.S.Processing);
998                     $.get(NDM.attr('href'), null, function(data) {
999                         $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
1000                         NDMF = $('.entity_send-a-message .form_notice');
1001                         SN.U.FormNoticeXHR(NDMF);
1002                         SN.U.FormNoticeEnhancements(NDMF);
1003                         NDMF.append('<button class="close">&#215;</button>');
1004                         $('.entity_send-a-message button').click(function(){
1005                             NDMF.hide();
1006                             return false;
1007                         });
1008                         NDM.removeClass(SN.C.S.Processing);
1009                     });
1010                 }
1011                 else {
1012                     NDMF.show();
1013                     $('.entity_send-a-message textarea').focus();
1014                 }
1015                 return false;
1016             });
1017         },
1018
1019         /**
1020          * Return a date object with the current local time on the
1021          * given year, month, and day.
1022          *
1023          * @param {number} year: 4-digit year
1024          * @param {number} month: 0 == January
1025          * @param {number} day: 1 == 1
1026          * @return {Date}
1027          */
1028         GetFullYear: function(year, month, day) {
1029             var date = new Date();
1030             date.setFullYear(year, month, day);
1031
1032             return date;
1033         },
1034
1035         /**
1036          * Some sort of object interface for storing some structured
1037          * information in a cookie.
1038          *
1039          * Appears to be used to save the last-used login nickname?
1040          * That's something that browsers usually take care of for us
1041          * these days, do we really need to do it? Does anything else
1042          * use this interface?
1043          *
1044          * @fixme what is this?
1045          * @fixme should this use non-cookie local storage when available?
1046          */
1047         StatusNetInstance: {
1048             /**
1049              * @fixme what is this?
1050              */
1051             Set: function(value) {
1052                 var SNI = SN.U.StatusNetInstance.Get();
1053                 if (SNI !== null) {
1054                     value = $.extend(SNI, value);
1055                 }
1056
1057                 $.cookie(
1058                     SN.C.S.StatusNetInstance,
1059                     JSON.stringify(value),
1060                     {
1061                         path: '/',
1062                         expires: SN.U.GetFullYear(2029, 0, 1)
1063                     });
1064             },
1065
1066             /**
1067              * @fixme what is this?
1068              */
1069             Get: function() {
1070                 var cookieValue = $.cookie(SN.C.S.StatusNetInstance);
1071                 if (cookieValue !== null) {
1072                     return JSON.parse(cookieValue);
1073                 }
1074                 return null;
1075             },
1076
1077             /**
1078              * @fixme what is this?
1079              */
1080             Delete: function() {
1081                 $.cookie(SN.C.S.StatusNetInstance, null);
1082             }
1083         },
1084
1085         /**
1086          * Check if the current page is a timeline where the current user's
1087          * posts should be displayed immediately on success.
1088          *
1089          * @fixme this should be done in a saner way, with machine-readable
1090          * info about what page we're looking at.
1091          *
1092          * @param {DOMElement} notice: HTML chunk with formatted notice
1093          * @return boolean
1094          */
1095         belongsOnTimeline: function(notice) {
1096             var action = $("body").attr('id');
1097             if (action == 'public') {
1098                 return true;
1099             }
1100
1101             var profileLink = $('#nav_profile a').attr('href');
1102             if (profileLink) {
1103                 var authorUrl = $(notice).find('.entry-title .author a.url').attr('href');
1104                 if (authorUrl == profileLink) {
1105                     if (action == 'all' || action == 'showstream') {
1106                         // Posts always show on your own friends and profile streams.
1107                         return true;
1108                     }
1109                 }
1110             }
1111
1112             // @fixme tag, group, reply timelines should be feasible as well.
1113             // Mismatch between id-based and name-based user/group links currently complicates
1114             // the lookup, since all our inline mentions contain the absolute links but the
1115             // UI links currently on the page use malleable names.
1116
1117             return false;
1118         }
1119     },
1120
1121     Init: {
1122         /**
1123          * If user is logged in, run setup code for the new notice form:
1124          *
1125          *  - char counter
1126          *  - AJAX submission
1127          *  - location events
1128          *  - file upload events
1129          */
1130         NoticeForm: function() {
1131             if ($('body.user_in').length > 0) {
1132                 SN.U.NoticeLocationAttach();
1133
1134                 $('.'+SN.C.S.FormNotice).each(function() {
1135                     SN.U.FormNoticeXHR($(this));
1136                     SN.U.FormNoticeEnhancements($(this));
1137                 });
1138
1139                 SN.U.NoticeDataAttach();
1140             }
1141         },
1142
1143         /**
1144          * Run setup code for notice timeline views items:
1145          *
1146          * - AJAX submission for fave/repeat/reply (if logged in)
1147          * - Attachment link extras ('more' links)
1148          */
1149         Notices: function() {
1150             if ($('body.user_in').length > 0) {
1151                 SN.U.NoticeFavor();
1152                 SN.U.NoticeRepeat();
1153                 SN.U.NoticeReply();
1154             }
1155
1156             SN.U.NoticeAttachments();
1157         },
1158
1159         /**
1160          * Run setup code for user & group profile page header area if logged in:
1161          *
1162          * - AJAX submission for sub/unsub/join/leave/nudge
1163          * - AJAX form popup for direct-message
1164          */
1165         EntityActions: function() {
1166             if ($('body.user_in').length > 0) {
1167                 $('.form_user_subscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
1168                 $('.form_user_unsubscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
1169                 $('.form_group_join').live('click', function() { SN.U.FormXHR($(this)); return false; });
1170                 $('.form_group_leave').live('click', function() { SN.U.FormXHR($(this)); return false; });
1171                 $('.form_user_nudge').live('click', function() { SN.U.FormXHR($(this)); return false; });
1172
1173                 SN.U.NewDirectMessage();
1174             }
1175         },
1176
1177         /**
1178          * Run setup code for login form:
1179          *
1180          * - loads saved last-used-nickname from cookie
1181          * - sets event handler to save nickname to cookie on submit
1182          *
1183          * @fixme is this necessary? Browsers do their own form saving these days.
1184          */
1185         Login: function() {
1186             if (SN.U.StatusNetInstance.Get() !== null) {
1187                 var nickname = SN.U.StatusNetInstance.Get().Nickname;
1188                 if (nickname !== null) {
1189                     $('#form_login #nickname').val(nickname);
1190                 }
1191             }
1192
1193             $('#form_login').bind('submit', function() {
1194                 SN.U.StatusNetInstance.Set({Nickname: $('#form_login #nickname').val()});
1195                 return true;
1196             });
1197         }
1198     }
1199 };
1200
1201 /**
1202  * Run initialization functions on DOM-ready.
1203  *
1204  * Note that if we're waiting on other scripts to load, this won't happen
1205  * until that's done. To load scripts asynchronously without delaying setup,
1206  * don't start them loading until after DOM-ready time!
1207  */
1208 $(document).ready(function(){
1209     if ($('.'+SN.C.S.FormNotice).length > 0) {
1210         SN.Init.NoticeForm();
1211     }
1212     if ($('#content .notices').length > 0) {
1213         SN.Init.Notices();
1214     }
1215     if ($('#content .entity_actions').length > 0) {
1216         SN.Init.EntityActions();
1217     }
1218     if ($('#form_login').length > 0) {
1219         SN.Init.Login();
1220     }
1221 });
1222
1223 // Formerly in xbImportNode.js
1224 // @fixme put it back there -- since we're minifying we can concat in the makefile now
1225
1226 /* is this stuff defined? */
1227 if (!document.ELEMENT_NODE) {
1228         document.ELEMENT_NODE = 1;
1229         document.ATTRIBUTE_NODE = 2;
1230         document.TEXT_NODE = 3;
1231         document.CDATA_SECTION_NODE = 4;
1232         document.ENTITY_REFERENCE_NODE = 5;
1233         document.ENTITY_NODE = 6;
1234         document.PROCESSING_INSTRUCTION_NODE = 7;
1235         document.COMMENT_NODE = 8;
1236         document.DOCUMENT_NODE = 9;
1237         document.DOCUMENT_TYPE_NODE = 10;
1238         document.DOCUMENT_FRAGMENT_NODE = 11;
1239         document.NOTATION_NODE = 12;
1240 }
1241
1242 document._importNode = function(node, allChildren) {
1243         /* find the node type to import */
1244         switch (node.nodeType) {
1245                 case document.ELEMENT_NODE:
1246                         /* create a new element */
1247                         var newNode = document.createElement(node.nodeName);
1248                         /* does the node have any attributes to add? */
1249                         if (node.attributes && node.attributes.length > 0)
1250                                 /* add all of the attributes */
1251                                 for (var i = 0, il = node.attributes.length; i < il;) {
1252                                         if (node.attributes[i].nodeName == 'class') {
1253                                                 newNode.className = node.getAttribute(node.attributes[i++].nodeName);
1254                                         } else {
1255                                                 newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i++].nodeName));
1256                                         }
1257                                 }
1258                         /* are we going after children too, and does the node have any? */
1259                         if (allChildren && node.childNodes && node.childNodes.length > 0)
1260                                 /* recursively get all of the child nodes */
1261                                 for (var i = 0, il = node.childNodes.length; i < il;)
1262                                         newNode.appendChild(document._importNode(node.childNodes[i++], allChildren));
1263                         return newNode;
1264                         break;
1265                 case document.TEXT_NODE:
1266                 case document.CDATA_SECTION_NODE:
1267                 case document.COMMENT_NODE:
1268                         return document.createTextNode(node.nodeValue);
1269                         break;
1270         }
1271 };
1272
1273 // @fixme put this next bit back too -- since we're minifying we can concat in the makefile now
1274 // A shim to implement the W3C Geolocation API Specification using Gears or the Ajax API
1275 if (typeof navigator.geolocation == "undefined" || navigator.geolocation.shim ) { (function(){
1276
1277 // -- BEGIN GEARS_INIT
1278 (function() {
1279   // We are already defined. Hooray!
1280   if (window.google && google.gears) {
1281     return;
1282   }
1283
1284   var factory = null;
1285
1286   // Firefox
1287   if (typeof GearsFactory != 'undefined') {
1288     factory = new GearsFactory();
1289   } else {
1290     // IE
1291     try {
1292       factory = new ActiveXObject('Gears.Factory');
1293       // privateSetGlobalObject is only required and supported on WinCE.
1294       if (factory.getBuildInfo().indexOf('ie_mobile') != -1) {
1295         factory.privateSetGlobalObject(this);
1296       }
1297     } catch (e) {
1298       // Safari
1299       if ((typeof navigator.mimeTypes != 'undefined') && navigator.mimeTypes["application/x-googlegears"]) {
1300         factory = document.createElement("object");
1301         factory.style.display = "none";
1302         factory.width = 0;
1303         factory.height = 0;
1304         factory.type = "application/x-googlegears";
1305         document.documentElement.appendChild(factory);
1306       }
1307     }
1308   }
1309
1310   // *Do not* define any objects if Gears is not installed. This mimics the
1311   // behavior of Gears defining the objects in the future.
1312   if (!factory) {
1313     return;
1314   }
1315
1316   // Now set up the objects, being careful not to overwrite anything.
1317   //
1318   // Note: In Internet Explorer for Windows Mobile, you can't add properties to
1319   // the window object. However, global objects are automatically added as
1320   // properties of the window object in all browsers.
1321   if (!window.google) {
1322     google = {};
1323   }
1324
1325   if (!google.gears) {
1326     google.gears = {factory: factory};
1327   }
1328 })();
1329 // -- END GEARS_INIT
1330
1331 var GearsGeoLocation = (function() {
1332     // -- PRIVATE
1333     var geo = google.gears.factory.create('beta.geolocation');
1334
1335     var wrapSuccess = function(callback, self) { // wrap it for lastPosition love
1336         return function(position) {
1337             callback(position);
1338             self.lastPosition = position;
1339         };
1340     };
1341
1342     // -- PUBLIC
1343     return {
1344         shim: true,
1345
1346         type: "Gears",
1347
1348         lastPosition: null,
1349
1350         getCurrentPosition: function(successCallback, errorCallback, options) {
1351             var self = this;
1352             var sc = wrapSuccess(successCallback, self);
1353             geo.getCurrentPosition(sc, errorCallback, options);
1354         },
1355
1356         watchPosition: function(successCallback, errorCallback, options) {
1357             geo.watchPosition(successCallback, errorCallback, options);
1358         },
1359
1360         clearWatch: function(watchId) {
1361             geo.clearWatch(watchId);
1362         },
1363
1364         getPermission: function(siteName, imageUrl, extraMessage) {
1365             geo.getPermission(siteName, imageUrl, extraMessage);
1366         }
1367
1368     };
1369 });
1370
1371 var AjaxGeoLocation = (function() {
1372     // -- PRIVATE
1373     var loading = false;
1374     var loadGoogleLoader = function() {
1375         if (!hasGoogleLoader() && !loading) {
1376             loading = true;
1377             var s = document.createElement('script');
1378             s.src = (document.location.protocol == "https:"?"https://":"http://") + 'www.google.com/jsapi?callback=_google_loader_apiLoaded';
1379             s.type = "text/javascript";
1380             document.getElementsByTagName('body')[0].appendChild(s);
1381         }
1382     };
1383
1384     var queue = [];
1385     var addLocationQueue = function(callback) {
1386         queue.push(callback);
1387     };
1388
1389     var runLocationQueue = function() {
1390         if (hasGoogleLoader()) {
1391             while (queue.length > 0) {
1392                 var call = queue.pop();
1393                 call();
1394             }
1395         }
1396     };
1397
1398     window['_google_loader_apiLoaded'] = function() {
1399         runLocationQueue();
1400     };
1401
1402     var hasGoogleLoader = function() {
1403         return (window['google'] && google['loader']);
1404     };
1405
1406     var checkGoogleLoader = function(callback) {
1407         if (hasGoogleLoader()) { return true; }
1408
1409         addLocationQueue(callback);
1410
1411         loadGoogleLoader();
1412
1413         return false;
1414     };
1415
1416     loadGoogleLoader(); // start to load as soon as possible just in case
1417
1418     // -- PUBLIC
1419     return {
1420         shim: true,
1421
1422         type: "ClientLocation",
1423
1424         lastPosition: null,
1425
1426         getCurrentPosition: function(successCallback, errorCallback, options) {
1427             var self = this;
1428             if (!checkGoogleLoader(function() {
1429                 self.getCurrentPosition(successCallback, errorCallback, options);
1430             })) { return; }
1431
1432             if (google.loader.ClientLocation) {
1433                 var cl = google.loader.ClientLocation;
1434
1435                 var position = {
1436                     coords: {
1437                         latitude: cl.latitude,
1438                         longitude: cl.longitude,
1439                         altitude: null,
1440                         accuracy: 43000, // same as Gears accuracy over wifi?
1441                         altitudeAccuracy: null,
1442                         heading: null,
1443                         speed: null
1444                     },
1445                     // extra info that is outside of the bounds of the core API
1446                     address: {
1447                         city: cl.address.city,
1448                         country: cl.address.country,
1449                         country_code: cl.address.country_code,
1450                         region: cl.address.region
1451                     },
1452                     timestamp: new Date()
1453                 };
1454
1455                 successCallback(position);
1456
1457                 this.lastPosition = position;
1458             } else if (errorCallback === "function")  {
1459                 errorCallback({ code: 3, message: "Using the Google ClientLocation API and it is not able to calculate a location."});
1460             }
1461         },
1462
1463         watchPosition: function(successCallback, errorCallback, options) {
1464             this.getCurrentPosition(successCallback, errorCallback, options);
1465
1466             var self = this;
1467             var watchId = setInterval(function() {
1468                 self.getCurrentPosition(successCallback, errorCallback, options);
1469             }, 10000);
1470
1471             return watchId;
1472         },
1473
1474         clearWatch: function(watchId) {
1475             clearInterval(watchId);
1476         },
1477
1478         getPermission: function(siteName, imageUrl, extraMessage) {
1479             // for now just say yes :)
1480             return true;
1481         }
1482
1483     };
1484 });
1485
1486 // If you have Gears installed use that, else use Ajax ClientLocation
1487 navigator.geolocation = (window.google && google.gears) ? GearsGeoLocation() : AjaxGeoLocation();
1488
1489 })();
1490 }