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.
5 * Copyright (c) 2005-2010, Nitobi Software Inc.
6 * Copyright (c) 2010-2011, IBM Corporation
9 if (typeof PhoneGap === "undefined") {
12 * The order of events during page load and PhoneGap startup is as follows:
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).
25 * The only PhoneGap events that user code should register for are:
29 * Listeners can be registered as:
30 * document.addEventListener("deviceready", myDeviceReadyListener, false);
31 * document.addEventListener("resume", myResumeListener, false);
32 * document.addEventListener("pause", myPauseListener, false);
35 if (typeof(DeviceInfo) !== 'object') {
40 * This represents the PhoneGap API itself, and provides a global namespace for accessing
41 * information about the state of PhoneGap.
53 * List of resource files loaded by PhoneGap.
54 * This is used to ensure JS and other files are loaded only once.
56 PhoneGap.resources = {base: true};
59 * Determine if resource has been loaded by PhoneGap
64 PhoneGap.hasResource = function(name) {
65 return PhoneGap.resources[name];
69 * Add a resource to list of loaded resources by PhoneGap
73 PhoneGap.addResource = function(name) {
74 PhoneGap.resources[name] = true;
78 * Custom pub-sub channel that can have functions subscribed to it
81 PhoneGap.Channel = function (type)
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.
97 PhoneGap.Channel.prototype.subscribe = function(f, c, g) {
98 // need a function to call
99 if (f === null) { return; }
102 if (typeof c === "object" && typeof f === "function") { func = PhoneGap.close(c, f); }
104 g = g || func.observer_guid || f.observer_guid || this.guid++;
105 func.observer_guid = g;
107 this.handlers[g] = func;
112 * Like subscribe but the function is only called once and then it
113 * auto-unsubscribes itself.
115 PhoneGap.Channel.prototype.subscribeOnce = function(f, c) {
119 f.apply(c || null, arguments);
120 _this.unsubscribe(g);
123 if (typeof c === "object" && typeof f === "function") { f = PhoneGap.close(c, f); }
124 f.apply(this, this.fireArgs);
126 g = this.subscribe(m);
132 * Unsubscribes the function with the given guid from the channel.
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];
141 * Calls all functions subscribed to this channel.
143 PhoneGap.Channel.prototype.fire = function(e) {
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);
157 this.fireArgs = arguments;
164 * Calls the provided function only after all of the channels specified
167 PhoneGap.Channel.join = function(h, c) {
176 for (j=0; j<len; j++) {
178 c[j].subscribeOnce(f);
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;
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
199 PhoneGap.addConstructor = function(func) {
200 PhoneGap.onPhoneGapInit.subscribeOnce(function() {
204 console.log("Failed to run constructor: " + e);
212 if (!window.plugins) {
217 * Adds a plugin object to window.plugins.
218 * The plugin is accessed using window.plugins.<name>
220 * @param name The plugin name
221 * @param obj The plugin object
223 PhoneGap.addPlugin = function(name, obj) {
224 if (!window.plugins[name]) {
225 window.plugins[name] = obj;
228 console.log("Error: Plugin "+name+" already exists.");
233 * onDOMContentLoaded channel is fired when the DOM content
234 * of the page has been parsed.
236 PhoneGap.onDOMContentLoaded = new PhoneGap.Channel('onDOMContentLoaded');
239 * onNativeReady channel is fired when the PhoneGap native code
240 * has been initialized.
242 PhoneGap.onNativeReady = new PhoneGap.Channel('onNativeReady');
245 * onPhoneGapInit channel is fired when the web page is fully loaded and
246 * PhoneGap native code has been initialized.
248 PhoneGap.onPhoneGapInit = new PhoneGap.Channel('onPhoneGapInit');
251 * onPhoneGapReady channel is fired when the JS PhoneGap objects have been created.
253 PhoneGap.onPhoneGapReady = new PhoneGap.Channel('onPhoneGapReady');
256 * onPhoneGapInfoReady channel is fired when the PhoneGap device properties
259 PhoneGap.onPhoneGapInfoReady = new PhoneGap.Channel('onPhoneGapInfoReady');
262 * onPhoneGapConnectionReady channel is fired when the PhoneGap connection properties
265 PhoneGap.onPhoneGapConnectionReady = new PhoneGap.Channel('onPhoneGapConnectionReady');
268 * onResume channel is fired when the PhoneGap native code
271 PhoneGap.onResume = new PhoneGap.Channel('onResume');
274 * onPause channel is fired when the PhoneGap native code
277 PhoneGap.onPause = new PhoneGap.Channel('onPause');
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.
284 PhoneGap.onDestroy = new PhoneGap.Channel('onDestroy');
285 PhoneGap.onDestroy.subscribeOnce(function() {
286 PhoneGap.shuttingDown = true;
288 PhoneGap.shuttingDown = false;
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(); }
296 * onDeviceReady is fired only after all PhoneGap objects are created and
297 * the device properties are set.
299 PhoneGap.onDeviceReady = new PhoneGap.Channel('onDeviceReady');
302 // Array of channels that must fire before "deviceready" is fired
303 PhoneGap.deviceReadyChannelsArray = [ PhoneGap.onPhoneGapReady, PhoneGap.onPhoneGapInfoReady, PhoneGap.onPhoneGapConnectionReady];
305 // Hashtable of user defined channels that must also fire before "deviceready" is fired
306 PhoneGap.deviceReadyChannelsMap = {};
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.
313 * @param feature {String} The unique feature name
315 PhoneGap.waitForInitialization = function(feature) {
317 var channel = new PhoneGap.Channel(feature);
318 PhoneGap.deviceReadyChannelsMap[feature] = channel;
319 PhoneGap.deviceReadyChannelsArray.push(channel);
324 * Indicate that initialization code has completed and the feature is ready to be used.
326 * @param feature {String} The unique feature name
328 PhoneGap.initializationComplete = function(feature) {
329 var channel = PhoneGap.deviceReadyChannelsMap[feature];
336 * Create all PhoneGap objects once page has fully loaded and native side is ready.
338 PhoneGap.Channel.join(function() {
340 // Start listening for XHR callbacks
341 setTimeout(function() {
342 if (PhoneGap.UsePolling) {
343 PhoneGap.JSCallbackPolling();
346 var polling = prompt("usePolling", "gap_callbackServer:");
347 PhoneGap.UsePolling = polling;
348 if (polling == "true") {
349 PhoneGap.UsePolling = true;
350 PhoneGap.JSCallbackPolling();
353 PhoneGap.UsePolling = false;
354 PhoneGap.JSCallback();
359 // Run PhoneGap constructors
360 PhoneGap.onPhoneGapInit.fire();
362 // Fire event to notify that all objects are created
363 PhoneGap.onPhoneGapReady.fire();
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();
370 // Fire the onresume event, since first one happens before JavaScript is loaded
371 PhoneGap.onResume.fire();
372 }, PhoneGap.deviceReadyChannelsArray);
374 }, [ PhoneGap.onDOMContentLoaded, PhoneGap.onNativeReady ]);
376 // Listen for DOMContentLoaded and notify our channel subscribers
377 document.addEventListener('DOMContentLoaded', function() {
378 PhoneGap.onDOMContentLoaded.fire();
381 // Intercept calls to document.addEventListener and watch for deviceready
382 PhoneGap.m_document_addEventListener = document.addEventListener;
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();
393 } else if (e === 'pause') {
394 PhoneGap.onPause.subscribe(handler);
397 // If subscribing to Android backbutton
398 if (e === 'backbutton') {
399 PhoneGap.exec(null, null, "App", "overrideBackbutton", [true]);
402 PhoneGap.m_document_addEventListener.call(document, evt, handler, capture);
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;
410 document.removeEventListener = function(evt, handler, capture) {
411 var e = evt.toLowerCase();
413 // If unsubscribing to Android backbutton
414 if (e === 'backbutton') {
415 PhoneGap.exec(null, null, "App", "overrideBackbutton", [false]);
418 PhoneGap.m_document_removeEventListener.call(document, evt, handler, capture);
422 * Method to fire event from native code
424 PhoneGap.fireEvent = function(type) {
425 var e = document.createEvent('Events');
427 document.dispatchEvent(e);
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.
437 PhoneGap.stringify = function(args) {
438 if (typeof JSON === "undefined") {
440 var i, type, start, name, nameType, a;
441 for (i = 0; i < args.length; i++) {
442 if (args[i] !== null) {
446 type = typeof args[i];
447 if ((type === "number") || (type === "boolean")) {
449 } else if (args[i] instanceof Array) {
450 s = s + "[" + args[i] + "]";
451 } else if (args[i] instanceof Object) {
454 for (name in args[i]) {
455 if (args[i][name] !== null) {
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
466 } else if (args[i][name] instanceof Object) {
467 s = s + PhoneGap.stringify(args[i][name]);
469 s = s + '"' + args[i][name] + '"';
476 a = args[i].replace(/\\/g, '\\\\');
477 a = a.replace(/"/g, '\\"');
478 s = s + '"' + a + '"';
485 return JSON.stringify(args);
490 * Does a deep clone of the object.
495 PhoneGap.clone = function(obj) {
501 if(obj instanceof Array){
503 for(i = 0; i < obj.length; ++i){
504 retVal.push(PhoneGap.clone(obj[i]));
509 if (typeof obj === "function") {
513 if(!(obj instanceof Object)){
517 if (obj instanceof Date) {
523 if(!(i in retVal) || retVal[i] !== obj[i]) {
524 retVal[i] = PhoneGap.clone(obj[i]);
530 PhoneGap.callbackId = 0;
531 PhoneGap.callbacks = {};
532 PhoneGap.callbackStatus = {
535 CLASS_NOT_FOUND_EXCEPTION: 2,
536 ILLEGAL_ACCESS_EXCEPTION: 3,
537 INSTANTIATION_EXCEPTION: 4,
538 MALFORMED_URL_EXCEPTION: 5,
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.
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
560 PhoneGap.exec = function(success, fail, service, action, args) {
562 var callbackId = service + PhoneGap.callbackId++;
563 if (success || fail) {
564 PhoneGap.callbacks[callbackId] = {success:success, fail:fail};
567 var r = prompt(PhoneGap.stringify(args), "gap:"+PhoneGap.stringify([service, action, callbackId, true]));
569 // If a result was returned
571 eval("var v="+r+";");
573 // If status is OK, then return value back to caller
574 if (v.status === PhoneGap.callbackStatus.OK) {
576 // If there is a success callback, then call it now with
582 console.log("Error in success callback: " + callbackId + " = " + e);
585 // Clear callback if not expecting any more results
586 if (!v.keepCallback) {
587 delete PhoneGap.callbacks[callbackId];
594 else if (v.status === PhoneGap.callbackStatus.NO_RESULT) {
596 // Clear callback if not expecting any more results
597 if (!v.keepCallback) {
598 delete PhoneGap.callbacks[callbackId];
602 // If error, then display error
604 console.log("Error: Status="+v.status+" Message="+v.message);
606 // If there is a fail callback, then call it now with returned value
612 console.log("Error in error callback: "+callbackId+" = "+e1);
615 // Clear callback if not expecting any more results
616 if (!v.keepCallback) {
617 delete PhoneGap.callbacks[callbackId];
624 console.log("Error: "+e2);
629 * Called by native code when returning successful result from an action.
634 PhoneGap.callbackSuccess = function(callbackId, args) {
635 if (PhoneGap.callbacks[callbackId]) {
637 // If result is to be sent to callback
638 if (args.status === PhoneGap.callbackStatus.OK) {
640 if (PhoneGap.callbacks[callbackId].success) {
641 PhoneGap.callbacks[callbackId].success(args.message);
645 console.log("Error in success callback: "+callbackId+" = "+e);
649 // Clear callback if not expecting any more results
650 if (!args.keepCallback) {
651 delete PhoneGap.callbacks[callbackId];
657 * Called by native code when returning error result from an action.
662 PhoneGap.callbackError = function(callbackId, args) {
663 if (PhoneGap.callbacks[callbackId]) {
665 if (PhoneGap.callbacks[callbackId].fail) {
666 PhoneGap.callbacks[callbackId].fail(args.message);
670 console.log("Error in error callback: "+callbackId+" = "+e);
673 // Clear callback if not expecting any more results
674 if (!args.keepCallback) {
675 delete PhoneGap.callbacks[callbackId];
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.
688 // TODO: Is this used?
689 PhoneGap.run_command = function() {
690 if (!PhoneGap.available || !PhoneGap.queue.ready) {
693 PhoneGap.queue.ready = false;
695 var args = PhoneGap.queue.commands.shift();
696 if (PhoneGap.queue.commands.length === 0) {
697 clearInterval(PhoneGap.queue.timer);
698 PhoneGap.queue.timer = null;
704 for (i = 1; i < args.length; i++) {
706 if (arg === undefined || arg === null) {
709 if (typeof(arg) === 'object') {
712 uri.push(encodeURIComponent(arg));
715 var url = "gap://" + args[0] + "/" + uri.join("/");
720 if (dict.hasOwnProperty(name) && (typeof (name) === 'string')) {
721 query_args.push(encodeURIComponent(name) + "=" + encodeURIComponent(dict[name]));
724 if (query_args.length > 0) {
725 url += "?" + query_args.join("&");
728 document.location = url;
732 PhoneGap.JSCallbackPort = null;
733 PhoneGap.JSCallbackToken = null;
736 * This is only for Android.
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.
742 PhoneGap.JSCallback = function() {
744 // Exit if shutting down app
745 if (PhoneGap.shuttingDown) {
749 // If polling flag was changed, start using polling from now on
750 if (PhoneGap.UsePolling) {
751 PhoneGap.JSCallbackPolling();
755 var xmlhttp = new XMLHttpRequest();
757 // Callback function when XMLHttpRequest is ready
758 xmlhttp.onreadystatechange=function(){
759 if(xmlhttp.readyState === 4){
761 // Exit if shutting down app
762 if (PhoneGap.shuttingDown) {
766 // If callback has JavaScript statement to execute
767 if (xmlhttp.status === 200) {
769 // Need to url decode the response
770 var msg = decodeURIComponent(xmlhttp.responseText);
771 setTimeout(function() {
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);
781 setTimeout(PhoneGap.JSCallback, 1);
784 // If callback ping (used to keep XHR request from timing out)
785 else if (xmlhttp.status === 404) {
786 setTimeout(PhoneGap.JSCallback, 10);
790 else if (xmlhttp.status === 403) {
791 console.log("JSCallback Error: Invalid token. Stopping callbacks.");
794 // If server is stopping
795 else if (xmlhttp.status === 503) {
796 console.log("JSCallback Error: Service unavailable. Stopping callbacks.");
799 // If request wasn't GET
800 else if (xmlhttp.status === 400) {
801 console.log("JSCallback Error: Bad request. Stopping callbacks.");
804 // If error, revert to polling
806 console.log("JSCallback Error: Request failed.");
807 PhoneGap.UsePolling = true;
808 PhoneGap.JSCallbackPolling();
813 if (PhoneGap.JSCallbackPort === null) {
814 PhoneGap.JSCallbackPort = prompt("getPort", "gap_callbackServer:");
816 if (PhoneGap.JSCallbackToken === null) {
817 PhoneGap.JSCallbackToken = prompt("getToken", "gap_callbackServer:");
819 xmlhttp.open("GET", "http://127.0.0.1:"+PhoneGap.JSCallbackPort+"/"+PhoneGap.JSCallbackToken , true);
824 * The polling period to use with JSCallbackPolling.
825 * This can be changed by the application. The default is 50ms.
827 PhoneGap.JSCallbackPollingPeriod = 50;
830 * Flag that can be set by the user to force polling to be used or force XHR to be used.
832 PhoneGap.UsePolling = false; // T=use polling, F=use XHR
835 * This is only for Android.
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.
841 PhoneGap.JSCallbackPolling = function() {
843 // Exit if shutting down app
844 if (PhoneGap.shuttingDown) {
848 // If polling flag was changed, stop using polling from now on
849 if (!PhoneGap.UsePolling) {
850 PhoneGap.JSCallback();
854 var msg = prompt("", "gap_poll:");
856 setTimeout(function() {
858 var t = eval(""+msg);
861 console.log("JSCallbackPolling: Message from Server: " + msg);
862 console.log("JSCallbackPolling Error: "+e);
865 setTimeout(PhoneGap.JSCallbackPolling, 1);
868 setTimeout(PhoneGap.JSCallbackPolling, PhoneGap.JSCallbackPollingPeriod);
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);
885 PhoneGap.UUIDcreatePart = function(length) {
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;
893 uuidpart += uuidchar;
898 PhoneGap.close = function(context, func, params) {
899 if (typeof params === 'undefined') {
901 return func.apply(context, arguments);
905 return func.apply(context, params);
911 * Load a JavaScript file after page has loaded.
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.
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;
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.
932 * Copyright (c) 2005-2010, Nitobi Software Inc.
933 * Copyright (c) 2010-2011, IBM Corporation
936 if (!PhoneGap.hasResource("accelerometer")) {
937 PhoneGap.addResource("accelerometer");
940 var Acceleration = function(x, y, z) {
944 this.timestamp = new Date().getTime();
948 * This class provides access to device accelerometer data.
951 var Accelerometer = function() {
954 * The last known acceleration. type=Acceleration()
956 this.lastAcceleration = null;
959 * List of accelerometer watch timers
964 Accelerometer.ERROR_MSG = ["Not running", "Starting", "", "Failed to start"];
967 * Asynchronously aquires the current acceleration.
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)
973 Accelerometer.prototype.getCurrentAcceleration = function(successCallback, errorCallback, options) {
975 // successCallback required
976 if (typeof successCallback !== "function") {
977 console.log("Accelerometer Error: successCallback is not a function");
981 // errorCallback optional
982 if (errorCallback && (typeof errorCallback !== "function")) {
983 console.log("Accelerometer Error: errorCallback is not a function");
988 PhoneGap.exec(successCallback, errorCallback, "Accelerometer", "getAcceleration", []);
992 * Asynchronously aquires the acceleration repeatedly at a given interval.
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.
999 Accelerometer.prototype.watchAcceleration = function(successCallback, errorCallback, options) {
1001 // Default interval (10 sec)
1002 var frequency = (options !== undefined)? options.frequency : 10000;
1004 // successCallback required
1005 if (typeof successCallback !== "function") {
1006 console.log("Accelerometer Error: successCallback is not a function");
1010 // errorCallback optional
1011 if (errorCallback && (typeof errorCallback !== "function")) {
1012 console.log("Accelerometer Error: errorCallback is not a function");
1016 // Make sure accelerometer timeout > frequency + 10 sec
1019 if (timeout < (frequency + 10000)) {
1020 PhoneGap.exec(null, null, "Accelerometer", "setTimeout", [frequency + 10000]);
1023 function(e) { }, "Accelerometer", "getTimeout", []);
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));
1035 * Clears the specified accelerometer watch.
1037 * @param {String} id The id of the watch returned from #watchAcceleration.
1039 Accelerometer.prototype.clearWatch = function(id) {
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];
1048 PhoneGap.addConstructor(function() {
1049 if (typeof navigator.accelerometer === "undefined") {
1050 navigator.accelerometer = new Accelerometer();
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.
1060 * Copyright (c) 2005-2010, Nitobi Software Inc.
1061 * Copyright (c) 2010-2011, IBM Corporation
1064 if (!PhoneGap.hasResource("app")) {
1065 PhoneGap.addResource("app");
1072 var App = function() {};
1075 * Clear the resource cache.
1077 App.prototype.clearCache = function() {
1078 PhoneGap.exec(null, null, "App", "clearCache", []);
1082 * Load the url into the webview.
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
1095 * App app = new App();
1096 * app.loadUrl("http://server/myapp/index.html", {wait:2000, loadingDialog:"Wait,Loading App", loadUrlTimeoutValue: 60000});
1098 App.prototype.loadUrl = function(url, props) {
1099 PhoneGap.exec(null, null, "App", "loadUrl", [url, props]);
1103 * Cancel loadUrl that is waiting to be loaded.
1105 App.prototype.cancelLoadUrl = function() {
1106 PhoneGap.exec(null, null, "App", "cancelLoadUrl", []);
1110 * Clear web history in this web view.
1111 * Instead of BACK button loading the previous web page, it will exit the app.
1113 App.prototype.clearHistory = function() {
1114 PhoneGap.exec(null, null, "App", "clearHistory", []);
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.
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.
1124 * @param override T=override, F=cancel override
1126 App.prototype.overrideBackbutton = function(override) {
1127 PhoneGap.exec(null, null, "App", "overrideBackbutton", [override]);
1131 * Exit and terminate the application.
1133 App.prototype.exitApp = function() {
1134 return PhoneGap.exec(null, null, "App", "exitApp", []);
1137 PhoneGap.addConstructor(function() {
1138 navigator.app = new App();
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.
1148 * Copyright (c) 2005-2010, Nitobi Software Inc.
1149 * Copyright (c) 2010-2011, IBM Corporation
1152 if (!PhoneGap.hasResource("camera")) {
1153 PhoneGap.addResource("camera");
1156 * This class provides access to the device camera.
1160 var Camera = function() {
1161 this.successCallback = null;
1162 this.errorCallback = null;
1163 this.options = null;
1167 * Format of image that returned from getPicture.
1169 * Example: navigator.camera.getPicture(success, fail,
1171 * destinationType: Camera.DestinationType.DATA_URL,
1172 * sourceType: Camera.PictureSourceType.PHOTOLIBRARY})
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)
1178 Camera.prototype.DestinationType = Camera.DestinationType;
1181 * Encoding of image returned from getPicture.
1183 * Example: navigator.camera.getPicture(success, fail,
1185 * destinationType: Camera.DestinationType.DATA_URL,
1186 * sourceType: Camera.PictureSourceType.CAMERA,
1187 * encodingType: Camera.EncodingType.PNG})
1189 Camera.EncodingType = {
1190 JPEG: 0, // Return JPEG encoded image
1191 PNG: 1 // Return PNG encoded image
1193 Camera.prototype.EncodingType = Camera.EncodingType;
1196 * Source to getPicture from.
1198 * Example: navigator.camera.getPicture(success, fail,
1200 * destinationType: Camera.DestinationType.DATA_URL,
1201 * sourceType: Camera.PictureSourceType.PHOTOLIBRARY})
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)
1208 Camera.prototype.PictureSourceType = Camera.PictureSourceType;
1211 * Gets a picture from source defined by "options.sourceType", and returns the
1212 * image as defined by the "options.destinationType" option.
1214 * The defaults are sourceType=CAMERA and destinationType=DATA_URL.
1216 * @param {Function} successCallback
1217 * @param {Function} errorCallback
1218 * @param {Object} options
1220 Camera.prototype.getPicture = function(successCallback, errorCallback, options) {
1222 // successCallback required
1223 if (typeof successCallback !== "function") {
1224 console.log("Camera Error: successCallback is not a function");
1228 // errorCallback optional
1229 if (errorCallback && (typeof errorCallback !== "function")) {
1230 console.log("Camera Error: errorCallback is not a function");
1234 this.options = options;
1236 if (options.quality) {
1237 quality = this.options.quality;
1240 var maxResolution = 0;
1241 if (options.maxResolution) {
1242 maxResolution = this.options.maxResolution;
1245 var destinationType = Camera.DestinationType.DATA_URL;
1246 if (this.options.destinationType) {
1247 destinationType = this.options.destinationType;
1249 var sourceType = Camera.PictureSourceType.CAMERA;
1250 if (typeof this.options.sourceType === "number") {
1251 sourceType = this.options.sourceType;
1253 var encodingType = Camera.EncodingType.JPEG;
1254 if (typeof options.encodingType == "number") {
1255 encodingType = this.options.encodingType;
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();
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();
1278 PhoneGap.exec(successCallback, errorCallback, "Camera", "takePicture", [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType]);
1281 PhoneGap.addConstructor(function() {
1282 if (typeof navigator.camera === "undefined") {
1283 navigator.camera = new Camera();
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.
1293 * Copyright (c) 2005-2010, Nitobi Software Inc.
1294 * Copyright (c) 2010-2011, IBM Corporation
1297 if (!PhoneGap.hasResource("capture")) {
1298 PhoneGap.addResource("capture");
1301 * Represents a single file.
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
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;
1318 * Launch device camera application for recording video(s).
1320 * @param {Function} successCB
1321 * @param {Function} errorCB
1323 MediaFile.prototype.getFormatData = function(successCallback, errorCallback){
1324 PhoneGap.exec(successCallback, errorCallback, "Capture", "getFormatData", [this.fullPath, this.type]);
1328 * MediaFileData encapsulates format information of a media file.
1330 * @param {DOMString} codecs
1331 * @param {long} bitrate
1332 * @param {long} height
1333 * @param {long} width
1334 * @param {float} duration
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;
1345 * The CaptureError interface encapsulates all errors in the Capture API.
1347 var CaptureError = function(){
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;
1359 * The Capture interface exposes an interface to the camera and microphone of the hosting device.
1361 var Capture = function(){
1362 this.supportedAudioModes = [];
1363 this.supportedImageModes = [];
1364 this.supportedVideoModes = [];
1368 * Launch audio recorder application for recording audio clip(s).
1370 * @param {Function} successCB
1371 * @param {Function} errorCB
1372 * @param {CaptureAudioOptions} options
1374 Capture.prototype.captureAudio = function(successCallback, errorCallback, options){
1375 PhoneGap.exec(successCallback, errorCallback, "Capture", "captureAudio", [options]);
1379 * Launch camera application for taking image(s).
1381 * @param {Function} successCB
1382 * @param {Function} errorCB
1383 * @param {CaptureImageOptions} options
1385 Capture.prototype.captureImage = function(successCallback, errorCallback, options){
1386 PhoneGap.exec(successCallback, errorCallback, "Capture", "captureImage", [options]);
1390 * Launch camera application for taking image(s).
1392 * @param {Function} successCB
1393 * @param {Function} errorCB
1394 * @param {CaptureImageOptions} options
1396 Capture.prototype._castMediaFile = function(pluginResult){
1397 var mediaFiles = [];
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);
1408 pluginResult.message = mediaFiles;
1409 return pluginResult;
1413 * Launch device camera application for recording video(s).
1415 * @param {Function} successCB
1416 * @param {Function} errorCB
1417 * @param {CaptureVideoOptions} options
1419 Capture.prototype.captureVideo = function(successCallback, errorCallback, options){
1420 PhoneGap.exec(successCallback, errorCallback, "Capture", "captureVideo", [options]);
1424 * Encapsulates a set of parameters that the capture device supports.
1426 var ConfigurationData = function(){
1427 // The ASCII-encoded string in lower case representing the media type.
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.
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
1438 * Encapsulates all image capture operation configuration options.
1440 var CaptureImageOptions = function(){
1441 // Upper limit of images user can take. Value must be equal or greater than 1.
1443 // The selected image mode. Must match with one of the elements in supportedImageModes array.
1448 * Encapsulates all video capture operation configuration options.
1450 var CaptureVideoOptions = function(){
1451 // Upper limit of videos user can record. Value must be equal or greater than 1.
1453 // Maximum duration of a single video clip in seconds.
1455 // The selected video mode. Must match with one of the elements in supportedVideoModes array.
1460 * Encapsulates all audio capture operation configuration options.
1462 var CaptureAudioOptions = function(){
1463 // Upper limit of sound clips user can record. Value must be equal or greater than 1.
1465 // Maximum duration of a single sound clip in seconds.
1467 // The selected audio mode. Must match with one of the elements in supportedAudioModes array.
1471 PhoneGap.addConstructor(function(){
1472 if (typeof navigator.device === "undefined") {
1473 navigator.device = window.device = new Device();
1475 if (typeof navigator.device.capture === "undefined") {
1476 navigator.device.capture = window.device.capture = new Capture();
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.
1485 * Copyright (c) 2005-2010, Nitobi Software Inc.
1486 * Copyright (c) 2010-2011, IBM Corporation
1489 if (!PhoneGap.hasResource("compass")) {
1490 PhoneGap.addResource("compass");
1493 * This class provides access to device Compass data.
1496 var Compass = function() {
1498 * The last known Compass position.
1500 this.lastHeading = null;
1503 * List of compass watch timers
1508 Compass.ERROR_MSG = ["Not running", "Starting", "", "Failed to start"];
1511 * Asynchronously aquires the current heading.
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)
1517 Compass.prototype.getCurrentHeading = function(successCallback, errorCallback, options) {
1519 // successCallback required
1520 if (typeof successCallback !== "function") {
1521 console.log("Compass Error: successCallback is not a function");
1525 // errorCallback optional
1526 if (errorCallback && (typeof errorCallback !== "function")) {
1527 console.log("Compass Error: errorCallback is not a function");
1532 PhoneGap.exec(successCallback, errorCallback, "Compass", "getHeading", []);
1536 * Asynchronously aquires the heading repeatedly at a given interval.
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.
1543 Compass.prototype.watchHeading= function(successCallback, errorCallback, options) {
1545 // Default interval (100 msec)
1546 var frequency = (options !== undefined) ? options.frequency : 100;
1548 // successCallback required
1549 if (typeof successCallback !== "function") {
1550 console.log("Compass Error: successCallback is not a function");
1554 // errorCallback optional
1555 if (errorCallback && (typeof errorCallback !== "function")) {
1556 console.log("Compass Error: errorCallback is not a function");
1560 // Make sure compass timeout > frequency + 10 sec
1563 if (timeout < (frequency + 10000)) {
1564 PhoneGap.exec(null, null, "Compass", "setTimeout", [frequency + 10000]);
1567 function(e) { }, "Compass", "getTimeout", []);
1569 // Start watch timer to get headings
1570 var id = PhoneGap.createUUID();
1571 navigator.compass.timers[id] = setInterval(
1573 PhoneGap.exec(successCallback, errorCallback, "Compass", "getHeading", []);
1574 }, (frequency ? frequency : 1));
1581 * Clears the specified heading watch.
1583 * @param {String} id The ID of the watch returned from #watchHeading.
1585 Compass.prototype.clearWatch = function(id) {
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];
1594 PhoneGap.addConstructor(function() {
1595 if (typeof navigator.compass === "undefined") {
1596 navigator.compass = new Compass();
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.
1606 * Copyright (c) 2005-2010, Nitobi Software Inc.
1607 * Copyright (c) 2010-2011, IBM Corporation
1610 if (!PhoneGap.hasResource("contact")) {
1611 PhoneGap.addResource("contact");
1614 * Contains information about a single contact.
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
1631 var Contact = function (id, displayName, name, nickname, phoneNumbers, emails, addresses,
1632 ims, organizations, birthday, note, photos, categories, urls) {
1633 this.id = id || 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[]
1652 * An error code assigned by an implementation when an error has occurreds
1655 var ContactError = function() {
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;
1671 * Removes contact from device storage.
1672 * @param successCB success callback
1673 * @param errorCB error callback
1675 Contact.prototype.remove = function(successCB, errorCB) {
1676 if (this.id === null) {
1677 var errorObj = new ContactError();
1678 errorObj.code = ContactError.UNKNOWN_ERROR;
1682 PhoneGap.exec(successCB, errorCB, "Contacts", "remove", [this.id]);
1687 * Creates a deep copy of this Contact.
1688 * With the contact ID set to null.
1689 * @return copy of this Contact
1691 Contact.prototype.clone = function() {
1692 var clonedContact = PhoneGap.clone(this);
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;
1702 if (clonedContact.emails) {
1703 for (i = 0; i < clonedContact.emails.length; i++) {
1704 clonedContact.emails[i].id = null;
1707 if (clonedContact.addresses) {
1708 for (i = 0; i < clonedContact.addresses.length; i++) {
1709 clonedContact.addresses[i].id = null;
1712 if (clonedContact.ims) {
1713 for (i = 0; i < clonedContact.ims.length; i++) {
1714 clonedContact.ims[i].id = null;
1717 if (clonedContact.organizations) {
1718 for (i = 0; i < clonedContact.organizations.length; i++) {
1719 clonedContact.organizations[i].id = null;
1722 if (clonedContact.tags) {
1723 for (i = 0; i < clonedContact.tags.length; i++) {
1724 clonedContact.tags[i].id = null;
1727 if (clonedContact.photos) {
1728 for (i = 0; i < clonedContact.photos.length; i++) {
1729 clonedContact.photos[i].id = null;
1732 if (clonedContact.urls) {
1733 for (i = 0; i < clonedContact.urls.length; i++) {
1734 clonedContact.urls[i].id = null;
1737 return clonedContact;
1741 * Persists contact to device storage.
1742 * @param successCB success callback
1743 * @param errorCB error callback
1745 Contact.prototype.save = function(successCB, errorCB) {
1746 PhoneGap.exec(successCB, errorCB, "Contacts", "save", [this]);
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;
1769 * Generic contact field.
1771 * @param {DOMString} id unique identifier, should only be set by native code
1776 var ContactField = function(type, value, pref) {
1778 this.type = type || null;
1779 this.value = value || null;
1780 this.pref = pref || null;
1786 * @param {DOMString} id unique identifier, should only be set by native code
1788 * @param streetAddress
1794 var ContactAddress = function(pref, type, formatted, streetAddress, locality, region, postalCode, country) {
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;
1807 * Contact organization.
1809 * @param {DOMString} id unique identifier, should only be set by native code
1818 var ContactOrganization = function(pref, type, name, dept, title) {
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;
1828 * Represents a group of Contacts.
1831 var Contacts = function() {
1832 this.inProgress = false;
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
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.");
1847 if (fields === null || fields === "undefined" || fields.length === "undefined" || fields.length <= 0) {
1848 if (typeof errorCB === "function") {
1849 errorCB({"code": ContactError.INVALID_ARGUMENT_ERROR});
1852 PhoneGap.exec(successCB, errorCB, "Contacts", "search", [fields, options]);
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
1860 * @param properties an object who's properties will be examined to create a new Contact
1861 * @returns new Contact object
1863 Contacts.prototype.create = function(properties) {
1865 var contact = new Contact();
1866 for (i in properties) {
1867 if (contact[i] !== 'undefined') {
1868 contact[i] = properties[i];
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.
1879 * @param jsonArray an array of JSON Objects that need to be converted to Contact objects.
1880 * @returns an array of Contact objects
1882 Contacts.prototype.cast = function(pluginResult) {
1885 for (i=0; i<pluginResult.message.length; i++) {
1886 contacts.push(navigator.contacts.create(pluginResult.message[i]));
1888 pluginResult.message = contacts;
1889 return pluginResult;
1893 * ContactFindOptions.
1895 * @param filter used to match contacts against
1896 * @param multiple boolean used to determine if more than one contact should be returned
1898 var ContactFindOptions = function(filter, multiple) {
1899 this.filter = filter || '';
1900 this.multiple = multiple || false;
1904 * Add the contact interface into the browser.
1906 PhoneGap.addConstructor(function() {
1907 if(typeof navigator.contacts === "undefined") {
1908 navigator.contacts = new Contacts();
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.
1918 * Copyright (c) 2005-2010, Nitobi Software Inc.
1919 * Copyright (c) 2010-2011, IBM Corporation
1922 // TODO: Needs to be commented
1924 if (!PhoneGap.hasResource("crypto")) {
1925 PhoneGap.addResource("crypto");
1930 var Crypto = function() {
1933 Crypto.prototype.encrypt = function(seed, string, callback) {
1934 this.encryptWin = callback;
1935 PhoneGap.exec(null, null, "Crypto", "encrypt", [seed, string]);
1938 Crypto.prototype.decrypt = function(seed, string, callback) {
1939 this.decryptWin = callback;
1940 PhoneGap.exec(null, null, "Crypto", "decrypt", [seed, string]);
1943 Crypto.prototype.gotCryptedString = function(string) {
1944 this.encryptWin(string);
1947 Crypto.prototype.getPlainString = function(string) {
1948 this.decryptWin(string);
1951 PhoneGap.addConstructor(function() {
1952 if (typeof navigator.Crypto === "undefined") {
1953 navigator.Crypto = new Crypto();
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.
1963 * Copyright (c) 2005-2010, Nitobi Software Inc.
1964 * Copyright (c) 2010-2011, IBM Corporation
1967 if (!PhoneGap.hasResource("device")) {
1968 PhoneGap.addResource("device");
1971 * This represents the mobile device, and provides properties for inspecting the model, version, UUID of the
1975 var Device = function() {
1976 this.available = PhoneGap.available;
1977 this.platform = null;
1978 this.version = null;
1981 this.phonegap = null;
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();
1995 me.available = false;
1996 console.log("Error initializing PhoneGap: " + e);
1997 alert("Error initializing PhoneGap: "+e);
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)
2007 Device.prototype.getInfo = function(successCallback, errorCallback) {
2009 // successCallback required
2010 if (typeof successCallback !== "function") {
2011 console.log("Device Error: successCallback is not a function");
2015 // errorCallback optional
2016 if (errorCallback && (typeof errorCallback !== "function")) {
2017 console.log("Device Error: errorCallback is not a function");
2022 PhoneGap.exec(successCallback, errorCallback, "Device", "getDeviceInfo", []);
2027 * This is only for Android.
2029 * You must explicitly override the back button.
2031 Device.prototype.overrideBackButton = function() {
2032 console.log("Device.overrideBackButton() is deprecated. Use App.overrideBackbutton(true).");
2033 navigator.app.overrideBackbutton(true);
2038 * This is only for Android.
2040 * This resets the back button to the default behaviour
2042 Device.prototype.resetBackButton = function() {
2043 console.log("Device.resetBackButton() is deprecated. Use App.overrideBackbutton(false).");
2044 navigator.app.overrideBackbutton(false);
2049 * This is only for Android.
2051 * This terminates the activity!
2053 Device.prototype.exitApp = function() {
2054 console.log("Device.exitApp() is deprecated. Use App.exitApp().");
2055 navigator.app.exitApp();
2058 PhoneGap.addConstructor(function() {
2059 if (typeof navigator.device === "undefined") {
2060 navigator.device = window.device = new Device();
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.
2070 * Copyright (c) 2005-2010, Nitobi Software Inc.
2071 * Copyright (c) 2010-2011, IBM Corporation
2074 if (!PhoneGap.hasResource("file")) {
2075 PhoneGap.addResource("file");
2078 * This class provides some useful information about a file.
2079 * This is the fields returned when navigator.fileMgr.getFileProperties()
2083 var FileProperties = function(filePath) {
2084 this.filePath = filePath;
2086 this.lastModifiedDate = null;
2090 * Represents a single file.
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
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;
2108 var FileError = function() {
2113 // Found in DOMException
2114 FileError.NOT_FOUND_ERR = 1;
2115 FileError.SECURITY_ERR = 2;
2116 FileError.ABORT_ERR = 3;
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;
2129 //-----------------------------------------------------------------------------
2131 //-----------------------------------------------------------------------------
2134 var FileMgr = function() {
2137 FileMgr.prototype.getFileProperties = function(filePath) {
2138 return PhoneGap.exec(null, null, "File", "getFileProperties", [filePath]);
2141 FileMgr.prototype.getFileBasePaths = function() {
2144 FileMgr.prototype.testSaveLocationExists = function(successCallback, errorCallback) {
2145 return PhoneGap.exec(successCallback, errorCallback, "File", "testSaveLocationExists", []);
2148 FileMgr.prototype.testFileExists = function(fileName, successCallback, errorCallback) {
2149 return PhoneGap.exec(successCallback, errorCallback, "File", "testFileExists", [fileName]);
2152 FileMgr.prototype.testDirectoryExists = function(dirName, successCallback, errorCallback) {
2153 return PhoneGap.exec(successCallback, errorCallback, "File", "testDirectoryExists", [dirName]);
2156 FileMgr.prototype.getFreeDiskSpace = function(successCallback, errorCallback) {
2157 return PhoneGap.exec(successCallback, errorCallback, "File", "getFreeDiskSpace", []);
2160 FileMgr.prototype.write = function(fileName, data, position, successCallback, errorCallback) {
2161 PhoneGap.exec(successCallback, errorCallback, "File", "write", [fileName, data, position]);
2164 FileMgr.prototype.truncate = function(fileName, size, successCallback, errorCallback) {
2165 PhoneGap.exec(successCallback, errorCallback, "File", "truncate", [fileName, size]);
2168 FileMgr.prototype.readAsText = function(fileName, encoding, successCallback, errorCallback) {
2169 PhoneGap.exec(successCallback, errorCallback, "File", "readAsText", [fileName, encoding]);
2172 FileMgr.prototype.readAsDataURL = function(fileName, successCallback, errorCallback) {
2173 PhoneGap.exec(successCallback, errorCallback, "File", "readAsDataURL", [fileName]);
2176 PhoneGap.addConstructor(function() {
2177 if (typeof navigator.fileMgr === "undefined") {
2178 navigator.fileMgr = new FileMgr();
2182 //-----------------------------------------------------------------------------
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?
2189 * This class reads the mobile device file system.
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"
2196 var FileReader = function() {
2199 this.readyState = 0;
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.
2217 FileReader.EMPTY = 0;
2218 FileReader.LOADING = 1;
2219 FileReader.DONE = 2;
2222 * Abort reading file.
2224 FileReader.prototype.abort = function() {
2226 this.readyState = FileReader.DONE;
2230 var error = new FileError();
2231 error.code = error.ABORT_ERR;
2234 // If error callback
2235 if (typeof this.onerror === "function") {
2236 this.onerror({"type":"error", "target":this});
2238 // If abort callback
2239 if (typeof this.onabort === "function") {
2240 this.onabort({"type":"abort", "target":this});
2242 // If load end callback
2243 if (typeof this.onloadend === "function") {
2244 this.onloadend({"type":"loadend", "target":this});
2251 * @param file {File} File object containing file properties
2252 * @param encoding [Optional] (see http://www.iana.org/assignments/character-sets)
2254 FileReader.prototype.readAsText = function(file, encoding) {
2256 if (typeof file.fullPath === "undefined") {
2257 this.fileName = file;
2259 this.fileName = file.fullPath;
2263 this.readyState = FileReader.LOADING;
2265 // If loadstart callback
2266 if (typeof this.onloadstart === "function") {
2267 this.onloadstart({"type":"loadstart", "target":this});
2270 // Default encoding is UTF-8
2271 var enc = encoding ? encoding : "UTF-8";
2276 navigator.fileMgr.readAsText(this.fileName, enc,
2282 // If DONE (cancelled), then don't do anything
2283 if (me.readyState === FileReader.DONE) {
2290 // If onload callback
2291 if (typeof me.onload === "function") {
2292 me.onload({"type":"load", "target":me});
2296 me.readyState = FileReader.DONE;
2298 // If onloadend callback
2299 if (typeof me.onloadend === "function") {
2300 me.onloadend({"type":"loadend", "target":me});
2307 // If DONE (cancelled), then don't do anything
2308 if (me.readyState === FileReader.DONE) {
2315 // If onerror callback
2316 if (typeof me.onerror === "function") {
2317 me.onerror({"type":"error", "target":me});
2321 me.readyState = FileReader.DONE;
2323 // If onloadend callback
2324 if (typeof me.onloadend === "function") {
2325 me.onloadend({"type":"loadend", "target":me});
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>
2337 * @param file {File} File object containing file properties
2339 FileReader.prototype.readAsDataURL = function(file) {
2341 if (typeof file.fullPath === "undefined") {
2342 this.fileName = file;
2344 this.fileName = file.fullPath;
2348 this.readyState = FileReader.LOADING;
2350 // If loadstart callback
2351 if (typeof this.onloadstart === "function") {
2352 this.onloadstart({"type":"loadstart", "target":this});
2358 navigator.fileMgr.readAsDataURL(this.fileName,
2364 // If DONE (cancelled), then don't do anything
2365 if (me.readyState === FileReader.DONE) {
2372 // If onload callback
2373 if (typeof me.onload === "function") {
2374 me.onload({"type":"load", "target":me});
2378 me.readyState = FileReader.DONE;
2380 // If onloadend callback
2381 if (typeof me.onloadend === "function") {
2382 me.onloadend({"type":"loadend", "target":me});
2389 // If DONE (cancelled), then don't do anything
2390 if (me.readyState === FileReader.DONE) {
2397 // If onerror callback
2398 if (typeof me.onerror === "function") {
2399 me.onerror({"type":"error", "target":me});
2403 me.readyState = FileReader.DONE;
2405 // If onloadend callback
2406 if (typeof me.onloadend === "function") {
2407 me.onloadend({"type":"loadend", "target":me});
2414 * Read file and return data as a binary data.
2416 * @param file {File} File object containing file properties
2418 FileReader.prototype.readAsBinaryString = function(file) {
2419 // TODO - Can't return binary data to browser.
2420 this.fileName = file;
2424 * Read file and return data as a binary data.
2426 * @param file {File} File object containing file properties
2428 FileReader.prototype.readAsArrayBuffer = function(file) {
2429 // TODO - Can't return binary data to browser.
2430 this.fileName = file;
2433 //-----------------------------------------------------------------------------
2435 //-----------------------------------------------------------------------------
2438 * This class writes to the mobile device file system.
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"
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
2448 var FileWriter = function(file) {
2452 this.fileName = file.fullPath || file;
2453 this.length = file.size || 0;
2455 // default is to write at the beginning of the file
2458 this.readyState = 0; // EMPTY
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).
2475 FileWriter.INIT = 0;
2476 FileWriter.WRITING = 1;
2477 FileWriter.DONE = 2;
2480 * Abort writing file.
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;
2489 var error = new FileError(), evt;
2490 error.code = error.ABORT_ERR;
2493 // If error callback
2494 if (typeof this.onerror === "function") {
2495 this.onerror({"type":"error", "target":this});
2497 // If abort callback
2498 if (typeof this.onabort === "function") {
2499 this.onabort({"type":"abort", "target":this});
2502 this.readyState = FileWriter.DONE;
2504 // If write end callback
2505 if (typeof this.onwriteend == "function") {
2506 this.onwriteend({"type":"writeend", "target":this});
2511 * Writes data to the file
2513 * @param text to be written
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;
2522 this.readyState = FileWriter.WRITING;
2526 // If onwritestart callback
2527 if (typeof me.onwritestart === "function") {
2528 me.onwritestart({"type":"writestart", "target":me});
2532 navigator.fileMgr.write(this.fileName, text, this.position,
2537 // If DONE (cancelled), then don't do anything
2538 if (me.readyState === FileWriter.DONE) {
2542 // position always increases by bytes written because file would be extended
2544 // The length of the file is now where we are done writing.
2545 me.length = me.position;
2547 // If onwrite callback
2548 if (typeof me.onwrite === "function") {
2549 me.onwrite({"type":"write", "target":me});
2553 me.readyState = FileWriter.DONE;
2555 // If onwriteend callback
2556 if (typeof me.onwriteend === "function") {
2557 me.onwriteend({"type":"writeend", "target":me});
2565 // If DONE (cancelled), then don't do anything
2566 if (me.readyState === FileWriter.DONE) {
2573 // If onerror callback
2574 if (typeof me.onerror === "function") {
2575 me.onerror({"type":"error", "target":me});
2579 me.readyState = FileWriter.DONE;
2581 // If onwriteend callback
2582 if (typeof me.onwriteend === "function") {
2583 me.onwriteend({"type":"writeend", "target":me});
2591 * Moves the file pointer to the location specified.
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.
2597 * @param offset is the location to move the file pointer to.
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;
2609 // See back from end of file.
2611 this.position = Math.max(offset + this.length, 0);
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;
2618 // Offset is between 0 and file size so set the position
2619 // to start writing.
2621 this.position = offset;
2626 * Truncates the file to the size specified.
2628 * @param size to chop the file at.
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;
2637 this.readyState = FileWriter.WRITING;
2641 // If onwritestart callback
2642 if (typeof me.onwritestart === "function") {
2643 me.onwritestart({"type":"writestart", "target":this});
2647 navigator.fileMgr.truncate(this.fileName, size,
2652 // If DONE (cancelled), then don't do anything
2653 if (me.readyState === FileWriter.DONE) {
2657 // Update the length of the file
2659 me.position = Math.min(me.position, r);
2661 // If onwrite callback
2662 if (typeof me.onwrite === "function") {
2663 me.onwrite({"type":"write", "target":me});
2667 me.readyState = FileWriter.DONE;
2669 // If onwriteend callback
2670 if (typeof me.onwriteend === "function") {
2671 me.onwriteend({"type":"writeend", "target":me});
2678 // If DONE (cancelled), then don't do anything
2679 if (me.readyState === FileWriter.DONE) {
2686 // If onerror callback
2687 if (typeof me.onerror === "function") {
2688 me.onerror({"type":"error", "target":me});
2692 me.readyState = FileWriter.DONE;
2694 // If onwriteend callback
2695 if (typeof me.onwriteend === "function") {
2696 me.onwriteend({"type":"writeend", "target":me});
2703 * Information about the state of the file or directory
2706 * {Date} modificationTime (readonly)
2708 var Metadata = function() {
2709 this.modificationTime=null;
2713 * Supplies arguments to methods that lookup or create files and directories
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
2719 var Flags = function(create, exclusive) {
2720 this.create = create || false;
2721 this.exclusive = exclusive || false;
2725 * An interface representing a file system
2728 * {DOMString} name the unique name of the file system (readonly)
2729 * {DirectoryEntry} root directory of the file system (readonly)
2731 var FileSystem = function() {
2737 * An interface that lists the files and directories in a directory.
2740 var DirectoryReader = function(fullPath){
2741 this.fullPath = fullPath || null;
2745 * Returns a list of entries from a directory.
2747 * @param {Function} successCallback is called with a list of entries
2748 * @param {Function} errorCallback is called with a FileError
2750 DirectoryReader.prototype.readEntries = function(successCallback, errorCallback) {
2751 PhoneGap.exec(successCallback, errorCallback, "File", "readEntries", [this.fullPath]);
2755 * An interface representing a directory on the file system.
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)
2764 var DirectoryEntry = function() {
2765 this.isFile = false;
2766 this.isDirectory = true;
2768 this.fullPath = null;
2769 this.filesystem = null;
2773 * Copies a directory to a new location
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
2780 DirectoryEntry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) {
2781 PhoneGap.exec(successCallback, errorCallback, "File", "copyTo", [this.fullPath, parent, newName]);
2785 * Looks up the metadata of the entry
2787 * @param {Function} successCallback is called with a Metadata object
2788 * @param {Function} errorCallback is called with a FileError
2790 DirectoryEntry.prototype.getMetadata = function(successCallback, errorCallback) {
2791 PhoneGap.exec(successCallback, errorCallback, "File", "getMetadata", [this.fullPath]);
2795 * Gets the parent of the entry
2797 * @param {Function} successCallback is called with a parent entry
2798 * @param {Function} errorCallback is called with a FileError
2800 DirectoryEntry.prototype.getParent = function(successCallback, errorCallback) {
2801 PhoneGap.exec(successCallback, errorCallback, "File", "getParent", [this.fullPath]);
2805 * Moves a directory to a new location
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
2812 DirectoryEntry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) {
2813 PhoneGap.exec(successCallback, errorCallback, "File", "moveTo", [this.fullPath, parent, newName]);
2819 * @param {Function} successCallback is called with no parameters
2820 * @param {Function} errorCallback is called with a FileError
2822 DirectoryEntry.prototype.remove = function(successCallback, errorCallback) {
2823 PhoneGap.exec(successCallback, errorCallback, "File", "remove", [this.fullPath]);
2827 * Returns a URI that can be used to identify this entry.
2829 * @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.
2832 DirectoryEntry.prototype.toURI = function(mimeType) {
2833 return "file://" + this.fullPath;
2837 * Creates a new DirectoryReader to read entries from this directory
2839 DirectoryEntry.prototype.createReader = function(successCallback, errorCallback) {
2840 return new DirectoryReader(this.fullPath);
2844 * Creates or looks up a directory
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
2851 DirectoryEntry.prototype.getDirectory = function(path, options, successCallback, errorCallback) {
2852 PhoneGap.exec(successCallback, errorCallback, "File", "getDirectory", [this.fullPath, path, options]);
2856 * Creates or looks up a file
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
2863 DirectoryEntry.prototype.getFile = function(path, options, successCallback, errorCallback) {
2864 PhoneGap.exec(successCallback, errorCallback, "File", "getFile", [this.fullPath, path, options]);
2868 * Deletes a directory and all of it's contents
2870 * @param {Function} successCallback is called with no parameters
2871 * @param {Function} errorCallback is called with a FileError
2873 DirectoryEntry.prototype.removeRecursively = function(successCallback, errorCallback) {
2874 PhoneGap.exec(successCallback, errorCallback, "File", "removeRecursively", [this.fullPath]);
2878 * An interface representing a directory on the file system.
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)
2887 var FileEntry = function() {
2889 this.isDirectory = false;
2891 this.fullPath = null;
2892 this.filesystem = null;
2896 * Copies a file to a new location
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
2903 FileEntry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) {
2904 PhoneGap.exec(successCallback, errorCallback, "File", "copyTo", [this.fullPath, parent, newName]);
2908 * Looks up the metadata of the entry
2910 * @param {Function} successCallback is called with a Metadata object
2911 * @param {Function} errorCallback is called with a FileError
2913 FileEntry.prototype.getMetadata = function(successCallback, errorCallback) {
2914 PhoneGap.exec(successCallback, errorCallback, "File", "getMetadata", [this.fullPath]);
2918 * Gets the parent of the entry
2920 * @param {Function} successCallback is called with a parent entry
2921 * @param {Function} errorCallback is called with a FileError
2923 FileEntry.prototype.getParent = function(successCallback, errorCallback) {
2924 PhoneGap.exec(successCallback, errorCallback, "File", "getParent", [this.fullPath]);
2928 * Moves a directory to a new location
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
2935 FileEntry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) {
2936 PhoneGap.exec(successCallback, errorCallback, "File", "moveTo", [this.fullPath, parent, newName]);
2942 * @param {Function} successCallback is called with no parameters
2943 * @param {Function} errorCallback is called with a FileError
2945 FileEntry.prototype.remove = function(successCallback, errorCallback) {
2946 PhoneGap.exec(successCallback, errorCallback, "File", "remove", [this.fullPath]);
2950 * Returns a URI that can be used to identify this entry.
2952 * @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.
2955 FileEntry.prototype.toURI = function(mimeType) {
2956 return "file://" + this.fullPath;
2960 * Creates a new FileWriter associated with the file that this FileEntry represents.
2962 * @param {Function} successCallback is called with the new FileWriter
2963 * @param {Function} errorCallback is called with a FileError
2965 FileEntry.prototype.createWriter = function(successCallback, errorCallback) {
2966 this.file(function(filePointer) {
2967 var writer = new FileWriter(filePointer);
2969 if (writer.fileName === null || writer.fileName === "") {
2970 if (typeof errorCallback == "function") {
2972 "code": FileError.INVALID_STATE_ERR
2977 if (typeof successCallback == "function") {
2978 successCallback(writer);
2984 * Returns a File that represents the current state of the file that this FileEntry represents.
2986 * @param {Function} successCallback is called with the new File object
2987 * @param {Function} errorCallback is called with a FileError
2989 FileEntry.prototype.file = function(successCallback, errorCallback) {
2990 PhoneGap.exec(successCallback, errorCallback, "File", "getFileMetadata", [this.fullPath]);
2994 var LocalFileSystem = function() {
2998 LocalFileSystem.TEMPORARY = 0;
2999 LocalFileSystem.PERSISTENT = 1;
3000 LocalFileSystem.RESOURCE = 2;
3001 LocalFileSystem.APPLICATION = 3;
3004 * Requests a filesystem in which to store application data.
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
3010 LocalFileSystem.prototype.requestFileSystem = function(type, size, successCallback, errorCallback) {
3011 if (type < 0 || type > 3) {
3012 if (typeof errorCallback == "function") {
3014 "code": FileError.SYNTAX_ERR
3019 PhoneGap.exec(successCallback, errorCallback, "File", "requestFileSystem", [type, size]);
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
3029 LocalFileSystem.prototype.resolveLocalFileSystemURI = function(uri, successCallback, errorCallback) {
3030 PhoneGap.exec(successCallback, errorCallback, "File", "resolveLocalFileSystemURI", [uri]);
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.
3038 * @param a JSON Objects that need to be converted to DirectoryEntry or FileEntry objects.
3041 LocalFileSystem.prototype._castFS = function(pluginResult) {
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;
3052 LocalFileSystem.prototype._castEntry = function(pluginResult) {
3054 if (pluginResult.message.isDirectory) {
3055 console.log("This is a dir");
3056 entry = new DirectoryEntry();
3058 else if (pluginResult.message.isFile) {
3059 console.log("This is a file");
3060 entry = new FileEntry();
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;
3070 LocalFileSystem.prototype._castEntries = function(pluginResult) {
3071 var entries = pluginResult.message;
3073 for (var i=0; i<entries.length; i++) {
3074 retVal.push(window.localFileSystem._createEntry(entries[i]));
3076 pluginResult.message = retVal;
3077 return pluginResult;
3080 LocalFileSystem.prototype._createEntry = function(castMe) {
3082 if (castMe.isDirectory) {
3083 console.log("This is a dir");
3084 entry = new DirectoryEntry();
3086 else if (castMe.isFile) {
3087 console.log("This is a file");
3088 entry = new FileEntry();
3090 entry.isDirectory = castMe.isDirectory;
3091 entry.isFile = castMe.isFile;
3092 entry.name = castMe.name;
3093 entry.fullPath = castMe.fullPath;
3097 LocalFileSystem.prototype._castDate = function(pluginResult) {
3098 if (pluginResult.message.modificationTime) {
3099 var modTime = new Date(pluginResult.message.modificationTime);
3100 pluginResult.message.modificationTime = modTime;
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;
3111 return pluginResult;
3115 * Add the FileSystem interface into the browser.
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;
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.
3131 * Copyright (c) 2005-2010, Nitobi Software Inc.
3132 * Copyright (c) 2010-2011, IBM Corporation
3135 if (!PhoneGap.hasResource("filetransfer")) {
3136 PhoneGap.addResource("filetransfer");
3139 * FileTransfer uploads a file to a remote server.
3142 var FileTransfer = function() {};
3148 var FileUploadResult = function() {
3150 this.responseCode = null;
3151 this.response = null;
3158 var FileTransferError = function() {
3162 FileTransferError.FILE_NOT_FOUND_ERR = 1;
3163 FileTransferError.INVALID_URL_ERR = 2;
3164 FileTransferError.CONNECTION_ERR = 3;
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
3175 FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, debug) {
3177 // check for options
3179 var fileName = null;
3180 var mimeType = null;
3183 fileKey = options.fileKey;
3184 fileName = options.fileName;
3185 mimeType = options.mimeType;
3186 if (options.params) {
3187 params = options.params;
3194 PhoneGap.exec(successCallback, errorCallback, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, debug]);
3198 * Options to customize the HTTP request used to upload files.
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.
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;
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.
3218 * Copyright (c) 2005-2010, Nitobi Software Inc.
3219 * Copyright (c) 2010-2011, IBM Corporation
3222 if (!PhoneGap.hasResource("geolocation")) {
3223 PhoneGap.addResource("geolocation");
3226 * This class provides access to device GPS data.
3229 var Geolocation = function() {
3231 // The last known GPS position.
3232 this.lastPosition = null;
3234 // Geolocation listeners
3235 this.listeners = {};
3239 * Position error object
3245 var PositionError = function(code, message) {
3247 this.message = message;
3250 PositionError.PERMISSION_DENIED = 1;
3251 PositionError.POSITION_UNAVAILABLE = 2;
3252 PositionError.TIMEOUT = 3;
3255 * Asynchronously aquires the current position.
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)
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.");
3265 errorCallback(new PositionError(PositionError.TIMEOUT, "Geolocation Error: Still waiting for previous getCurrentPosition() request."));
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;
3277 if (typeof options.enableHighAccuracy !== "undefined") {
3278 enableHighAccuracy = options.enableHighAccuracy;
3280 if (typeof options.timeout !== "undefined") {
3281 timeout = options.timeout;
3284 navigator._geo.listeners.global = {"success" : successCallback, "fail" : errorCallback };
3285 PhoneGap.exec(null, null, "Geolocation", "getCurrentLocation", [enableHighAccuracy, timeout, maximumAge]);
3289 * Asynchronously watches the geolocation for changes to geolocation. When a change occurs,
3290 * the successCallback is called with the new location.
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.
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;
3305 if (typeof options.maximumAge !== "undefined") {
3306 maximumAge = options.maximumAge;
3308 if (typeof options.enableHighAccuracy !== "undefined") {
3309 enableHighAccuracy = options.enableHighAccuracy;
3311 if (typeof options.timeout !== "undefined") {
3312 timeout = options.timeout;
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]);
3322 * Native callback when watch position has a new position.
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
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);
3338 if (lat === "undefined" || lng === "undefined") {
3339 navigator._geo.listeners[id].fail(new PositionError(PositionError.POSITION_UNAVAILABLE, "Lat/Lng are undefined."));
3342 navigator._geo.lastPosition = loc;
3343 navigator._geo.listeners[id].success(loc);
3347 console.log("Geolocation Error: Error calling success callback function.");
3350 if (id === "global") {
3351 delete navigator._geo.listeners.global;
3356 * Native callback when watch position has an error.
3359 * @param {String} id The ID of the watch
3360 * @param {Number} code The error code
3361 * @param {String} msg The error message
3363 Geolocation.prototype.fail = function(id, code, msg) {
3365 navigator._geo.listeners[id].fail(new PositionError(code, msg));
3368 console.log("Geolocation Error: Error calling error callback function.");
3373 * Clears the specified heading watch.
3375 * @param {String} id The ID of the watch returned from #watchPosition
3377 Geolocation.prototype.clearWatch = function(id) {
3378 PhoneGap.exec(null, null, "Geolocation", "stop", [id]);
3379 delete navigator._geo.listeners[id];
3383 * Force the PhoneGap geolocation to be used instead of built-in.
3385 Geolocation.usingPhoneGap = false;
3386 Geolocation.usePhoneGap = function() {
3387 if (Geolocation.usingPhoneGap) {
3390 Geolocation.usingPhoneGap = true;
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;
3402 PhoneGap.addConstructor(function() {
3403 navigator._geo = new Geolocation();
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;
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.
3418 * Copyright (c) 2005-2010, Nitobi Software Inc.
3419 * Copyright (c) 2010, IBM Corporation
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.
3427 * Copyright (c) 2005-2010, Nitobi Software Inc.
3428 * Copyright (c) 2010-2011, IBM Corporation
3431 if (!PhoneGap.hasResource("media")) {
3432 PhoneGap.addResource("media");
3435 * This class provides access to the device media, interfaces to both sound and video
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
3448 var Media = function(src, successCallback, errorCallback, statusCallback, positionCallback) {
3450 // successCallback optional
3451 if (successCallback && (typeof successCallback !== "function")) {
3452 console.log("Media Error: successCallback is not a function");
3456 // errorCallback optional
3457 if (errorCallback && (typeof errorCallback !== "function")) {
3458 console.log("Media Error: errorCallback is not a function");
3462 // statusCallback optional
3463 if (statusCallback && (typeof statusCallback !== "function")) {
3464 console.log("Media Error: statusCallback is not a function");
3468 // statusCallback optional
3469 if (positionCallback && (typeof positionCallback !== "function")) {
3470 console.log("Media Error: positionCallback is not a function");
3474 this.id = PhoneGap.createUUID();
3475 PhoneGap.mediaObjects[this.id] = this;
3477 this.successCallback = successCallback;
3478 this.errorCallback = errorCallback;
3479 this.statusCallback = statusCallback;
3480 this.positionCallback = positionCallback;
3481 this._duration = -1;
3482 this._position = -1;
3486 Media.MEDIA_STATE = 1;
3487 Media.MEDIA_DURATION = 2;
3488 Media.MEDIA_POSITION = 3;
3489 Media.MEDIA_ERROR = 9;
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"];
3499 // TODO: Will MediaError be used?
3501 * This class contains information about any Media errors.
3504 var MediaError = function() {
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;
3515 * Start or resume playing audio file.
3517 Media.prototype.play = function() {
3518 PhoneGap.exec(null, null, "Media", "startPlayingAudio", [this.id, this.src]);
3522 * Stop playing audio file.
3524 Media.prototype.stop = function() {
3525 return PhoneGap.exec(null, null, "Media", "stopPlayingAudio", [this.id]);
3529 * Seek or jump to a new time in the track..
3531 Media.prototype.seekTo = function(milliseconds) {
3532 PhoneGap.exec(null, null, "Media", "seekToAudio", [this.id, milliseconds]);
3536 * Pause playing audio file.
3538 Media.prototype.pause = function() {
3539 PhoneGap.exec(null, null, "Media", "pausePlayingAudio", [this.id]);
3543 * Get duration of an audio file.
3544 * The duration is only set for audio that is playing, paused or stopped.
3546 * @return duration or -1 if not known.
3548 Media.prototype.getDuration = function() {
3549 return this._duration;
3553 * Get position of audio.
3555 Media.prototype.getCurrentPosition = function(success, fail) {
3556 PhoneGap.exec(success, fail, "Media", "getCurrentPositionAudio", [this.id]);
3560 * Start recording audio file.
3562 Media.prototype.startRecord = function() {
3563 PhoneGap.exec(null, null, "Media", "startRecordingAudio", [this.id, this.src]);
3567 * Stop recording audio file.
3569 Media.prototype.stopRecord = function() {
3570 PhoneGap.exec(null, null, "Media", "stopRecordingAudio", [this.id]);
3574 * Release the resources.
3576 Media.prototype.release = function() {
3577 PhoneGap.exec(null, null, "Media", "release", [this.id]);
3581 * List of media objects.
3584 PhoneGap.mediaObjects = {};
3587 * Object that receives native callbacks.
3591 PhoneGap.Media = function() {};
3594 * Get the media object.
3597 * @param id The media object id (string)
3599 PhoneGap.Media.getMediaObject = function(id) {
3600 return PhoneGap.mediaObjects[id];
3604 * Audio has status update.
3607 * @param id The media object id (string)
3608 * @param status The status code (int)
3609 * @param msg The status message (string)
3611 PhoneGap.Media.onStatus = function(id, msg, value) {
3612 var media = PhoneGap.mediaObjects[id];
3614 if (msg === Media.MEDIA_STATE) {
3615 if (value === Media.MEDIA_STOPPED) {
3616 if (media.successCallback) {
3617 media.successCallback();
3620 if (media.statusCallback) {
3621 media.statusCallback(value);
3624 else if (msg === Media.MEDIA_DURATION) {
3625 media._duration = value;
3627 else if (msg === Media.MEDIA_ERROR) {
3628 if (media.errorCallback) {
3629 media.errorCallback(value);
3632 else if (msg == Media.MEDIA_POSITION) {
3633 media._position = value;
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.
3643 * Copyright (c) 2005-2010, Nitobi Software Inc.
3644 * Copyright (c) 2010-2011, IBM Corporation
3647 if (!PhoneGap.hasResource("network")) {
3648 PhoneGap.addResource("network");
3651 * This class contains information about the current network Connection.
3654 var Connection = function() {
3656 this._firstRun = true;
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(){
3668 PhoneGap.fireEvent('offline');
3672 // If there is a current offline event pending clear it
3673 if (me._timer != null) {
3674 clearTimeout(me._timer);
3678 PhoneGap.fireEvent('online');
3681 // should only fire this once
3683 me._firstRun = false;
3684 PhoneGap.onPhoneGapConnectionReady.fire();
3688 console.log("Error initializing Network Connection: " + e);
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";
3701 * Get connection info
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)
3706 Connection.prototype.getInfo = function(successCallback, errorCallback) {
3708 PhoneGap.exec(successCallback, errorCallback, "Network Status", "getConnectionInfo", []);
3712 PhoneGap.addConstructor(function() {
3713 if (typeof navigator.network === "undefined") {
3714 navigator.network = new Object();
3716 if (typeof navigator.network.connection === "undefined") {
3717 navigator.network.connection = new Connection();
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.
3727 * Copyright (c) 2005-2010, Nitobi Software Inc.
3728 * Copyright (c) 2010-2011, IBM Corporation
3731 if (!PhoneGap.hasResource("notification")) {
3732 PhoneGap.addResource("notification");
3735 * This class provides access to notifications on the device.
3738 var Notification = function() {
3742 * Open a native alert dialog, with a customizable title and button text.
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)
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]);
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.
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')
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]);
3771 * Start spinning the activity indicator on the statusbar
3773 Notification.prototype.activityStart = function() {
3774 PhoneGap.exec(null, null, "Notification", "activityStart", ["Busy","Please wait..."]);
3778 * Stop spinning the activity indicator on the statusbar, if it's currently spinning
3780 Notification.prototype.activityStop = function() {
3781 PhoneGap.exec(null, null, "Notification", "activityStop", []);
3785 * Display a progress dialog with progress bar that goes from 0 to 100.
3787 * @param {String} title Title of the progress dialog.
3788 * @param {String} message Message to display in the dialog.
3790 Notification.prototype.progressStart = function(title, message) {
3791 PhoneGap.exec(null, null, "Notification", "progressStart", [title, message]);
3795 * Set the progress dialog value.
3797 * @param {Number} value 0-100
3799 Notification.prototype.progressValue = function(value) {
3800 PhoneGap.exec(null, null, "Notification", "progressValue", [value]);
3804 * Close the progress dialog.
3806 Notification.prototype.progressStop = function() {
3807 PhoneGap.exec(null, null, "Notification", "progressStop", []);
3811 * Causes the device to blink a status LED.
3813 * @param {Integer} count The number of blinks.
3814 * @param {String} colour The colour of the light.
3816 Notification.prototype.blink = function(count, colour) {
3821 * Causes the device to vibrate.
3823 * @param {Integer} mills The number of milliseconds to vibrate for.
3825 Notification.prototype.vibrate = function(mills) {
3826 PhoneGap.exec(null, null, "Notification", "vibrate", [mills]);
3830 * Causes the device to beep.
3831 * On Android, the default notification ringtone is played "count" times.
3833 * @param {Integer} count The number of beeps.
3835 Notification.prototype.beep = function(count) {
3836 PhoneGap.exec(null, null, "Notification", "beep", [count]);
3839 PhoneGap.addConstructor(function() {
3840 if (typeof navigator.notification === "undefined") {
3841 navigator.notification = new Notification();
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.
3851 * Copyright (c) 2005-2010, Nitobi Software Inc.
3852 * Copyright (c) 2010-2011, IBM Corporation
3855 if (!PhoneGap.hasResource("position")) {
3856 PhoneGap.addResource("position");
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
3869 var Position = function(coords, timestamp) {
3870 this.coords = coords;
3871 this.timestamp = (timestamp !== 'undefined') ? timestamp : new Date().getTime();
3875 var Coordinates = function(lat, lng, alt, acc, head, vel, altacc) {
3877 * The latitude of the position.
3879 this.latitude = lat;
3881 * The longitude of the position,
3883 this.longitude = lng;
3885 * The accuracy of the position.
3887 this.accuracy = acc;
3889 * The altitude of the position.
3891 this.altitude = alt;
3893 * The direction the device is moving at the position.
3895 this.heading = head;
3897 * The velocity with which the device is moving at the position.
3901 * The altitude accuracy of the position.
3903 this.altitudeAccuracy = (altacc !== 'undefined') ? altacc : null;
3907 * This class specifies the options for requesting position data.
3910 var PositionOptions = function() {
3912 * Specifies the desired position accuracy.
3914 this.enableHighAccuracy = true;
3916 * The timeout after which if position data cannot be obtained the errorCallback
3919 this.timeout = 10000;
3923 * This class contains information about any GSP errors.
3926 var PositionError = function() {
3931 PositionError.UNKNOWN_ERROR = 0;
3932 PositionError.PERMISSION_DENIED = 1;
3933 PositionError.POSITION_UNAVAILABLE = 2;
3934 PositionError.TIMEOUT = 3;
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.
3942 * Copyright (c) 2005-2010, Nitobi Software Inc.
3943 * Copyright (c) 2010-2011, IBM Corporation
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
3952 if (!PhoneGap.hasResource("storage")) {
3953 PhoneGap.addResource("storage");
3956 * SQL result set object
3960 var DroidDB_Rows = function() {
3961 this.resultSet = []; // results array
3962 this.length = 0; // number of rows
3966 * Get item from SQL result set
3968 * @param row The row number to return
3969 * @return The row object
3971 DroidDB_Rows.prototype.item = function(row) {
3972 return this.resultSet[row];
3976 * SQL result set that is returned to user.
3980 var DroidDB_Result = function() {
3981 this.rows = new DroidDB_Rows();
3985 * Storage object that is called by native code when performing queries.
3989 var DroidDB = function() {
3990 this.queryQueue = {};
3994 * Callback from native code when query is complete.
3997 * @param id Query id
3999 DroidDB.prototype.completeQuery = function(id, data) {
4000 var query = this.queryQueue[id];
4003 delete this.queryQueue[id];
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]) {
4013 // Save query results
4014 var r = new DroidDB_Result();
4015 r.rows.resultSet = data;
4016 r.rows.length = data.length;
4018 if (typeof query.successCallback === 'function') {
4019 query.successCallback(query.tx, r);
4022 console.log("executeSql error calling user success callback: "+ex);
4025 tx.queryComplete(id);
4028 console.log("executeSql error: "+e);
4034 * Callback from native code when query fails
4037 * @param reason Error message
4038 * @param id Query id
4040 DroidDB.prototype.fail = function(reason, id) {
4041 var query = this.queryQueue[id];
4044 delete this.queryQueue[id];
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]) {
4056 if (typeof query.errorCallback === 'function') {
4057 query.errorCallback(query.tx, reason);
4060 console.log("executeSql error calling user error callback: "+ex);
4063 tx.queryFailed(id, reason);
4067 console.log("executeSql error: "+e);
4077 * @param tx The transaction object that this query belongs to
4079 var DroidDB_Query = function(tx) {
4081 // Set the id of the query
4082 this.id = PhoneGap.createUUID();
4084 // Add this query to the queue
4085 droiddb.queryQueue[this.id] = this;
4088 this.resultSet = [];
4090 // Set transaction that this query belongs to
4093 // Add this query to transaction list
4094 this.tx.queryList[this.id] = this;
4097 this.successCallback = null;
4098 this.errorCallback = null;
4103 * Transaction object
4107 var DroidDB_Tx = function() {
4109 // Set the id of the transaction
4110 this.id = PhoneGap.createUUID();
4113 this.successCallback = null;
4114 this.errorCallback = null;
4117 this.queryList = {};
4121 * Mark query in transaction as complete.
4122 * If all queries are complete, call the user's transaction success callback.
4124 * @param id Query id
4126 DroidDB_Tx.prototype.queryComplete = function(id) {
4127 delete this.queryList[id];
4129 // If no more outstanding queries, then fire transaction success
4130 if (this.successCallback) {
4133 for (i in this.queryList) {
4134 if (this.queryList.hasOwnProperty(i)) {
4140 this.successCallback();
4142 console.log("Transaction error calling user success callback: " + e);
4149 * Mark query in transaction as failed.
4151 * @param id Query id
4152 * @param reason Error message
4154 DroidDB_Tx.prototype.queryFailed = function(id, reason) {
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 = {};
4162 if (this.errorCallback) {
4164 this.errorCallback(reason);
4166 console.log("Transaction error calling user error callback: " + e);
4172 * Execute SQL statement
4174 * @param sql SQL statement to execute
4175 * @param params Statement parameters
4176 * @param successCallback Success callback
4177 * @param errorCallback Error callback
4179 DroidDB_Tx.prototype.executeSql = function(sql, params, successCallback, errorCallback) {
4181 // Init params array
4182 if (typeof params === 'undefined') {
4186 // Create query and add to queue
4187 var query = new DroidDB_Query(this);
4188 droiddb.queryQueue[query.id] = query;
4191 query.successCallback = successCallback;
4192 query.errorCallback = errorCallback;
4195 PhoneGap.exec(null, null, "Storage", "executeSql", [sql, params, query.id]);
4198 var DatabaseShell = function() {
4202 * Start a transaction.
4203 * Does not support rollback in event of failure.
4205 * @param process {Function} The transaction function
4206 * @param successCallback {Function}
4207 * @param errorCallback {Function}
4209 DatabaseShell.prototype.transaction = function(process, errorCallback, successCallback) {
4210 var tx = new DroidDB_Tx();
4211 tx.successCallback = successCallback;
4212 tx.errorCallback = errorCallback;
4216 console.log("Transaction error: "+e);
4217 if (tx.errorCallback) {
4219 tx.errorCallback(e);
4221 console.log("Transaction error calling user error callback: "+e);
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
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();
4243 * For browsers with no localStorage we emulate it with SQLite. Follows the w3c api.
4244 * TODO: Do similar for sessionStorage.
4250 var CupcakeLocalStorage = function() {
4253 this.db = openDatabase('localStorage', '1.0', 'localStorage', 2621440);
4256 function setLength (length) {
4257 this.length = length;
4258 localStorage.length = length;
4260 this.db.transaction(
4261 function (transaction) {
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'];
4268 setLength(result.rows.length);
4269 PhoneGap.initializationComplete("cupcakeStorage");
4277 this.setItem = function(key, val) {
4278 if (typeof(storage[key])=='undefined') {
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]);
4289 this.getItem = function(key) {
4290 return storage[key];
4292 this.removeItem = function(key) {
4293 delete storage[key];
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]);
4302 this.clear = function() {
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', []);
4312 this.key = function(index) {
4314 for (var j in storage) {
4325 alert("Database error "+e+".");
4330 PhoneGap.addConstructor(function() {
4331 var setupDroidDB = function() {
4332 navigator.openDatabase = window.openDatabase = DroidDB_openDatabase;
4333 window.droiddb = new DroidDB();
4335 if (typeof window.openDatabase === "undefined") {
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.
4344 db = window.openDatabase_orig(name, version, desc, size);
4352 return DroidDB_openDatabase(name, version, desc, size);
4360 if (typeof window.localStorage === "undefined") {
4361 navigator.localStorage = window.localStorage = new CupcakeLocalStorage();
4362 PhoneGap.waitForInitialization("cupcakeStorage");