]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - js/util.js
99f15e717113f8b7a07d0e47d5ba2e5cf06479f6
[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             form.ajaxForm({
319                 dataType: 'xml',
320                 timeout: '60000',
321                 beforeSend: function(formData) {
322                     if (form.find('#'+SN.C.S.NoticeDataText)[0].value.length === 0) {
323                         form.addClass(SN.C.S.Warning);
324                         return false;
325                     }
326                     form
327                         .addClass(SN.C.S.Processing)
328                         .find('#'+SN.C.S.NoticeActionSubmit)
329                             .addClass(SN.C.S.Disabled)
330                             .attr(SN.C.S.Disabled, SN.C.S.Disabled);
331
332                     SN.C.I.NoticeDataGeo.NLat = $('#'+SN.C.S.NoticeLat).val();
333                     SN.C.I.NoticeDataGeo.NLon = $('#'+SN.C.S.NoticeLon).val();
334                     SN.C.I.NoticeDataGeo.NLNS = $('#'+SN.C.S.NoticeLocationNs).val();
335                     SN.C.I.NoticeDataGeo.NLID = $('#'+SN.C.S.NoticeLocationId).val();
336                     SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked');
337
338                     cookieValue = $.cookie(SN.C.S.NoticeDataGeoCookie);
339
340                     if (cookieValue !== null && cookieValue != 'disabled') {
341                         cookieValue = JSON.parse(cookieValue);
342                         SN.C.I.NoticeDataGeo.NLat = $('#'+SN.C.S.NoticeLat).val(cookieValue.NLat).val();
343                         SN.C.I.NoticeDataGeo.NLon = $('#'+SN.C.S.NoticeLon).val(cookieValue.NLon).val();
344                         if ($('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS)) {
345                             SN.C.I.NoticeDataGeo.NLNS = $('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS).val();
346                             SN.C.I.NoticeDataGeo.NLID = $('#'+SN.C.S.NoticeLocationId).val(cookieValue.NLID).val();
347                         }
348                     }
349                     if (cookieValue == 'disabled') {
350                         SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked', false).attr('checked');
351                     }
352                     else {
353                         SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked', true).attr('checked');
354                     }
355
356                     return true;
357                 },
358                 error: function (xhr, textStatus, errorThrown) {
359                     form
360                         .removeClass(SN.C.S.Processing)
361                         .find('#'+SN.C.S.NoticeActionSubmit)
362                             .removeClass(SN.C.S.Disabled)
363                             .removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
364                     form.find('.form_response').remove();
365                     if (textStatus == 'timeout') {
366                         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>');
367                     }
368                     else {
369                         var response = SN.U.GetResponseXML(xhr);
370                         if ($('.'+SN.C.S.Error, response).length > 0) {
371                             form.append(document._importNode($('.'+SN.C.S.Error, response)[0], true));
372                         }
373                         else {
374                             if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
375                                 form
376                                     .resetForm()
377                                     .find('#'+SN.C.S.NoticeDataAttachSelected).remove();
378                                 SN.U.FormNoticeEnhancements(form);
379                             }
380                             else {
381                                 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>');
382                             }
383                         }
384                     }
385                 },
386                 success: function(data, textStatus) {
387                     form.find('.form_response').remove();
388                     var result;
389                     if ($('#'+SN.C.S.Error, data).length > 0) {
390                         result = document._importNode($('p', data)[0], true);
391                         result = result.textContent || result.innerHTML;
392                         form.append('<p class="form_response error">'+result+'</p>');
393                     }
394                     else {
395                         if($('body')[0].id == 'bookmarklet') {
396                             self.close();
397                         }
398
399                         if ($('#'+SN.C.S.CommandResult, data).length > 0) {
400                             result = document._importNode($('p', data)[0], true);
401                             result = result.textContent || result.innerHTML;
402                             form.append('<p class="form_response success">'+result+'</p>');
403                         }
404                         else {
405                             // New notice post was successful. If on our timeline, show it!
406                             var notice = document._importNode($('li', data)[0], true);
407                             var notices = $('#notices_primary .notices');
408                             if (notices.length > 0 && SN.U.belongsOnTimeline(notice)) {
409                                 if ($('#'+notice.id).length === 0) {
410                                     var notice_irt_value = $('#'+SN.C.S.NoticeInReplyTo).val();
411                                     var notice_irt = '#notices_primary #notice-'+notice_irt_value;
412                                     if($('body')[0].id == 'conversation') {
413                                         if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
414                                             $(notice_irt).append('<ul class="notices"></ul>');
415                                         }
416                                         $($(notice_irt+' .notices')[0]).append(notice);
417                                     }
418                                     else {
419                                         notices.prepend(notice);
420                                     }
421                                     $('#'+notice.id)
422                                         .css({display:'none'})
423                                         .fadeIn(2500);
424                                     SN.U.NoticeWithAttachment($('#'+notice.id));
425                                     SN.U.NoticeReplyTo($('#'+notice.id));
426                                 }
427                             }
428                             else {
429                                 // Not on a timeline that this belongs on?
430                                 // Just show a success message.
431                                 result = document._importNode($('title', data)[0], true);
432                                 result_title = result.textContent || result.innerHTML;
433                                 form.append('<p class="form_response success">'+result_title+'</p>');
434                             }
435                         }
436                         form.resetForm();
437                         form.find('#'+SN.C.S.NoticeInReplyTo).val('');
438                         form.find('#'+SN.C.S.NoticeDataAttachSelected).remove();
439                         SN.U.FormNoticeEnhancements(form);
440                     }
441                 },
442                 complete: function(xhr, textStatus) {
443                     form
444                         .removeClass(SN.C.S.Processing)
445                         .find('#'+SN.C.S.NoticeActionSubmit)
446                             .removeAttr(SN.C.S.Disabled)
447                             .removeClass(SN.C.S.Disabled);
448
449                     $('#'+SN.C.S.NoticeLat).val(SN.C.I.NoticeDataGeo.NLat);
450                     $('#'+SN.C.S.NoticeLon).val(SN.C.I.NoticeDataGeo.NLon);
451                     if ($('#'+SN.C.S.NoticeLocationNs)) {
452                         $('#'+SN.C.S.NoticeLocationNs).val(SN.C.I.NoticeDataGeo.NLNS);
453                         $('#'+SN.C.S.NoticeLocationId).val(SN.C.I.NoticeDataGeo.NLID);
454                     }
455                     $('#'+SN.C.S.NoticeDataGeo).attr('checked', SN.C.I.NoticeDataGeo.NDG);
456                 }
457             });
458         },
459
460         /**
461          * Fetch an XML DOM from an XHR's response data.
462          *
463          * Works around unavailable responseXML when document.domain
464          * has been modified by Meteor or other tools, in some but not
465          * all browsers.
466          *
467          * @param {XMLHTTPRequest} xhr
468          * @return DOMDocument
469          */
470         GetResponseXML: function(xhr) {
471             try {
472                 return xhr.responseXML;
473             } catch (e) {
474                 return (new DOMParser()).parseFromString(xhr.responseText, "text/xml");
475             }
476         },
477
478         /**
479          * Setup function -- DOES NOT trigger actions immediately.
480          *
481          * Sets up event handlers on all visible notice's reply buttons to
482          * tweak the new-notice form with needed variables and focus it
483          * when pushed.
484          *
485          * (This replaces the default reply button behavior to submit
486          * directly to a form which comes back with a specialized page
487          * with the form data prefilled.)
488          *
489          * @access private
490          */
491         NoticeReply: function() {
492             if ($('#'+SN.C.S.NoticeDataText).length > 0 && $('#content .notice_reply').length > 0) {
493                 $('#content .notice').each(function() { SN.U.NoticeReplyTo($(this)); });
494             }
495         },
496
497         /**
498          * Setup function -- DOES NOT trigger actions immediately.
499          *
500          * Sets up event handlers on the given notice's reply button to
501          * tweak the new-notice form with needed variables and focus it
502          * when pushed.
503          *
504          * (This replaces the default reply button behavior to submit
505          * directly to a form which comes back with a specialized page
506          * with the form data prefilled.)
507          *
508          * @param {jQuery} notice: jQuery object containing one or more notices
509          * @access private
510          */
511         NoticeReplyTo: function(notice) {
512             notice.find('.notice_reply').live('click', function() {
513                 var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
514                 SN.U.NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
515                 return false;
516             });
517         },
518
519         /**
520          * Updates the new notice posting form with bits for replying to the
521          * given user. Adds replyto parameter to the form, and a "@foo" to the
522          * text area.
523          *
524          * @fixme replyto is a global variable, but probably shouldn't be
525          *
526          * @param {String} nick
527          * @param {String} id
528          */
529         NoticeReplySet: function(nick,id) {
530             if (nick.match(SN.C.I.PatternUsername)) {
531                 var text = $('#'+SN.C.S.NoticeDataText);
532                 if (text.length > 0) {
533                     replyto = '@' + nick + ' ';
534                     text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
535                     $('#'+SN.C.S.FormNotice+' #'+SN.C.S.NoticeInReplyTo).val(id);
536
537                     text[0].focus();
538                     if (text[0].setSelectionRange) {
539                         var len = text.val().length;
540                         text[0].setSelectionRange(len,len);
541                     }
542                 }
543             }
544         },
545
546         /**
547          * Setup function -- DOES NOT apply immediately.
548          *
549          * Sets up event handlers for favor/disfavor forms to submit via XHR.
550          * Uses 'live' rather than 'bind', so applies to future as well as present items.
551          */
552         NoticeFavor: function() {
553             $('.form_favor').live('click', function() { SN.U.FormXHR($(this)); return false; });
554             $('.form_disfavor').live('click', function() { SN.U.FormXHR($(this)); return false; });
555         },
556
557         /**
558          * Setup function -- DOES NOT trigger actions immediately.
559          *
560          * Sets up event handlers for repeat forms to toss up a confirmation
561          * popout before submitting.
562          *
563          * Uses 'live' rather than 'bind', so applies to future as well as present items.
564          */
565         NoticeRepeat: function() {
566             $('.form_repeat').live('click', function(e) {
567                 e.preventDefault();
568
569                 SN.U.NoticeRepeatConfirmation($(this));
570                 return false;
571             });
572         },
573
574         /**
575          * Shows a confirmation dialog box variant of the repeat button form.
576          * This seems to use a technique where the repeat form contains
577          * _both_ a standalone button _and_ text and buttons for a dialog.
578          * The dialog will close after its copy of the form is submitted,
579          * or if you click its 'close' button.
580          *
581          * The dialog is created by duplicating the original form and changing
582          * its style; while clever, this is hard to generalize and probably
583          * duplicates a lot of unnecessary HTML output.
584          *
585          * @fixme create confirmation dialogs through a generalized interface
586          * that can be reused instead of hardcoded text and styles.
587          *
588          * @param {jQuery} form
589          */
590         NoticeRepeatConfirmation: function(form) {
591             var submit_i = form.find('.submit');
592
593             var submit = submit_i.clone();
594             submit
595                 .addClass('submit_dialogbox')
596                 .removeClass('submit');
597             form.append(submit);
598             submit.bind('click', function() { SN.U.FormXHR(form); return false; });
599
600             submit_i.hide();
601
602             form
603                 .addClass('dialogbox')
604                 .append('<button class="close">&#215;</button>')
605                 .closest('.notice-options')
606                     .addClass('opaque');
607
608             form.find('button.close').click(function(){
609                 $(this).remove();
610
611                 form
612                     .removeClass('dialogbox')
613                     .closest('.notice-options')
614                         .removeClass('opaque');
615
616                 form.find('.submit_dialogbox').remove();
617                 form.find('.submit').show();
618
619                 return false;
620             });
621         },
622
623         /**
624          * Setup function -- DOES NOT trigger actions immediately.
625          *
626          * Goes through all notices currently displayed and sets up attachment
627          * handling if needed.
628          */
629         NoticeAttachments: function() {
630             $('.notice a.attachment').each(function() {
631                 SN.U.NoticeWithAttachment($(this).closest('.notice'));
632             });
633         },
634
635         /**
636          * Setup function -- DOES NOT trigger actions immediately.
637          *
638          * Sets up special attachment link handling if needed. Currently this
639          * consists only of making the "more" button used for OStatus message
640          * cropping turn into an auto-expansion button that loads the full
641          * text from an attachment file.
642          *
643          * @param {jQuery} notice
644          */
645         NoticeWithAttachment: function(notice) {
646             if (notice.find('.attachment').length === 0) {
647                 return;
648             }
649
650             var attachment_more = notice.find('.attachment.more');
651             if (attachment_more.length > 0) {
652                 $(attachment_more[0]).click(function() {
653                     var m = $(this);
654                     m.addClass(SN.C.S.Processing);
655                     $.get(m.attr('href')+'/ajax', null, function(data) {
656                         m.parent('.entry-content').html($(data).find('#attachment_view .entry-content').html());
657                     });
658
659                     return false;
660                 }).attr('title', SN.msg('showmore_tooltip'));
661             }
662         },
663
664         /**
665          * Setup function -- DOES NOT trigger actions immediately.
666          *
667          * Sets up event handlers for the file-attachment widget in the
668          * new notice form. When a file is selected, a box will be added
669          * below the text input showing the filename and, if supported
670          * by the browser, a thumbnail preview.
671          *
672          * This preview box will also allow removing the attachment
673          * prior to posting.
674          */
675         NoticeDataAttach: function() {
676             NDA = $('#'+SN.C.S.NoticeDataAttach);
677             NDA.change(function() {
678                 S = '<div id="'+SN.C.S.NoticeDataAttachSelected+'" class="'+SN.C.S.Success+'"><code>'+$(this).val()+'</code> <button class="close">&#215;</button></div>';
679                 NDAS = $('#'+SN.C.S.NoticeDataAttachSelected);
680                 if (NDAS.length > 0) {
681                     NDAS.replaceWith(S);
682                 }
683                 else {
684                     $('#'+SN.C.S.FormNotice).append(S);
685                 }
686                 $('#'+SN.C.S.NoticeDataAttachSelected+' button').click(function(){
687                     $('#'+SN.C.S.NoticeDataAttachSelected).remove();
688                     NDA.val('');
689
690                     return false;
691                 });
692                 if (typeof this.files == "object") {
693                     // Some newer browsers will let us fetch the files for preview.
694                     for (var i = 0; i < this.files.length; i++) {
695                         SN.U.PreviewAttach(this.files[i]);
696                     }
697                 }
698             });
699         },
700
701         /**
702          * For browsers with FileAPI support: make a thumbnail if possible,
703          * and append it into the attachment display widget.
704          *
705          * Known good:
706          * - Firefox 3.6.6, 4.0b7
707          * - Chrome 8.0.552.210
708          *
709          * Known ok metadata, can't get contents:
710          * - Safari 5.0.2
711          *
712          * Known fail:
713          * - Opera 10.63, 11 beta (no input.files interface)
714          *
715          * @param {File} file
716          *
717          * @todo use configured thumbnail size
718          * @todo detect pixel size?
719          * @todo should we render a thumbnail to a canvas and then use the smaller image?
720          */
721         PreviewAttach: function(file) {
722             var tooltip = file.type + ' ' + Math.round(file.size / 1024) + 'KB';
723             var preview = true;
724
725             var blobAsDataURL;
726             if (typeof window.createObjectURL != "undefined") {
727                 /**
728                  * createObjectURL lets us reference the file directly from an <img>
729                  * This produces a compact URL with an opaque reference to the file,
730                  * which we can reference immediately.
731                  *
732                  * - Firefox 3.6.6: no
733                  * - Firefox 4.0b7: no
734                  * - Safari 5.0.2: no
735                  * - Chrome 8.0.552.210: works!
736                  */
737                 blobAsDataURL = function(blob, callback) {
738                     callback(window.createObjectURL(blob));
739                 }
740             } else if (typeof window.FileReader != "undefined") {
741                 /**
742                  * FileAPI's FileReader can build a data URL from a blob's contents,
743                  * but it must read the file and build it asynchronously. This means
744                  * we'll be passing a giant data URL around, which may be inefficient.
745                  *
746                  * - Firefox 3.6.6: works!
747                  * - Firefox 4.0b7: works!
748                  * - Safari 5.0.2: no
749                  * - Chrome 8.0.552.210: works!
750                  */
751                 blobAsDataURL = function(blob, callback) {
752                     var reader = new FileReader();
753                     reader.onload = function(event) {
754                         callback(reader.result);
755                     }
756                     reader.readAsDataURL(blob);
757                 }
758             } else {
759                 preview = false;
760             }
761
762             var imageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/svg+xml'];
763             if ($.inArray(file.type, imageTypes) == -1) {
764                 // We probably don't know how to show the file.
765                 preview = false;
766             }
767
768             var maxSize = 8 * 1024 * 1024;
769             if (file.size > maxSize) {
770                 // Don't kill the browser trying to load some giant image.
771                 preview = false;
772             }
773
774             if (preview) {
775                 blobAsDataURL(file, function(url) {
776                     var img = $('<img>')
777                         .attr('title', tooltip)
778                         .attr('alt', tooltip)
779                         .attr('src', url)
780                         .attr('style', 'height: 120px');
781                     $('#'+SN.C.S.NoticeDataAttachSelected).append(img);
782                 });
783             } else {
784                 var img = $('<div></div>').text(tooltip);
785                 $('#'+SN.C.S.NoticeDataAttachSelected).append(img);
786             }
787         },
788
789         /**
790          * Setup function -- DOES NOT trigger actions immediately.
791          *
792          * Initializes state for the location-lookup features in the
793          * new-notice form. Seems to set up some event handlers for
794          * triggering lookups and using the new values.
795          *
796          * @fixme tl;dr
797          * @fixme there's not good visual state update here, so users have a
798          *        hard time figuring out if it's working or fixing if it's wrong.
799          *
800          */
801         NoticeLocationAttach: function() {
802             var NLat = $('#'+SN.C.S.NoticeLat).val();
803             var NLon = $('#'+SN.C.S.NoticeLon).val();
804             var NLNS = $('#'+SN.C.S.NoticeLocationNs).val();
805             var NLID = $('#'+SN.C.S.NoticeLocationId).val();
806             var NLN = $('#'+SN.C.S.NoticeGeoName).text();
807             var NDGe = $('#'+SN.C.S.NoticeDataGeo);
808
809             function removeNoticeDataGeo() {
810                 $('label[for='+SN.C.S.NoticeDataGeo+']')
811                     .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()))
812                     .removeClass('checked');
813
814                 $('#'+SN.C.S.NoticeLat).val('');
815                 $('#'+SN.C.S.NoticeLon).val('');
816                 $('#'+SN.C.S.NoticeLocationNs).val('');
817                 $('#'+SN.C.S.NoticeLocationId).val('');
818                 $('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
819
820                 $.cookie(SN.C.S.NoticeDataGeoCookie, 'disabled', { path: '/' });
821             }
822
823             function getJSONgeocodeURL(geocodeURL, data) {
824                 $.getJSON(geocodeURL, data, function(location) {
825                     var lns, lid;
826
827                     if (typeof(location.location_ns) != 'undefined') {
828                         $('#'+SN.C.S.NoticeLocationNs).val(location.location_ns);
829                         lns = location.location_ns;
830                     }
831
832                     if (typeof(location.location_id) != 'undefined') {
833                         $('#'+SN.C.S.NoticeLocationId).val(location.location_id);
834                         lid = location.location_id;
835                     }
836
837                     if (typeof(location.name) == 'undefined') {
838                         NLN_text = data.lat + ';' + data.lon;
839                     }
840                     else {
841                         NLN_text = location.name;
842                     }
843
844                     $('label[for='+SN.C.S.NoticeDataGeo+']')
845                         .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + NLN_text + ')');
846
847                     $('#'+SN.C.S.NoticeLat).val(data.lat);
848                     $('#'+SN.C.S.NoticeLon).val(data.lon);
849                     $('#'+SN.C.S.NoticeLocationNs).val(lns);
850                     $('#'+SN.C.S.NoticeLocationId).val(lid);
851                     $('#'+SN.C.S.NoticeDataGeo).attr('checked', true);
852
853                     var cookieValue = {
854                         NLat: data.lat,
855                         NLon: data.lon,
856                         NLNS: lns,
857                         NLID: lid,
858                         NLN: NLN_text,
859                         NLNU: location.url,
860                         NDG: true
861                     };
862
863                     $.cookie(SN.C.S.NoticeDataGeoCookie, JSON.stringify(cookieValue), { path: '/' });
864                 });
865             }
866
867             if (NDGe.length > 0) {
868                 if ($.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
869                     NDGe.attr('checked', false);
870                 }
871                 else {
872                     NDGe.attr('checked', true);
873                 }
874
875                 var NGW = $('#notice_data-geo_wrap');
876                 var geocodeURL = NGW.attr('title');
877                 NGW.removeAttr('title');
878
879                 $('label[for='+SN.C.S.NoticeDataGeo+']')
880                     .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()));
881
882                 NDGe.change(function() {
883                     if ($('#'+SN.C.S.NoticeDataGeo).attr('checked') === true || $.cookie(SN.C.S.NoticeDataGeoCookie) === null) {
884                         $('label[for='+SN.C.S.NoticeDataGeo+']')
885                             .attr('title', NoticeDataGeo_text.ShareDisable)
886                             .addClass('checked');
887
888                         if ($.cookie(SN.C.S.NoticeDataGeoCookie) === null || $.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
889                             if (navigator.geolocation) {
890                                 navigator.geolocation.getCurrentPosition(
891                                     function(position) {
892                                         $('#'+SN.C.S.NoticeLat).val(position.coords.latitude);
893                                         $('#'+SN.C.S.NoticeLon).val(position.coords.longitude);
894
895                                         var data = {
896                                             lat: position.coords.latitude,
897                                             lon: position.coords.longitude,
898                                             token: $('#token').val()
899                                         };
900
901                                         getJSONgeocodeURL(geocodeURL, data);
902                                     },
903
904                                     function(error) {
905                                         switch(error.code) {
906                                             case error.PERMISSION_DENIED:
907                                                 removeNoticeDataGeo();
908                                                 break;
909                                             case error.TIMEOUT:
910                                                 $('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
911                                                 break;
912                                         }
913                                     },
914
915                                     {
916                                         timeout: 10000
917                                     }
918                                 );
919                             }
920                             else {
921                                 if (NLat.length > 0 && NLon.length > 0) {
922                                     var data = {
923                                         lat: NLat,
924                                         lon: NLon,
925                                         token: $('#token').val()
926                                     };
927
928                                     getJSONgeocodeURL(geocodeURL, data);
929                                 }
930                                 else {
931                                     removeNoticeDataGeo();
932                                     $('#'+SN.C.S.NoticeDataGeo).remove();
933                                     $('label[for='+SN.C.S.NoticeDataGeo+']').remove();
934                                 }
935                             }
936                         }
937                         else {
938                             var cookieValue = JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));
939
940                             $('#'+SN.C.S.NoticeLat).val(cookieValue.NLat);
941                             $('#'+SN.C.S.NoticeLon).val(cookieValue.NLon);
942                             $('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS);
943                             $('#'+SN.C.S.NoticeLocationId).val(cookieValue.NLID);
944                             $('#'+SN.C.S.NoticeDataGeo).attr('checked', cookieValue.NDG);
945
946                             $('label[for='+SN.C.S.NoticeDataGeo+']')
947                                 .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + cookieValue.NLN + ')')
948                                 .addClass('checked');
949                         }
950                     }
951                     else {
952                         removeNoticeDataGeo();
953                     }
954                 }).change();
955             }
956         },
957
958         /**
959          * Setup function -- DOES NOT trigger actions immediately.
960          *
961          * Initializes event handlers for the "Send direct message" link on
962          * profile pages, setting it up to display a dialog box when clicked.
963          *
964          * Unlike the repeat confirmation form, this appears to fetch
965          * the form _from the original link target_, so the form itself
966          * doesn't need to be in the current document.
967          *
968          * @fixme breaks ability to open link in new window?
969          */
970         NewDirectMessage: function() {
971             NDM = $('.entity_send-a-message a');
972             NDM.attr({'href':NDM.attr('href')+'&ajax=1'});
973             NDM.bind('click', function() {
974                 var NDMF = $('.entity_send-a-message form');
975                 if (NDMF.length === 0) {
976                     $(this).addClass(SN.C.S.Processing);
977                     $.get(NDM.attr('href'), null, function(data) {
978                         $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
979                         NDMF = $('.entity_send-a-message .form_notice');
980                         SN.U.FormNoticeXHR(NDMF);
981                         SN.U.FormNoticeEnhancements(NDMF);
982                         NDMF.append('<button class="close">&#215;</button>');
983                         $('.entity_send-a-message button').click(function(){
984                             NDMF.hide();
985                             return false;
986                         });
987                         NDM.removeClass(SN.C.S.Processing);
988                     });
989                 }
990                 else {
991                     NDMF.show();
992                     $('.entity_send-a-message textarea').focus();
993                 }
994                 return false;
995             });
996         },
997
998         /**
999          * Return a date object with the current local time on the
1000          * given year, month, and day.
1001          *
1002          * @param {number} year: 4-digit year
1003          * @param {number} month: 0 == January
1004          * @param {number} day: 1 == 1
1005          * @return {Date}
1006          */
1007         GetFullYear: function(year, month, day) {
1008             var date = new Date();
1009             date.setFullYear(year, month, day);
1010
1011             return date;
1012         },
1013
1014         /**
1015          * Some sort of object interface for storing some structured
1016          * information in a cookie.
1017          *
1018          * Appears to be used to save the last-used login nickname?
1019          * That's something that browsers usually take care of for us
1020          * these days, do we really need to do it? Does anything else
1021          * use this interface?
1022          *
1023          * @fixme what is this?
1024          * @fixme should this use non-cookie local storage when available?
1025          */
1026         StatusNetInstance: {
1027             /**
1028              * @fixme what is this?
1029              */
1030             Set: function(value) {
1031                 var SNI = SN.U.StatusNetInstance.Get();
1032                 if (SNI !== null) {
1033                     value = $.extend(SNI, value);
1034                 }
1035
1036                 $.cookie(
1037                     SN.C.S.StatusNetInstance,
1038                     JSON.stringify(value),
1039                     {
1040                         path: '/',
1041                         expires: SN.U.GetFullYear(2029, 0, 1)
1042                     });
1043             },
1044
1045             /**
1046              * @fixme what is this?
1047              */
1048             Get: function() {
1049                 var cookieValue = $.cookie(SN.C.S.StatusNetInstance);
1050                 if (cookieValue !== null) {
1051                     return JSON.parse(cookieValue);
1052                 }
1053                 return null;
1054             },
1055
1056             /**
1057              * @fixme what is this?
1058              */
1059             Delete: function() {
1060                 $.cookie(SN.C.S.StatusNetInstance, null);
1061             }
1062         },
1063
1064         /**
1065          * Check if the current page is a timeline where the current user's
1066          * posts should be displayed immediately on success.
1067          *
1068          * @fixme this should be done in a saner way, with machine-readable
1069          * info about what page we're looking at.
1070          *
1071          * @param {DOMElement} notice: HTML chunk with formatted notice
1072          * @return boolean
1073          */
1074         belongsOnTimeline: function(notice) {
1075             var action = $("body").attr('id');
1076             if (action == 'public') {
1077                 return true;
1078             }
1079
1080             var profileLink = $('#nav_profile a').attr('href');
1081             if (profileLink) {
1082                 var authorUrl = $(notice).find('.entry-title .author a.url').attr('href');
1083                 if (authorUrl == profileLink) {
1084                     if (action == 'all' || action == 'showstream') {
1085                         // Posts always show on your own friends and profile streams.
1086                         return true;
1087                     }
1088                 }
1089             }
1090
1091             // @fixme tag, group, reply timelines should be feasible as well.
1092             // Mismatch between id-based and name-based user/group links currently complicates
1093             // the lookup, since all our inline mentions contain the absolute links but the
1094             // UI links currently on the page use malleable names.
1095
1096             return false;
1097         }
1098     },
1099
1100     Init: {
1101         /**
1102          * If user is logged in, run setup code for the new notice form:
1103          *
1104          *  - char counter
1105          *  - AJAX submission
1106          *  - location events
1107          *  - file upload events
1108          */
1109         NoticeForm: function() {
1110             if ($('body.user_in').length > 0) {
1111                 SN.U.NoticeLocationAttach();
1112
1113                 $('.'+SN.C.S.FormNotice).each(function() {
1114                     SN.U.FormNoticeXHR($(this));
1115                     SN.U.FormNoticeEnhancements($(this));
1116                 });
1117
1118                 SN.U.NoticeDataAttach();
1119             }
1120         },
1121
1122         /**
1123          * Run setup code for notice timeline views items:
1124          *
1125          * - AJAX submission for fave/repeat/reply (if logged in)
1126          * - Attachment link extras ('more' links)
1127          */
1128         Notices: function() {
1129             if ($('body.user_in').length > 0) {
1130                 SN.U.NoticeFavor();
1131                 SN.U.NoticeRepeat();
1132                 SN.U.NoticeReply();
1133             }
1134
1135             SN.U.NoticeAttachments();
1136         },
1137
1138         /**
1139          * Run setup code for user & group profile page header area if logged in:
1140          *
1141          * - AJAX submission for sub/unsub/join/leave/nudge
1142          * - AJAX form popup for direct-message
1143          */
1144         EntityActions: function() {
1145             if ($('body.user_in').length > 0) {
1146                 $('.form_user_subscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
1147                 $('.form_user_unsubscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
1148                 $('.form_group_join').live('click', function() { SN.U.FormXHR($(this)); return false; });
1149                 $('.form_group_leave').live('click', function() { SN.U.FormXHR($(this)); return false; });
1150                 $('.form_user_nudge').live('click', function() { SN.U.FormXHR($(this)); return false; });
1151
1152                 SN.U.NewDirectMessage();
1153             }
1154         },
1155
1156         /**
1157          * Run setup code for login form:
1158          *
1159          * - loads saved last-used-nickname from cookie
1160          * - sets event handler to save nickname to cookie on submit
1161          *
1162          * @fixme is this necessary? Browsers do their own form saving these days.
1163          */
1164         Login: function() {
1165             if (SN.U.StatusNetInstance.Get() !== null) {
1166                 var nickname = SN.U.StatusNetInstance.Get().Nickname;
1167                 if (nickname !== null) {
1168                     $('#form_login #nickname').val(nickname);
1169                 }
1170             }
1171
1172             $('#form_login').bind('submit', function() {
1173                 SN.U.StatusNetInstance.Set({Nickname: $('#form_login #nickname').val()});
1174                 return true;
1175             });
1176         }
1177     }
1178 };
1179
1180 /**
1181  * Run initialization functions on DOM-ready.
1182  *
1183  * Note that if we're waiting on other scripts to load, this won't happen
1184  * until that's done. To load scripts asynchronously without delaying setup,
1185  * don't start them loading until after DOM-ready time!
1186  */
1187 $(document).ready(function(){
1188     if ($('.'+SN.C.S.FormNotice).length > 0) {
1189         SN.Init.NoticeForm();
1190     }
1191     if ($('#content .notices').length > 0) {
1192         SN.Init.Notices();
1193     }
1194     if ($('#content .entity_actions').length > 0) {
1195         SN.Init.EntityActions();
1196     }
1197     if ($('#form_login').length > 0) {
1198         SN.Init.Login();
1199     }
1200 });
1201
1202 // Formerly in xbImportNode.js
1203 // @fixme put it back there -- since we're minifying we can concat in the makefile now
1204
1205 /* is this stuff defined? */
1206 if (!document.ELEMENT_NODE) {
1207         document.ELEMENT_NODE = 1;
1208         document.ATTRIBUTE_NODE = 2;
1209         document.TEXT_NODE = 3;
1210         document.CDATA_SECTION_NODE = 4;
1211         document.ENTITY_REFERENCE_NODE = 5;
1212         document.ENTITY_NODE = 6;
1213         document.PROCESSING_INSTRUCTION_NODE = 7;
1214         document.COMMENT_NODE = 8;
1215         document.DOCUMENT_NODE = 9;
1216         document.DOCUMENT_TYPE_NODE = 10;
1217         document.DOCUMENT_FRAGMENT_NODE = 11;
1218         document.NOTATION_NODE = 12;
1219 }
1220
1221 document._importNode = function(node, allChildren) {
1222         /* find the node type to import */
1223         switch (node.nodeType) {
1224                 case document.ELEMENT_NODE:
1225                         /* create a new element */
1226                         var newNode = document.createElement(node.nodeName);
1227                         /* does the node have any attributes to add? */
1228                         if (node.attributes && node.attributes.length > 0)
1229                                 /* add all of the attributes */
1230                                 for (var i = 0, il = node.attributes.length; i < il;) {
1231                                         if (node.attributes[i].nodeName == 'class') {
1232                                                 newNode.className = node.getAttribute(node.attributes[i++].nodeName);
1233                                         } else {
1234                                                 newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i++].nodeName));
1235                                         }
1236                                 }
1237                         /* are we going after children too, and does the node have any? */
1238                         if (allChildren && node.childNodes && node.childNodes.length > 0)
1239                                 /* recursively get all of the child nodes */
1240                                 for (var i = 0, il = node.childNodes.length; i < il;)
1241                                         newNode.appendChild(document._importNode(node.childNodes[i++], allChildren));
1242                         return newNode;
1243                         break;
1244                 case document.TEXT_NODE:
1245                 case document.CDATA_SECTION_NODE:
1246                 case document.COMMENT_NODE:
1247                         return document.createTextNode(node.nodeValue);
1248                         break;
1249         }
1250 };
1251
1252 // @fixme put this next bit back too -- since we're minifying we can concat in the makefile now
1253 // A shim to implement the W3C Geolocation API Specification using Gears or the Ajax API
1254 if (typeof navigator.geolocation == "undefined" || navigator.geolocation.shim ) { (function(){
1255
1256 // -- BEGIN GEARS_INIT
1257 (function() {
1258   // We are already defined. Hooray!
1259   if (window.google && google.gears) {
1260     return;
1261   }
1262
1263   var factory = null;
1264
1265   // Firefox
1266   if (typeof GearsFactory != 'undefined') {
1267     factory = new GearsFactory();
1268   } else {
1269     // IE
1270     try {
1271       factory = new ActiveXObject('Gears.Factory');
1272       // privateSetGlobalObject is only required and supported on WinCE.
1273       if (factory.getBuildInfo().indexOf('ie_mobile') != -1) {
1274         factory.privateSetGlobalObject(this);
1275       }
1276     } catch (e) {
1277       // Safari
1278       if ((typeof navigator.mimeTypes != 'undefined') && navigator.mimeTypes["application/x-googlegears"]) {
1279         factory = document.createElement("object");
1280         factory.style.display = "none";
1281         factory.width = 0;
1282         factory.height = 0;
1283         factory.type = "application/x-googlegears";
1284         document.documentElement.appendChild(factory);
1285       }
1286     }
1287   }
1288
1289   // *Do not* define any objects if Gears is not installed. This mimics the
1290   // behavior of Gears defining the objects in the future.
1291   if (!factory) {
1292     return;
1293   }
1294
1295   // Now set up the objects, being careful not to overwrite anything.
1296   //
1297   // Note: In Internet Explorer for Windows Mobile, you can't add properties to
1298   // the window object. However, global objects are automatically added as
1299   // properties of the window object in all browsers.
1300   if (!window.google) {
1301     google = {};
1302   }
1303
1304   if (!google.gears) {
1305     google.gears = {factory: factory};
1306   }
1307 })();
1308 // -- END GEARS_INIT
1309
1310 var GearsGeoLocation = (function() {
1311     // -- PRIVATE
1312     var geo = google.gears.factory.create('beta.geolocation');
1313
1314     var wrapSuccess = function(callback, self) { // wrap it for lastPosition love
1315         return function(position) {
1316             callback(position);
1317             self.lastPosition = position;
1318         };
1319     };
1320
1321     // -- PUBLIC
1322     return {
1323         shim: true,
1324
1325         type: "Gears",
1326
1327         lastPosition: null,
1328
1329         getCurrentPosition: function(successCallback, errorCallback, options) {
1330             var self = this;
1331             var sc = wrapSuccess(successCallback, self);
1332             geo.getCurrentPosition(sc, errorCallback, options);
1333         },
1334
1335         watchPosition: function(successCallback, errorCallback, options) {
1336             geo.watchPosition(successCallback, errorCallback, options);
1337         },
1338
1339         clearWatch: function(watchId) {
1340             geo.clearWatch(watchId);
1341         },
1342
1343         getPermission: function(siteName, imageUrl, extraMessage) {
1344             geo.getPermission(siteName, imageUrl, extraMessage);
1345         }
1346
1347     };
1348 });
1349
1350 var AjaxGeoLocation = (function() {
1351     // -- PRIVATE
1352     var loading = false;
1353     var loadGoogleLoader = function() {
1354         if (!hasGoogleLoader() && !loading) {
1355             loading = true;
1356             var s = document.createElement('script');
1357             s.src = (document.location.protocol == "https:"?"https://":"http://") + 'www.google.com/jsapi?callback=_google_loader_apiLoaded';
1358             s.type = "text/javascript";
1359             document.getElementsByTagName('body')[0].appendChild(s);
1360         }
1361     };
1362
1363     var queue = [];
1364     var addLocationQueue = function(callback) {
1365         queue.push(callback);
1366     };
1367
1368     var runLocationQueue = function() {
1369         if (hasGoogleLoader()) {
1370             while (queue.length > 0) {
1371                 var call = queue.pop();
1372                 call();
1373             }
1374         }
1375     };
1376
1377     window['_google_loader_apiLoaded'] = function() {
1378         runLocationQueue();
1379     };
1380
1381     var hasGoogleLoader = function() {
1382         return (window['google'] && google['loader']);
1383     };
1384
1385     var checkGoogleLoader = function(callback) {
1386         if (hasGoogleLoader()) { return true; }
1387
1388         addLocationQueue(callback);
1389
1390         loadGoogleLoader();
1391
1392         return false;
1393     };
1394
1395     loadGoogleLoader(); // start to load as soon as possible just in case
1396
1397     // -- PUBLIC
1398     return {
1399         shim: true,
1400
1401         type: "ClientLocation",
1402
1403         lastPosition: null,
1404
1405         getCurrentPosition: function(successCallback, errorCallback, options) {
1406             var self = this;
1407             if (!checkGoogleLoader(function() {
1408                 self.getCurrentPosition(successCallback, errorCallback, options);
1409             })) { return; }
1410
1411             if (google.loader.ClientLocation) {
1412                 var cl = google.loader.ClientLocation;
1413
1414                 var position = {
1415                     coords: {
1416                         latitude: cl.latitude,
1417                         longitude: cl.longitude,
1418                         altitude: null,
1419                         accuracy: 43000, // same as Gears accuracy over wifi?
1420                         altitudeAccuracy: null,
1421                         heading: null,
1422                         speed: null
1423                     },
1424                     // extra info that is outside of the bounds of the core API
1425                     address: {
1426                         city: cl.address.city,
1427                         country: cl.address.country,
1428                         country_code: cl.address.country_code,
1429                         region: cl.address.region
1430                     },
1431                     timestamp: new Date()
1432                 };
1433
1434                 successCallback(position);
1435
1436                 this.lastPosition = position;
1437             } else if (errorCallback === "function")  {
1438                 errorCallback({ code: 3, message: "Using the Google ClientLocation API and it is not able to calculate a location."});
1439             }
1440         },
1441
1442         watchPosition: function(successCallback, errorCallback, options) {
1443             this.getCurrentPosition(successCallback, errorCallback, options);
1444
1445             var self = this;
1446             var watchId = setInterval(function() {
1447                 self.getCurrentPosition(successCallback, errorCallback, options);
1448             }, 10000);
1449
1450             return watchId;
1451         },
1452
1453         clearWatch: function(watchId) {
1454             clearInterval(watchId);
1455         },
1456
1457         getPermission: function(siteName, imageUrl, extraMessage) {
1458             // for now just say yes :)
1459             return true;
1460         }
1461
1462     };
1463 });
1464
1465 // If you have Gears installed use that, else use Ajax ClientLocation
1466 navigator.geolocation = (window.google && google.gears) ? GearsGeoLocation() : AjaxGeoLocation();
1467
1468 })();
1469 }