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