pretty much working version
[wl-mobile.git] / assets / www / js / phonegap-1.0.0.js
1 /*
2  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
3  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
4  *
5  * Copyright (c) 2005-2010, Nitobi Software Inc.
6  * Copyright (c) 2010-2011, IBM Corporation
7  */
8
9 if (typeof PhoneGap === "undefined") {
10
11 /**
12  * The order of events during page load and PhoneGap startup is as follows:
13  *
14  * onDOMContentLoaded         Internal event that is received when the web page is loaded and parsed.
15  * window.onload              Body onload event.
16  * onNativeReady              Internal event that indicates the PhoneGap native side is ready.
17  * onPhoneGapInit             Internal event that kicks off creation of all PhoneGap JavaScript objects (runs constructors).
18  * onPhoneGapReady            Internal event fired when all PhoneGap JavaScript objects have been created
19  * onPhoneGapInfoReady        Internal event fired when device properties are available
20  * onDeviceReady              User event fired to indicate that PhoneGap is ready
21  * onResume                   User event fired to indicate a start/resume lifecycle event
22  * onPause                    User event fired to indicate a pause lifecycle event
23  * onDestroy                  Internal event fired when app is being destroyed (User should use window.onunload event, not this one).
24  *
25  * The only PhoneGap events that user code should register for are:
26  *      onDeviceReady
27  *      onResume
28  *
29  * Listeners can be registered as:
30  *      document.addEventListener("deviceready", myDeviceReadyListener, false);
31  *      document.addEventListener("resume", myResumeListener, false);
32  *      document.addEventListener("pause", myPauseListener, false);
33  */
34
35 if (typeof(DeviceInfo) !== 'object') {
36     var DeviceInfo = {};
37 }
38
39 /**
40  * This represents the PhoneGap API itself, and provides a global namespace for accessing
41  * information about the state of PhoneGap.
42  * @class
43  */
44 var PhoneGap = {
45     queue: {
46         ready: true,
47         commands: [],
48         timer: null
49     }
50 };
51
52 /**
53  * List of resource files loaded by PhoneGap.
54  * This is used to ensure JS and other files are loaded only once.
55  */
56 PhoneGap.resources = {base: true};
57
58 /**
59  * Determine if resource has been loaded by PhoneGap
60  *
61  * @param name
62  * @return
63  */
64 PhoneGap.hasResource = function(name) {
65     return PhoneGap.resources[name];
66 };
67
68 /**
69  * Add a resource to list of loaded resources by PhoneGap
70  *
71  * @param name
72  */
73 PhoneGap.addResource = function(name) {
74     PhoneGap.resources[name] = true;
75 };
76
77 /**
78  * Custom pub-sub channel that can have functions subscribed to it
79  * @constructor
80  */
81 PhoneGap.Channel = function (type)
82 {
83     this.type = type;
84     this.handlers = {};
85     this.guid = 0;
86     this.fired = false;
87     this.enabled = true;
88 };
89
90 /**
91  * Subscribes the given function to the channel. Any time that
92  * Channel.fire is called so too will the function.
93  * Optionally specify an execution context for the function
94  * and a guid that can be used to stop subscribing to the channel.
95  * Returns the guid.
96  */
97 PhoneGap.Channel.prototype.subscribe = function(f, c, g) {
98     // need a function to call
99     if (f === null) { return; }
100
101     var func = f;
102     if (typeof c === "object" && typeof f === "function") { func = PhoneGap.close(c, f); }
103
104     g = g || func.observer_guid || f.observer_guid || this.guid++;
105     func.observer_guid = g;
106     f.observer_guid = g;
107     this.handlers[g] = func;
108     return g;
109 };
110
111 /**
112  * Like subscribe but the function is only called once and then it
113  * auto-unsubscribes itself.
114  */
115 PhoneGap.Channel.prototype.subscribeOnce = function(f, c) {
116     var g = null;
117     var _this = this;
118     var m = function() {
119         f.apply(c || null, arguments);
120         _this.unsubscribe(g);
121     };
122     if (this.fired) {
123         if (typeof c === "object" && typeof f === "function") { f = PhoneGap.close(c, f); }
124         f.apply(this, this.fireArgs);
125     } else {
126         g = this.subscribe(m);
127     }
128     return g;
129 };
130
131 /**
132  * Unsubscribes the function with the given guid from the channel.
133  */
134 PhoneGap.Channel.prototype.unsubscribe = function(g) {
135     if (typeof g === "function") { g = g.observer_guid; }
136     this.handlers[g] = null;
137     delete this.handlers[g];
138 };
139
140 /**
141  * Calls all functions subscribed to this channel.
142  */
143 PhoneGap.Channel.prototype.fire = function(e) {
144     if (this.enabled) {
145         var fail = false;
146         var item, handler, rv;
147         for (item in this.handlers) {
148             if (this.handlers.hasOwnProperty(item)) {
149                 handler = this.handlers[item];
150                 if (typeof handler === "function") {
151                     rv = (handler.apply(this, arguments) === false);
152                     fail = fail || rv;
153                 }
154             }
155         }
156         this.fired = true;
157         this.fireArgs = arguments;
158         return !fail;
159     }
160     return true;
161 };
162
163 /**
164  * Calls the provided function only after all of the channels specified
165  * have been fired.
166  */
167 PhoneGap.Channel.join = function(h, c) {
168     var i = c.length;
169     var f = function() {
170         if (!(--i)) {
171             h();
172         }
173     };
174     var len = i;
175     var j;
176     for (j=0; j<len; j++) {
177         if (!c[j].fired) {
178             c[j].subscribeOnce(f);
179         }
180         else {
181             i--;
182         }
183     }
184     if (!i) {
185         h();
186     }
187 };
188
189 /**
190  * Boolean flag indicating if the PhoneGap API is available and initialized.
191  */ // TODO: Remove this, it is unused here ... -jm
192 PhoneGap.available = DeviceInfo.uuid !== undefined;
193
194 /**
195  * Add an initialization function to a queue that ensures it will run and initialize
196  * application constructors only once PhoneGap has been initialized.
197  * @param {Function} func The function callback you want run once PhoneGap is initialized
198  */
199 PhoneGap.addConstructor = function(func) {
200     PhoneGap.onPhoneGapInit.subscribeOnce(function() {
201         try {
202             func();
203         } catch(e) {
204             console.log("Failed to run constructor: " + e);
205         }
206     });
207 };
208
209 /**
210  * Plugins object
211  */
212 if (!window.plugins) {
213     window.plugins = {};
214 }
215
216 /**
217  * Adds a plugin object to window.plugins.
218  * The plugin is accessed using window.plugins.<name>
219  *
220  * @param name          The plugin name
221  * @param obj           The plugin object
222  */
223 PhoneGap.addPlugin = function(name, obj) {
224     if (!window.plugins[name]) {
225         window.plugins[name] = obj;
226     }
227     else {
228         console.log("Error: Plugin "+name+" already exists.");
229     }
230 };
231
232 /**
233  * onDOMContentLoaded channel is fired when the DOM content
234  * of the page has been parsed.
235  */
236 PhoneGap.onDOMContentLoaded = new PhoneGap.Channel('onDOMContentLoaded');
237
238 /**
239  * onNativeReady channel is fired when the PhoneGap native code
240  * has been initialized.
241  */
242 PhoneGap.onNativeReady = new PhoneGap.Channel('onNativeReady');
243
244 /**
245  * onPhoneGapInit channel is fired when the web page is fully loaded and
246  * PhoneGap native code has been initialized.
247  */
248 PhoneGap.onPhoneGapInit = new PhoneGap.Channel('onPhoneGapInit');
249
250 /**
251  * onPhoneGapReady channel is fired when the JS PhoneGap objects have been created.
252  */
253 PhoneGap.onPhoneGapReady = new PhoneGap.Channel('onPhoneGapReady');
254
255 /**
256  * onPhoneGapInfoReady channel is fired when the PhoneGap device properties
257  * has been set.
258  */
259 PhoneGap.onPhoneGapInfoReady = new PhoneGap.Channel('onPhoneGapInfoReady');
260
261 /**
262  * onPhoneGapConnectionReady channel is fired when the PhoneGap connection properties
263  * has been set.
264  */
265 PhoneGap.onPhoneGapConnectionReady = new PhoneGap.Channel('onPhoneGapConnectionReady');
266
267 /**
268  * onResume channel is fired when the PhoneGap native code
269  * resumes.
270  */
271 PhoneGap.onResume = new PhoneGap.Channel('onResume');
272
273 /**
274  * onPause channel is fired when the PhoneGap native code
275  * pauses.
276  */
277 PhoneGap.onPause = new PhoneGap.Channel('onPause');
278
279 /**
280  * onDestroy channel is fired when the PhoneGap native code
281  * is destroyed.  It is used internally.
282  * Window.onunload should be used by the user.
283  */
284 PhoneGap.onDestroy = new PhoneGap.Channel('onDestroy');
285 PhoneGap.onDestroy.subscribeOnce(function() {
286     PhoneGap.shuttingDown = true;
287 });
288 PhoneGap.shuttingDown = false;
289
290 // _nativeReady is global variable that the native side can set
291 // to signify that the native code is ready. It is a global since
292 // it may be called before any PhoneGap JS is ready.
293 if (typeof _nativeReady !== 'undefined') { PhoneGap.onNativeReady.fire(); }
294
295 /**
296  * onDeviceReady is fired only after all PhoneGap objects are created and
297  * the device properties are set.
298  */
299 PhoneGap.onDeviceReady = new PhoneGap.Channel('onDeviceReady');
300
301
302 // Array of channels that must fire before "deviceready" is fired
303 PhoneGap.deviceReadyChannelsArray = [ PhoneGap.onPhoneGapReady, PhoneGap.onPhoneGapInfoReady, PhoneGap.onPhoneGapConnectionReady];
304
305 // Hashtable of user defined channels that must also fire before "deviceready" is fired
306 PhoneGap.deviceReadyChannelsMap = {};
307
308 /**
309  * Indicate that a feature needs to be initialized before it is ready to be used.
310  * This holds up PhoneGap's "deviceready" event until the feature has been initialized
311  * and PhoneGap.initComplete(feature) is called.
312  *
313  * @param feature {String}     The unique feature name
314  */
315 PhoneGap.waitForInitialization = function(feature) {
316     if (feature) {
317         var channel = new PhoneGap.Channel(feature);
318         PhoneGap.deviceReadyChannelsMap[feature] = channel;
319         PhoneGap.deviceReadyChannelsArray.push(channel);
320     }
321 };
322
323 /**
324  * Indicate that initialization code has completed and the feature is ready to be used.
325  *
326  * @param feature {String}     The unique feature name
327  */
328 PhoneGap.initializationComplete = function(feature) {
329     var channel = PhoneGap.deviceReadyChannelsMap[feature];
330     if (channel) {
331         channel.fire();
332     }
333 };
334
335 /**
336  * Create all PhoneGap objects once page has fully loaded and native side is ready.
337  */
338 PhoneGap.Channel.join(function() {
339
340     // Start listening for XHR callbacks
341     setTimeout(function() {
342             if (PhoneGap.UsePolling) {
343                 PhoneGap.JSCallbackPolling();
344             }
345             else {
346                 var polling = prompt("usePolling", "gap_callbackServer:");
347                 PhoneGap.UsePolling = polling;
348                 if (polling == "true") {
349                     PhoneGap.UsePolling = true;
350                     PhoneGap.JSCallbackPolling();
351                 }
352                 else {
353                     PhoneGap.UsePolling = false;
354                     PhoneGap.JSCallback();
355                 }
356             }
357         }, 1);
358
359     // Run PhoneGap constructors
360     PhoneGap.onPhoneGapInit.fire();
361
362     // Fire event to notify that all objects are created
363     PhoneGap.onPhoneGapReady.fire();
364
365     // Fire onDeviceReady event once all constructors have run and PhoneGap info has been
366     // received from native side, and any user defined initialization channels.
367     PhoneGap.Channel.join(function() {
368         PhoneGap.onDeviceReady.fire();
369
370         // Fire the onresume event, since first one happens before JavaScript is loaded
371         PhoneGap.onResume.fire();
372     }, PhoneGap.deviceReadyChannelsArray);
373
374 }, [ PhoneGap.onDOMContentLoaded, PhoneGap.onNativeReady ]);
375
376 // Listen for DOMContentLoaded and notify our channel subscribers
377 document.addEventListener('DOMContentLoaded', function() {
378     PhoneGap.onDOMContentLoaded.fire();
379 }, false);
380
381 // Intercept calls to document.addEventListener and watch for deviceready
382 PhoneGap.m_document_addEventListener = document.addEventListener;
383
384 document.addEventListener = function(evt, handler, capture) {
385     var e = evt.toLowerCase();
386     if (e === 'deviceready') {
387         PhoneGap.onDeviceReady.subscribeOnce(handler);
388     } else if (e === 'resume') {
389         PhoneGap.onResume.subscribe(handler);
390         if (PhoneGap.onDeviceReady.fired) {
391             PhoneGap.onResume.fire();
392         }
393     } else if (e === 'pause') {
394         PhoneGap.onPause.subscribe(handler);
395     }
396     else {
397         // If subscribing to Android backbutton
398         if (e === 'backbutton') {
399             PhoneGap.exec(null, null, "App", "overrideBackbutton", [true]);
400         }
401
402         PhoneGap.m_document_addEventListener.call(document, evt, handler, capture);
403     }
404 };
405
406 // Intercept calls to document.removeEventListener and watch for events that
407 // are generated by PhoneGap native code
408 PhoneGap.m_document_removeEventListener = document.removeEventListener;
409
410 document.removeEventListener = function(evt, handler, capture) {
411     var e = evt.toLowerCase();
412
413     // If unsubscribing to Android backbutton
414     if (e === 'backbutton') {
415         PhoneGap.exec(null, null, "App", "overrideBackbutton", [false]);
416     }
417
418     PhoneGap.m_document_removeEventListener.call(document, evt, handler, capture);
419 };
420
421 /**
422  * Method to fire event from native code
423  */
424 PhoneGap.fireEvent = function(type) {
425     var e = document.createEvent('Events');
426     e.initEvent(type);
427     document.dispatchEvent(e);
428 };
429
430 /**
431  * If JSON not included, use our own stringify. (Android 1.6)
432  * The restriction on ours is that it must be an array of simple types.
433  *
434  * @param args
435  * @return {String}
436  */
437 PhoneGap.stringify = function(args) {
438     if (typeof JSON === "undefined") {
439         var s = "[";
440         var i, type, start, name, nameType, a;
441         for (i = 0; i < args.length; i++) {
442             if (args[i] !== null) {
443                 if (i > 0) {
444                     s = s + ",";
445                 }
446                 type = typeof args[i];
447                 if ((type === "number") || (type === "boolean")) {
448                     s = s + args[i];
449                 } else if (args[i] instanceof Array) {
450                     s = s + "[" + args[i] + "]";
451                 } else if (args[i] instanceof Object) {
452                     start = true;
453                     s = s + '{';
454                     for (name in args[i]) {
455                         if (args[i][name] !== null) {
456                             if (!start) {
457                                 s = s + ',';
458                             }
459                             s = s + '"' + name + '":';
460                             nameType = typeof args[i][name];
461                             if ((nameType === "number") || (nameType === "boolean")) {
462                                 s = s + args[i][name];
463                             } else if ((typeof args[i][name]) === 'function') {
464                                 // don't copy the functions
465                                 s = s + '""';
466                             } else if (args[i][name] instanceof Object) {
467                                 s = s + PhoneGap.stringify(args[i][name]);
468                             } else {
469                                 s = s + '"' + args[i][name] + '"';
470                             }
471                             start = false;
472                         }
473                     }
474                     s = s + '}';
475                 } else {
476                     a = args[i].replace(/\\/g, '\\\\');
477                     a = a.replace(/"/g, '\\"');
478                     s = s + '"' + a + '"';
479                 }
480             }
481         }
482         s = s + "]";
483         return s;
484     } else {
485         return JSON.stringify(args);
486     }
487 };
488
489 /**
490  * Does a deep clone of the object.
491  *
492  * @param obj
493  * @return {Object}
494  */
495 PhoneGap.clone = function(obj) {
496     var i, retVal;
497     if(!obj) { 
498         return obj;
499     }
500     
501     if(obj instanceof Array){
502         retVal = [];
503         for(i = 0; i < obj.length; ++i){
504             retVal.push(PhoneGap.clone(obj[i]));
505         }
506         return retVal;
507     }
508     
509     if (typeof obj === "function") {
510         return obj;
511     }
512     
513     if(!(obj instanceof Object)){
514         return obj;
515     }
516     
517     if (obj instanceof Date) {
518         return obj;
519     }
520     
521     retVal = {};
522     for(i in obj){
523         if(!(i in retVal) || retVal[i] !== obj[i]) {
524             retVal[i] = PhoneGap.clone(obj[i]);
525         }
526     }
527     return retVal;
528 };
529
530 PhoneGap.callbackId = 0;
531 PhoneGap.callbacks = {};
532 PhoneGap.callbackStatus = {
533     NO_RESULT: 0,
534     OK: 1,
535     CLASS_NOT_FOUND_EXCEPTION: 2,
536     ILLEGAL_ACCESS_EXCEPTION: 3,
537     INSTANTIATION_EXCEPTION: 4,
538     MALFORMED_URL_EXCEPTION: 5,
539     IO_EXCEPTION: 6,
540     INVALID_ACTION: 7,
541     JSON_EXCEPTION: 8,
542     ERROR: 9
543     };
544
545
546 /**
547  * Execute a PhoneGap command.  It is up to the native side whether this action is synch or async.
548  * The native side can return:
549  *      Synchronous: PluginResult object as a JSON string
550  *      Asynchrounous: Empty string ""
551  * If async, the native side will PhoneGap.callbackSuccess or PhoneGap.callbackError,
552  * depending upon the result of the action.
553  *
554  * @param {Function} success    The success callback
555  * @param {Function} fail       The fail callback
556  * @param {String} service      The name of the service to use
557  * @param {String} action       Action to be run in PhoneGap
558  * @param {Array.<String>} [args]     Zero or more arguments to pass to the method
559  */
560 PhoneGap.exec = function(success, fail, service, action, args) {
561     try {
562         var callbackId = service + PhoneGap.callbackId++;
563         if (success || fail) {
564             PhoneGap.callbacks[callbackId] = {success:success, fail:fail};
565         }
566
567         var r = prompt(PhoneGap.stringify(args), "gap:"+PhoneGap.stringify([service, action, callbackId, true]));
568
569         // If a result was returned
570         if (r.length > 0) {
571             eval("var v="+r+";");
572
573             // If status is OK, then return value back to caller
574             if (v.status === PhoneGap.callbackStatus.OK) {
575
576                 // If there is a success callback, then call it now with
577                 // returned value
578                 if (success) {
579                     try {
580                         success(v.message);
581                     } catch (e) {
582                         console.log("Error in success callback: " + callbackId  + " = " + e);
583                     }
584
585                     // Clear callback if not expecting any more results
586                     if (!v.keepCallback) {
587                         delete PhoneGap.callbacks[callbackId];
588                     }
589                 }
590                 return v.message;
591             }
592
593             // If no result
594             else if (v.status === PhoneGap.callbackStatus.NO_RESULT) {
595
596                 // Clear callback if not expecting any more results
597                 if (!v.keepCallback) {
598                     delete PhoneGap.callbacks[callbackId];
599                 }
600             }
601
602             // If error, then display error
603             else {
604                 console.log("Error: Status="+v.status+" Message="+v.message);
605
606                 // If there is a fail callback, then call it now with returned value
607                 if (fail) {
608                     try {
609                         fail(v.message);
610                     }
611                     catch (e1) {
612                         console.log("Error in error callback: "+callbackId+" = "+e1);
613                     }
614
615                     // Clear callback if not expecting any more results
616                     if (!v.keepCallback) {
617                         delete PhoneGap.callbacks[callbackId];
618                     }
619                 }
620                 return null;
621             }
622         }
623     } catch (e2) {
624         console.log("Error: "+e2);
625     }
626 };
627
628 /**
629  * Called by native code when returning successful result from an action.
630  *
631  * @param callbackId
632  * @param args
633  */
634 PhoneGap.callbackSuccess = function(callbackId, args) {
635     if (PhoneGap.callbacks[callbackId]) {
636
637         // If result is to be sent to callback
638         if (args.status === PhoneGap.callbackStatus.OK) {
639             try {
640                 if (PhoneGap.callbacks[callbackId].success) {
641                     PhoneGap.callbacks[callbackId].success(args.message);
642                 }
643             }
644             catch (e) {
645                 console.log("Error in success callback: "+callbackId+" = "+e);
646             }
647         }
648
649         // Clear callback if not expecting any more results
650         if (!args.keepCallback) {
651             delete PhoneGap.callbacks[callbackId];
652         }
653     }
654 };
655
656 /**
657  * Called by native code when returning error result from an action.
658  *
659  * @param callbackId
660  * @param args
661  */
662 PhoneGap.callbackError = function(callbackId, args) {
663     if (PhoneGap.callbacks[callbackId]) {
664         try {
665             if (PhoneGap.callbacks[callbackId].fail) {
666                 PhoneGap.callbacks[callbackId].fail(args.message);
667             }
668         }
669         catch (e) {
670             console.log("Error in error callback: "+callbackId+" = "+e);
671         }
672
673         // Clear callback if not expecting any more results
674         if (!args.keepCallback) {
675             delete PhoneGap.callbacks[callbackId];
676         }
677     }
678 };
679
680
681 /**
682  * Internal function used to dispatch the request to PhoneGap.  It processes the
683  * command queue and executes the next command on the list.  If one of the
684  * arguments is a JavaScript object, it will be passed on the QueryString of the
685  * url, which will be turned into a dictionary on the other end.
686  * @private
687  */
688 // TODO: Is this used?
689 PhoneGap.run_command = function() {
690     if (!PhoneGap.available || !PhoneGap.queue.ready) {
691         return;
692     }
693     PhoneGap.queue.ready = false;
694
695     var args = PhoneGap.queue.commands.shift();
696     if (PhoneGap.queue.commands.length === 0) {
697         clearInterval(PhoneGap.queue.timer);
698         PhoneGap.queue.timer = null;
699     }
700
701     var uri = [];
702     var dict = null;
703     var i;
704     for (i = 1; i < args.length; i++) {
705         var arg = args[i];
706         if (arg === undefined || arg === null) {
707             arg = '';
708         }
709         if (typeof(arg) === 'object') {
710             dict = arg;
711         } else {
712             uri.push(encodeURIComponent(arg));
713         }
714     }
715     var url = "gap://" + args[0] + "/" + uri.join("/");
716     if (dict !== null) {
717         var name;
718         var query_args = [];
719         for (name in dict) {
720             if (dict.hasOwnProperty(name) && (typeof (name) === 'string')) {
721                 query_args.push(encodeURIComponent(name) + "=" + encodeURIComponent(dict[name]));
722             }
723         }
724         if (query_args.length > 0) {
725             url += "?" + query_args.join("&");
726         }
727     }
728     document.location = url;
729
730 };
731
732 PhoneGap.JSCallbackPort = null;
733 PhoneGap.JSCallbackToken = null;
734
735 /**
736  * This is only for Android.
737  *
738  * Internal function that uses XHR to call into PhoneGap Java code and retrieve
739  * any JavaScript code that needs to be run.  This is used for callbacks from
740  * Java to JavaScript.
741  */
742 PhoneGap.JSCallback = function() {
743
744     // Exit if shutting down app
745     if (PhoneGap.shuttingDown) {
746         return;
747     }
748
749     // If polling flag was changed, start using polling from now on
750     if (PhoneGap.UsePolling) {
751         PhoneGap.JSCallbackPolling();
752         return;
753     }
754
755     var xmlhttp = new XMLHttpRequest();
756
757     // Callback function when XMLHttpRequest is ready
758     xmlhttp.onreadystatechange=function(){
759         if(xmlhttp.readyState === 4){
760
761             // Exit if shutting down app
762             if (PhoneGap.shuttingDown) {
763                 return;
764             }
765
766             // If callback has JavaScript statement to execute
767             if (xmlhttp.status === 200) {
768
769                 // Need to url decode the response
770                 var msg = decodeURIComponent(xmlhttp.responseText);
771                 setTimeout(function() {
772                     try {
773                         var t = eval(msg);
774                     }
775                     catch (e) {
776                         // If we're getting an error here, seeing the message will help in debugging
777                         console.log("JSCallback: Message from Server: " + msg);
778                         console.log("JSCallback Error: "+e);
779                     }
780                 }, 1);
781                 setTimeout(PhoneGap.JSCallback, 1);
782             }
783
784             // If callback ping (used to keep XHR request from timing out)
785             else if (xmlhttp.status === 404) {
786                 setTimeout(PhoneGap.JSCallback, 10);
787             }
788
789             // If security error
790             else if (xmlhttp.status === 403) {
791                 console.log("JSCallback Error: Invalid token.  Stopping callbacks.");
792             }
793
794             // If server is stopping
795             else if (xmlhttp.status === 503) {
796                 console.log("JSCallback Error: Service unavailable.  Stopping callbacks.");
797             }
798
799             // If request wasn't GET
800             else if (xmlhttp.status === 400) {
801                 console.log("JSCallback Error: Bad request.  Stopping callbacks.");
802             }
803
804             // If error, revert to polling
805             else {
806                 console.log("JSCallback Error: Request failed.");
807                 PhoneGap.UsePolling = true;
808                 PhoneGap.JSCallbackPolling();
809             }
810         }
811     };
812
813     if (PhoneGap.JSCallbackPort === null) {
814         PhoneGap.JSCallbackPort = prompt("getPort", "gap_callbackServer:");
815     }
816     if (PhoneGap.JSCallbackToken === null) {
817         PhoneGap.JSCallbackToken = prompt("getToken", "gap_callbackServer:");
818     }
819     xmlhttp.open("GET", "http://127.0.0.1:"+PhoneGap.JSCallbackPort+"/"+PhoneGap.JSCallbackToken , true);
820     xmlhttp.send();
821 };
822
823 /**
824  * The polling period to use with JSCallbackPolling.
825  * This can be changed by the application.  The default is 50ms.
826  */
827 PhoneGap.JSCallbackPollingPeriod = 50;
828
829 /**
830  * Flag that can be set by the user to force polling to be used or force XHR to be used.
831  */
832 PhoneGap.UsePolling = false;    // T=use polling, F=use XHR
833
834 /**
835  * This is only for Android.
836  *
837  * Internal function that uses polling to call into PhoneGap Java code and retrieve
838  * any JavaScript code that needs to be run.  This is used for callbacks from
839  * Java to JavaScript.
840  */
841 PhoneGap.JSCallbackPolling = function() {
842
843     // Exit if shutting down app
844     if (PhoneGap.shuttingDown) {
845         return;
846     }
847
848     // If polling flag was changed, stop using polling from now on
849     if (!PhoneGap.UsePolling) {
850         PhoneGap.JSCallback();
851         return;
852     }
853
854     var msg = prompt("", "gap_poll:");
855     if (msg) {
856         setTimeout(function() {
857             try {
858                 var t = eval(""+msg);
859             }
860             catch (e) {
861                 console.log("JSCallbackPolling: Message from Server: " + msg);
862                 console.log("JSCallbackPolling Error: "+e);
863             }
864         }, 1);
865         setTimeout(PhoneGap.JSCallbackPolling, 1);
866     }
867     else {
868         setTimeout(PhoneGap.JSCallbackPolling, PhoneGap.JSCallbackPollingPeriod);
869     }
870 };
871
872 /**
873  * Create a UUID
874  *
875  * @return {String}
876  */
877 PhoneGap.createUUID = function() {
878     return PhoneGap.UUIDcreatePart(4) + '-' +
879         PhoneGap.UUIDcreatePart(2) + '-' +
880         PhoneGap.UUIDcreatePart(2) + '-' +
881         PhoneGap.UUIDcreatePart(2) + '-' +
882         PhoneGap.UUIDcreatePart(6);
883 };
884
885 PhoneGap.UUIDcreatePart = function(length) {
886     var uuidpart = "";
887     var i, uuidchar;
888     for (i=0; i<length; i++) {
889         uuidchar = parseInt((Math.random() * 256),0).toString(16);
890         if (uuidchar.length === 1) {
891             uuidchar = "0" + uuidchar;
892         }
893         uuidpart += uuidchar;
894     }
895     return uuidpart;
896 };
897
898 PhoneGap.close = function(context, func, params) {
899     if (typeof params === 'undefined') {
900         return function() {
901             return func.apply(context, arguments);
902         };
903     } else {
904         return function() {
905             return func.apply(context, params);
906         };
907     }
908 };
909
910 /**
911  * Load a JavaScript file after page has loaded.
912  *
913  * @param {String} jsfile               The url of the JavaScript file to load.
914  * @param {Function} successCallback    The callback to call when the file has been loaded.
915  */
916 PhoneGap.includeJavascript = function(jsfile, successCallback) {
917     var id = document.getElementsByTagName("head")[0];
918     var el = document.createElement('script');
919     el.type = 'text/javascript';
920     if (typeof successCallback === 'function') {
921         el.onload = successCallback;
922     }
923     el.src = jsfile;
924     id.appendChild(el);
925 };
926
927 }
928 /*
929  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
930  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
931  *
932  * Copyright (c) 2005-2010, Nitobi Software Inc.
933  * Copyright (c) 2010-2011, IBM Corporation
934  */
935
936 if (!PhoneGap.hasResource("accelerometer")) {
937 PhoneGap.addResource("accelerometer");
938
939 /** @constructor */
940 var Acceleration = function(x, y, z) {
941   this.x = x;
942   this.y = y;
943   this.z = z;
944   this.timestamp = new Date().getTime();
945 };
946
947 /**
948  * This class provides access to device accelerometer data.
949  * @constructor
950  */
951 var Accelerometer = function() {
952
953     /**
954      * The last known acceleration.  type=Acceleration()
955      */
956     this.lastAcceleration = null;
957
958     /**
959      * List of accelerometer watch timers
960      */
961     this.timers = {};
962 };
963
964 Accelerometer.ERROR_MSG = ["Not running", "Starting", "", "Failed to start"];
965
966 /**
967  * Asynchronously aquires the current acceleration.
968  *
969  * @param {Function} successCallback    The function to call when the acceleration data is available
970  * @param {Function} errorCallback      The function to call when there is an error getting the acceleration data. (OPTIONAL)
971  * @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
972  */
973 Accelerometer.prototype.getCurrentAcceleration = function(successCallback, errorCallback, options) {
974
975     // successCallback required
976     if (typeof successCallback !== "function") {
977         console.log("Accelerometer Error: successCallback is not a function");
978         return;
979     }
980
981     // errorCallback optional
982     if (errorCallback && (typeof errorCallback !== "function")) {
983         console.log("Accelerometer Error: errorCallback is not a function");
984         return;
985     }
986
987     // Get acceleration
988     PhoneGap.exec(successCallback, errorCallback, "Accelerometer", "getAcceleration", []);
989 };
990
991 /**
992  * Asynchronously aquires the acceleration repeatedly at a given interval.
993  *
994  * @param {Function} successCallback    The function to call each time the acceleration data is available
995  * @param {Function} errorCallback      The function to call when there is an error getting the acceleration data. (OPTIONAL)
996  * @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
997  * @return String                       The watch id that must be passed to #clearWatch to stop watching.
998  */
999 Accelerometer.prototype.watchAcceleration = function(successCallback, errorCallback, options) {
1000
1001     // Default interval (10 sec)
1002     var frequency = (options !== undefined)? options.frequency : 10000;
1003
1004     // successCallback required
1005     if (typeof successCallback !== "function") {
1006         console.log("Accelerometer Error: successCallback is not a function");
1007         return;
1008     }
1009
1010     // errorCallback optional
1011     if (errorCallback && (typeof errorCallback !== "function")) {
1012         console.log("Accelerometer Error: errorCallback is not a function");
1013         return;
1014     }
1015
1016     // Make sure accelerometer timeout > frequency + 10 sec
1017     PhoneGap.exec(
1018         function(timeout) {
1019             if (timeout < (frequency + 10000)) {
1020                 PhoneGap.exec(null, null, "Accelerometer", "setTimeout", [frequency + 10000]);
1021             }
1022         },
1023         function(e) { }, "Accelerometer", "getTimeout", []);
1024
1025     // Start watch timer
1026     var id = PhoneGap.createUUID();
1027     navigator.accelerometer.timers[id] = setInterval(function() {
1028         PhoneGap.exec(successCallback, errorCallback, "Accelerometer", "getAcceleration", []);
1029     }, (frequency ? frequency : 1));
1030
1031     return id;
1032 };
1033
1034 /**
1035  * Clears the specified accelerometer watch.
1036  *
1037  * @param {String} id       The id of the watch returned from #watchAcceleration.
1038  */
1039 Accelerometer.prototype.clearWatch = function(id) {
1040
1041     // Stop javascript timer & remove from timer list
1042     if (id && navigator.accelerometer.timers[id] !== undefined) {
1043         clearInterval(navigator.accelerometer.timers[id]);
1044         delete navigator.accelerometer.timers[id];
1045     }
1046 };
1047
1048 PhoneGap.addConstructor(function() {
1049     if (typeof navigator.accelerometer === "undefined") {
1050         navigator.accelerometer = new Accelerometer();
1051     }
1052 });
1053 }
1054
1055
1056 /*
1057  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
1058  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
1059  *
1060  * Copyright (c) 2005-2010, Nitobi Software Inc.
1061  * Copyright (c) 2010-2011, IBM Corporation
1062  */
1063
1064 if (!PhoneGap.hasResource("app")) {
1065 PhoneGap.addResource("app");
1066 (function() {
1067
1068 /**
1069  * Constructor
1070  * @constructor
1071  */
1072 var App = function() {};
1073
1074 /**
1075  * Clear the resource cache.
1076  */
1077 App.prototype.clearCache = function() {
1078     PhoneGap.exec(null, null, "App", "clearCache", []);
1079 };
1080
1081 /**
1082  * Load the url into the webview.
1083  *
1084  * @param url           The URL to load
1085  * @param props         Properties that can be passed in to the activity:
1086  *      wait: int                           => wait msec before loading URL
1087  *      loadingDialog: "Title,Message"      => display a native loading dialog
1088  *      hideLoadingDialogOnPage: boolean    => hide loadingDialog when page loaded instead of when deviceready event occurs.
1089  *      loadInWebView: boolean              => cause all links on web page to be loaded into existing web view, instead of being loaded into new browser.
1090  *      loadUrlTimeoutValue: int            => time in msec to wait before triggering a timeout error
1091  *      errorUrl: URL                       => URL to load if there's an error loading specified URL with loadUrl().  Should be a local URL such as file:///android_asset/www/error.html");
1092  *      keepRunning: boolean                => enable app to keep running in background
1093  *
1094  * Example:
1095  *      App app = new App();
1096  *      app.loadUrl("http://server/myapp/index.html", {wait:2000, loadingDialog:"Wait,Loading App", loadUrlTimeoutValue: 60000});
1097  */
1098 App.prototype.loadUrl = function(url, props) {
1099     PhoneGap.exec(null, null, "App", "loadUrl", [url, props]);
1100 };
1101
1102 /**
1103  * Cancel loadUrl that is waiting to be loaded.
1104  */
1105 App.prototype.cancelLoadUrl = function() {
1106     PhoneGap.exec(null, null, "App", "cancelLoadUrl", []);
1107 };
1108
1109 /**
1110  * Clear web history in this web view.
1111  * Instead of BACK button loading the previous web page, it will exit the app.
1112  */
1113 App.prototype.clearHistory = function() {
1114     PhoneGap.exec(null, null, "App", "clearHistory", []);
1115 };
1116
1117 /**
1118  * Override the default behavior of the Android back button.
1119  * If overridden, when the back button is pressed, the "backKeyDown" JavaScript event will be fired.
1120  *
1121  * Note: The user should not have to call this method.  Instead, when the user
1122  *       registers for the "backbutton" event, this is automatically done.
1123  *
1124  * @param override              T=override, F=cancel override
1125  */
1126 App.prototype.overrideBackbutton = function(override) {
1127     PhoneGap.exec(null, null, "App", "overrideBackbutton", [override]);
1128 };
1129
1130 /**
1131  * Exit and terminate the application.
1132  */
1133 App.prototype.exitApp = function() {
1134         return PhoneGap.exec(null, null, "App", "exitApp", []);
1135 };
1136
1137 PhoneGap.addConstructor(function() {
1138     navigator.app = new App();
1139 });
1140 }());
1141 }
1142
1143
1144 /*
1145  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
1146  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
1147  *
1148  * Copyright (c) 2005-2010, Nitobi Software Inc.
1149  * Copyright (c) 2010-2011, IBM Corporation
1150  */
1151
1152 if (!PhoneGap.hasResource("camera")) {
1153 PhoneGap.addResource("camera");
1154
1155 /**
1156  * This class provides access to the device camera.
1157  *
1158  * @constructor
1159  */
1160 var Camera = function() {
1161     this.successCallback = null;
1162     this.errorCallback = null;
1163     this.options = null;
1164 };
1165
1166 /**
1167  * Format of image that returned from getPicture.
1168  *
1169  * Example: navigator.camera.getPicture(success, fail,
1170  *              { quality: 80,
1171  *                destinationType: Camera.DestinationType.DATA_URL,
1172  *                sourceType: Camera.PictureSourceType.PHOTOLIBRARY})
1173  */
1174 Camera.DestinationType = {
1175     DATA_URL: 0,                // Return base64 encoded string
1176     FILE_URI: 1                 // Return file uri (content://media/external/images/media/2 for Android)
1177 };
1178 Camera.prototype.DestinationType = Camera.DestinationType;
1179
1180 /**
1181  * Encoding of image returned from getPicture.
1182  *
1183  * Example: navigator.camera.getPicture(success, fail,
1184  *              { quality: 80,
1185  *                destinationType: Camera.DestinationType.DATA_URL,
1186  *                sourceType: Camera.PictureSourceType.CAMERA,
1187  *                encodingType: Camera.EncodingType.PNG})
1188 */
1189 Camera.EncodingType = {
1190     JPEG: 0,                    // Return JPEG encoded image
1191     PNG: 1                      // Return PNG encoded image
1192 };
1193 Camera.prototype.EncodingType = Camera.EncodingType;
1194
1195 /**
1196  * Source to getPicture from.
1197  *
1198  * Example: navigator.camera.getPicture(success, fail,
1199  *              { quality: 80,
1200  *                destinationType: Camera.DestinationType.DATA_URL,
1201  *                sourceType: Camera.PictureSourceType.PHOTOLIBRARY})
1202  */
1203 Camera.PictureSourceType = {
1204     PHOTOLIBRARY : 0,           // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
1205     CAMERA : 1,                 // Take picture from camera
1206     SAVEDPHOTOALBUM : 2         // Choose image from picture library (same as PHOTOLIBRARY for Android)
1207 };
1208 Camera.prototype.PictureSourceType = Camera.PictureSourceType;
1209
1210 /**
1211  * Gets a picture from source defined by "options.sourceType", and returns the
1212  * image as defined by the "options.destinationType" option.
1213
1214  * The defaults are sourceType=CAMERA and destinationType=DATA_URL.
1215  *
1216  * @param {Function} successCallback
1217  * @param {Function} errorCallback
1218  * @param {Object} options
1219  */
1220 Camera.prototype.getPicture = function(successCallback, errorCallback, options) {
1221
1222     // successCallback required
1223     if (typeof successCallback !== "function") {
1224         console.log("Camera Error: successCallback is not a function");
1225         return;
1226     }
1227
1228     // errorCallback optional
1229     if (errorCallback && (typeof errorCallback !== "function")) {
1230         console.log("Camera Error: errorCallback is not a function");
1231         return;
1232     }
1233
1234     this.options = options;
1235     var quality = 80;
1236     if (options.quality) {
1237         quality = this.options.quality;
1238     }
1239     
1240     var maxResolution = 0;
1241     if (options.maxResolution) {
1242         maxResolution = this.options.maxResolution;
1243     }
1244     
1245     var destinationType = Camera.DestinationType.DATA_URL;
1246     if (this.options.destinationType) {
1247         destinationType = this.options.destinationType;
1248     }
1249     var sourceType = Camera.PictureSourceType.CAMERA;
1250     if (typeof this.options.sourceType === "number") {
1251         sourceType = this.options.sourceType;
1252     }
1253     var encodingType = Camera.EncodingType.JPEG;
1254     if (typeof options.encodingType == "number") {
1255         encodingType = this.options.encodingType;
1256     }
1257     
1258     var targetWidth = -1;
1259     if (typeof options.targetWidth == "number") {
1260         targetWidth = options.targetWidth;
1261     } else if (typeof options.targetWidth == "string") {
1262         var width = new Number(options.targetWidth);
1263         if (isNaN(width) === false) {
1264             targetWidth = width.valueOf();
1265         }
1266     }
1267
1268     var targetHeight = -1;
1269     if (typeof options.targetHeight == "number") {
1270         targetHeight = options.targetHeight;
1271     } else if (typeof options.targetHeight == "string") {
1272         var height = new Number(options.targetHeight);
1273         if (isNaN(height) === false) {
1274             targetHeight = height.valueOf();
1275         }
1276     }
1277     
1278     PhoneGap.exec(successCallback, errorCallback, "Camera", "takePicture", [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType]);
1279 };
1280
1281 PhoneGap.addConstructor(function() {
1282     if (typeof navigator.camera === "undefined") {
1283         navigator.camera = new Camera();
1284     }
1285 });
1286 }
1287
1288
1289 /*
1290  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
1291  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
1292  *
1293  * Copyright (c) 2005-2010, Nitobi Software Inc.
1294  * Copyright (c) 2010-2011, IBM Corporation
1295  */
1296
1297 if (!PhoneGap.hasResource("capture")) {
1298 PhoneGap.addResource("capture");
1299         
1300 /**
1301  * Represents a single file.
1302  *
1303  * name {DOMString} name of the file, without path information
1304  * fullPath {DOMString} the full path of the file, including the name
1305  * type {DOMString} mime type
1306  * lastModifiedDate {Date} last modified date
1307  * size {Number} size of the file in bytes
1308  */
1309 var MediaFile = function(name, fullPath, type, lastModifiedDate, size){
1310         this.name = name || null;
1311         this.fullPath = fullPath || null;
1312         this.type = type || null;
1313         this.lastModifiedDate = lastModifiedDate || null;
1314         this.size = size || 0;
1315 };
1316
1317 /**
1318  * Launch device camera application for recording video(s).
1319  *
1320  * @param {Function} successCB
1321  * @param {Function} errorCB
1322  */
1323 MediaFile.prototype.getFormatData = function(successCallback, errorCallback){
1324         PhoneGap.exec(successCallback, errorCallback, "Capture", "getFormatData", [this.fullPath, this.type]);
1325 };
1326
1327 /**
1328  * MediaFileData encapsulates format information of a media file.
1329  *
1330  * @param {DOMString} codecs
1331  * @param {long} bitrate
1332  * @param {long} height
1333  * @param {long} width
1334  * @param {float} duration
1335  */
1336 var MediaFileData = function(codecs, bitrate, height, width, duration){
1337         this.codecs = codecs || null;
1338         this.bitrate = bitrate || 0;
1339         this.height = height || 0;
1340         this.width = width || 0;
1341         this.duration = duration || 0;
1342 };
1343
1344 /**
1345  * The CaptureError interface encapsulates all errors in the Capture API.
1346  */
1347 var CaptureError = function(){
1348         this.code = null;
1349 };
1350
1351 // Capture error codes
1352 CaptureError.CAPTURE_INTERNAL_ERR = 0;
1353 CaptureError.CAPTURE_APPLICATION_BUSY = 1;
1354 CaptureError.CAPTURE_INVALID_ARGUMENT = 2;
1355 CaptureError.CAPTURE_NO_MEDIA_FILES = 3;
1356 CaptureError.CAPTURE_NOT_SUPPORTED = 20;
1357
1358 /**
1359  * The Capture interface exposes an interface to the camera and microphone of the hosting device.
1360  */
1361 var Capture = function(){
1362         this.supportedAudioModes = [];
1363         this.supportedImageModes = [];
1364         this.supportedVideoModes = [];
1365 };
1366
1367 /**
1368  * Launch audio recorder application for recording audio clip(s).
1369  *
1370  * @param {Function} successCB
1371  * @param {Function} errorCB
1372  * @param {CaptureAudioOptions} options
1373  */
1374 Capture.prototype.captureAudio = function(successCallback, errorCallback, options){
1375         PhoneGap.exec(successCallback, errorCallback, "Capture", "captureAudio", [options]);
1376 };
1377
1378 /**
1379  * Launch camera application for taking image(s).
1380  *
1381  * @param {Function} successCB
1382  * @param {Function} errorCB
1383  * @param {CaptureImageOptions} options
1384  */
1385 Capture.prototype.captureImage = function(successCallback, errorCallback, options){
1386         PhoneGap.exec(successCallback, errorCallback, "Capture", "captureImage", [options]);
1387 };
1388
1389 /**
1390  * Launch camera application for taking image(s).
1391  *
1392  * @param {Function} successCB
1393  * @param {Function} errorCB
1394  * @param {CaptureImageOptions} options
1395  */
1396 Capture.prototype._castMediaFile = function(pluginResult){
1397         var mediaFiles = [];
1398         var i;
1399         for (i = 0; i < pluginResult.message.length; i++) {
1400                 var mediaFile = new MediaFile();
1401                 mediaFile.name = pluginResult.message[i].name;
1402                 mediaFile.fullPath = pluginResult.message[i].fullPath;
1403                 mediaFile.type = pluginResult.message[i].type;
1404                 mediaFile.lastModifiedDate = pluginResult.message[i].lastModifiedDate;
1405                 mediaFile.size = pluginResult.message[i].size;
1406                 mediaFiles.push(mediaFile);
1407         }
1408         pluginResult.message = mediaFiles;
1409         return pluginResult;
1410 };
1411
1412 /**
1413  * Launch device camera application for recording video(s).
1414  *
1415  * @param {Function} successCB
1416  * @param {Function} errorCB
1417  * @param {CaptureVideoOptions} options
1418  */
1419 Capture.prototype.captureVideo = function(successCallback, errorCallback, options){
1420         PhoneGap.exec(successCallback, errorCallback, "Capture", "captureVideo", [options]);
1421 };
1422
1423 /**
1424  * Encapsulates a set of parameters that the capture device supports.
1425  */
1426 var ConfigurationData = function(){
1427         // The ASCII-encoded string in lower case representing the media type. 
1428         this.type = null;
1429         // The height attribute represents height of the image or video in pixels. 
1430         // In the case of a sound clip this attribute has value 0. 
1431         this.height = 0;
1432         // The width attribute represents width of the image or video in pixels. 
1433         // In the case of a sound clip this attribute has value 0
1434         this.width = 0;
1435 };
1436
1437 /**
1438  * Encapsulates all image capture operation configuration options.
1439  */
1440 var CaptureImageOptions = function(){
1441         // Upper limit of images user can take. Value must be equal or greater than 1.
1442         this.limit = 1;
1443         // The selected image mode. Must match with one of the elements in supportedImageModes array.
1444         this.mode = null;
1445 };
1446
1447 /**
1448  * Encapsulates all video capture operation configuration options.
1449  */
1450 var CaptureVideoOptions = function(){
1451         // Upper limit of videos user can record. Value must be equal or greater than 1.
1452         this.limit = 1;
1453         // Maximum duration of a single video clip in seconds.
1454         this.duration = 0;
1455         // The selected video mode. Must match with one of the elements in supportedVideoModes array.
1456         this.mode = null;
1457 };
1458
1459 /**
1460  * Encapsulates all audio capture operation configuration options.
1461  */
1462 var CaptureAudioOptions = function(){
1463         // Upper limit of sound clips user can record. Value must be equal or greater than 1.
1464         this.limit = 1;
1465         // Maximum duration of a single sound clip in seconds.
1466         this.duration = 0;
1467         // The selected audio mode. Must match with one of the elements in supportedAudioModes array.
1468         this.mode = null;
1469 };
1470
1471 PhoneGap.addConstructor(function(){
1472         if (typeof navigator.device === "undefined") {
1473                 navigator.device = window.device = new Device();
1474         }
1475         if (typeof navigator.device.capture === "undefined") {
1476                 navigator.device.capture = window.device.capture = new Capture();
1477         }
1478 });
1479 }
1480
1481 /*
1482  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
1483  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
1484  *
1485  * Copyright (c) 2005-2010, Nitobi Software Inc.
1486  * Copyright (c) 2010-2011, IBM Corporation
1487  */
1488
1489 if (!PhoneGap.hasResource("compass")) {
1490 PhoneGap.addResource("compass");
1491
1492 /**
1493  * This class provides access to device Compass data.
1494  * @constructor
1495  */
1496 var Compass = function() {
1497     /**
1498      * The last known Compass position.
1499      */
1500     this.lastHeading = null;
1501
1502     /**
1503      * List of compass watch timers
1504      */
1505     this.timers = {};
1506 };
1507
1508 Compass.ERROR_MSG = ["Not running", "Starting", "", "Failed to start"];
1509
1510 /**
1511  * Asynchronously aquires the current heading.
1512  *
1513  * @param {Function} successCallback The function to call when the heading data is available
1514  * @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
1515  * @param {PositionOptions} options The options for getting the heading data such as timeout. (OPTIONAL)
1516  */
1517 Compass.prototype.getCurrentHeading = function(successCallback, errorCallback, options) {
1518
1519     // successCallback required
1520     if (typeof successCallback !== "function") {
1521         console.log("Compass Error: successCallback is not a function");
1522         return;
1523     }
1524
1525     // errorCallback optional
1526     if (errorCallback && (typeof errorCallback !== "function")) {
1527         console.log("Compass Error: errorCallback is not a function");
1528         return;
1529     }
1530
1531     // Get heading
1532     PhoneGap.exec(successCallback, errorCallback, "Compass", "getHeading", []);
1533 };
1534
1535 /**
1536  * Asynchronously aquires the heading repeatedly at a given interval.
1537  *
1538  * @param {Function} successCallback    The function to call each time the heading data is available
1539  * @param {Function} errorCallback      The function to call when there is an error getting the heading data. (OPTIONAL)
1540  * @param {HeadingOptions} options      The options for getting the heading data such as timeout and the frequency of the watch. (OPTIONAL)
1541  * @return String                       The watch id that must be passed to #clearWatch to stop watching.
1542  */
1543 Compass.prototype.watchHeading= function(successCallback, errorCallback, options) {
1544
1545     // Default interval (100 msec)
1546     var frequency = (options !== undefined) ? options.frequency : 100;
1547
1548     // successCallback required
1549     if (typeof successCallback !== "function") {
1550         console.log("Compass Error: successCallback is not a function");
1551         return;
1552     }
1553
1554     // errorCallback optional
1555     if (errorCallback && (typeof errorCallback !== "function")) {
1556         console.log("Compass Error: errorCallback is not a function");
1557         return;
1558     }
1559
1560     // Make sure compass timeout > frequency + 10 sec
1561     PhoneGap.exec(
1562         function(timeout) {
1563             if (timeout < (frequency + 10000)) {
1564                 PhoneGap.exec(null, null, "Compass", "setTimeout", [frequency + 10000]);
1565             }
1566         },
1567         function(e) { }, "Compass", "getTimeout", []);
1568
1569     // Start watch timer to get headings
1570     var id = PhoneGap.createUUID();
1571     navigator.compass.timers[id] = setInterval(
1572         function() {
1573             PhoneGap.exec(successCallback, errorCallback, "Compass", "getHeading", []);
1574         }, (frequency ? frequency : 1));
1575
1576     return id;
1577 };
1578
1579
1580 /**
1581  * Clears the specified heading watch.
1582  *
1583  * @param {String} id       The ID of the watch returned from #watchHeading.
1584  */
1585 Compass.prototype.clearWatch = function(id) {
1586
1587     // Stop javascript timer & remove from timer list
1588     if (id && navigator.compass.timers[id]) {
1589         clearInterval(navigator.compass.timers[id]);
1590         delete navigator.compass.timers[id];
1591     }
1592 };
1593
1594 PhoneGap.addConstructor(function() {
1595     if (typeof navigator.compass === "undefined") {
1596         navigator.compass = new Compass();
1597     }
1598 });
1599 }
1600
1601
1602 /*
1603  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
1604  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
1605  *
1606  * Copyright (c) 2005-2010, Nitobi Software Inc.
1607  * Copyright (c) 2010-2011, IBM Corporation
1608  */
1609
1610 if (!PhoneGap.hasResource("contact")) {
1611 PhoneGap.addResource("contact");
1612
1613 /**
1614 * Contains information about a single contact.
1615 * @constructor
1616 * @param {DOMString} id unique identifier
1617 * @param {DOMString} displayName
1618 * @param {ContactName} name
1619 * @param {DOMString} nickname
1620 * @param {Array.<ContactField>} phoneNumbers array of phone numbers
1621 * @param {Array.<ContactField>} emails array of email addresses
1622 * @param {Array.<ContactAddress>} addresses array of addresses
1623 * @param {Array.<ContactField>} ims instant messaging user ids
1624 * @param {Array.<ContactOrganization>} organizations
1625 * @param {DOMString} birthday contact's birthday
1626 * @param {DOMString} note user notes about contact
1627 * @param {Array.<ContactField>} photos
1628 * @param {Array.<ContactField>} categories
1629 * @param {Array.<ContactField>} urls contact's web sites
1630 */
1631 var Contact = function (id, displayName, name, nickname, phoneNumbers, emails, addresses,
1632     ims, organizations, birthday, note, photos, categories, urls) {
1633     this.id = id || null;
1634     this.rawId = null;
1635     this.displayName = displayName || null;
1636     this.name = name || null; // ContactName
1637     this.nickname = nickname || null;
1638     this.phoneNumbers = phoneNumbers || null; // ContactField[]
1639     this.emails = emails || null; // ContactField[]
1640     this.addresses = addresses || null; // ContactAddress[]
1641     this.ims = ims || null; // ContactField[]
1642     this.organizations = organizations || null; // ContactOrganization[]
1643     this.birthday = birthday || null;
1644     this.note = note || null;
1645     this.photos = photos || null; // ContactField[]
1646     this.categories = categories || null; // ContactField[]
1647     this.urls = urls || null; // ContactField[]
1648 };
1649
1650 /**
1651  *  ContactError.
1652  *  An error code assigned by an implementation when an error has occurreds
1653  * @constructor
1654  */
1655 var ContactError = function() {
1656     this.code=null;
1657 };
1658
1659 /**
1660  * Error codes
1661  */
1662 ContactError.UNKNOWN_ERROR = 0;
1663 ContactError.INVALID_ARGUMENT_ERROR = 1;
1664 ContactError.TIMEOUT_ERROR = 2;
1665 ContactError.PENDING_OPERATION_ERROR = 3;
1666 ContactError.IO_ERROR = 4;
1667 ContactError.NOT_SUPPORTED_ERROR = 5;
1668 ContactError.PERMISSION_DENIED_ERROR = 20;
1669
1670 /**
1671 * Removes contact from device storage.
1672 * @param successCB success callback
1673 * @param errorCB error callback
1674 */
1675 Contact.prototype.remove = function(successCB, errorCB) {
1676     if (this.id === null) {
1677         var errorObj = new ContactError();
1678         errorObj.code = ContactError.UNKNOWN_ERROR;
1679         errorCB(errorObj);
1680     }
1681     else {
1682         PhoneGap.exec(successCB, errorCB, "Contacts", "remove", [this.id]);
1683     }
1684 };
1685
1686 /**
1687 * Creates a deep copy of this Contact.
1688 * With the contact ID set to null.
1689 * @return copy of this Contact
1690 */
1691 Contact.prototype.clone = function() {
1692     var clonedContact = PhoneGap.clone(this);
1693     var i;
1694     clonedContact.id = null;
1695     clonedContact.rawId = null;
1696     // Loop through and clear out any id's in phones, emails, etc.
1697     if (clonedContact.phoneNumbers) {
1698         for (i = 0; i < clonedContact.phoneNumbers.length; i++) {
1699             clonedContact.phoneNumbers[i].id = null;
1700         }
1701     }
1702     if (clonedContact.emails) {
1703         for (i = 0; i < clonedContact.emails.length; i++) {
1704             clonedContact.emails[i].id = null;
1705         }
1706     }
1707     if (clonedContact.addresses) {
1708         for (i = 0; i < clonedContact.addresses.length; i++) {
1709             clonedContact.addresses[i].id = null;
1710         }
1711     }
1712     if (clonedContact.ims) {
1713         for (i = 0; i < clonedContact.ims.length; i++) {
1714             clonedContact.ims[i].id = null;
1715         }
1716     }
1717     if (clonedContact.organizations) {
1718         for (i = 0; i < clonedContact.organizations.length; i++) {
1719             clonedContact.organizations[i].id = null;
1720         }
1721     }
1722     if (clonedContact.tags) {
1723         for (i = 0; i < clonedContact.tags.length; i++) {
1724             clonedContact.tags[i].id = null;
1725         }
1726     }
1727     if (clonedContact.photos) {
1728         for (i = 0; i < clonedContact.photos.length; i++) {
1729             clonedContact.photos[i].id = null;
1730         }
1731     }
1732     if (clonedContact.urls) {
1733         for (i = 0; i < clonedContact.urls.length; i++) {
1734             clonedContact.urls[i].id = null;
1735         }
1736     }
1737     return clonedContact;
1738 };
1739
1740 /**
1741 * Persists contact to device storage.
1742 * @param successCB success callback
1743 * @param errorCB error callback
1744 */
1745 Contact.prototype.save = function(successCB, errorCB) {
1746     PhoneGap.exec(successCB, errorCB, "Contacts", "save", [this]);
1747 };
1748
1749 /**
1750 * Contact name.
1751 * @constructor
1752 * @param formatted
1753 * @param familyName
1754 * @param givenName
1755 * @param middle
1756 * @param prefix
1757 * @param suffix
1758 */
1759 var ContactName = function(formatted, familyName, givenName, middle, prefix, suffix) {
1760     this.formatted = formatted || null;
1761     this.familyName = familyName || null;
1762     this.givenName = givenName || null;
1763     this.middleName = middle || null;
1764     this.honorificPrefix = prefix || null;
1765     this.honorificSuffix = suffix || null;
1766 };
1767
1768 /**
1769 * Generic contact field.
1770 * @constructor
1771 * @param {DOMString} id unique identifier, should only be set by native code
1772 * @param type
1773 * @param value
1774 * @param pref
1775 */
1776 var ContactField = function(type, value, pref) {
1777         this.id = null;
1778     this.type = type || null;
1779     this.value = value || null;
1780     this.pref = pref || null;
1781 };
1782
1783 /**
1784 * Contact address.
1785 * @constructor
1786 * @param {DOMString} id unique identifier, should only be set by native code
1787 * @param formatted
1788 * @param streetAddress
1789 * @param locality
1790 * @param region
1791 * @param postalCode
1792 * @param country
1793 */
1794 var ContactAddress = function(pref, type, formatted, streetAddress, locality, region, postalCode, country) {
1795         this.id = null;
1796     this.pref = pref || null;
1797     this.type = type || null;
1798     this.formatted = formatted || null;
1799     this.streetAddress = streetAddress || null;
1800     this.locality = locality || null;
1801     this.region = region || null;
1802     this.postalCode = postalCode || null;
1803     this.country = country || null;
1804 };
1805
1806 /**
1807 * Contact organization.
1808 * @constructor
1809 * @param {DOMString} id unique identifier, should only be set by native code
1810 * @param name
1811 * @param dept
1812 * @param title
1813 * @param startDate
1814 * @param endDate
1815 * @param location
1816 * @param desc
1817 */
1818 var ContactOrganization = function(pref, type, name, dept, title) {
1819         this.id = null;
1820     this.pref = pref || null;
1821     this.type = type || null;
1822     this.name = name || null;
1823     this.department = dept || null;
1824     this.title = title || null;
1825 };
1826
1827 /**
1828 * Represents a group of Contacts.
1829 * @constructor
1830 */
1831 var Contacts = function() {
1832     this.inProgress = false;
1833     this.records = [];
1834 };
1835 /**
1836 * Returns an array of Contacts matching the search criteria.
1837 * @param fields that should be searched
1838 * @param successCB success callback
1839 * @param errorCB error callback
1840 * @param {ContactFindOptions} options that can be applied to contact searching
1841 * @return array of Contacts matching search criteria
1842 */
1843 Contacts.prototype.find = function(fields, successCB, errorCB, options) {
1844     if (successCB === null) {
1845         throw new TypeError("You must specify a success callback for the find command.");
1846     }
1847     if (fields === null || fields === "undefined" || fields.length === "undefined" || fields.length <= 0) {
1848         if (typeof errorCB === "function") {
1849             errorCB({"code": ContactError.INVALID_ARGUMENT_ERROR});
1850         }
1851     } else {
1852         PhoneGap.exec(successCB, errorCB, "Contacts", "search", [fields, options]);        
1853     }
1854 };
1855
1856 /**
1857 * This function creates a new contact, but it does not persist the contact
1858 * to device storage. To persist the contact to device storage, invoke
1859 * contact.save().
1860 * @param properties an object who's properties will be examined to create a new Contact
1861 * @returns new Contact object
1862 */
1863 Contacts.prototype.create = function(properties) {
1864     var i;
1865         var contact = new Contact();
1866     for (i in properties) {
1867         if (contact[i] !== 'undefined') {
1868             contact[i] = properties[i];
1869         }
1870     }
1871     return contact;
1872 };
1873
1874 /**
1875 * This function returns and array of contacts.  It is required as we need to convert raw
1876 * JSON objects into concrete Contact objects.  Currently this method is called after
1877 * navigator.contacts.find but before the find methods success call back.
1878 *
1879 * @param jsonArray an array of JSON Objects that need to be converted to Contact objects.
1880 * @returns an array of Contact objects
1881 */
1882 Contacts.prototype.cast = function(pluginResult) {
1883         var contacts = [];
1884         var i;
1885         for (i=0; i<pluginResult.message.length; i++) {
1886                 contacts.push(navigator.contacts.create(pluginResult.message[i]));
1887         }
1888         pluginResult.message = contacts;
1889         return pluginResult;
1890 };
1891
1892 /**
1893  * ContactFindOptions.
1894  * @constructor
1895  * @param filter used to match contacts against
1896  * @param multiple boolean used to determine if more than one contact should be returned
1897  */
1898 var ContactFindOptions = function(filter, multiple) {
1899     this.filter = filter || '';
1900     this.multiple = multiple || false;
1901 };
1902
1903 /**
1904  * Add the contact interface into the browser.
1905  */
1906 PhoneGap.addConstructor(function() {
1907     if(typeof navigator.contacts === "undefined") {
1908         navigator.contacts = new Contacts();
1909     }
1910 });
1911 }
1912
1913
1914 /*
1915  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
1916  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
1917  *
1918  * Copyright (c) 2005-2010, Nitobi Software Inc.
1919  * Copyright (c) 2010-2011, IBM Corporation
1920  */
1921
1922 // TODO: Needs to be commented
1923
1924 if (!PhoneGap.hasResource("crypto")) {
1925 PhoneGap.addResource("crypto");
1926
1927 /**
1928 * @constructor
1929 */
1930 var Crypto = function() {
1931 };
1932
1933 Crypto.prototype.encrypt = function(seed, string, callback) {
1934     this.encryptWin = callback;
1935     PhoneGap.exec(null, null, "Crypto", "encrypt", [seed, string]);
1936 };
1937
1938 Crypto.prototype.decrypt = function(seed, string, callback) {
1939     this.decryptWin = callback;
1940     PhoneGap.exec(null, null, "Crypto", "decrypt", [seed, string]);
1941 };
1942
1943 Crypto.prototype.gotCryptedString = function(string) {
1944     this.encryptWin(string);
1945 };
1946
1947 Crypto.prototype.getPlainString = function(string) {
1948     this.decryptWin(string);
1949 };
1950
1951 PhoneGap.addConstructor(function() {
1952     if (typeof navigator.Crypto === "undefined") {
1953         navigator.Crypto = new Crypto();
1954     }
1955 });
1956 }
1957
1958
1959 /*
1960  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
1961  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
1962  *
1963  * Copyright (c) 2005-2010, Nitobi Software Inc.
1964  * Copyright (c) 2010-2011, IBM Corporation
1965  */
1966
1967 if (!PhoneGap.hasResource("device")) {
1968 PhoneGap.addResource("device");
1969
1970 /**
1971  * This represents the mobile device, and provides properties for inspecting the model, version, UUID of the
1972  * phone, etc.
1973  * @constructor
1974  */
1975 var Device = function() {
1976     this.available = PhoneGap.available;
1977     this.platform = null;
1978     this.version = null;
1979     this.name = null;
1980     this.uuid = null;
1981     this.phonegap = null;
1982
1983     var me = this;
1984     this.getInfo(
1985         function(info) {
1986             me.available = true;
1987             me.platform = info.platform;
1988             me.version = info.version;
1989             me.name = info.name;
1990             me.uuid = info.uuid;
1991             me.phonegap = info.phonegap;
1992             PhoneGap.onPhoneGapInfoReady.fire();
1993         },
1994         function(e) {
1995             me.available = false;
1996             console.log("Error initializing PhoneGap: " + e);
1997             alert("Error initializing PhoneGap: "+e);
1998         });
1999 };
2000
2001 /**
2002  * Get device info
2003  *
2004  * @param {Function} successCallback The function to call when the heading data is available
2005  * @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
2006  */
2007 Device.prototype.getInfo = function(successCallback, errorCallback) {
2008
2009     // successCallback required
2010     if (typeof successCallback !== "function") {
2011         console.log("Device Error: successCallback is not a function");
2012         return;
2013     }
2014
2015     // errorCallback optional
2016     if (errorCallback && (typeof errorCallback !== "function")) {
2017         console.log("Device Error: errorCallback is not a function");
2018         return;
2019     }
2020
2021     // Get info
2022     PhoneGap.exec(successCallback, errorCallback, "Device", "getDeviceInfo", []);
2023 };
2024
2025 /*
2026  * DEPRECATED
2027  * This is only for Android.
2028  *
2029  * You must explicitly override the back button.
2030  */
2031 Device.prototype.overrideBackButton = function() {
2032         console.log("Device.overrideBackButton() is deprecated.  Use App.overrideBackbutton(true).");
2033         navigator.app.overrideBackbutton(true);
2034 };
2035
2036 /*
2037  * DEPRECATED
2038  * This is only for Android.
2039  *
2040  * This resets the back button to the default behaviour
2041  */
2042 Device.prototype.resetBackButton = function() {
2043         console.log("Device.resetBackButton() is deprecated.  Use App.overrideBackbutton(false).");
2044         navigator.app.overrideBackbutton(false);
2045 };
2046
2047 /*
2048  * DEPRECATED
2049  * This is only for Android.
2050  *
2051  * This terminates the activity!
2052  */
2053 Device.prototype.exitApp = function() {
2054         console.log("Device.exitApp() is deprecated.  Use App.exitApp().");
2055         navigator.app.exitApp();
2056 };
2057
2058 PhoneGap.addConstructor(function() {
2059     if (typeof navigator.device === "undefined") {
2060         navigator.device = window.device = new Device();
2061     }
2062 });
2063 }
2064
2065
2066 /*
2067  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
2068  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
2069  *
2070  * Copyright (c) 2005-2010, Nitobi Software Inc.
2071  * Copyright (c) 2010-2011, IBM Corporation
2072  */
2073
2074 if (!PhoneGap.hasResource("file")) {
2075 PhoneGap.addResource("file");
2076
2077 /**
2078  * This class provides some useful information about a file.
2079  * This is the fields returned when navigator.fileMgr.getFileProperties()
2080  * is called.
2081  * @constructor
2082  */
2083 var FileProperties = function(filePath) {
2084     this.filePath = filePath;
2085     this.size = 0;
2086     this.lastModifiedDate = null;
2087 };
2088
2089 /**
2090  * Represents a single file.
2091  *
2092  * @constructor
2093  * @param name {DOMString} name of the file, without path information
2094  * @param fullPath {DOMString} the full path of the file, including the name
2095  * @param type {DOMString} mime type
2096  * @param lastModifiedDate {Date} last modified date
2097  * @param size {Number} size of the file in bytes
2098  */
2099 var File = function(name, fullPath, type, lastModifiedDate, size) {
2100         this.name = name || null;
2101     this.fullPath = fullPath || null;
2102         this.type = type || null;
2103     this.lastModifiedDate = lastModifiedDate || null;
2104     this.size = size || 0;
2105 };
2106
2107 /** @constructor */
2108 var FileError = function() {
2109    this.code = null;
2110 };
2111
2112 // File error codes
2113 // Found in DOMException
2114 FileError.NOT_FOUND_ERR = 1;
2115 FileError.SECURITY_ERR = 2;
2116 FileError.ABORT_ERR = 3;
2117
2118 // Added by this specification
2119 FileError.NOT_READABLE_ERR = 4;
2120 FileError.ENCODING_ERR = 5;
2121 FileError.NO_MODIFICATION_ALLOWED_ERR = 6;
2122 FileError.INVALID_STATE_ERR = 7;
2123 FileError.SYNTAX_ERR = 8;
2124 FileError.INVALID_MODIFICATION_ERR = 9;
2125 FileError.QUOTA_EXCEEDED_ERR = 10;
2126 FileError.TYPE_MISMATCH_ERR = 11;
2127 FileError.PATH_EXISTS_ERR = 12;
2128
2129 //-----------------------------------------------------------------------------
2130 // File manager
2131 //-----------------------------------------------------------------------------
2132
2133 /** @constructor */
2134 var FileMgr = function() {
2135 };
2136
2137 FileMgr.prototype.getFileProperties = function(filePath) {
2138     return PhoneGap.exec(null, null, "File", "getFileProperties", [filePath]);
2139 };
2140
2141 FileMgr.prototype.getFileBasePaths = function() {
2142 };
2143
2144 FileMgr.prototype.testSaveLocationExists = function(successCallback, errorCallback) {
2145     return PhoneGap.exec(successCallback, errorCallback, "File", "testSaveLocationExists", []);
2146 };
2147
2148 FileMgr.prototype.testFileExists = function(fileName, successCallback, errorCallback) {
2149     return PhoneGap.exec(successCallback, errorCallback, "File", "testFileExists", [fileName]);
2150 };
2151
2152 FileMgr.prototype.testDirectoryExists = function(dirName, successCallback, errorCallback) {
2153     return PhoneGap.exec(successCallback, errorCallback, "File", "testDirectoryExists", [dirName]);
2154 };
2155
2156 FileMgr.prototype.getFreeDiskSpace = function(successCallback, errorCallback) {
2157     return PhoneGap.exec(successCallback, errorCallback, "File", "getFreeDiskSpace", []);
2158 };
2159
2160 FileMgr.prototype.write = function(fileName, data, position, successCallback, errorCallback) {
2161     PhoneGap.exec(successCallback, errorCallback, "File", "write", [fileName, data, position]);
2162 };
2163
2164 FileMgr.prototype.truncate = function(fileName, size, successCallback, errorCallback) {
2165     PhoneGap.exec(successCallback, errorCallback, "File", "truncate", [fileName, size]);
2166 };
2167
2168 FileMgr.prototype.readAsText = function(fileName, encoding, successCallback, errorCallback) {
2169     PhoneGap.exec(successCallback, errorCallback, "File", "readAsText", [fileName, encoding]);
2170 };
2171
2172 FileMgr.prototype.readAsDataURL = function(fileName, successCallback, errorCallback) {
2173     PhoneGap.exec(successCallback, errorCallback, "File", "readAsDataURL", [fileName]);
2174 };
2175
2176 PhoneGap.addConstructor(function() {
2177     if (typeof navigator.fileMgr === "undefined") {
2178         navigator.fileMgr = new FileMgr();
2179     }
2180 });
2181
2182 //-----------------------------------------------------------------------------
2183 // File Reader
2184 //-----------------------------------------------------------------------------
2185 // TODO: All other FileMgr function operate on the SD card as root.  However,
2186 //       for FileReader & FileWriter the root is not SD card.  Should this be changed?
2187
2188 /**
2189  * This class reads the mobile device file system.
2190  *
2191  * For Android:
2192  *      The root directory is the root of the file system.
2193  *      To read from the SD card, the file name is "sdcard/my_file.txt"
2194  * @constructor
2195  */
2196 var FileReader = function() {
2197     this.fileName = "";
2198
2199     this.readyState = 0;
2200
2201     // File data
2202     this.result = null;
2203
2204     // Error
2205     this.error = null;
2206
2207     // Event handlers
2208     this.onloadstart = null;    // When the read starts.
2209     this.onprogress = null;     // While reading (and decoding) file or fileBlob data, and reporting partial file data (progess.loaded/progress.total)
2210     this.onload = null;         // When the read has successfully completed.
2211     this.onerror = null;        // When the read has failed (see errors).
2212     this.onloadend = null;      // When the request has completed (either in success or failure).
2213     this.onabort = null;        // When the read has been aborted. For instance, by invoking the abort() method.
2214 };
2215
2216 // States
2217 FileReader.EMPTY = 0;
2218 FileReader.LOADING = 1;
2219 FileReader.DONE = 2;
2220
2221 /**
2222  * Abort reading file.
2223  */
2224 FileReader.prototype.abort = function() {
2225     var evt;
2226     this.readyState = FileReader.DONE;
2227     this.result = null;
2228
2229     // set error
2230     var error = new FileError();
2231     error.code = error.ABORT_ERR;
2232     this.error = error;
2233
2234     // If error callback
2235     if (typeof this.onerror === "function") {
2236         this.onerror({"type":"error", "target":this});
2237     }
2238     // If abort callback
2239     if (typeof this.onabort === "function") {
2240         this.onabort({"type":"abort", "target":this});
2241     }
2242     // If load end callback
2243     if (typeof this.onloadend === "function") {
2244         this.onloadend({"type":"loadend", "target":this});
2245     }
2246 };
2247
2248 /**
2249  * Read text file.
2250  *
2251  * @param file          {File} File object containing file properties
2252  * @param encoding      [Optional] (see http://www.iana.org/assignments/character-sets)
2253  */
2254 FileReader.prototype.readAsText = function(file, encoding) {
2255     this.fileName = "";
2256         if (typeof file.fullPath === "undefined") {
2257                 this.fileName = file;
2258         } else {
2259                 this.fileName = file.fullPath;
2260         }
2261
2262     // LOADING state
2263     this.readyState = FileReader.LOADING;
2264
2265     // If loadstart callback
2266     if (typeof this.onloadstart === "function") {
2267         this.onloadstart({"type":"loadstart", "target":this});
2268     }
2269
2270     // Default encoding is UTF-8
2271     var enc = encoding ? encoding : "UTF-8";
2272
2273     var me = this;
2274
2275     // Read file
2276     navigator.fileMgr.readAsText(this.fileName, enc,
2277
2278         // Success callback
2279         function(r) {
2280             var evt;
2281
2282             // If DONE (cancelled), then don't do anything
2283             if (me.readyState === FileReader.DONE) {
2284                 return;
2285             }
2286
2287             // Save result
2288             me.result = r;
2289
2290             // If onload callback
2291             if (typeof me.onload === "function") {
2292                 me.onload({"type":"load", "target":me});
2293             }
2294
2295             // DONE state
2296             me.readyState = FileReader.DONE;
2297
2298             // If onloadend callback
2299             if (typeof me.onloadend === "function") {
2300                 me.onloadend({"type":"loadend", "target":me});
2301             }
2302         },
2303
2304         // Error callback
2305         function(e) {
2306             var evt;
2307             // If DONE (cancelled), then don't do anything
2308             if (me.readyState === FileReader.DONE) {
2309                 return;
2310             }
2311
2312             // Save error
2313                     me.error = e;
2314
2315             // If onerror callback
2316             if (typeof me.onerror === "function") {
2317                 me.onerror({"type":"error", "target":me});
2318             }
2319
2320             // DONE state
2321             me.readyState = FileReader.DONE;
2322
2323             // If onloadend callback
2324             if (typeof me.onloadend === "function") {
2325                 me.onloadend({"type":"loadend", "target":me});
2326             }
2327         }
2328         );
2329 };
2330
2331
2332 /**
2333  * Read file and return data as a base64 encoded data url.
2334  * A data url is of the form:
2335  *      data:[<mediatype>][;base64],<data>
2336  *
2337  * @param file          {File} File object containing file properties
2338  */
2339 FileReader.prototype.readAsDataURL = function(file) {
2340         this.fileName = "";
2341     if (typeof file.fullPath === "undefined") {
2342         this.fileName = file;
2343     } else {
2344         this.fileName = file.fullPath;
2345     }
2346
2347     // LOADING state
2348     this.readyState = FileReader.LOADING;
2349
2350     // If loadstart callback
2351     if (typeof this.onloadstart === "function") {
2352         this.onloadstart({"type":"loadstart", "target":this});
2353     }
2354
2355     var me = this;
2356
2357     // Read file
2358     navigator.fileMgr.readAsDataURL(this.fileName,
2359
2360         // Success callback
2361         function(r) {
2362             var evt;
2363
2364             // If DONE (cancelled), then don't do anything
2365             if (me.readyState === FileReader.DONE) {
2366                 return;
2367             }
2368
2369             // Save result
2370             me.result = r;
2371
2372             // If onload callback
2373             if (typeof me.onload === "function") {
2374                 me.onload({"type":"load", "target":me});
2375             }
2376
2377             // DONE state
2378             me.readyState = FileReader.DONE;
2379
2380             // If onloadend callback
2381             if (typeof me.onloadend === "function") {
2382                 me.onloadend({"type":"loadend", "target":me});
2383             }
2384         },
2385
2386         // Error callback
2387         function(e) {
2388             var evt;
2389             // If DONE (cancelled), then don't do anything
2390             if (me.readyState === FileReader.DONE) {
2391                 return;
2392             }
2393
2394             // Save error
2395             me.error = e;
2396
2397             // If onerror callback
2398             if (typeof me.onerror === "function") {
2399                 me.onerror({"type":"error", "target":me});
2400             }
2401
2402             // DONE state
2403             me.readyState = FileReader.DONE;
2404
2405             // If onloadend callback
2406             if (typeof me.onloadend === "function") {
2407                 me.onloadend({"type":"loadend", "target":me});
2408             }
2409         }
2410         );
2411 };
2412
2413 /**
2414  * Read file and return data as a binary data.
2415  *
2416  * @param file          {File} File object containing file properties
2417  */
2418 FileReader.prototype.readAsBinaryString = function(file) {
2419     // TODO - Can't return binary data to browser.
2420     this.fileName = file;
2421 };
2422
2423 /**
2424  * Read file and return data as a binary data.
2425  *
2426  * @param file          {File} File object containing file properties
2427  */
2428 FileReader.prototype.readAsArrayBuffer = function(file) {
2429     // TODO - Can't return binary data to browser.
2430     this.fileName = file;
2431 };
2432
2433 //-----------------------------------------------------------------------------
2434 // File Writer
2435 //-----------------------------------------------------------------------------
2436
2437 /**
2438  * This class writes to the mobile device file system.
2439  *
2440  * For Android:
2441  *      The root directory is the root of the file system.
2442  *      To write to the SD card, the file name is "sdcard/my_file.txt"
2443  *
2444  * @constructor
2445  * @param file {File} File object containing file properties
2446  * @param append if true write to the end of the file, otherwise overwrite the file
2447  */
2448 var FileWriter = function(file) {
2449     this.fileName = "";
2450     this.length = 0;
2451         if (file) {
2452             this.fileName = file.fullPath || file;
2453             this.length = file.size || 0;
2454         }
2455     // default is to write at the beginning of the file
2456     this.position = 0;
2457
2458     this.readyState = 0; // EMPTY
2459
2460     this.result = null;
2461
2462     // Error
2463     this.error = null;
2464
2465     // Event handlers
2466     this.onwritestart = null;   // When writing starts
2467     this.onprogress = null;             // While writing the file, and reporting partial file data
2468     this.onwrite = null;                // When the write has successfully completed.
2469     this.onwriteend = null;             // When the request has completed (either in success or failure).
2470     this.onabort = null;                // When the write has been aborted. For instance, by invoking the abort() method.
2471     this.onerror = null;                // When the write has failed (see errors).
2472 };
2473
2474 // States
2475 FileWriter.INIT = 0;
2476 FileWriter.WRITING = 1;
2477 FileWriter.DONE = 2;
2478
2479 /**
2480  * Abort writing file.
2481  */
2482 FileWriter.prototype.abort = function() {
2483     // check for invalid state
2484         if (this.readyState === FileWriter.DONE || this.readyState === FileWriter.INIT) {
2485                 throw FileError.INVALID_STATE_ERR;
2486         }
2487
2488     // set error
2489     var error = new FileError(), evt;
2490     error.code = error.ABORT_ERR;
2491     this.error = error;
2492
2493     // If error callback
2494     if (typeof this.onerror === "function") {
2495         this.onerror({"type":"error", "target":this});
2496     }
2497     // If abort callback
2498     if (typeof this.onabort === "function") {
2499         this.onabort({"type":"abort", "target":this});
2500     }
2501
2502     this.readyState = FileWriter.DONE;
2503
2504     // If write end callback
2505     if (typeof this.onwriteend == "function") {
2506         this.onwriteend({"type":"writeend", "target":this});
2507     }
2508 };
2509
2510 /**
2511  * Writes data to the file
2512  *
2513  * @param text to be written
2514  */
2515 FileWriter.prototype.write = function(text) {
2516         // Throw an exception if we are already writing a file
2517         if (this.readyState === FileWriter.WRITING) {
2518                 throw FileError.INVALID_STATE_ERR;
2519         }
2520
2521     // WRITING state
2522     this.readyState = FileWriter.WRITING;
2523
2524     var me = this;
2525
2526     // If onwritestart callback
2527     if (typeof me.onwritestart === "function") {
2528         me.onwritestart({"type":"writestart", "target":me});
2529     }
2530
2531     // Write file
2532     navigator.fileMgr.write(this.fileName, text, this.position,
2533
2534         // Success callback
2535         function(r) {
2536             var evt;
2537             // If DONE (cancelled), then don't do anything
2538             if (me.readyState === FileWriter.DONE) {
2539                 return;
2540             }
2541
2542             // position always increases by bytes written because file would be extended
2543             me.position += r;
2544             // The length of the file is now where we are done writing.
2545             me.length = me.position;
2546
2547             // If onwrite callback
2548             if (typeof me.onwrite === "function") {
2549                 me.onwrite({"type":"write", "target":me});
2550             }
2551
2552             // DONE state
2553             me.readyState = FileWriter.DONE;
2554
2555             // If onwriteend callback
2556             if (typeof me.onwriteend === "function") {
2557                 me.onwriteend({"type":"writeend", "target":me});
2558             }
2559         },
2560
2561         // Error callback
2562         function(e) {
2563             var evt;
2564
2565             // If DONE (cancelled), then don't do anything
2566             if (me.readyState === FileWriter.DONE) {
2567                 return;
2568             }
2569
2570             // Save error
2571             me.error = e;
2572
2573             // If onerror callback
2574             if (typeof me.onerror === "function") {
2575                 me.onerror({"type":"error", "target":me});
2576             }
2577
2578             // DONE state
2579             me.readyState = FileWriter.DONE;
2580
2581             // If onwriteend callback
2582             if (typeof me.onwriteend === "function") {
2583                 me.onwriteend({"type":"writeend", "target":me});
2584             }
2585         }
2586         );
2587
2588 };
2589
2590 /**
2591  * Moves the file pointer to the location specified.
2592  *
2593  * If the offset is a negative number the position of the file
2594  * pointer is rewound.  If the offset is greater than the file
2595  * size the position is set to the end of the file.
2596  *
2597  * @param offset is the location to move the file pointer to.
2598  */
2599 FileWriter.prototype.seek = function(offset) {
2600     // Throw an exception if we are already writing a file
2601     if (this.readyState === FileWriter.WRITING) {
2602         throw FileError.INVALID_STATE_ERR;
2603     }
2604
2605     if (!offset) {
2606         return;
2607     }
2608
2609     // See back from end of file.
2610     if (offset < 0) {
2611                 this.position = Math.max(offset + this.length, 0);
2612         }
2613     // Offset is bigger then file size so set position
2614     // to the end of the file.
2615         else if (offset > this.length) {
2616                 this.position = this.length;
2617         }
2618     // Offset is between 0 and file size so set the position
2619     // to start writing.
2620         else {
2621                 this.position = offset;
2622         }
2623 };
2624
2625 /**
2626  * Truncates the file to the size specified.
2627  *
2628  * @param size to chop the file at.
2629  */
2630 FileWriter.prototype.truncate = function(size) {
2631         // Throw an exception if we are already writing a file
2632         if (this.readyState === FileWriter.WRITING) {
2633                 throw FileError.INVALID_STATE_ERR;
2634         }
2635
2636     // WRITING state
2637     this.readyState = FileWriter.WRITING;
2638
2639     var me = this;
2640
2641     // If onwritestart callback
2642     if (typeof me.onwritestart === "function") {
2643         me.onwritestart({"type":"writestart", "target":this});
2644     }
2645
2646     // Write file
2647     navigator.fileMgr.truncate(this.fileName, size,
2648
2649         // Success callback
2650         function(r) {
2651             var evt;
2652             // If DONE (cancelled), then don't do anything
2653             if (me.readyState === FileWriter.DONE) {
2654                 return;
2655             }
2656
2657             // Update the length of the file
2658             me.length = r;
2659             me.position = Math.min(me.position, r);
2660
2661             // If onwrite callback
2662             if (typeof me.onwrite === "function") {
2663                 me.onwrite({"type":"write", "target":me});
2664             }
2665
2666             // DONE state
2667             me.readyState = FileWriter.DONE;
2668
2669             // If onwriteend callback
2670             if (typeof me.onwriteend === "function") {
2671                 me.onwriteend({"type":"writeend", "target":me});
2672             }
2673         },
2674
2675         // Error callback
2676         function(e) {
2677             var evt;
2678             // If DONE (cancelled), then don't do anything
2679             if (me.readyState === FileWriter.DONE) {
2680                 return;
2681             }
2682
2683             // Save error
2684             me.error = e;
2685
2686             // If onerror callback
2687             if (typeof me.onerror === "function") {
2688                 me.onerror({"type":"error", "target":me});
2689             }
2690
2691             // DONE state
2692             me.readyState = FileWriter.DONE;
2693
2694             // If onwriteend callback
2695             if (typeof me.onwriteend === "function") {
2696                 me.onwriteend({"type":"writeend", "target":me});
2697             }
2698         }
2699     );
2700 };
2701
2702 /**
2703  * Information about the state of the file or directory
2704  *
2705  * @constructor
2706  * {Date} modificationTime (readonly)
2707  */
2708 var Metadata = function() {
2709     this.modificationTime=null;
2710 };
2711
2712 /**
2713  * Supplies arguments to methods that lookup or create files and directories
2714  *
2715  * @constructor
2716  * @param {boolean} create file or directory if it doesn't exist
2717  * @param {boolean} exclusive if true the command will fail if the file or directory exists
2718  */
2719 var Flags = function(create, exclusive) {
2720     this.create = create || false;
2721     this.exclusive = exclusive || false;
2722 };
2723
2724 /**
2725  * An interface representing a file system
2726  *
2727  * @constructor
2728  * {DOMString} name the unique name of the file system (readonly)
2729  * {DirectoryEntry} root directory of the file system (readonly)
2730  */
2731 var FileSystem = function() {
2732     this.name = null;
2733     this.root = null;
2734 };
2735
2736 /**
2737  * An interface that lists the files and directories in a directory.
2738  * @constructor
2739  */
2740 var DirectoryReader = function(fullPath){
2741     this.fullPath = fullPath || null;
2742 };
2743
2744 /**
2745  * Returns a list of entries from a directory.
2746  *
2747  * @param {Function} successCallback is called with a list of entries
2748  * @param {Function} errorCallback is called with a FileError
2749  */
2750 DirectoryReader.prototype.readEntries = function(successCallback, errorCallback) {
2751     PhoneGap.exec(successCallback, errorCallback, "File", "readEntries", [this.fullPath]);
2752 };
2753
2754 /**
2755  * An interface representing a directory on the file system.
2756  *
2757  * @constructor
2758  * {boolean} isFile always false (readonly)
2759  * {boolean} isDirectory always true (readonly)
2760  * {DOMString} name of the directory, excluding the path leading to it (readonly)
2761  * {DOMString} fullPath the absolute full path to the directory (readonly)
2762  * {FileSystem} filesystem on which the directory resides (readonly)
2763  */
2764 var DirectoryEntry = function() {
2765     this.isFile = false;
2766     this.isDirectory = true;
2767     this.name = null;
2768     this.fullPath = null;
2769     this.filesystem = null;
2770 };
2771
2772 /**
2773  * Copies a directory to a new location
2774  *
2775  * @param {DirectoryEntry} parent the directory to which to copy the entry
2776  * @param {DOMString} newName the new name of the entry, defaults to the current name
2777  * @param {Function} successCallback is called with the new entry
2778  * @param {Function} errorCallback is called with a FileError
2779  */
2780 DirectoryEntry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) {
2781     PhoneGap.exec(successCallback, errorCallback, "File", "copyTo", [this.fullPath, parent, newName]);
2782 };
2783
2784 /**
2785  * Looks up the metadata of the entry
2786  *
2787  * @param {Function} successCallback is called with a Metadata object
2788  * @param {Function} errorCallback is called with a FileError
2789  */
2790 DirectoryEntry.prototype.getMetadata = function(successCallback, errorCallback) {
2791     PhoneGap.exec(successCallback, errorCallback, "File", "getMetadata", [this.fullPath]);
2792 };
2793
2794 /**
2795  * Gets the parent of the entry
2796  *
2797  * @param {Function} successCallback is called with a parent entry
2798  * @param {Function} errorCallback is called with a FileError
2799  */
2800 DirectoryEntry.prototype.getParent = function(successCallback, errorCallback) {
2801     PhoneGap.exec(successCallback, errorCallback, "File", "getParent", [this.fullPath]);
2802 };
2803
2804 /**
2805  * Moves a directory to a new location
2806  *
2807  * @param {DirectoryEntry} parent the directory to which to move the entry
2808  * @param {DOMString} newName the new name of the entry, defaults to the current name
2809  * @param {Function} successCallback is called with the new entry
2810  * @param {Function} errorCallback is called with a FileError
2811  */
2812 DirectoryEntry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) {
2813     PhoneGap.exec(successCallback, errorCallback, "File", "moveTo", [this.fullPath, parent, newName]);
2814 };
2815
2816 /**
2817  * Removes the entry
2818  *
2819  * @param {Function} successCallback is called with no parameters
2820  * @param {Function} errorCallback is called with a FileError
2821  */
2822 DirectoryEntry.prototype.remove = function(successCallback, errorCallback) {
2823     PhoneGap.exec(successCallback, errorCallback, "File", "remove", [this.fullPath]);
2824 };
2825
2826 /**
2827  * Returns a URI that can be used to identify this entry.
2828  *
2829  * @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.
2830  * @return uri
2831  */
2832 DirectoryEntry.prototype.toURI = function(mimeType) {
2833     return "file://" + this.fullPath;
2834 };
2835
2836 /**
2837  * Creates a new DirectoryReader to read entries from this directory
2838  */
2839 DirectoryEntry.prototype.createReader = function(successCallback, errorCallback) {
2840     return new DirectoryReader(this.fullPath);
2841 };
2842
2843 /**
2844  * Creates or looks up a directory
2845  *
2846  * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory
2847  * @param {Flags} options to create or excluively create the directory
2848  * @param {Function} successCallback is called with the new entry
2849  * @param {Function} errorCallback is called with a FileError
2850  */
2851 DirectoryEntry.prototype.getDirectory = function(path, options, successCallback, errorCallback) {
2852     PhoneGap.exec(successCallback, errorCallback, "File", "getDirectory", [this.fullPath, path, options]);
2853 };
2854
2855 /**
2856  * Creates or looks up a file
2857  *
2858  * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file
2859  * @param {Flags} options to create or excluively create the file
2860  * @param {Function} successCallback is called with the new entry
2861  * @param {Function} errorCallback is called with a FileError
2862  */
2863 DirectoryEntry.prototype.getFile = function(path, options, successCallback, errorCallback) {
2864     PhoneGap.exec(successCallback, errorCallback, "File", "getFile", [this.fullPath, path, options]);
2865 };
2866
2867 /**
2868  * Deletes a directory and all of it's contents
2869  *
2870  * @param {Function} successCallback is called with no parameters
2871  * @param {Function} errorCallback is called with a FileError
2872  */
2873 DirectoryEntry.prototype.removeRecursively = function(successCallback, errorCallback) {
2874     PhoneGap.exec(successCallback, errorCallback, "File", "removeRecursively", [this.fullPath]);
2875 };
2876
2877 /**
2878  * An interface representing a directory on the file system.
2879  *
2880  * @constructor
2881  * {boolean} isFile always true (readonly)
2882  * {boolean} isDirectory always false (readonly)
2883  * {DOMString} name of the file, excluding the path leading to it (readonly)
2884  * {DOMString} fullPath the absolute full path to the file (readonly)
2885  * {FileSystem} filesystem on which the directory resides (readonly)
2886  */
2887 var FileEntry = function() {
2888     this.isFile = true;
2889     this.isDirectory = false;
2890     this.name = null;
2891     this.fullPath = null;
2892     this.filesystem = null;
2893 };
2894
2895 /**
2896  * Copies a file to a new location
2897  *
2898  * @param {DirectoryEntry} parent the directory to which to copy the entry
2899  * @param {DOMString} newName the new name of the entry, defaults to the current name
2900  * @param {Function} successCallback is called with the new entry
2901  * @param {Function} errorCallback is called with a FileError
2902  */
2903 FileEntry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) {
2904     PhoneGap.exec(successCallback, errorCallback, "File", "copyTo", [this.fullPath, parent, newName]);
2905 };
2906
2907 /**
2908  * Looks up the metadata of the entry
2909  *
2910  * @param {Function} successCallback is called with a Metadata object
2911  * @param {Function} errorCallback is called with a FileError
2912  */
2913 FileEntry.prototype.getMetadata = function(successCallback, errorCallback) {
2914     PhoneGap.exec(successCallback, errorCallback, "File", "getMetadata", [this.fullPath]);
2915 };
2916
2917 /**
2918  * Gets the parent of the entry
2919  *
2920  * @param {Function} successCallback is called with a parent entry
2921  * @param {Function} errorCallback is called with a FileError
2922  */
2923 FileEntry.prototype.getParent = function(successCallback, errorCallback) {
2924     PhoneGap.exec(successCallback, errorCallback, "File", "getParent", [this.fullPath]);
2925 };
2926
2927 /**
2928  * Moves a directory to a new location
2929  *
2930  * @param {DirectoryEntry} parent the directory to which to move the entry
2931  * @param {DOMString} newName the new name of the entry, defaults to the current name
2932  * @param {Function} successCallback is called with the new entry
2933  * @param {Function} errorCallback is called with a FileError
2934  */
2935 FileEntry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) {
2936     PhoneGap.exec(successCallback, errorCallback, "File", "moveTo", [this.fullPath, parent, newName]);
2937 };
2938
2939 /**
2940  * Removes the entry
2941  *
2942  * @param {Function} successCallback is called with no parameters
2943  * @param {Function} errorCallback is called with a FileError
2944  */
2945 FileEntry.prototype.remove = function(successCallback, errorCallback) {
2946     PhoneGap.exec(successCallback, errorCallback, "File", "remove", [this.fullPath]);
2947 };
2948
2949 /**
2950  * Returns a URI that can be used to identify this entry.
2951  *
2952  * @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.
2953  * @return uri
2954  */
2955 FileEntry.prototype.toURI = function(mimeType) {
2956     return "file://" + this.fullPath;
2957 };
2958
2959 /**
2960  * Creates a new FileWriter associated with the file that this FileEntry represents.
2961  *
2962  * @param {Function} successCallback is called with the new FileWriter
2963  * @param {Function} errorCallback is called with a FileError
2964  */
2965 FileEntry.prototype.createWriter = function(successCallback, errorCallback) {
2966     this.file(function(filePointer) {
2967         var writer = new FileWriter(filePointer);
2968     
2969         if (writer.fileName === null || writer.fileName === "") {
2970             if (typeof errorCallback == "function") {
2971                 errorCallback({
2972                     "code": FileError.INVALID_STATE_ERR
2973                 });
2974             }
2975         }
2976     
2977         if (typeof successCallback == "function") {
2978             successCallback(writer);
2979         }       
2980     }, errorCallback);
2981 };
2982
2983 /**
2984  * Returns a File that represents the current state of the file that this FileEntry represents.
2985  *
2986  * @param {Function} successCallback is called with the new File object
2987  * @param {Function} errorCallback is called with a FileError
2988  */
2989 FileEntry.prototype.file = function(successCallback, errorCallback) {
2990     PhoneGap.exec(successCallback, errorCallback, "File", "getFileMetadata", [this.fullPath]);
2991 };
2992
2993 /** @constructor */
2994 var LocalFileSystem = function() {
2995 };
2996
2997 // File error codes
2998 LocalFileSystem.TEMPORARY = 0;
2999 LocalFileSystem.PERSISTENT = 1;
3000 LocalFileSystem.RESOURCE = 2;
3001 LocalFileSystem.APPLICATION = 3;
3002
3003 /**
3004  * Requests a filesystem in which to store application data.
3005  *
3006  * @param {int} type of file system being requested
3007  * @param {Function} successCallback is called with the new FileSystem
3008  * @param {Function} errorCallback is called with a FileError
3009  */
3010 LocalFileSystem.prototype.requestFileSystem = function(type, size, successCallback, errorCallback) {
3011     if (type < 0 || type > 3) {
3012         if (typeof errorCallback == "function") {
3013             errorCallback({
3014                 "code": FileError.SYNTAX_ERR
3015             });
3016         }
3017     }
3018     else {
3019         PhoneGap.exec(successCallback, errorCallback, "File", "requestFileSystem", [type, size]);
3020     }
3021 };
3022
3023 /**
3024  *
3025  * @param {DOMString} uri referring to a local file in a filesystem
3026  * @param {Function} successCallback is called with the new entry
3027  * @param {Function} errorCallback is called with a FileError
3028  */
3029 LocalFileSystem.prototype.resolveLocalFileSystemURI = function(uri, successCallback, errorCallback) {
3030     PhoneGap.exec(successCallback, errorCallback, "File", "resolveLocalFileSystemURI", [uri]);
3031 };
3032
3033 /**
3034 * This function returns and array of contacts.  It is required as we need to convert raw
3035 * JSON objects into concrete Contact objects.  Currently this method is called after
3036 * navigator.service.contacts.find but before the find methods success call back.
3037 *
3038 * @param a JSON Objects that need to be converted to DirectoryEntry or FileEntry objects.
3039 * @returns an entry
3040 */
3041 LocalFileSystem.prototype._castFS = function(pluginResult) {
3042     var entry = null;
3043     entry = new DirectoryEntry();
3044     entry.isDirectory = pluginResult.message.root.isDirectory;
3045     entry.isFile = pluginResult.message.root.isFile;
3046     entry.name = pluginResult.message.root.name;
3047     entry.fullPath = pluginResult.message.root.fullPath;
3048     pluginResult.message.root = entry;
3049     return pluginResult;
3050 };
3051
3052 LocalFileSystem.prototype._castEntry = function(pluginResult) {
3053     var entry = null;
3054     if (pluginResult.message.isDirectory) {
3055         console.log("This is a dir");
3056         entry = new DirectoryEntry();
3057     }
3058     else if (pluginResult.message.isFile) {
3059         console.log("This is a file");
3060         entry = new FileEntry();
3061     }
3062     entry.isDirectory = pluginResult.message.isDirectory;
3063     entry.isFile = pluginResult.message.isFile;
3064     entry.name = pluginResult.message.name;
3065     entry.fullPath = pluginResult.message.fullPath;
3066     pluginResult.message = entry;
3067     return pluginResult;
3068 };
3069
3070 LocalFileSystem.prototype._castEntries = function(pluginResult) {
3071     var entries = pluginResult.message;
3072     var retVal = [];
3073     for (var i=0; i<entries.length; i++) {
3074         retVal.push(window.localFileSystem._createEntry(entries[i]));
3075     }
3076     pluginResult.message = retVal;
3077     return pluginResult;
3078 };
3079
3080 LocalFileSystem.prototype._createEntry = function(castMe) {
3081     var entry = null;
3082     if (castMe.isDirectory) {
3083         console.log("This is a dir");
3084         entry = new DirectoryEntry();
3085     }
3086     else if (castMe.isFile) {
3087         console.log("This is a file");
3088         entry = new FileEntry();
3089     }
3090     entry.isDirectory = castMe.isDirectory;
3091     entry.isFile = castMe.isFile;
3092     entry.name = castMe.name;
3093     entry.fullPath = castMe.fullPath;
3094     return entry;
3095 };
3096
3097 LocalFileSystem.prototype._castDate = function(pluginResult) {
3098     if (pluginResult.message.modificationTime) {
3099         var modTime = new Date(pluginResult.message.modificationTime);
3100         pluginResult.message.modificationTime = modTime;
3101     }
3102     else if (pluginResult.message.lastModifiedDate) {
3103         var file = new File();
3104         file.size = pluginResult.message.size;
3105         file.type = pluginResult.message.type;
3106         file.name = pluginResult.message.name;
3107         file.fullPath = pluginResult.message.fullPath;
3108         file.lastModifiedDate = new Date(pluginResult.message.lastModifiedDate);
3109         pluginResult.message = file;
3110     }
3111     return pluginResult;
3112 };
3113
3114 /**
3115  * Add the FileSystem interface into the browser.
3116  */
3117 PhoneGap.addConstructor(function() {
3118         var pgLocalFileSystem = new LocalFileSystem();
3119         // Needed for cast methods
3120     if(typeof window.localFileSystem == "undefined") window.localFileSystem  = pgLocalFileSystem;
3121     if(typeof window.requestFileSystem == "undefined") window.requestFileSystem  = pgLocalFileSystem.requestFileSystem;
3122     if(typeof window.resolveLocalFileSystemURI == "undefined") window.resolveLocalFileSystemURI = pgLocalFileSystem.resolveLocalFileSystemURI;
3123 });
3124 }
3125
3126
3127 /*
3128  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
3129  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
3130  *
3131  * Copyright (c) 2005-2010, Nitobi Software Inc.
3132  * Copyright (c) 2010-2011, IBM Corporation
3133  */
3134
3135 if (!PhoneGap.hasResource("filetransfer")) {
3136 PhoneGap.addResource("filetransfer");
3137
3138 /**
3139  * FileTransfer uploads a file to a remote server.
3140  * @constructor
3141  */
3142 var FileTransfer = function() {};
3143
3144 /**
3145  * FileUploadResult
3146  * @constructor
3147  */
3148 var FileUploadResult = function() {
3149     this.bytesSent = 0;
3150     this.responseCode = null;
3151     this.response = null;
3152 };
3153
3154 /**
3155  * FileTransferError
3156  * @constructor
3157  */
3158 var FileTransferError = function() {
3159     this.code = null;
3160 };
3161
3162 FileTransferError.FILE_NOT_FOUND_ERR = 1;
3163 FileTransferError.INVALID_URL_ERR = 2;
3164 FileTransferError.CONNECTION_ERR = 3;
3165
3166 /**
3167 * Given an absolute file path, uploads a file on the device to a remote server
3168 * using a multipart HTTP request.
3169 * @param filePath {String}           Full path of the file on the device
3170 * @param server {String}             URL of the server to receive the file
3171 * @param successCallback (Function}  Callback to be invoked when upload has completed
3172 * @param errorCallback {Function}    Callback to be invoked upon error
3173 * @param options {FileUploadOptions} Optional parameters such as file name and mimetype
3174 */
3175 FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, debug) {
3176
3177     // check for options
3178     var fileKey = null;
3179     var fileName = null;
3180     var mimeType = null;
3181     var params = null;
3182     if (options) {
3183         fileKey = options.fileKey;
3184         fileName = options.fileName;
3185         mimeType = options.mimeType;
3186         if (options.params) {
3187             params = options.params;
3188         }
3189         else {
3190             params = {};
3191         }
3192     }
3193
3194     PhoneGap.exec(successCallback, errorCallback, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, debug]);
3195 };
3196
3197 /**
3198  * Options to customize the HTTP request used to upload files.
3199  * @constructor
3200  * @param fileKey {String}   Name of file request parameter.
3201  * @param fileName {String}  Filename to be used by the server. Defaults to image.jpg.
3202  * @param mimeType {String}  Mimetype of the uploaded file. Defaults to image/jpeg.
3203  * @param params {Object}    Object with key: value params to send to the server.
3204  */
3205 var FileUploadOptions = function(fileKey, fileName, mimeType, params) {
3206     this.fileKey = fileKey || null;
3207     this.fileName = fileName || null;
3208     this.mimeType = mimeType || null;
3209     this.params = params || null;
3210 };
3211 }
3212
3213
3214 /*
3215  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
3216  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
3217  *
3218  * Copyright (c) 2005-2010, Nitobi Software Inc.
3219  * Copyright (c) 2010-2011, IBM Corporation
3220  */
3221
3222 if (!PhoneGap.hasResource("geolocation")) {
3223 PhoneGap.addResource("geolocation");
3224
3225 /**
3226  * This class provides access to device GPS data.
3227  * @constructor
3228  */
3229 var Geolocation = function() {
3230
3231     // The last known GPS position.
3232     this.lastPosition = null;
3233
3234     // Geolocation listeners
3235     this.listeners = {};
3236 };
3237
3238 /**
3239  * Position error object
3240  *
3241  * @constructor
3242  * @param code
3243  * @param message
3244  */
3245 var PositionError = function(code, message) {
3246     this.code = code;
3247     this.message = message;
3248 };
3249
3250 PositionError.PERMISSION_DENIED = 1;
3251 PositionError.POSITION_UNAVAILABLE = 2;
3252 PositionError.TIMEOUT = 3;
3253
3254 /**
3255  * Asynchronously aquires the current position.
3256  *
3257  * @param {Function} successCallback    The function to call when the position data is available
3258  * @param {Function} errorCallback      The function to call when there is an error getting the heading position. (OPTIONAL)
3259  * @param {PositionOptions} options     The options for getting the position data. (OPTIONAL)
3260  */
3261 Geolocation.prototype.getCurrentPosition = function(successCallback, errorCallback, options) {
3262     if (navigator._geo.listeners.global) {
3263         console.log("Geolocation Error: Still waiting for previous getCurrentPosition() request.");
3264         try {
3265             errorCallback(new PositionError(PositionError.TIMEOUT, "Geolocation Error: Still waiting for previous getCurrentPosition() request."));
3266         } catch (e) {
3267         }
3268         return;
3269     }
3270     var maximumAge = 10000;
3271     var enableHighAccuracy = false;
3272     var timeout = 10000;
3273     if (typeof options !== "undefined") {
3274         if (typeof options.maximumAge !== "undefined") {
3275             maximumAge = options.maximumAge;
3276         }
3277         if (typeof options.enableHighAccuracy !== "undefined") {
3278             enableHighAccuracy = options.enableHighAccuracy;
3279         }
3280         if (typeof options.timeout !== "undefined") {
3281             timeout = options.timeout;
3282         }
3283     }
3284     navigator._geo.listeners.global = {"success" : successCallback, "fail" : errorCallback };
3285     PhoneGap.exec(null, null, "Geolocation", "getCurrentLocation", [enableHighAccuracy, timeout, maximumAge]);
3286 };
3287
3288 /**
3289  * Asynchronously watches the geolocation for changes to geolocation.  When a change occurs,
3290  * the successCallback is called with the new location.
3291  *
3292  * @param {Function} successCallback    The function to call each time the location data is available
3293  * @param {Function} errorCallback      The function to call when there is an error getting the location data. (OPTIONAL)
3294  * @param {PositionOptions} options     The options for getting the location data such as frequency. (OPTIONAL)
3295  * @return String                       The watch id that must be passed to #clearWatch to stop watching.
3296  */
3297 Geolocation.prototype.watchPosition = function(successCallback, errorCallback, options) {
3298     var maximumAge = 10000;
3299     var enableHighAccuracy = false;
3300     var timeout = 10000;
3301     if (typeof options !== "undefined") {
3302         if (typeof options.frequency  !== "undefined") {
3303             maximumAge = options.frequency;
3304         }
3305         if (typeof options.maximumAge !== "undefined") {
3306             maximumAge = options.maximumAge;
3307         }
3308         if (typeof options.enableHighAccuracy !== "undefined") {
3309             enableHighAccuracy = options.enableHighAccuracy;
3310         }
3311         if (typeof options.timeout !== "undefined") {
3312             timeout = options.timeout;
3313         }
3314     }
3315     var id = PhoneGap.createUUID();
3316     navigator._geo.listeners[id] = {"success" : successCallback, "fail" : errorCallback };
3317     PhoneGap.exec(null, null, "Geolocation", "start", [id, enableHighAccuracy, timeout, maximumAge]);
3318     return id;
3319 };
3320
3321 /*
3322  * Native callback when watch position has a new position.
3323  * PRIVATE METHOD
3324  *
3325  * @param {String} id
3326  * @param {Number} lat
3327  * @param {Number} lng
3328  * @param {Number} alt
3329  * @param {Number} altacc
3330  * @param {Number} head
3331  * @param {Number} vel
3332  * @param {Number} stamp
3333  */
3334 Geolocation.prototype.success = function(id, lat, lng, alt, altacc, head, vel, stamp) {
3335     var coords = new Coordinates(lat, lng, alt, altacc, head, vel);
3336     var loc = new Position(coords, stamp);
3337     try {
3338         if (lat === "undefined" || lng === "undefined") {
3339             navigator._geo.listeners[id].fail(new PositionError(PositionError.POSITION_UNAVAILABLE, "Lat/Lng are undefined."));
3340         }
3341         else {
3342             navigator._geo.lastPosition = loc;
3343             navigator._geo.listeners[id].success(loc);
3344         }
3345     }
3346     catch (e) {
3347         console.log("Geolocation Error: Error calling success callback function.");
3348     }
3349
3350     if (id === "global") {
3351         delete navigator._geo.listeners.global;
3352     }
3353 };
3354
3355 /**
3356  * Native callback when watch position has an error.
3357  * PRIVATE METHOD
3358  *
3359  * @param {String} id       The ID of the watch
3360  * @param {Number} code     The error code
3361  * @param {String} msg      The error message
3362  */
3363 Geolocation.prototype.fail = function(id, code, msg) {
3364     try {
3365         navigator._geo.listeners[id].fail(new PositionError(code, msg));
3366     }
3367     catch (e) {
3368         console.log("Geolocation Error: Error calling error callback function.");
3369     }
3370 };
3371
3372 /**
3373  * Clears the specified heading watch.
3374  *
3375  * @param {String} id       The ID of the watch returned from #watchPosition
3376  */
3377 Geolocation.prototype.clearWatch = function(id) {
3378     PhoneGap.exec(null, null, "Geolocation", "stop", [id]);
3379     delete navigator._geo.listeners[id];
3380 };
3381
3382 /**
3383  * Force the PhoneGap geolocation to be used instead of built-in.
3384  */
3385 Geolocation.usingPhoneGap = false;
3386 Geolocation.usePhoneGap = function() {
3387     if (Geolocation.usingPhoneGap) {
3388         return;
3389     }
3390     Geolocation.usingPhoneGap = true;
3391
3392     // Set built-in geolocation methods to our own implementations
3393     // (Cannot replace entire geolocation, but can replace individual methods)
3394     navigator.geolocation.setLocation = navigator._geo.setLocation;
3395     navigator.geolocation.getCurrentPosition = navigator._geo.getCurrentPosition;
3396     navigator.geolocation.watchPosition = navigator._geo.watchPosition;
3397     navigator.geolocation.clearWatch = navigator._geo.clearWatch;
3398     navigator.geolocation.start = navigator._geo.start;
3399     navigator.geolocation.stop = navigator._geo.stop;
3400 };
3401
3402 PhoneGap.addConstructor(function() {
3403     navigator._geo = new Geolocation();
3404
3405     // No native geolocation object for Android 1.x, so use PhoneGap geolocation
3406     if (typeof navigator.geolocation === 'undefined') {
3407         navigator.geolocation = navigator._geo;
3408         Geolocation.usingPhoneGap = true;
3409     }
3410 });
3411 }
3412
3413
3414 /*
3415  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
3416  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
3417  *
3418  * Copyright (c) 2005-2010, Nitobi Software Inc.
3419  * Copyright (c) 2010, IBM Corporation
3420  */
3421
3422
3423 /*
3424  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
3425  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
3426  *
3427  * Copyright (c) 2005-2010, Nitobi Software Inc.
3428  * Copyright (c) 2010-2011, IBM Corporation
3429  */
3430
3431 if (!PhoneGap.hasResource("media")) {
3432 PhoneGap.addResource("media");
3433
3434 /**
3435  * This class provides access to the device media, interfaces to both sound and video
3436  *
3437  * @constructor
3438  * @param src                   The file name or url to play
3439  * @param successCallback       The callback to be called when the file is done playing or recording.
3440  *                                  successCallback() - OPTIONAL
3441  * @param errorCallback         The callback to be called if there is an error.
3442  *                                  errorCallback(int errorCode) - OPTIONAL
3443  * @param statusCallback        The callback to be called when media status has changed.
3444  *                                  statusCallback(int statusCode) - OPTIONAL
3445  * @param positionCallback      The callback to be called when media position has changed.
3446  *                                  positionCallback(long position) - OPTIONAL
3447  */
3448 var Media = function(src, successCallback, errorCallback, statusCallback, positionCallback) {
3449
3450     // successCallback optional
3451     if (successCallback && (typeof successCallback !== "function")) {
3452         console.log("Media Error: successCallback is not a function");
3453         return;
3454     }
3455
3456     // errorCallback optional
3457     if (errorCallback && (typeof errorCallback !== "function")) {
3458         console.log("Media Error: errorCallback is not a function");
3459         return;
3460     }
3461
3462     // statusCallback optional
3463     if (statusCallback && (typeof statusCallback !== "function")) {
3464         console.log("Media Error: statusCallback is not a function");
3465         return;
3466     }
3467
3468     // statusCallback optional
3469     if (positionCallback && (typeof positionCallback !== "function")) {
3470         console.log("Media Error: positionCallback is not a function");
3471         return;
3472     }
3473
3474     this.id = PhoneGap.createUUID();
3475     PhoneGap.mediaObjects[this.id] = this;
3476     this.src = src;
3477     this.successCallback = successCallback;
3478     this.errorCallback = errorCallback;
3479     this.statusCallback = statusCallback;
3480     this.positionCallback = positionCallback;
3481     this._duration = -1;
3482     this._position = -1;
3483 };
3484
3485 // Media messages
3486 Media.MEDIA_STATE = 1;
3487 Media.MEDIA_DURATION = 2;
3488 Media.MEDIA_POSITION = 3;
3489 Media.MEDIA_ERROR = 9;
3490
3491 // Media states
3492 Media.MEDIA_NONE = 0;
3493 Media.MEDIA_STARTING = 1;
3494 Media.MEDIA_RUNNING = 2;
3495 Media.MEDIA_PAUSED = 3;
3496 Media.MEDIA_STOPPED = 4;
3497 Media.MEDIA_MSG = ["None", "Starting", "Running", "Paused", "Stopped"];
3498
3499 // TODO: Will MediaError be used?
3500 /**
3501  * This class contains information about any Media errors.
3502  * @constructor
3503  */
3504 var MediaError = function() {
3505     this.code = null;
3506     this.message = "";
3507 };
3508
3509 MediaError.MEDIA_ERR_ABORTED        = 1;
3510 MediaError.MEDIA_ERR_NETWORK        = 2;
3511 MediaError.MEDIA_ERR_DECODE         = 3;
3512 MediaError.MEDIA_ERR_NONE_SUPPORTED = 4;
3513
3514 /**
3515  * Start or resume playing audio file.
3516  */
3517 Media.prototype.play = function() {
3518     PhoneGap.exec(null, null, "Media", "startPlayingAudio", [this.id, this.src]);
3519 };
3520
3521 /**
3522  * Stop playing audio file.
3523  */
3524 Media.prototype.stop = function() {
3525     return PhoneGap.exec(null, null, "Media", "stopPlayingAudio", [this.id]);
3526 };
3527
3528 /**
3529  * Seek or jump to a new time in the track..
3530  */
3531 Media.prototype.seekTo = function(milliseconds) {
3532     PhoneGap.exec(null, null, "Media", "seekToAudio", [this.id, milliseconds]);
3533 };
3534
3535 /**
3536  * Pause playing audio file.
3537  */
3538 Media.prototype.pause = function() {
3539     PhoneGap.exec(null, null, "Media", "pausePlayingAudio", [this.id]);
3540 };
3541
3542 /**
3543  * Get duration of an audio file.
3544  * The duration is only set for audio that is playing, paused or stopped.
3545  *
3546  * @return      duration or -1 if not known.
3547  */
3548 Media.prototype.getDuration = function() {
3549     return this._duration;
3550 };
3551
3552 /**
3553  * Get position of audio.
3554  */
3555 Media.prototype.getCurrentPosition = function(success, fail) {
3556     PhoneGap.exec(success, fail, "Media", "getCurrentPositionAudio", [this.id]);
3557 };
3558
3559 /**
3560  * Start recording audio file.
3561  */
3562 Media.prototype.startRecord = function() {
3563     PhoneGap.exec(null, null, "Media", "startRecordingAudio", [this.id, this.src]);
3564 };
3565
3566 /**
3567  * Stop recording audio file.
3568  */
3569 Media.prototype.stopRecord = function() {
3570     PhoneGap.exec(null, null, "Media", "stopRecordingAudio", [this.id]);
3571 };
3572
3573 /**
3574  * Release the resources.
3575  */
3576 Media.prototype.release = function() {
3577     PhoneGap.exec(null, null, "Media", "release", [this.id]);
3578 };
3579
3580 /**
3581  * List of media objects.
3582  * PRIVATE
3583  */
3584 PhoneGap.mediaObjects = {};
3585
3586 /**
3587  * Object that receives native callbacks.
3588  * PRIVATE
3589  * @constructor
3590  */
3591 PhoneGap.Media = function() {};
3592
3593 /**
3594  * Get the media object.
3595  * PRIVATE
3596  *
3597  * @param id            The media object id (string)
3598  */
3599 PhoneGap.Media.getMediaObject = function(id) {
3600     return PhoneGap.mediaObjects[id];
3601 };
3602
3603 /**
3604  * Audio has status update.
3605  * PRIVATE
3606  *
3607  * @param id            The media object id (string)
3608  * @param status        The status code (int)
3609  * @param msg           The status message (string)
3610  */
3611 PhoneGap.Media.onStatus = function(id, msg, value) {
3612     var media = PhoneGap.mediaObjects[id];
3613     // If state update
3614     if (msg === Media.MEDIA_STATE) {
3615         if (value === Media.MEDIA_STOPPED) {
3616             if (media.successCallback) {
3617                 media.successCallback();
3618             }
3619         }
3620         if (media.statusCallback) {
3621             media.statusCallback(value);
3622         }
3623     }
3624     else if (msg === Media.MEDIA_DURATION) {
3625         media._duration = value;
3626     }
3627     else if (msg === Media.MEDIA_ERROR) {
3628         if (media.errorCallback) {
3629             media.errorCallback(value);
3630         }
3631     }
3632     else if (msg == Media.MEDIA_POSITION) {
3633         media._position = value;
3634     }
3635 };
3636 }
3637
3638
3639 /*
3640  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
3641  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
3642  *
3643  * Copyright (c) 2005-2010, Nitobi Software Inc.
3644  * Copyright (c) 2010-2011, IBM Corporation
3645  */
3646
3647 if (!PhoneGap.hasResource("network")) {
3648 PhoneGap.addResource("network");
3649
3650 /**
3651  * This class contains information about the current network Connection.
3652  * @constructor
3653  */
3654 var Connection = function() {
3655     this.type = null;
3656     this._firstRun = true;
3657     this._timer = null;
3658     this.timeout = 500;
3659
3660     var me = this;
3661     this.getInfo(
3662         function(type) {
3663             // Need to send events if we are on or offline
3664             if (type == "none") {
3665                 // set a timer if still offline at the end of timer send the offline event
3666                 me._timer = setTimeout(function(){
3667                     me.type = type;
3668                     PhoneGap.fireEvent('offline');
3669                     me._timer = null;
3670                     }, me.timeout);
3671             } else {
3672                 // If there is a current offline event pending clear it
3673                 if (me._timer != null) {
3674                     clearTimeout(me._timer);
3675                     me._timer = null;
3676                 }
3677                 me.type = type;
3678                 PhoneGap.fireEvent('online');
3679             }
3680             
3681             // should only fire this once
3682             if (me._firstRun) {
3683                 me._firstRun = false;
3684                 PhoneGap.onPhoneGapConnectionReady.fire();
3685             }            
3686         },
3687         function(e) {
3688             console.log("Error initializing Network Connection: " + e);
3689         });
3690 };
3691
3692 Connection.UNKNOWN = "unknown";
3693 Connection.ETHERNET = "ethernet";
3694 Connection.WIFI = "wifi";
3695 Connection.CELL_2G = "2g";
3696 Connection.CELL_3G = "3g";
3697 Connection.CELL_4G = "4g";
3698 Connection.NONE = "none";
3699
3700 /**
3701  * Get connection info
3702  *
3703  * @param {Function} successCallback The function to call when the Connection data is available
3704  * @param {Function} errorCallback The function to call when there is an error getting the Connection data. (OPTIONAL)
3705  */
3706 Connection.prototype.getInfo = function(successCallback, errorCallback) {
3707     // Get info
3708     PhoneGap.exec(successCallback, errorCallback, "Network Status", "getConnectionInfo", []);
3709 };
3710
3711
3712 PhoneGap.addConstructor(function() {
3713     if (typeof navigator.network === "undefined") {
3714         navigator.network = new Object();
3715     }
3716     if (typeof navigator.network.connection === "undefined") {
3717         navigator.network.connection = new Connection();
3718     }
3719 });
3720 }
3721
3722
3723 /*
3724  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
3725  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
3726  *
3727  * Copyright (c) 2005-2010, Nitobi Software Inc.
3728  * Copyright (c) 2010-2011, IBM Corporation
3729  */
3730
3731 if (!PhoneGap.hasResource("notification")) {
3732 PhoneGap.addResource("notification");
3733
3734 /**
3735  * This class provides access to notifications on the device.
3736  * @constructor
3737  */
3738 var Notification = function() {
3739 };
3740
3741 /**
3742  * Open a native alert dialog, with a customizable title and button text.
3743  *
3744  * @param {String} message              Message to print in the body of the alert
3745  * @param {Function} completeCallback   The callback that is called when user clicks on a button.
3746  * @param {String} title                Title of the alert dialog (default: Alert)
3747  * @param {String} buttonLabel          Label of the close button (default: OK)
3748  */
3749 Notification.prototype.alert = function(message, completeCallback, title, buttonLabel) {
3750     var _title = (title || "Alert");
3751     var _buttonLabel = (buttonLabel || "OK");
3752     PhoneGap.exec(completeCallback, null, "Notification", "alert", [message,_title,_buttonLabel]);
3753 };
3754
3755 /**
3756  * Open a native confirm dialog, with a customizable title and button text.
3757  * The result that the user selects is returned to the result callback.
3758  *
3759  * @param {String} message              Message to print in the body of the alert
3760  * @param {Function} resultCallback     The callback that is called when user clicks on a button.
3761  * @param {String} title                Title of the alert dialog (default: Confirm)
3762  * @param {String} buttonLabels         Comma separated list of the labels of the buttons (default: 'OK,Cancel')
3763  */
3764 Notification.prototype.confirm = function(message, resultCallback, title, buttonLabels) {
3765     var _title = (title || "Confirm");
3766     var _buttonLabels = (buttonLabels || "OK,Cancel");
3767     PhoneGap.exec(resultCallback, null, "Notification", "confirm", [message,_title,_buttonLabels]);
3768 };
3769
3770 /**
3771  * Start spinning the activity indicator on the statusbar
3772  */
3773 Notification.prototype.activityStart = function() {
3774     PhoneGap.exec(null, null, "Notification", "activityStart", ["Busy","Please wait..."]);
3775 };
3776
3777 /**
3778  * Stop spinning the activity indicator on the statusbar, if it's currently spinning
3779  */
3780 Notification.prototype.activityStop = function() {
3781     PhoneGap.exec(null, null, "Notification", "activityStop", []);
3782 };
3783
3784 /**
3785  * Display a progress dialog with progress bar that goes from 0 to 100.
3786  *
3787  * @param {String} title        Title of the progress dialog.
3788  * @param {String} message      Message to display in the dialog.
3789  */
3790 Notification.prototype.progressStart = function(title, message) {
3791     PhoneGap.exec(null, null, "Notification", "progressStart", [title, message]);
3792 };
3793
3794 /**
3795  * Set the progress dialog value.
3796  *
3797  * @param {Number} value         0-100
3798  */
3799 Notification.prototype.progressValue = function(value) {
3800     PhoneGap.exec(null, null, "Notification", "progressValue", [value]);
3801 };
3802
3803 /**
3804  * Close the progress dialog.
3805  */
3806 Notification.prototype.progressStop = function() {
3807     PhoneGap.exec(null, null, "Notification", "progressStop", []);
3808 };
3809
3810 /**
3811  * Causes the device to blink a status LED.
3812  *
3813  * @param {Integer} count       The number of blinks.
3814  * @param {String} colour       The colour of the light.
3815  */
3816 Notification.prototype.blink = function(count, colour) {
3817     // NOT IMPLEMENTED
3818 };
3819
3820 /**
3821  * Causes the device to vibrate.
3822  *
3823  * @param {Integer} mills       The number of milliseconds to vibrate for.
3824  */
3825 Notification.prototype.vibrate = function(mills) {
3826     PhoneGap.exec(null, null, "Notification", "vibrate", [mills]);
3827 };
3828
3829 /**
3830  * Causes the device to beep.
3831  * On Android, the default notification ringtone is played "count" times.
3832  *
3833  * @param {Integer} count       The number of beeps.
3834  */
3835 Notification.prototype.beep = function(count) {
3836     PhoneGap.exec(null, null, "Notification", "beep", [count]);
3837 };
3838
3839 PhoneGap.addConstructor(function() {
3840     if (typeof navigator.notification === "undefined") {
3841         navigator.notification = new Notification();
3842     }
3843 });
3844 }
3845
3846
3847 /*
3848  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
3849  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
3850  *
3851  * Copyright (c) 2005-2010, Nitobi Software Inc.
3852  * Copyright (c) 2010-2011, IBM Corporation
3853  */
3854
3855 if (!PhoneGap.hasResource("position")) {
3856 PhoneGap.addResource("position");
3857
3858 /**
3859  * This class contains position information.
3860  * @param {Object} lat
3861  * @param {Object} lng
3862  * @param {Object} acc
3863  * @param {Object} alt
3864  * @param {Object} altacc
3865  * @param {Object} head
3866  * @param {Object} vel
3867  * @constructor
3868  */
3869 var Position = function(coords, timestamp) {
3870         this.coords = coords;
3871         this.timestamp = (timestamp !== 'undefined') ? timestamp : new Date().getTime();
3872 };
3873
3874 /** @constructor */
3875 var Coordinates = function(lat, lng, alt, acc, head, vel, altacc) {
3876         /**
3877          * The latitude of the position.
3878          */
3879         this.latitude = lat;
3880         /**
3881          * The longitude of the position,
3882          */
3883         this.longitude = lng;
3884         /**
3885          * The accuracy of the position.
3886          */
3887         this.accuracy = acc;
3888         /**
3889          * The altitude of the position.
3890          */
3891         this.altitude = alt;
3892         /**
3893          * The direction the device is moving at the position.
3894          */
3895         this.heading = head;
3896         /**
3897          * The velocity with which the device is moving at the position.
3898          */
3899         this.speed = vel;
3900         /**
3901          * The altitude accuracy of the position.
3902          */
3903         this.altitudeAccuracy = (altacc !== 'undefined') ? altacc : null;
3904 };
3905
3906 /**
3907  * This class specifies the options for requesting position data.
3908  * @constructor
3909  */
3910 var PositionOptions = function() {
3911         /**
3912          * Specifies the desired position accuracy.
3913          */
3914         this.enableHighAccuracy = true;
3915         /**
3916          * The timeout after which if position data cannot be obtained the errorCallback
3917          * is called.
3918          */
3919         this.timeout = 10000;
3920 };
3921
3922 /**
3923  * This class contains information about any GSP errors.
3924  * @constructor
3925  */
3926 var PositionError = function() {
3927         this.code = null;
3928         this.message = "";
3929 };
3930
3931 PositionError.UNKNOWN_ERROR = 0;
3932 PositionError.PERMISSION_DENIED = 1;
3933 PositionError.POSITION_UNAVAILABLE = 2;
3934 PositionError.TIMEOUT = 3;
3935 }
3936
3937
3938 /*
3939  * PhoneGap is available under *either* the terms of the modified BSD license *or* the
3940  * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
3941  *
3942  * Copyright (c) 2005-2010, Nitobi Software Inc.
3943  * Copyright (c) 2010-2011, IBM Corporation
3944  */
3945
3946 /*
3947  * This is purely for the Android 1.5/1.6 HTML 5 Storage
3948  * I was hoping that Android 2.0 would deprecate this, but given the fact that
3949  * most manufacturers ship with Android 1.5 and do not do OTA Updates, this is required
3950  */
3951
3952 if (!PhoneGap.hasResource("storage")) {
3953 PhoneGap.addResource("storage");
3954
3955 /**
3956  * SQL result set object
3957  * PRIVATE METHOD
3958  * @constructor
3959  */
3960 var DroidDB_Rows = function() {
3961     this.resultSet = [];    // results array
3962     this.length = 0;        // number of rows
3963 };
3964
3965 /**
3966  * Get item from SQL result set
3967  *
3968  * @param row           The row number to return
3969  * @return              The row object
3970  */
3971 DroidDB_Rows.prototype.item = function(row) {
3972     return this.resultSet[row];
3973 };
3974
3975 /**
3976  * SQL result set that is returned to user.
3977  * PRIVATE METHOD
3978  * @constructor
3979  */
3980 var DroidDB_Result = function() {
3981     this.rows = new DroidDB_Rows();
3982 };
3983
3984 /**
3985  * Storage object that is called by native code when performing queries.
3986  * PRIVATE METHOD
3987  * @constructor
3988  */
3989 var DroidDB = function() {
3990     this.queryQueue = {};
3991 };
3992
3993 /**
3994  * Callback from native code when query is complete.
3995  * PRIVATE METHOD
3996  *
3997  * @param id                Query id
3998  */
3999 DroidDB.prototype.completeQuery = function(id, data) {
4000     var query = this.queryQueue[id];
4001     if (query) {
4002         try {
4003             delete this.queryQueue[id];
4004
4005             // Get transaction
4006             var tx = query.tx;
4007
4008             // If transaction hasn't failed
4009             // Note: We ignore all query results if previous query
4010             //       in the same transaction failed.
4011             if (tx && tx.queryList[id]) {
4012
4013                 // Save query results
4014                 var r = new DroidDB_Result();
4015                 r.rows.resultSet = data;
4016                 r.rows.length = data.length;
4017                 try {
4018                     if (typeof query.successCallback === 'function') {
4019                         query.successCallback(query.tx, r);
4020                     }
4021                 } catch (ex) {
4022                     console.log("executeSql error calling user success callback: "+ex);
4023                 }
4024
4025                 tx.queryComplete(id);
4026             }
4027         } catch (e) {
4028             console.log("executeSql error: "+e);
4029         }
4030     }
4031 };
4032
4033 /**
4034  * Callback from native code when query fails
4035  * PRIVATE METHOD
4036  *
4037  * @param reason            Error message
4038  * @param id                Query id
4039  */
4040 DroidDB.prototype.fail = function(reason, id) {
4041     var query = this.queryQueue[id];
4042     if (query) {
4043         try {
4044             delete this.queryQueue[id];
4045
4046             // Get transaction
4047             var tx = query.tx;
4048
4049             // If transaction hasn't failed
4050             // Note: We ignore all query results if previous query
4051             //       in the same transaction failed.
4052             if (tx && tx.queryList[id]) {
4053                 tx.queryList = {};
4054
4055                 try {
4056                     if (typeof query.errorCallback === 'function') {
4057                         query.errorCallback(query.tx, reason);
4058                     }
4059                 } catch (ex) {
4060                     console.log("executeSql error calling user error callback: "+ex);
4061                 }
4062
4063                 tx.queryFailed(id, reason);
4064             }
4065
4066         } catch (e) {
4067             console.log("executeSql error: "+e);
4068         }
4069     }
4070 };
4071
4072 /**
4073  * SQL query object
4074  * PRIVATE METHOD
4075  *
4076  * @constructor
4077  * @param tx                The transaction object that this query belongs to
4078  */
4079 var DroidDB_Query = function(tx) {
4080
4081     // Set the id of the query
4082     this.id = PhoneGap.createUUID();
4083
4084     // Add this query to the queue
4085     droiddb.queryQueue[this.id] = this;
4086
4087     // Init result
4088     this.resultSet = [];
4089
4090     // Set transaction that this query belongs to
4091     this.tx = tx;
4092
4093     // Add this query to transaction list
4094     this.tx.queryList[this.id] = this;
4095
4096     // Callbacks
4097     this.successCallback = null;
4098     this.errorCallback = null;
4099
4100 };
4101
4102 /**
4103  * Transaction object
4104  * PRIVATE METHOD
4105  * @constructor
4106  */
4107 var DroidDB_Tx = function() {
4108
4109     // Set the id of the transaction
4110     this.id = PhoneGap.createUUID();
4111
4112     // Callbacks
4113     this.successCallback = null;
4114     this.errorCallback = null;
4115
4116     // Query list
4117     this.queryList = {};
4118 };
4119
4120 /**
4121  * Mark query in transaction as complete.
4122  * If all queries are complete, call the user's transaction success callback.
4123  *
4124  * @param id                Query id
4125  */
4126 DroidDB_Tx.prototype.queryComplete = function(id) {
4127     delete this.queryList[id];
4128
4129     // If no more outstanding queries, then fire transaction success
4130     if (this.successCallback) {
4131         var count = 0;
4132         var i;
4133         for (i in this.queryList) {
4134             if (this.queryList.hasOwnProperty(i)) {
4135                 count++;
4136             }
4137         }
4138         if (count === 0) {
4139             try {
4140                 this.successCallback();
4141             } catch(e) {
4142                 console.log("Transaction error calling user success callback: " + e);
4143             }
4144         }
4145     }
4146 };
4147
4148 /**
4149  * Mark query in transaction as failed.
4150  *
4151  * @param id                Query id
4152  * @param reason            Error message
4153  */
4154 DroidDB_Tx.prototype.queryFailed = function(id, reason) {
4155
4156     // The sql queries in this transaction have already been run, since
4157     // we really don't have a real transaction implemented in native code.
4158     // However, the user callbacks for the remaining sql queries in transaction
4159     // will not be called.
4160     this.queryList = {};
4161
4162     if (this.errorCallback) {
4163         try {
4164             this.errorCallback(reason);
4165         } catch(e) {
4166             console.log("Transaction error calling user error callback: " + e);
4167         }
4168     }
4169 };
4170
4171 /**
4172  * Execute SQL statement
4173  *
4174  * @param sql                   SQL statement to execute
4175  * @param params                Statement parameters
4176  * @param successCallback       Success callback
4177  * @param errorCallback         Error callback
4178  */
4179 DroidDB_Tx.prototype.executeSql = function(sql, params, successCallback, errorCallback) {
4180
4181     // Init params array
4182     if (typeof params === 'undefined') {
4183         params = [];
4184     }
4185
4186     // Create query and add to queue
4187     var query = new DroidDB_Query(this);
4188     droiddb.queryQueue[query.id] = query;
4189
4190     // Save callbacks
4191     query.successCallback = successCallback;
4192     query.errorCallback = errorCallback;
4193
4194     // Call native code
4195     PhoneGap.exec(null, null, "Storage", "executeSql", [sql, params, query.id]);
4196 };
4197
4198 var DatabaseShell = function() {
4199 };
4200
4201 /**
4202  * Start a transaction.
4203  * Does not support rollback in event of failure.
4204  *
4205  * @param process {Function}            The transaction function
4206  * @param successCallback {Function}
4207  * @param errorCallback {Function}
4208  */
4209 DatabaseShell.prototype.transaction = function(process, errorCallback, successCallback) {
4210     var tx = new DroidDB_Tx();
4211     tx.successCallback = successCallback;
4212     tx.errorCallback = errorCallback;
4213     try {
4214         process(tx);
4215     } catch (e) {
4216         console.log("Transaction error: "+e);
4217         if (tx.errorCallback) {
4218             try {
4219                 tx.errorCallback(e);
4220             } catch (ex) {
4221                 console.log("Transaction error calling user error callback: "+e);
4222             }
4223         }
4224     }
4225 };
4226
4227 /**
4228  * Open database
4229  *
4230  * @param name              Database name
4231  * @param version           Database version
4232  * @param display_name      Database display name
4233  * @param size              Database size in bytes
4234  * @return                  Database object
4235  */
4236 var DroidDB_openDatabase = function(name, version, display_name, size) {
4237     PhoneGap.exec(null, null, "Storage", "openDatabase", [name, version, display_name, size]);
4238     var db = new DatabaseShell();
4239     return db;
4240 };
4241
4242 /**
4243  * For browsers with no localStorage we emulate it with SQLite. Follows the w3c api.
4244  * TODO: Do similar for sessionStorage.
4245  */
4246
4247 /**
4248  * @constructor
4249  */
4250 var CupcakeLocalStorage = function() {
4251                 try {
4252
4253                         this.db = openDatabase('localStorage', '1.0', 'localStorage', 2621440);
4254                         var storage = {};
4255                         this.length = 0;
4256                         function setLength (length) {
4257                                 this.length = length;
4258                                 localStorage.length = length;
4259                         }
4260                         this.db.transaction(
4261                                 function (transaction) {
4262                                     var i;
4263                                         transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))');
4264                                         transaction.executeSql('SELECT * FROM storage', [], function(tx, result) {
4265                                                 for(var i = 0; i < result.rows.length; i++) {
4266                                                         storage[result.rows.item(i)['id']] =  result.rows.item(i)['body'];
4267                                                 }
4268                                                 setLength(result.rows.length);
4269                                                 PhoneGap.initializationComplete("cupcakeStorage");
4270                                         });
4271
4272                                 },
4273                                 function (err) {
4274                                         alert(err.message);
4275                                 }
4276                         );
4277                         this.setItem = function(key, val) {
4278                                 if (typeof(storage[key])=='undefined') {
4279                                         this.length++;
4280                                 }
4281                                 storage[key] = val;
4282                                 this.db.transaction(
4283                                         function (transaction) {
4284                                                 transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))');
4285                                                 transaction.executeSql('REPLACE INTO storage (id, body) values(?,?)', [key,val]);
4286                                         }
4287                                 );
4288                         };
4289                         this.getItem = function(key) {
4290                                 return storage[key];
4291                         };
4292                         this.removeItem = function(key) {
4293                                 delete storage[key];
4294                                 this.length--;
4295                                 this.db.transaction(
4296                                         function (transaction) {
4297                                                 transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))');
4298                                                 transaction.executeSql('DELETE FROM storage where id=?', [key]);
4299                                         }
4300                                 );
4301                         };
4302                         this.clear = function() {
4303                                 storage = {};
4304                                 this.length = 0;
4305                                 this.db.transaction(
4306                                         function (transaction) {
4307                                                 transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))');
4308                                                 transaction.executeSql('DELETE FROM storage', []);
4309                                         }
4310                                 );
4311                         };
4312                         this.key = function(index) {
4313                                 var i = 0;
4314                                 for (var j in storage) {
4315                                         if (i==index) {
4316                                                 return j;
4317                                         } else {
4318                                                 i++;
4319                                         }
4320                                 }
4321                                 return null;
4322                         };
4323
4324                 } catch(e) {
4325                         alert("Database error "+e+".");
4326                     return;
4327                 }
4328 };
4329
4330 PhoneGap.addConstructor(function() {
4331     var setupDroidDB = function() {
4332         navigator.openDatabase = window.openDatabase = DroidDB_openDatabase;
4333         window.droiddb = new DroidDB();
4334     }
4335     if (typeof window.openDatabase === "undefined") {
4336         setupDroidDB();
4337     } else {
4338         window.openDatabase_orig = window.openDatabase;
4339         window.openDatabase = function(name, version, desc, size){
4340             // Some versions of Android will throw a SECURITY_ERR so we need 
4341             // to catch the exception and seutp our own DB handling.
4342             var db = null;
4343             try {
4344                 db = window.openDatabase_orig(name, version, desc, size);
4345             } 
4346             catch (ex) {
4347                 db = null;
4348             }
4349
4350             if (db == null) {
4351                 setupDroidDB();
4352                 return DroidDB_openDatabase(name, version, desc, size);
4353             }
4354             else {
4355                 return db;
4356             }
4357         }
4358     }
4359     
4360     if (typeof window.localStorage === "undefined") {
4361         navigator.localStorage = window.localStorage = new CupcakeLocalStorage();
4362         PhoneGap.waitForInitialization("cupcakeStorage");
4363     }
4364 });
4365 }
4366
4367