UNPKG

110 kBHTMLView Raw
1<!DOCTYPE html>
2
3<html lang="en">
4<head>
5 <meta charset="utf-8">
6 <meta name="viewport" content="width=device-width">
7 <title>CrossBrowdy API documentation Source: CrossBase/device/CB_Device.js</title>
8
9 <!--[if lt IE 9]>
10 <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
11 <![endif]-->
12 <link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">
13
14 <link type="text/css" rel="stylesheet" href="styles/site.cosmo.css">
15
16</head>
17
18<body style="min-width:800px; overflow-wrap:break-word; word-wrap:break-word; word-break:break-word; line-break:strict; hyphens:none; -webkit-hyphens:none; -moz-hyphens:none;">
19
20<div class="navbar navbar-default navbar-fixed-top ">
21<div class="container">
22 <div class="navbar-header">
23 <a class="navbar-brand" href="index.html">CrossBrowdy API documentation</a>
24 <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation">
25 <span class="icon-bar"></span>
26 <span class="icon-bar"></span>
27 <span class="icon-bar"></span>
28 </button>
29 </div>
30 <div class="navbar-collapse collapse" id="topNavigation">
31 <ul class="nav navbar-nav">
32
33 <li class="dropdown">
34 <a href="namespaces.list.html" class="dropdown-toggle" data-toggle="dropdown">Namespaces<b class="caret"></b></a>
35 <ul class="dropdown-menu inline">
36 <li><a href="CB_Arrays.html">CB_Arrays</a></li><li><a href="CB_AudioDetector.html">CB_AudioDetector</a></li><li><a href="CB_baseSymbols.html">CB_baseSymbols</a></li><li><a href="CB_Client.html">CB_Client</a></li><li><a href="CB_Collisions.html">CB_Collisions</a></li><li><a href="CB_Configuration.html">CB_Configuration</a></li><li><a href="CB_Configuration.CrossBase.html">CB_Configuration.CrossBase</a></li><li><a href="CB_Configuration.CrossBrowdy.html">CB_Configuration.CrossBrowdy</a></li><li><a href="CB_Controllers.html">CB_Controllers</a></li><li><a href="CB_Controllers_Proprietary.html">CB_Controllers_Proprietary</a></li><li><a href="CB_Controllers_Proprietary.WII.html">CB_Controllers_Proprietary.WII</a></li><li><a href="CB_Controllers_Proprietary.WII_U.html">CB_Controllers_Proprietary.WII_U</a></li><li><a href="CB_Device.html">CB_Device</a></li><li><a href="CB_Device.AmbientLight.html">CB_Device.AmbientLight</a></li><li><a href="CB_Device.Battery.html">CB_Device.Battery</a></li><li><a href="CB_Device.Location.html">CB_Device.Location</a></li><li><a href="CB_Device.Motion.html">CB_Device.Motion</a></li><li><a href="CB_Device.Orientation.html">CB_Device.Orientation</a></li><li><a href="CB_Device.Proximity.html">CB_Device.Proximity</a></li><li><a href="CB_Device.Vibration.html">CB_Device.Vibration</a></li><li><a href="CB_Elements.html">CB_Elements</a></li><li><a href="CB_Events.html">CB_Events</a></li><li><a href="CB_Keyboard.html">CB_Keyboard</a></li><li><a href="CB_Keyboard.chars.html">CB_Keyboard.chars</a></li><li><a href="CB_Keyboard.extended.html">CB_Keyboard.extended</a></li><li><a href="CB_Keyboard.keys.html">CB_Keyboard.keys</a></li><li><a href="CB_Modules.html">CB_Modules</a></li><li><a href="CB_Mouse.html">CB_Mouse</a></li><li><a href="CB_Mouse.CursorImage.html">CB_Mouse.CursorImage</a></li><li><a href="CB_Net.html">CB_Net</a></li><li><a href="CB_Net.Fetch.html">CB_Net.Fetch</a></li><li><a href="CB_Net.REST.html">CB_Net.REST</a></li><li><a href="CB_Net.Sockets.html">CB_Net.Sockets</a></li><li><a href="CB_Net.Sockets.SockJS.html">CB_Net.Sockets.SockJS</a></li><li><a href="CB_Net.XHR.html">CB_Net.XHR</a></li><li><a href="CB_Pointer.html">CB_Pointer</a></li><li><a href="CB_Screen.html">CB_Screen</a></li><li><a href="CB_Speaker.html">CB_Speaker</a></li><li><a href="CB_Touch.html">CB_Touch</a></li>
37 </ul>
38 </li>
39
40 <li class="dropdown">
41 <a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a>
42 <ul class="dropdown-menu inline">
43 <li><a href="CB_AudioFile.html">CB_AudioFile</a></li><li><a href="CB_AudioFile_API.AAPI.html">CB_AudioFile_API.AAPI</a></li><li><a href="CB_AudioFile_API.ACMP.html">CB_AudioFile_API.ACMP</a></li><li><a href="CB_AudioFile_API.SM2.html">CB_AudioFile_API.SM2</a></li><li><a href="CB_AudioFile_API.WAAPI.html">CB_AudioFile_API.WAAPI</a></li><li><a href="CB_AudioFileCache.html">CB_AudioFileCache</a></li><li><a href="CB_AudioFileSprites.html">CB_AudioFileSprites</a></li><li><a href="CB_AudioFileSpritesPool.html">CB_AudioFileSpritesPool</a></li><li><a href="CB_Canvas.html">CB_Canvas</a></li><li><a href="CB_GraphicSprites.html">CB_GraphicSprites</a></li><li><a href="CB_GraphicSpritesScene.html">CB_GraphicSpritesScene</a></li>
44 </ul>
45 </li>
46
47 <li class="dropdown">
48 <a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a>
49 <ul class="dropdown-menu inline">
50 <li><a href="global.html#CB_addCredits">CB_addCredits</a></li><li><a href="global.html#CB_BASE_NAME">CB_BASE_NAME</a></li><li><a href="global.html#CB_baseToBase">CB_baseToBase</a></li><li><a href="global.html#CB_baseToInt">CB_baseToInt</a></li><li><a href="global.html#CB_br2nl">CB_br2nl</a></li><li><a href="global.html#CB_brToNl">CB_brToNl</a></li><li><a href="global.html#CB_combineArraysOrObjects">CB_combineArraysOrObjects</a></li><li><a href="global.html#CB_combineAutomatically">CB_combineAutomatically</a></li><li><a href="global.html#CB_combineJSON">CB_combineJSON</a></li><li><a href="global.html#CB_combineURIParameters">CB_combineURIParameters</a></li><li><a href="global.html#CB_combineURLParameters">CB_combineURLParameters</a></li><li><a href="global.html#CB_console">CB_console</a></li><li><a href="global.html#CB_copyObject">CB_copyObject</a></li><li><a href="global.html#CB_countDecimalDigits">CB_countDecimalDigits</a></li><li><a href="global.html#CB_countDecimalPart">CB_countDecimalPart</a></li><li><a href="global.html#CB_countDecimals">CB_countDecimals</a></li><li><a href="global.html#CB_countIntegerDigits">CB_countIntegerDigits</a></li><li><a href="global.html#CB_countIntegerPart">CB_countIntegerPart</a></li><li><a href="global.html#CB_credits">CB_credits</a></li><li><a href="global.html#CB_CREDITS_DEFAULT">CB_CREDITS_DEFAULT</a></li><li><a href="global.html#CB_forceString">CB_forceString</a></li><li><a href="global.html#CB_forEach">CB_forEach</a></li><li><a href="global.html#CB_getBase64StringObject">CB_getBase64StringObject</a></li><li><a href="global.html#CB_getCookie">CB_getCookie</a></li><li><a href="global.html#CB_getDatum">CB_getDatum</a></li><li><a href="global.html#CB_getJSONPropertyValue">CB_getJSONPropertyValue</a></li><li><a href="global.html#CB_getLZStringObject">CB_getLZStringObject</a></li><li><a href="global.html#CB_getValueIndex">CB_getValueIndex</a></li><li><a href="global.html#CB_getValuePath">CB_getValuePath</a></li><li><a href="global.html#CB_includeJSFile">CB_includeJSFile</a></li><li><a href="global.html#CB_indexOf">CB_indexOf</a></li><li><a href="global.html#CB_init">CB_init</a></li><li><a href="global.html#CB_intToBase">CB_intToBase</a></li><li><a href="global.html#CB_isArray">CB_isArray</a></li><li><a href="global.html#CB_isEmail">CB_isEmail</a></li><li><a href="global.html#CB_isFileLocal">CB_isFileLocal</a></li><li><a href="global.html#CB_isString">CB_isString</a></li><li><a href="global.html#CB_lastIndexOf">CB_lastIndexOf</a></li><li><a href="global.html#CB_ltrim">CB_ltrim</a></li><li><a href="global.html#CB_NAME">CB_NAME</a></li><li><a href="global.html#CB_nl2br">CB_nl2br</a></li><li><a href="global.html#CB_nlToBr">CB_nlToBr</a></li><li><a href="global.html#CB_numberFormat">CB_numberFormat</a></li><li><a href="global.html#CB_numberOfDecimalDigits">CB_numberOfDecimalDigits</a></li><li><a href="global.html#CB_numberOfDecimals">CB_numberOfDecimals</a></li><li><a href="global.html#CB_numberOfIntegerDigits">CB_numberOfIntegerDigits</a></li><li><a href="global.html#CB_OPTIONS">CB_OPTIONS</a></li><li><a href="global.html#CB_parseJSON">CB_parseJSON</a></li><li><a href="global.html#CB_parseString">CB_parseString</a></li><li><a href="global.html#CB_regularExpressionString">CB_regularExpressionString</a></li><li><a href="global.html#CB_renderString">CB_renderString</a></li><li><a href="global.html#CB_replaceAll">CB_replaceAll</a></li><li><a href="global.html#CB_rtrim">CB_rtrim</a></li><li><a href="global.html#CB_scriptPath">CB_scriptPath</a></li><li><a href="global.html#CB_scriptPathCalculate">CB_scriptPathCalculate</a></li><li><a href="global.html#CB_setCookie">CB_setCookie</a></li><li><a href="global.html#CB_setDatum">CB_setDatum</a></li><li><a href="global.html#CB_sizeof">CB_sizeof</a></li><li><a href="global.html#CB_sizeOf">CB_sizeOf</a></li><li><a href="global.html#CB_stringifyJSON">CB_stringifyJSON</a></li><li><a href="global.html#CB_symmetricCall">CB_symmetricCall</a></li><li><a href="global.html#CB_symmetricCallClear">CB_symmetricCallClear</a></li><li><a href="global.html#CB_this">CB_this</a></li><li><a href="global.html#CB_trim">CB_trim</a></li><li><a href="global.html#CB_VERSION">CB_VERSION</a></li>
51 </ul>
52 </li>
53
54 </ul>
55
56 <div class="col-sm-3 col-md-3">
57 <form class="navbar-form" role="search">
58 <div class="input-group">
59 <input type="text" class="form-control" placeholder="Search" name="q" id="search-input">
60 <div class="input-group-btn">
61 <button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button>
62 </div>
63 </div>
64 </form>
65 </div>
66
67 </div>
68
69</div>
70</div>
71
72
73<div class="container" id="toc-content" style="width:100%;">
74<div class="row" style="width:100%;">
75
76
77 <div class="col-md-12">
78
79 <div id="main">
80
81
82 <h1 class="page-title">Source: CrossBase/device/CB_Device.js</h1>
83
84<section>
85 <article>
86 <pre
87 class="sunlight-highlight-javascript linenums">/**
88 * @file Device management. Contains the {@link CB_Device} static class.
89 * @author Joan Alba Maldonado &lt;workindalian@gmail.com>
90 * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}.
91 */
92
93
94/**
95 * Static class to manage the device. It will return itself if it is tried to be instantiated.
96 * @namespace
97 * @todo Think about defining a parameter on many of the events to disable automatic normalization of the event object.
98 */
99var CB_Device = function() { return CB_Device; };
100{
101 CB_Device.initialized = false; //It will tells whether the object has been initialized or not.
102
103
104 //Initializes all values:
105 CB_Device.init = function()
106 {
107 if (CB_Device.initialized) { return CB_Device; }
108
109 //The object has been initialized:
110 CB_Device.initialized = true;
111
112 //If now() static function not available, uses getTime() method:
113 if (!Date.now) { Date.now = function() { return new Date().getTime(); }; }
114
115 //If desired and it is possible, changes the CB_Device.getTime method to use high precission:
116 if (CB_Configuration.CrossBase.CB_Device_getTime_HIGH_PRECISION &amp;&amp; window.performance &amp;&amp; window.performance.timing &amp;&amp; window.performance.timing.navigationStart) //window.performance.now is always available (polyfilled).
117 {
118 CB_Device.getTime = function() { return window.performance.timing.navigationStart + window.performance.now() || Date.now(); };
119 }
120
121 //Initializes sub-classes:
122 CB_Device.Battery.init();
123
124 return CB_Device;
125 }
126
127
128 /**
129 * Gets a timestamp in milliseconds (elapsed since 1st of January 1970 00:00:00 UTC) representing the current time. Using high precision if the {@link CB_Configuration.CrossBase.CB_Device_getTime_HIGH_PRECISION} option is true (it would return '[window.performance.timing.navigationStart]{@link https://developer.mozilla.org/en-US/docs/Web/API/PerformanceTiming/navigationStart} + [window.performance.now]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance/now}()', where '[window.performance.now]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance/now}' could be polyfilled) or normal precision otherwise (it would return '[Date.now]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now}()', where '[Date.now]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now}' could be polyfilled).
130 * @function
131 * @returns {integer} Returns a timestamp in milliseconds (elapsed since 1st of January 1970 00:00:00 UTC) representing the current time or zero (0) if it was not possible.
132 */
133 CB_Device.getTime = function() //Can be replaced in CB_Device.init to use high precision.
134 {
135 return Date.now();
136 };
137
138
139 /**
140 * Gets the time elapsed since the [time origin]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin}. If possible, it uses [window.performance.now]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance/now}, which could be polyfilled (if it is polyfilled it will not have high precision timing but, if it is not, time precision/resolution will depend on the client).
141 * @function
142 * @returns {number} Returns the time elapsed since the [time origin]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin}. If possible, it uses [window.performance.now]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance/now}, which could be polyfilled (if it is polyfilled it will not have high precision timing but, if it is not, time precision/resolution will depend on the client).
143 */
144 CB_Device.getTiming = function() //Can be replaced in CB_Device.init to use high precision.
145 {
146 return window.performance.now();
147 };
148
149
150 //Sets a function to execute when a desired event is fired:
151 CB_Device._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture, target)
152 {
153 //If they are not set, use default values for optional parameters:
154 if (typeof(keepOldFunction) === "undefined" || keepOldFunction === null) { keepOldFunction = true; } //If not set, it keeps old function by default.
155 if (typeof(target) === "undefined" || target === null)
156 {
157 target = window;
158 }
159
160 //If a function has been sent:
161 if (typeof(eventFunction) === "function")
162 {
163 //If able, adds the function given to the event:
164 CB_Events.add(target, eventName, eventFunction, useCapture, keepOldFunction, true);
165 }
166 //...but if the function given is null, it will cancel the event:
167 else if (eventFunction === null)
168 {
169 CB_Events.removeByName(target, eventName);
170 }
171 }
172
173
174} //End of the static class CB_Device.
175
176
177/**
178 * Static class to manage the device's location. It will return itself if it is tried to be instantiated.
179 * @namespace
180 * @todo Normalize more differences between web clients.
181 */
182CB_Device.Location = function() { return CB_Device.Location; };
183{
184 /**
185 * Keeps the last watch ID that gets the location constantly. Used by the {@link CB_Device.Location.getConstantly} function.
186 * @var
187 * @readonly
188 * @type {integer|null}
189 * @default
190 */
191 CB_Device.Location.getConstantly_lastId = null;
192
193
194 /**
195 * Keeps the "WakeLock" ([MozWakeLock]{@link https://developer.mozilla.org/docs/Web/API/MozWakeLock}) object to be able to release the lock related with the GPS (so far, only works in Firefox/Firefox OS). Used by the {@link CB_Device.Location.keepAwake} function.
196 * @var
197 * @readonly
198 * @type {Object|null}
199 * @default
200 */
201 CB_Device.Location.keepAwake_locationLockGPS = null;
202
203
204 /**
205 * Keeps the callback function used when location can be gotten successfully for the {@link CB_Device.Location.get} function.
206 * @var
207 * @readonly
208 * @type {function|null}
209 * @default
210 */
211 CB_Device.Location.get_callbackOk = null;
212
213
214 /**
215 * Keeps the callback function used when there is an error getting the location for the {@link CB_Device.Location.get} function.
216 * @var
217 * @readonly
218 * @type {function|null}
219 * @default
220 */
221 CB_Device.Location.get_callbackError = null;
222
223
224 /**
225 * Keeps the last options used by the {@link CB_Device.Location.get} function.
226 * @var
227 * @readonly
228 * @type {Object|undefined}
229 * @default
230 */
231 CB_Device.Location.get_options = undefined;
232
233
234 /**
235 * Keeps the callback function used when location can be gotten successfully for the {@link CB_Device.Location.getConstantly} function.
236 * @var
237 * @readonly
238 * @type {function|null}
239 * @default
240 */
241 CB_Device.Location.getConstantly_callbackOk = null;
242
243
244 /**
245 * Keeps the callback function used when there is an error getting the location for the {@link CB_Device.Location.getConstantly} function.
246 * @var
247 * @readonly
248 * @type {function|null}
249 * @default
250 */
251 CB_Device.Location.getConstantly_callbackError = null;
252
253
254 /**
255 * Keeps the last options used by the {@link CB_Device.Location.getConstantly} function.
256 * @var
257 * @readonly
258 * @type {Object|undefined}
259 * @default
260 */
261 CB_Device.Location.getConstantly_options = undefined;
262
263
264 /**
265 * Tells whether the [Geolocation API]{@link https://developer.mozilla.org/docs/Web/API/Geolocation} (or compatible one as [Apache Cordova's Geolocation plugin]{@link https://github.com/apache/cordova-plugin-geolocation}) is supported or not.
266 * @function
267 * @returns {boolean}
268 */
269 CB_Device.Location.isSupported = function()
270 {
271 return (window.navigator &amp;&amp; "geolocation" in navigator &amp;&amp; typeof(navigator.geolocation.getCurrentPosition) !== "undefined");
272 }
273
274
275 CB_Device.Location._getFirstTime = false;
276 /**
277 * Gets the current position. Uses the [Geolocation API]{@link https://developer.mozilla.org/docs/Web/API/Geolocation} (or compatible one as [Apache Cordova's Geolocation plugin]{@link https://github.com/apache/cordova-plugin-geolocation}).
278 * @function
279 * @param {function} [callbackOk] - Callback that will be called if it gets the location successfully. Following the same rules as the first parameter of the native [getCurrentPosition]{@link https://developer.mozilla.org/docs/Web/API/Geolocation/getCurrentPosition} function.
280 * @param {function} [callbackError] - Callback that will be called if there is any error getting the location. Following the same rules as the second parameter of the native [getCurrentPosition]{@link https://developer.mozilla.org/docs/Web/API/Geolocation/getCurrentPosition} function.
281 * @param {Object} [options] - Object that represents the desired options. This parameter will be ignored if "keepOldOptions" is set to true. Following the same rules as the third parameter of the native [getCurrentPosition]{@link https://developer.mozilla.org/docs/Web/API/Geolocation/getCurrentPosition} function.
282 * @param {boolean} [keepOldCallbackOk=true] - If it is set to false, it will not keep the old previous "callbackOk" (if any) which was/were set in previous calls to this function.
283 * @param {boolean} [keepOldCallbackError=true] - If it is set to false, it will not keep the old previous "callbackError" (if any) which was/were set in previous calls to this function.
284 * @param {boolean} [keepOldOptions=false] - If it is set to true, it will ignore the given options and it will try to use the old previous options (if any) which were set in previous calls to this function.
285 * @returns {undefined|false} Returns false in the case that [Geolocation API]{@link https://developer.mozilla.org/docs/Web/API/Geolocation} (or compatible one as [Apache Cordova's Geolocation plugin]{@link https://github.com/apache/cordova-plugin-geolocation}) is not supported or undefined otherwise.
286 */
287 CB_Device.Location.get = function(callbackOk, callbackError, options, keepOldCallbackOk, keepOldCallbackError, keepOldOptions)
288 {
289 if (typeof(keepOldCallbackOk) === "undefined" || keepOldCallbackOk === null) { keepOldCallbackOk = true; } //If not set, it keeps old ok function by default.
290 if (typeof(keepOldCallbackError) === "undefined" || keepOldCallbackError === null) { keepOldCallbackError = true; } //If not set, it keeps old error function by default.
291
292 if (CB_Device.Location.isSupported() &amp;&amp; typeof(callbackOk) === "function")
293 {
294 if (!keepOldCallbackOk)
295 {
296 CB_Device.Location.get_callbackOk = callbackOk;
297 }
298 else
299 {
300 var callbackOkOld = CB_Device.Location.get_callbackOk;
301 CB_Device.Location.get_callbackOk =
302 function(locationObject)
303 {
304 if (typeof(callbackOkOld) === "function") { callbackOkOld(locationObject); }
305 if (typeof(callbackOk) === "function") { callbackOk(locationObject); }
306 };
307 }
308
309 if (!keepOldCallbackError)
310 {
311 CB_Device.Location.get_callbackError = callbackError;
312 }
313 else
314 {
315 var callbackErrorOld = CB_Device.Location.get_callbackError;
316 CB_Device.Location.get_callbackError =
317 function(error)
318 {
319 if (typeof(callbackErrorOld) === "function") { callbackErrorOld(error); }
320 if (typeof(callbackError) === "function") { callbackError(error); }
321 };
322 }
323
324 if (!keepOldOptions) { CB_Device.Location.get_options = options; }
325
326 if (CB_Device.Location._getFirstTime === true)
327 {
328 CB_Device.Location._getFirstTime = false;
329 navigator.geolocation.getCurrentPosition(function(){}, function(){}, {}); //Hack. Source: Niels Steenbeek @ http://stackoverflow.com/questions/3397585/navigator-geolocation-getcurrentposition-sometimes-works-sometimes-doesnt
330 }
331
332 return navigator.geolocation.getCurrentPosition(CB_Device.Location.get_callbackOk, CB_Device.Location.get_callbackError, CB_Device.Location.get_options);
333 }
334
335 return false;
336 }
337
338
339 CB_Device.Location._getConstantlyFirstTime = true;
340 /**
341 * Starts or stops getting the current position constantly (real-time) every time it changes. Uses the [Geolocation API]{@link https://developer.mozilla.org/docs/Web/API/Geolocation} (or compatible one as [Apache Cordova's Geolocation plugin]{@link https://github.com/apache/cordova-plugin-geolocation}).
342 * @function
343 * @param {function|integer} [callbackOkOrId={@link CB_Device.Location.getConstantly_lastId}] - In the case that we want to start getting the position, use a function callback that will be called every time it gets the location successfully (using the native [watchPosition]{@link https://developer.mozilla.org/docs/Web/API/Geolocation/watchPosition} function). To stop getting the position, use the watch ID that we want to stop (using the native [clearWatch]{@link https://developer.mozilla.org/docs/Web/API/Geolocation/clearWatch} function). Following the same rules as the first parameter of the native [watchPosition]{@link https://developer.mozilla.org/docs/Web/API/Geolocation/watchPosition} function (when we want to start watching) or the first parameter of [clearWatch]{@link https://developer.mozilla.org/docs/Web/API/Geolocation/clearWatch} function (when we want to stop watching).
344 * @param {function} [callbackError] - Callback that will be called if there is any error getting the location. Only used when we want to start getting the current position ("callbackOkOrId" is a function). Following the same rules as the second parameter of the native [watchPosition]{@link https://developer.mozilla.org/docs/Web/API/Geolocation/watchPosition} function.
345 * @param {Object} [options] - Object that represents the desired options. This parameter will be ignored if "keepOldOptions" is set to true. Only used when we want to start getting the current position ("callbackOkOrId" is a function). Following the same rules as the third parameter of the native [watchPosition]{@link https://developer.mozilla.org/docs/Web/API/Geolocation/watchPosition} function.
346 * @param {boolean} [keepOldCallbackOk=true] - If it is set to false, it will not keep the old previous "callbackOk" (if any) which was/were set in previous calls to this function. Only used when we want to start getting the current position ("callbackOkOrId" is a function).
347 * @param {boolean} [keepOldCallbackError=true] - If it is set to false, it will not keep the old previous "callbackError" (if any) which was/were set in previous calls to this function. Only used when we want to start getting the current position ("callbackOkOrId" is a function).
348 * @param {boolean} [keepOldOptions=false] - If it is set to true, it will ignore the given options and it will try to use the old previous options (if any) which were set in previous calls to this function. Only used when we want to start getting the current position ("callbackOkOrId" is a function).
349 * @returns {integer|undefined|false} Returns false in the case that [Geolocation API]{@link https://developer.mozilla.org/docs/Web/API/Geolocation} (or compatible one as [Apache Cordova's Geolocation plugin]{@link https://github.com/apache/cordova-plugin-geolocation}) is not supported. In the case that we want to start getting the current position ("callbackOkOrId" is a function), it will return the watch ID that has been created. In the case that we want to stop getting the position ("callbackOkOrId" is a watch ID), it will return undefined.
350 */
351 CB_Device.Location.getConstantly = function(callbackOkOrId, callbackError, options, keepOldCallbackOk, keepOldCallbackError, keepOldOptions)
352 {
353 //If either callback function has been given, starts getting the position constantly:
354 if (typeof(callbackOkOrId) === "function")
355 {
356 if (typeof(keepOldCallbackOk) === "undefined" || keepOldCallbackOk === null) { keepOldCallbackOk = true; } //If not set, it keeps old ok function by default.
357 if (typeof(keepOldCallbackError) === "undefined" || keepOldCallbackError === null) { keepOldCallbackError = true; } //If not set, it keeps old error function by default.
358
359 if (CB_Device.Location.isSupported() &amp;&amp; typeof(navigator.geolocation.watchPosition) !== "undefined")
360 {
361 if (!keepOldCallbackOk)
362 {
363 CB_Device.Location.getConstantly_callbackOk = callbackOkOrId;
364 }
365 else
366 {
367 var callbackOkOld = CB_Device.Location.getConstantly_callbackOk;
368 CB_Device.Location.getConstantly_callbackOk =
369 function(locationObject)
370 {
371 if (typeof(callbackOkOld) === "function") { callbackOkOld(locationObject); }
372 if (typeof(callbackOkOrId) === "function") { callbackOkOrId(locationObject); }
373 };
374 }
375
376 if (!keepOldCallbackError)
377 {
378 CB_Device.Location.getConstantly_callbackError = callbackError;
379 }
380 else
381 {
382 var callbackErrorOld = CB_Device.Location.getConstantly_callbackError;
383 CB_Device.Location.getConstantly_callbackError =
384 function(error)
385 {
386 if (typeof(callbackErrorOld) === "function") { callbackErrorOld(error); }
387 if (typeof(callbackError) === "function") { callbackError(error); }
388 };
389 }
390
391 if (!keepOldOptions) { CB_Device.Location.getConstantly_options = options; }
392
393 if (CB_Device.Location._getConstantlyFirstTime === true)
394 {
395 CB_Device.Location._getConstantlyFirstTime = false;
396 navigator.geolocation.watchPosition(function(){}, function(){}, {}); //Hack. Source: Niels Steenbeek @ http://stackoverflow.com/questions/3397585/navigator-geolocation-getcurrentposition-sometimes-works-sometimes-doesnt
397 }
398
399 CB_Device.Location.getConstantly_lastId = navigator.geolocation.watchPosition(CB_Device.Location.getConstantly_callbackOk, CB_Device.Location.getConstantly_callbackError, CB_Device.Location.getConstantly_options);
400
401 return CB_Device.Location.getConstantly_lastId;
402 }
403 }
404 //...otherwise, stops getting the position constantly:
405 else
406 {
407 if (window.navigator &amp;&amp; "geolocation" in navigator &amp;&amp; typeof(navigator.geolocation.clearWatch) !== "undefined")
408 {
409 //if (typeof(callbackOkOrId) === "undefined" || callbackOkOrId === null) { callbackOkOrId = CB_Device.Location.getConstantly_lastId; }
410 if (isNaN(callbackOkOrId) || CB_trim(callbackOkOrId) === "") { callbackOkOrId = CB_Device.Location.getConstantly_lastId; }
411 return navigator.geolocation.clearWatch(callbackOkOrId);
412 }
413 }
414
415 return false;
416 }
417
418
419 /**
420 * Stops getting the current position constantly (real-time) every time it changes. Uses the [Geolocation API]{@link https://developer.mozilla.org/docs/Web/API/Geolocation} (or compatible one as [Apache Cordova's Geolocation plugin]{@link https://github.com/apache/cordova-plugin-geolocation}).
421 * @function
422 * @param {integer} [id={@link CB_Device.Location.getConstantly_lastId}] - The watch ID that we want to stop. Following the same rules as the first parameter of the native [clearWatch]{@link https://developer.mozilla.org/docs/Web/API/Geolocation/clearWatch} function.
423 * @param {boolean} [keepOldCallbackOk=false] - If it is set to false, it will not remove the current "callbackOk" (if any) which was/were set previously.
424 * @param {boolean} [keepOldCallbackError=false] - If it is set to false, it will remove the current "callbackError" (if any) which was/were set previously.
425 * @param {boolean} [keepOldOptions=false] - If it is set to false, it will remove the current "options" (if any) which were set previously.
426 * @returns {undefined|false} Returns false in the case that [Geolocation API]{@link https://developer.mozilla.org/docs/Web/API/Geolocation} (or compatible one as [Apache Cordova's Geolocation plugin]{@link https://github.com/apache/cordova-plugin-geolocation}) is not supported or undefined otherwise.
427 */
428 CB_Device.Location.getConstantlyDisable = function(id, keepOldCallbackOk, keepOldCallbackError, keepOldOptions)
429 {
430 //if (typeof(id) === "function") { id = undefined; } //Prevents calling CB_Device.Location.getConstantly with a function as parameter since that is for starting the watcher.
431 if (isNaN(id) || !id) { id = undefined; } //Prevents calling CB_Device.Location.getConstantly with a function as parameter since that is for starting the watcher.
432 if (!keepOldCallbackOk) { CB_Device.Location.getConstantly_callbackOk = null; }
433 if (!keepOldCallbackError) { CB_Device.Location.getConstantly_callbackError = null; }
434 if (!keepOldOptions) { CB_Device.Location.getConstantly_options = undefined; }
435 return CB_Device.Location.getConstantly(id);
436 }
437
438
439 /**
440 * Keeps or stops keeping the application getting the position, even when the application is invisible or screen is locked, by using [requestWakeLock]{@link https://developer.mozilla.org/docs/Web/API/Navigator/requestWakeLock} (so far, only works in Firefox/Firefox OS).
441 * @function
442 * @param {boolean} [keepAwake=true] - Defines whether we want to keep it awake or stop doing it.
443 * @param {Object} [lock={@link CB_Device.Location.keepAwake_locationLockGPS}] - The "WakeLock" ([MozWakeLock]{@link https://developer.mozilla.org/docs/Web/API/MozWakeLock}) object that we want to unlock. It will be used only when "keepAwake" is set to false.
444 * @returns {undefined|Object|false} Returns false in the case that "WakeLock" ([MozWakeLock]{@link https://developer.mozilla.org/docs/Web/API/MozWakeLock}) is not supported or something went wrong. Returns the "WakeLock" ([MozWakeLock]{@link https://developer.mozilla.org/docs/Web/API/MozWakeLock}) object in the case that we wanted to keep it awake ("keepAwake" is set to true). Returns undefined in the case that we do not want it to keep it awake ("keepAwake" is set to false and the lock is a valid "WakeLock" object).
445 */
446 CB_Device.Location.keepAwake = function(keepAwake, lock)
447 {
448 if (typeof(keepAwake) === "undefined" || keepAwake === null) { keepAwake = true; }
449
450 //If we want to lock the device to keep it awake:
451 if (keepAwake)
452 {
453 if (window.navigator &amp;&amp; typeof(window.navigator.requestWakeLock) !== "undefined")
454 {
455 CB_Device.Location.keepAwake_locationLockGPS = window.navigator.requestWakeLock("gps"); //So far, only works in Firefox/Firefox OS.
456 return CB_Device.Location.keepAwake_locationLockGPS;
457 }
458 }
459 //...otherwise, if we want to release the lock that keeps the device awake:
460 else
461 {
462 if (typeof(lock) === "undefined" || lock === null)
463 {
464 if (typeof(CB_Device.Location.keepAwake_locationLockGPS) !== "undefined" &amp;&amp; CB_Device.Location.keepAwake_locationLockGPS !== null) { lock = CB_Device.Location.keepAwake_locationLockGPS; }
465 else { return false; }
466 }
467 if (typeof(lock.unlock) !== "undefined") { return lock.unlock(); } //So far, only works in Firefox/Firefox OS.
468 }
469 return false;
470 }
471
472} //End of the static class CB_Device.Location.
473
474
475/**
476 * Static class to manage the device's orientation. It will return itself if it is tried to be instantiated.
477 * @namespace
478 * @todo Normalize more differences between web clients.
479 */
480CB_Device.Orientation = function() { return CB_Device.Orientation; };
481{
482 /**
483 * Keeps the last watch ID that gets the compass heading constantly using the [Apache Cordova's Device Orientation plugin]{@link https://github.com/apache/cordova-plugin-device-orientation}. Used by the {@link CB_Device.Orientation.cordova_getCompassConstantly} function.
484 * @var
485 * @readonly
486 * @type {integer|null}
487 * @default
488 */
489 CB_Device.Orientation.cordova_getCompassConstantly_lastId = null;
490
491
492 /**
493 * Tells whether the [Device Orientation Event]{@link https://developer.mozilla.org/docs/Web/API/DeviceOrientationEvent} (used by the [Device Orientation API]{@link https://developer.mozilla.org/docs/Web/API/Detecting_device_orientation} or compatible one) is supported or not.
494 * @function
495 * @returns {boolean}
496 * @todo Think about using the "ondeviceorientationabsolute" event.
497 */
498 CB_Device.Orientation.isSupported = function()
499 {
500 return ("DeviceOrientationEvent" in window || "ondeviceorientation" in window);
501 }
502
503
504 /**
505 * Tells whether the [MozOrientation API]{@link https://developer.mozilla.org/docs/Web/Events/MozOrientation} is supported or not.
506 * @function
507 * @returns {boolean}
508 */
509 CB_Device.Orientation.isMozOrientationSupported = function()
510 {
511 return ("MozOrientation" in window);
512 }
513
514
515 /**
516 * Sets a function to execute for the [Device Orientation Event]{@link https://developer.mozilla.org/docs/Web/API/DeviceOrientationEvent} (used by the [Device Orientation API]{@link https://developer.mozilla.org/docs/Web/API/Detecting_device_orientation} or compatible one) or removes it. Falls back to the [MozOrientation API]{@link https://developer.mozilla.org/docs/Web/Events/MozOrientation} if possible.
517 * @function
518 * @param {function|null} eventFunction - The function that will be called when the event is fired. The event object received will already be normalized by the {@link CB_Device.Orientation.normalizeEvent} function automatically. Following the same rules as in {@link https://developer.mozilla.org/docs/Web/API/DeviceOrientationEvent}. If a null value is used, the event will be removed.
519 * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not.
520 * @param {float} [useCapture=false] - Defines whether the event we want to add will use capture or not. This parameter will be effective only if the current client supports the [addEventListener]{@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener} method and will be used as its third parameter.
521 * @returns {undefined|false} Returns false in the case that neither the [Device Orientation API]{@link https://developer.mozilla.org/docs/Web/API/Detecting_device_orientation} (or compatible one) nor the [MozOrientation API]{@link https://developer.mozilla.org/docs/Web/Events/MozOrientation} are supported or undefined otherwise.
522 * @todo Think about using the "deviceorientationabsolute" event.
523 */
524 CB_Device.Orientation.onChange = function(eventFunction, keepOldFunction, useCapture)
525 {
526 if (CB_Device.Orientation.isSupported())
527 {
528 return CB_Device.Orientation._setEvent("deviceorientation", eventFunction, keepOldFunction, useCapture, window);
529 }
530 else if (CB_Device.Orientation.isMozOrientationSupported())
531 {
532 return CB_Device.Orientation._setEvent("MozOrientation", eventFunction, keepOldFunction, useCapture, window);
533 }
534 else { return false; }
535 }
536
537
538 //Sets a function to execute when a desired event is fired:
539 CB_Device.Orientation._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture, target)
540 {
541 var wrapperFunction = eventFunction;
542 if (typeof(eventFunction) === "function")
543 {
544 wrapperFunction = function(e)
545 {
546 e = CB_Device.Orientation.normalizeEvent(e, eventName);
547 return eventFunction(e);
548 };
549 }
550 CB_Device._setEvent(eventName, wrapperFunction, keepOldFunction, useCapture, target);
551 }
552
553
554 /**
555 * Normalizes the data gotten from the [Device Orientation Event]{@link https://developer.mozilla.org/docs/Web/API/DeviceOrientationEvent} produced by different clients to try to match the [Device Orientation API]{@link https://developer.mozilla.org/docs/Web/API/Detecting_device_orientation} and follow always the same rules as much as possible.
556 * @function
557 * @param {Event} e - The event object that we want to normalize.
558 * @param {('deviceorientation'|'MozOrientation')} eventName - The name of the event that we want to normalize. Case sensitive.
559 * @returns {Event} Returns the given event object again but normalized (if possible).
560 * @todo Think about using the "deviceorientationabsolute" event.
561 * @todo Normalize more differences between web clients.
562 */
563 CB_Device.Orientation.normalizeEvent = function(e, eventName)
564 {
565 e = CB_Events.normalize(e);
566 if (typeof(e) !== "undefined" &amp;&amp; e !== null)
567 {
568 if (eventName === "deviceorientation")
569 {
570 if (e.webkitCompassHeading) { e.alpha = /*360 - */e.webkitCompassHeading; } //Source: https://mobiforge.com/design-development/html5-mobile-web-device-orientation-events and https://dev.opera.com/articles/w3c-device-orientation-usage/
571 }
572 else if (eventName === "MozOrientation")
573 {
574 if (!e.gamma &amp;&amp; !e.beta) //For FF3.6+ (Source: https://developer.mozilla.org/en-US/docs/Web/Events/MozOrientation)
575 {
576 e.gamma = -(e.x * (180 / Math.PI));
577 e.beta = -(e.y * (180 / Math.PI));
578 }
579 }
580 //TODO: there are still more differences between web clients!
581 }
582 return e;
583 }
584
585
586 /**
587 * Tells whether the [Compass Needs Calibration Event]{@link https://w3c.github.io/deviceorientation/spec-source-orientation.html#compassneedscalibration} (used by the [Device Orientation API]{@link https://developer.mozilla.org/docs/Web/API/Detecting_device_orientation} or compatible one) is supported or not.
588 * @function
589 * @returns {boolean}
590 */
591 CB_Device.Orientation.isCompassNeedsCalibrationSupported = function()
592 {
593 return ("CompassNeedsCalibration" in window || "oncompassneedscalibration" in window); //return ("DeviceMotionEvent" in window || "ondevicemotion" in window);
594 }
595
596
597 /**
598 * Sets a function to execute for the [Compass Needs Calibration Event]{@link https://w3c.github.io/deviceorientation/spec-source-orientation.html#compassneedscalibration} (used by the [Device Orientation API]{@link https://developer.mozilla.org/docs/Web/API/Detecting_device_orientation} or compatible one) or removes it.
599 * @function
600 * @param {function|null} eventFunction - The function that will be called when the event is fired. Following the same rules as in {@link https://w3c.github.io/deviceorientation/spec-source-orientation.html#compassneedscalibration}. If a null value is used, the event will be removed.
601 * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not.
602 * @param {float} [useCapture=false] - Defines whether the event we want to add will use capture or not. This parameter will be effective only if the current client supports the [addEventListener]{@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener} method and will be used as its third parameter.
603 * @returns {undefined|false} Returns false in the case that the [Compass Needs Calibration Event]{@link https://w3c.github.io/deviceorientation/spec-source-orientation.html#compassneedscalibration} is not supported or undefined otherwise.
604 */
605 CB_Device.Orientation.onCompassNeedsCalibration = function(eventFunction, keepOldFunction, useCapture)
606 {
607 if (!CB_Device.Orientation.isCompassNeedsCalibrationSupported()) { return false; }
608 return CB_Device._setEvent("compassneedscalibration", eventFunction, keepOldFunction, useCapture, window);
609 }
610
611
612 /**
613 * Tells whether the [Apache Cordova's Device Orientation plugin]{@link https://github.com/apache/cordova-plugin-device-orientation} is available or not.
614 * @function
615 * @returns {boolean}
616 */
617 CB_Device.Orientation.cordova_isCompassSupported = function()
618 {
619 return (typeof(navigator) !== "undefined" &amp;&amp; navigator !== null &amp;&amp; navigator.compass &amp;&amp; navigator.compass.getCurrentHeading &amp;&amp; navigator.compass.watchHeading &amp;&amp; navigator.compass.clearWatch);
620 }
621
622
623 /**
624 * Gets the compass heading using the [Apache Cordova's Device Orientation plugin]{@link https://github.com/apache/cordova-plugin-device-orientation}. Uses "navigator.compass.getCurrentHeading" internally.
625 * @function
626 * @param {function} callbackOk - The function that will be called when it succeeds getting the compass heading. Following the same rules as in {@link https://github.com/apache/cordova-plugin-device-orientation} ("navigator.compass.getCurrentHeading" function).
627 * @param {function} callbackError - The function that will be called if there is any error getting the compass heading. Following the same rules as in {@link https://github.com/apache/cordova-plugin-device-orientation} ("navigator.compass.getCurrentHeading" function).
628 * @returns {undefined|false} Returns false in the case that the [Apache Cordova's Device Orientation plugin]{@link https://github.com/apache/cordova-plugin-device-orientation} is not supported or undefined otherwise.
629 * @todo Add a function to normalize the event and call it automatically.
630 */
631 CB_Device.Orientation.cordova_getCompass = function(callbackOk, callbackError)
632 {
633 if (!CB_Device.Orientation.cordova_isCompassSupported()) { return false; }
634 navigator.compass.getCurrentHeading(callbackOk, callbackError);
635 }
636
637
638 /**
639 * Starts or stops getting the compass heading constantly at a regular interval. Uses the [Apache Cordova's Device Orientation plugin]{@link https://github.com/apache/cordova-plugin-device-orientation} ("navigator.compass.watchHeading" and "navigator.compass.clearWatch" functions).
640 * @function
641 * @param {function|integer} [callbackOkOrId={@link CB_Device.Orientation.cordova_getCompassConstantly_lastId}] - In the case that we want to start getting the compass heading, use a function callback that will be called regularly when the compass heading is gotten successfully (using the "navigator.compass.watchHeading" function). To stop getting the compass heading, use the watch ID that we want to stop (using the "navigator.compass.clearWatch" function). Following the same rules as the first parameter of the "navigator.compass.watchHeading" function (when we want to start watching) or the first parameter of "navigator.compass.clearWatch" function (when we want to stop watching) described in {@link https://github.com/apache/cordova-plugin-device-orientation}.
642 * @param {function} [callbackError] - Callback that will be called if there is any error getting the compass heading. Only used when we want to start getting the compass heading ("callbackOkOrId" is a function). Following the same rules as the second parameter of the "navigator.compass.watchHeading" function described in {@link https://github.com/apache/cordova-plugin-device-orientation}.
643 * @param {Object} [options] - Object that represents the desired options. Only used when we want to start getting the compass heading ("callbackOkOrId" is a function). Following the same rules as the third parameter of the "navigator.compass.watchHeading" function described in {@link https://github.com/apache/cordova-plugin-device-orientation}.
644 * @returns {integer|undefined|false} Returns false in the case that [Apache Cordova's Device Orientation plugin]{@link https://github.com/apache/cordova-plugin-device-orientation} is not supported. In the case that we want to start getting the compass heading ("callbackOkOrId" is a function), it will return the watch ID that has been created. In the case that we want to stop getting the compass heading ("callbackOkOrId" is a watch ID), it will return undefined.
645 * @todo Add a function to normalize the event and call it automatically.
646 * @todo Add parameters to keep old callbacks and options.
647 */
648 CB_Device.Orientation.cordova_getCompassConstantly = function(callbackOkOrId, callbackError, options) //Note: options can be an object with two optional properties ("frequency" and "filter").
649 {
650 if (!CB_Device.Orientation.cordova_isCompassSupported()) { return false; }
651
652 //If either callback function has been given, starts getting the compass heading constantly:
653 if (typeof(callbackOkOrId) === "function")
654 {
655 CB_Device.Orientation.cordova_getCompassConstantly_lastId = navigator.compass.watchHeading(callbackOkOrId, callbackError, options);
656 return CB_Device.Orientation.cordova_getCompassConstantly_lastId;
657 }
658 //...otherwise, stops getting the compass heading constantly:
659 else
660 {
661 //if (typeof(callbackOkOrId) === "undefined" || callbackOkOrId === null) { callbackOkOrId = CB_Device.Orientation.cordova_getCompassConstantly_lastId; }
662 if (isNaN(callbackOkOrId) || CB_trim(callbackOkOrId) === "") { callbackOkOrId = CB_Device.Orientation.cordova_getCompassConstantly_lastId; }
663 navigator.compass.clearWatch(callbackOkOrId);
664 return;
665 }
666 return false;
667 }
668
669
670 /**
671 * Stops getting the compass heading constantly at a regular interval. Uses the [Apache Cordova's Device Orientation plugin]{@link https://github.com/apache/cordova-plugin-device-orientation} ("navigator.compass.clearWatch" function).
672 * @function
673 * @param {integer} [id={@link CB_Device.Orientation.cordova_getCompassConstantly_lastId}] - The watch ID that we want to stop. Following the same rules as the first parameter of the "navigator.compass.clearWatch" function described in {@link https://github.com/apache/cordova-plugin-device-orientation}.
674 * @returns {undefined|false} Returns false in the case that [Apache Cordova's Device Orientation plugin]{@link https://github.com/apache/cordova-plugin-device-orientation} is not supported or undefined otherwise.
675 * @todo Add parameters to keep old callbacks and options.
676 */
677 CB_Device.Orientation.cordova_getCompassConstantlyDisable = function(id)
678 {
679 if (typeof(id) === "function") { id = undefined; } //Prevents calling CB_Device.Orientation.cordova_getCompassConstantly with a function as parameter since that is for starting the watcher.
680 return CB_Device.Orientation.cordova_getCompassConstantly(id);
681 }
682
683} //End of the static class CB_Device.Orientation.
684
685
686/**
687 * Static class to manage the device's motion. It will return itself if it is tried to be instantiated.
688 * @namespace
689 * @todo Normalize more differences between web clients.
690 */
691CB_Device.Motion = function() { return CB_Device.Motion; };
692{
693 /**
694 * Keeps the last watch ID that gets the acceleration constantly using the [Apache Cordova's Device Motion plugin]{@link https://github.com/apache/cordova-plugin-device-motion}. Used by the {@link CB_Device.Motion.cordova_getAccelerationConstantly} function.
695 * @var
696 * @readonly
697 * @type {integer|null}
698 * @default
699 */
700 CB_Device.Motion.cordova_getAccelerationConstantly_lastId = null;
701
702
703 /**
704 * Tells whether the [Device Motion Event]{@link https://developer.mozilla.org/docs/Web/API/DeviceMotionEvent} (used by the [Device Orientation API]{@link https://developer.mozilla.org/docs/Web/API/Detecting_device_orientation} or compatible one) is supported or not.
705 * @function
706 * @returns {boolean}
707 */
708 CB_Device.Motion.isSupported = function()
709 {
710 return ("DeviceMotionEvent" in window || "ondevicemotion" in window);
711 }
712
713
714 /**
715 * Sets a function to execute for the [Device Motion Event]{@link https://developer.mozilla.org/docs/Web/API/DeviceMotionEvent} (used by the [Device Orientation API]{@link https://developer.mozilla.org/docs/Web/API/Detecting_device_orientation} or compatible one) or removes it.
716 * @function
717 * @param {function|null} eventFunction - The function that will be called when the event is fired. Following the same rules as in {@link https://developer.mozilla.org/docs/Web/API/DeviceMotionEvent}. If a null value is used, the event will be removed.
718 * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not.
719 * @param {float} [useCapture=false] - Defines whether the event we want to add will use capture or not. This parameter will be effective only if the current client supports the [addEventListener]{@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener} method and will be used as its third parameter.
720 * @returns {undefined|false} Returns false in the case that the [Device Motion Event]{@link https://developer.mozilla.org/docs/Web/API/DeviceMotionEvent} is not supported or undefined otherwise.
721 */
722 CB_Device.Motion.onChange = function(eventFunction, keepOldFunction, useCapture)
723 {
724 if (!CB_Device.Motion.isSupported()) { return false; }
725 return CB_Device._setEvent("devicemotion", eventFunction, keepOldFunction, useCapture, window);
726 }
727
728
729 /**
730 * Tells whether the [Apache Cordova's Device Motion plugin]{@link https://github.com/apache/cordova-plugin-device-motion} is available or not.
731 * @function
732 * @returns {boolean}
733 */
734 CB_Device.Motion.cordova_isAccelerationSupported = function()
735 {
736 return (typeof(navigator) !== "undefined" &amp;&amp; navigator !== null &amp;&amp; navigator.accelerometer &amp;&amp; navigator.accelerometer.getCurrentAcceleration &amp;&amp; navigator.accelerometer.watchAcceleration &amp;&amp; navigator.accelerometer.clearWatch);
737 }
738
739
740 /**
741 * Gets the acceleration using the [Apache Cordova's Device Motion plugin]{@link https://github.com/apache/cordova-plugin-device-motion}. Uses "navigator.accelerometer.getCurrentAcceleration" internally.
742 * @function
743 * @param {function} callbackOk - The function that will be called when it succeeds getting the acceleration. The event object received will already be normalized by the {@link CB_Device.Motion.cordova_getAccelerationNormalized} function automatically. Following the same rules as in {@link https://github.com/apache/cordova-plugin-device-motion} ("navigator.accelerometer.getCurrentAcceleration" function).
744 * @param {function} callbackError - The function that will be called if there is any error getting the acceleration. Following the same rules as in {@link https://github.com/apache/cordova-plugin-device-motion} ("navigator.accelerometer.getCurrentAcceleration" function).
745 * @returns {undefined|false} Returns false in the case that the [Apache Cordova's Device Motion plugin]{@link https://github.com/apache/cordova-plugin-device-motion} is not supported or undefined otherwise.
746 */
747 CB_Device.Motion.cordova_getAcceleration = function(callbackOk, callbackError)
748 {
749 if (!CB_Device.Motion.cordova_isAccelerationSupported()) { return false; }
750 var callbackOkWrapper = function(e) { e = CB_Device.Motion.cordova_getAccelerationNormalized(e); if (typeof(callbackOk) === "function") { callbackOk(e); } } //Normalizes the event.
751 navigator.accelerometer.getCurrentAcceleration(callbackOkWrapper, callbackError);
752 }
753
754
755 /**
756 * Starts or stops getting the acceleration constantly at a regular interval. Uses the [Apache Cordova's Device Motion plugin]{@link https://github.com/apache/cordova-plugin-device-motion} ("navigator.accelerometer.watchAcceleration" and "navigator.accelerometer.clearWatch" functions).
757 * @function
758 * @param {function|integer} [callbackOkOrId={@link CB_Device.Motion.cordova_getAccelerationConstantly_lastId}] - In the case that we want to start getting the acceleration, use a function callback that will be called regularly when the acceleration is gotten successfully (using the "navigator.accelerometer.watchAcceleration" function) and the event object received will already be normalized by the {@link CB_Device.Motion.cordova_getAccelerationNormalized} function automatically. To stop getting the acceleration, use the watch ID that we want to stop (using the "navigator.accelerometer.clearWatch" function). Following the same rules as the first parameter of the "navigator.accelerometer.watchAcceleration" function (when we want to start watching) or the first parameter of "navigator.accelerometer.clearWatch" function (when we want to stop watching) described in {@link https://github.com/apache/cordova-plugin-device-motion}.
759 * @param {function} [callbackError] - Callback that will be called if there is any error getting the acceleration. Only used when we want to start getting the acceleration ("callbackOkOrId" is a function). Following the same rules as the second parameter of the "navigator.accelerometer.watchAcceleration" function described in {@link https://github.com/apache/cordova-plugin-device-motion}.
760 * @param {Object} [options] - Object that represents the desired options. Only used when we want to start getting the acceleration ("callbackOkOrId" is a function). Following the same rules as the third parameter of the "navigator.accelerometer.watchAcceleration" function described in {@link https://github.com/apache/cordova-plugin-device-motion}.
761 * @returns {integer|undefined|false} Returns false in the case that [Apache Cordova's Device Motion plugin]{@link https://github.com/apache/cordova-plugin-device-motion} is not supported. In the case that we want to start getting the acceleration ("callbackOkOrId" is a function), it will return the watch ID that has been created. In the case that we want to stop getting the acceleration ("callbackOkOrId" is a watch ID), it will return undefined.
762 * @todo Add parameters to keep old callbacks and options.
763 */
764 CB_Device.Motion.cordova_getAccelerationConstantly = function(callbackOkOrId, callbackError, options) //Note: options can be an object with an optional property ("frequency").
765 {
766 if (!CB_Device.Motion.cordova_isAccelerationSupported()) { return false; }
767
768 //If either callback function has been given, starts getting the acceleration constantly:
769 if (typeof(callbackOkOrId) === "function")
770 {
771 var callbackOkOrIdWrapper = function(e) { e = CB_Device.Motion.cordova_getAccelerationNormalized(e); if (typeof(callbackOkOrId) === "function") { callbackOkOrId(e); } } //Normalizes the event.
772 CB_Device.Motion.cordova_getAccelerationConstantly_lastId = navigator.accelerometer.watchAcceleration(callbackOkOrIdWrapper, callbackError, options);
773 return CB_Device.Motion.cordova_getAccelerationConstantly_lastId;
774 }
775 //...otherwise, stops getting the acceleration constantly:
776 else
777 {
778 //if (typeof(callbackOkOrId) === "undefined" || callbackOkOrId === null) { callbackOkOrId = CB_Device.Motion.cordova_getAccelerationConstantly_lastId; }
779 if (isNaN(callbackOkOrId) || CB_trim(callbackOkOrId) === "") { callbackOkOrId = CB_Device.Motion.cordova_getAccelerationConstantly_lastId; }
780 navigator.accelerometer.clearWatch(callbackOkOrId);
781 return;
782 }
783 return false;
784 }
785
786
787 /**
788 * Stops getting the acceleration constantly at a regular interval. Uses the [Apache Cordova's Device Motion plugin]{@link https://github.com/apache/cordova-plugin-device-motion} ("navigator.accelerometer.clearWatch" function).
789 * @function
790 * @param {integer} [id={@link CB_Device.Motion.cordova_getAccelerationConstantly_lastId}] - The watch ID that we want to stop. Following the same rules as the first parameter of the "navigator.accelerometer.clearWatch" function described in {@link https://github.com/apache/cordova-plugin-device-motion}.
791 * @returns {undefined|false} Returns false in the case that [Apache Cordova's Device Motion plugin]{@link https://github.com/apache/cordova-plugin-device-motion} is not supported or undefined otherwise.
792 * @todo Add parameters to keep old callbacks and options.
793 */
794 CB_Device.Motion.cordova_getAccelerationConstantlyDisable = function(id)
795 {
796 if (typeof(id) === "function") { id = undefined; } //Prevents calling CB_Device.Motion.cordova_getAccelerationConstantly with a function as parameter since that is for starting the watcher.
797 return CB_Device.Motion.cordova_getAccelerationConstantly(id);
798 }
799
800
801 /**
802 * Normalizes the data gotten from the [Apache Cordova's Device Motion plugin]{@link https://github.com/apache/cordova-plugin-device-motion} to try to match the [Device Motion Event]{@link https://developer.mozilla.org/docs/Web/API/DeviceMotionEvent} and follow always the same rules as much as possible.
803 * @function
804 * @param {Object} accelerometerData - The acceleration object that we want to normalize.
805 * @returns {Event} Returns the given acceleration object again but normalized (if possible).
806 * @todo Normalize the values without gravity too (accelerometerData.acceleration.x, accelerometerData.acceleration.y, accelerometerData.acceleration.z) if possible (needs gyroscope probably) and maybe more properties.
807 */
808 CB_Device.Motion.cordova_getAccelerationNormalized = function(accelerometerData)
809 {
810 if (typeof(accelerometerData) !== "undefined" &amp;&amp; accelerometerData !== null)
811 {
812 if (typeof(accelerometerData.accelerationIncludingGravity) === "undefined" || accelerometerData.accelerationIncludingGravity === null)
813 {
814 accelerometerData.accelerationIncludingGravity = {};
815 if (typeof(accelerometerData.x) !== "undefined") { accelerometerData.accelerationIncludingGravity.x = accelerometerData.x; }
816 if (typeof(accelerometerData.y) !== "undefined") { accelerometerData.accelerationIncludingGravity.y = accelerometerData.y; }
817 if (typeof(accelerometerData.z) !== "undefined") { accelerometerData.accelerationIncludingGravity.z = accelerometerData.z; }
818 }
819 //TODO: normalize the values without gravity too (accelerometerData.acceleration.x, accelerometerData.acceleration.y, accelerometerData.acceleration.z) if possible (needs gyroscope probably) and maybe more properties.
820 }
821 return accelerometerData;
822 }
823
824} //End of the static class CB_Device.Motion.
825
826
827/**
828 * Static class to manage the device's battery. It will return itself if it is tried to be instantiated.
829 * @namespace
830 * @todo Normalize more differences between web clients.
831 */
832CB_Device.Battery = function() { return CB_Device.Battery; };
833{
834 CB_Device.Battery._cordova_level = null; //Keeps the battery level for Apache Cordova.
835 CB_Device.Battery._cordova_isPlugged = null; //Keeps whether the device is plugged in or not for Apache Cordova.
836
837
838 //Initializes all values:
839 CB_Device.Battery.init = function()
840 {
841 //Adds the event listener to let Apache Cordova get the battery level:
842 CB_Events.add(window, "batterystatus", function(batteryStatus) { CB_Device.Battery._cordova_level = batteryStatus.level; CB_Device.Battery._cordova_isPlugged = batteryStatus.isPlugged; }, true, true, false);
843 }
844
845
846 /**
847 * Tells whether the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one) is available or not.
848 * @function
849 * @returns {boolean}
850 */
851 CB_Device.Battery.isSupported = function()
852 {
853 return !!(window.navigator &amp;&amp; (typeof(navigator.getBattery) === "function" || navigator.battery || navigator.webkitBattery || navigator.mozBattery || navigator.msBattery));
854 }
855
856
857 /**
858 * Gets the battery object ([BatteryManager]{@link https://developer.mozilla.org/docs/Web/API/BatteryManager}) using the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one) if available or falling back to [Apache Cordova's Battery Status plugin]{@link https://github.com/apache/cordova-plugin-battery-status} emulating the object if possible or a fake object otherwise. It could be synchronous or asynchronous depending on the client.
859 &lt;br />
860 When the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one) is not available, the generated object will always contain null values for the "onchargingchange", "onchargingtimechage", "ondischargingtimechange" and "onlevelchange" properties. The "charging" and "level" properties will be tried to be calculated by using [Apache Cordova's Battery Status plugin]{@link https://github.com/apache/cordova-plugin-battery-status} if possible.
861 &lt;br />
862 The return will be synchronous only when [getBattery]{@link https://developer.mozilla.org/docs/Web/API/Navigator/getBattery} function is not available. The best practice is to ignore the immediate return value and just trust the first parameter passed to the "callbackOk" function once it is called, since this one will be the final battery object (real or fake).
863 * @function
864 * @param {function} [callbackOk] - The callback function that will be called once the final battery object (real or fake one) is gotten (passed as the first and unique parameter). Highly recommended since it is the unique way to always get the final battery object (due the fact that some clients will execute the function asynchronously).
865 * @param {boolean} [chargingOnFail] - Desired value for the "charging" property of the fake battery object when neither the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one) nor [Apache Cordova's Battery Status plugin]{@link https://github.com/apache/cordova-plugin-battery-status} are available. It should follow the same rules as the real property of the [BatteryManager]{@link https://developer.mozilla.org/docs/Web/API/BatteryManager} object.
866 * @param {float} [levelOnFail] - Desired value for the "level" property of the fake battery object when neither the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one) nor [Apache Cordova's Battery Status plugin]{@link https://github.com/apache/cordova-plugin-battery-status} are available. It should follow the same rules as the real property of the [BatteryManager]{@link https://developer.mozilla.org/docs/Web/API/BatteryManager} object.
867 * @param {integer} [chargingTimeOnFail] - Desired value for the "chargingTime" property of the fake battery object when the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one) is not available. It should follow the same rules as the real property of the [BatteryManager]{@link https://developer.mozilla.org/docs/Web/API/BatteryManager} object.
868 * @param {integer} [dischargingTimeOnFail] - Desired value for the "dischargingTime" property of the fake battery object when the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one) is not available. It should follow the same rules as the real property of the [BatteryManager]{@link https://developer.mozilla.org/docs/Web/API/BatteryManager} object.
869 * @returns {Object|Promise} Returns the battery object (fake or real) synchronously only when the native [getBattery]{@link https://developer.mozilla.org/docs/Web/API/Navigator/getBattery} function is not available. Otherwise it returns a [Promise]{@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise} (the result of calling [navigator.getBattery()]{@link https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getBattery}.then(callbackOk)). It is highly recommended to ignore this returned value.
870 */
871 CB_Device.Battery.get = function(callbackOk, chargingOnFail, levelOnFail, chargingTimeOnFail, dischargingTimeOnFail)
872 {
873 var batteryObject = null;
874 if (window.navigator)
875 {
876 if (typeof(navigator.getBattery) === "function") { return navigator.getBattery().then(callbackOk); }
877 else if (typeof(navigator.battery) !== "undefined") { batteryObject = navigator.battery; }
878 else if (typeof(navigator.webkitBattery) !== "undefined") { batteryObject = navigator.webkitBattery; }
879 else if (typeof(navigator.mozBattery) !== "undefined") { batteryObject = navigator.mozBattery; }
880 else if (typeof(navigator.msBattery) !== "undefined") { batteryObject = navigator.msBattery; }
881 }
882 if (typeof(batteryObject) === "undefined" || batteryObject === null)
883 {
884 batteryObject =
885 {
886 "charging" : typeof(CB_Device.Battery._cordova_isPlugged) !== "undefined" &amp;&amp; CB_Device.Battery._cordova_isPlugged !== null ? CB_Device.Battery._cordova_isPlugged : chargingOnFail,
887 "level" : typeof(CB_Device.Battery._cordova_level) !== "undefined" &amp;&amp; CB_Device.Battery._cordova_level !== null &amp;&amp; !isNaN(CB_Device.Battery._cordova_level) ? CB_Device.Battery._cordova_level / 100 : levelOnFail,
888 "chargingTime" : chargingTimeOnFail,
889 "dischargingTime" : dischargingTimeOnFail,
890 "onchargingchange" : null,
891 "onchargingtimechage" : null,
892 "ondischargingtimechange" : null,
893 "onlevelchange" : null
894 };
895 }
896 if (typeof(callbackOk) === "function") { callbackOk(batteryObject); }
897 return batteryObject;
898 }
899
900
901 /**
902 * Returns whether the battery is charging or not. Using the {@link CB_Device.Battery.get} function internally. It could be synchronous or asynchronous depending on the client.
903 &lt;br />
904 The return will be synchronous only sometimes (when it is asynchronous it will just return a [Promise]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise}), following the same rules as the {@link CB_Device.Battery.get} function which is called internally. The best practice is to ignore the immediate return value and just trust the first parameter passed to the "callbackOk" function once it is called, since this one will be the final value that we want to get (real or fake).
905 * @function
906 * @param {function} [callbackOk] - The callback function that will be called once the final value (real or fake one) is gotten (passed as the first and unique parameter). Highly recommended since it is the unique way to always get the final value (due the fact that some clients will execute the function asynchronously).
907 * @param {boolean} [valueOnFail] - Desired value to use when it fails getting the real one. It should follow the same rules as the real "charging" property of the [BatteryManager]{@link https://developer.mozilla.org/docs/Web/API/BatteryManager} object.
908 * @returns {boolean|Promise} Returns the desired value only when the function is executed synchronously (following the same rules as the {@link CB_Device.Battery.get} function which is called internally). It is highly recommended to ignore this returned value.
909 */
910 CB_Device.Battery.isCharging = function(callbackOk, valueOnFail)
911 {
912 var objectOrPromise = CB_Device.Battery.get(function(batteryObject) { if (typeof(callbackOk) === "function") { callbackOk(batteryObject.charging); } }, valueOnFail);
913 if (typeof(objectOrPromise) !== "undefined" &amp;&amp; objectOrPromise !== null &amp;&amp; typeof(objectOrPromise.charging) !== "undefined") { return objectOrPromise.charging; }
914 return objectOrPromise;
915 }
916
917
918 /**
919 * Returns tha current charging level of the battery. Using the {@link CB_Device.Battery.get} function internally. It could be synchronous or asynchronous depending on the client.
920 &lt;br />
921 The return will be synchronous only sometimes (when it is asynchronous it will just return a [Promise]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise}), following the same rules as the {@link CB_Device.Battery.get} function which is called internally. The best practice is to ignore the immediate return value and just trust the first parameter passed to the "callbackOk" function once it is called, since this one will be the final value that we want to get (real or fake).
922 * @function
923 * @param {function} [callbackOk] - The callback function that will be called once the final value (real or fake one) is gotten (passed as the first and unique parameter). Highly recommended since it is the unique way to always get the final value (due the fact that some clients will execute the function asynchronously).
924 * @param {float} [valueOnFail] - Desired value to use when it fails getting the real one. It should follow the same rules as the real "level" property of the [BatteryManager]{@link https://developer.mozilla.org/docs/Web/API/BatteryManager} object.
925 * @returns {float|Promise} Returns the desired value only when the function is executed synchronously (following the same rules as the {@link CB_Device.Battery.get} function which is called internally). It is highly recommended to ignore this returned value.
926 */
927 CB_Device.Battery.getLevel = function(callbackOk, valueOnFail)
928 {
929 var objectOrPromise = CB_Device.Battery.get(function(batteryObject) { if (typeof(callbackOk) === "function") { callbackOk(batteryObject.level); } }, undefined, valueOnFail).level;
930 if (typeof(objectOrPromise) !== "undefined" &amp;&amp; objectOrPromise !== null &amp;&amp; typeof(objectOrPromise.level) !== "undefined") { return objectOrPromise.level; }
931 return objectOrPromise;
932 }
933
934
935 /**
936 * Returns the time (in seconds) that the battery needs to be completely charged. Using the {@link CB_Device.Battery.get} function internally. It could be synchronous or asynchronous depending on the client.
937 &lt;br />
938 The return will be synchronous only sometimes (when it is asynchronous it will just return a [Promise]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise}), following the same rules as the {@link CB_Device.Battery.get} function which is called internally. The best practice is to ignore the immediate return value and just trust the first parameter passed to the "callbackOk" function once it is called, since this one will be the final value that we want to get (real or fake).
939 * @function
940 * @param {function} [callbackOk] - The callback function that will be called once the final value (real or fake one) is gotten (passed as the first and unique parameter). Highly recommended since it is the unique way to always get the final value (due the fact that some clients will execute the function asynchronously).
941 * @param {integer} [valueOnFail] - Desired value to use when it fails getting the real one. It should follow the same rules as the real "chargingTime" property of the [BatteryManager]{@link https://developer.mozilla.org/docs/Web/API/BatteryManager} object.
942 * @returns {integer|Promise} Returns the desired value only when the function is executed synchronously (following the same rules as the {@link CB_Device.Battery.get} function which is called internally). It is highly recommended to ignore this returned value.
943 */
944 CB_Device.Battery.getChargingTime = function(callbackOk, valueOnFail)
945 {
946 var objectOrPromise = CB_Device.Battery.get(function(batteryObject) { if (typeof(callbackOk) === "function") { callbackOk(batteryObject.chargingTime); } }, undefined, undefined, valueOnFail).chargingTime;
947 if (typeof(objectOrPromise) !== "undefined" &amp;&amp; objectOrPromise !== null &amp;&amp; typeof(objectOrPromise.chargingTime) !== "undefined") { return objectOrPromise.chargingTime; }
948 return objectOrPromise;
949 }
950
951
952 /**
953 * Returns the time (in seconds) that the battery needs to be completely discharged (or when the device will shutdown, depending on the client). Using the {@link CB_Device.Battery.get} function internally. It could be synchronous or asynchronous depending on the client.
954 &lt;br />
955 The return will be synchronous only sometimes (when it is asynchronous it will just return a [Promise]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise}), following the same rules as the {@link CB_Device.Battery.get} function which is called internally. The best practice is to ignore the immediate return value and just trust the first parameter passed to the "callbackOk" function once it is called, since this one will be the final value that we want to get (real or fake).
956 * @function
957 * @param {function} [callbackOk] - The callback function that will be called once the final value (real or fake one) is gotten (passed as the first and unique parameter). Highly recommended since it is the unique way to always get the final value (due the fact that some clients will execute the function asynchronously).
958 * @param {integer} [valueOnFail] - Desired value to use when it fails getting the real one. It should follow the same rules as the real "dischargingTime" property of the [BatteryManager]{@link https://developer.mozilla.org/docs/Web/API/BatteryManager} object.
959 * @returns {integer|Promise} Returns the desired value only when the function is executed synchronously (following the same rules as the {@link CB_Device.Battery.get} function which is called internally). It is highly recommended to ignore this returned value.
960 */
961 CB_Device.Battery.getDischargingTime = function(callbackOk, valueOnFail)
962 {
963 var objectOrPromise = CB_Device.Battery.get(function(batteryObject) { if (typeof(callbackOk) === "function") { callbackOk(batteryObject.dischargingTime); } }, undefined, undefined, undefined, valueOnFail).dischargingTime;
964 if (typeof(objectOrPromise) !== "undefined" &amp;&amp; objectOrPromise !== null &amp;&amp; typeof(objectOrPromise.dischargingTime) !== "undefined") { return objectOrPromise.dischargingTime; }
965 return objectOrPromise;
966 }
967
968
969 /**
970 * Sets a function to execute when the "onchargingchange" event of the battery is fired or removes it. This should happen whenever the charging status changes (is charging now but before it was not or vice versa). Using the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one).
971 * @function
972 * @param {function|null} eventFunction - The function that will be called when the event is fired. Following the same rules as in {@link https://developer.mozilla.org/docs/Web/Events/chargingchange}. If a null value is used, the event will be removed.
973 * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not.
974 * @param {float} [useCapture=false] - Defines whether the event we want to add will use capture or not. This parameter will be effective only if the current client supports the [addEventListener]{@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener} method and will be used as its third parameter.
975 * @returns {undefined|false|Promise} Returns false when the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one) is not available. Returns a [Promise]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise} when the native [getBattery]{@link https://developer.mozilla.org/docs/Web/API/Navigator/getBattery} function is available. Otherwise, it returns undefined.
976 */
977 CB_Device.Battery.onChargingChange = function(eventFunction, keepOldFunction, useCapture)
978 {
979 return CB_Device.Battery._setEvent("chargingchange", eventFunction, keepOldFunction, useCapture)
980 }
981
982
983 /**
984 * Sets a function to execute when the "onchargingtimechage" event of the battery is fired or removes it. This should happen whenever the charging time changes. Using the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one).
985 * @function
986 * @param {function|null} eventFunction - The function that will be called when the event is fired. Following the same rules as in {@link https://developer.mozilla.org/docs/Web/Events/chargingtimechange}. If a null value is used, the event will be removed.
987 * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not.
988 * @param {float} [useCapture=false] - Defines whether the event we want to add will use capture or not. This parameter will be effective only if the current client supports the [addEventListener]{@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener} method and will be used as its third parameter.
989 * @returns {undefined|false|Promise} Returns false when the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one) is not available. Returns a [Promise]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise} when the native [getBattery]{@link https://developer.mozilla.org/docs/Web/API/Navigator/getBattery} function is available. Otherwise, it returns undefined.
990 */
991 CB_Device.Battery.onChargingTimeChange = function(eventFunction, keepOldFunction, useCapture)
992 {
993 return CB_Device.Battery._setEvent("chargingtimechage", eventFunction, keepOldFunction, useCapture)
994 }
995
996
997 /**
998 * Sets a function to execute when the "ondischargingtimechange" event of the battery is fired or removes it. This should happen whenever the discharging time changes. Using the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one).
999 * @function
1000 * @param {function|null} eventFunction - The function that will be called when the event is fired. Following the same rules as in {@link https://developer.mozilla.org/docs/Web/Events/dischargingtimechange}. If a null value is used, the event will be removed.
1001 * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not.
1002 * @param {float} [useCapture=false] - Defines whether the event we want to add will use capture or not. This parameter will be effective only if the current client supports the [addEventListener]{@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener} method and will be used as its third parameter.
1003 * @returns {undefined|false|Promise} Returns false when the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one) is not available. Returns a [Promise]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise} when the native [getBattery]{@link https://developer.mozilla.org/docs/Web/API/Navigator/getBattery} function is available. Otherwise, it returns undefined.
1004 */
1005 CB_Device.Battery.onDischargingTimeChange = function(eventFunction, keepOldFunction, useCapture)
1006 {
1007 return CB_Device.Battery._setEvent("dischargingtimechange", eventFunction, keepOldFunction, useCapture)
1008 }
1009
1010
1011 /**
1012 * Sets a function to execute when the "onlevelchange" event of the battery is fired or removes it. This should happen when the battery level changes. Using the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one).
1013 * @function
1014 * @param {function|null} eventFunction - The function that will be called when the event is fired. Following the same rules as in {@link https://developer.mozilla.org/docs/Web/Events/levelchange}. If a null value is used, the event will be removed.
1015 * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not.
1016 * @param {float} [useCapture=false] - Defines whether the event we want to add will use capture or not. This parameter will be effective only if the current client supports the [addEventListener]{@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener} method and will be used as its third parameter.
1017 * @returns {undefined|false|Promise} Returns false when the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one) is not available. Returns a [Promise]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise} when the native [getBattery]{@link https://developer.mozilla.org/docs/Web/API/Navigator/getBattery} function is available. Otherwise, it returns undefined.
1018 */
1019 CB_Device.Battery.onLevelChange = function(eventFunction, keepOldFunction, useCapture)
1020 {
1021 return CB_Device.Battery._setEvent("levelchange", eventFunction, keepOldFunction, useCapture)
1022 }
1023
1024
1025 //Sets an event for the Battery Status API (Battery API):
1026 CB_Device.Battery._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture)
1027 {
1028 if (!CB_Device.Battery.isSupported()) { return false; }
1029 if (window.navigator &amp;&amp; typeof(navigator.getBattery) === "function")
1030 {
1031 return navigator.getBattery().then
1032 (
1033 function(batteryObject)
1034 {
1035 CB_Device._setEvent
1036 (
1037 eventName,
1038 function(e) { if (typeof(eventFunction) === "function") { eventFunction(batteryObject, eventName, e); } },
1039 keepOldFunction,
1040 useCapture,
1041 batteryObject
1042 );
1043 }
1044 );
1045 }
1046 var eventFunctionWrapper = eventFunction;
1047 if (typeof(eventFunction) === "function")
1048 {
1049 eventFunctionWrapper = function(e) { eventFunction(CB_Device.Battery.get(), eventName, e); };
1050 }
1051 return CB_Device._setEvent(eventName, eventFunctionWrapper, keepOldFunction, useCapture, navigator.battery || navigator.webkitBattery || navigator.mozBattery || navigator.msBattery);
1052 }
1053
1054
1055 /**
1056 * Sets a function to execute when the "batterystatus" event of the battery is fired or removes it. Using the [Apache Cordova's Battery Status plugin]{@link https://github.com/apache/cordova-plugin-battery-status}.
1057 * @function
1058 * @param {function|null} eventFunction - The function that will be called when the event is fired. Following the same rules as in {@link https://github.com/apache/cordova-plugin-battery-status}. If a null value is used, the event will be removed.
1059 * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not.
1060 * @param {float} [useCapture=false] - Defines whether the event we want to add will use capture or not. This parameter will be effective only if the current client supports the [addEventListener]{@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener} method and will be used as its third parameter.
1061 */
1062 CB_Device.Battery.cordova_onChange = function(eventFunction, keepOldFunction, useCapture)
1063 {
1064 return CB_Device._setEvent("batterystatus", eventFunction, keepOldFunction, useCapture, window);
1065 }
1066
1067
1068 /**
1069 * Sets a function to execute when the "batterylow" event of the battery is fired or removes it. Using the [Apache Cordova's Battery Status plugin]{@link https://github.com/apache/cordova-plugin-battery-status}.
1070 * @function
1071 * @param {function|null} eventFunction - The function that will be called when the event is fired. Following the same rules as in {@link https://github.com/apache/cordova-plugin-battery-status}. If a null value is used, the event will be removed.
1072 * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not.
1073 * @param {float} [useCapture=false] - Defines whether the event we want to add will use capture or not. This parameter will be effective only if the current client supports the [addEventListener]{@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener} method and will be used as its third parameter.
1074 */
1075 CB_Device.Battery.cordova_onLow = function(eventFunction, keepOldFunction, useCapture)
1076 {
1077 return CB_Device._setEvent("batterylow", eventFunction, keepOldFunction, useCapture, window);
1078 }
1079
1080
1081 /**
1082 * Sets a function to execute when the "batterycritical" event of the battery is fired or removes it. Using the [Apache Cordova's Battery Status plugin]{@link https://github.com/apache/cordova-plugin-battery-status}.
1083 * @function
1084 * @param {function|null} eventFunction - The function that will be called when the event is fired. Following the same rules as in {@link https://github.com/apache/cordova-plugin-battery-status}. If a null value is used, the event will be removed.
1085 * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not.
1086 * @param {float} [useCapture=false] - Defines whether the event we want to add will use capture or not. This parameter will be effective only if the current client supports the [addEventListener]{@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener} method and will be used as its third parameter.
1087 */
1088 CB_Device.Battery.cordova_onCritical = function(eventFunction, keepOldFunction, useCapture)
1089 {
1090 return CB_Device._setEvent("batterycritical", eventFunction, keepOldFunction, useCapture, window);
1091 }
1092
1093} //End of the static class CB_Device.Battery.
1094
1095
1096/**
1097 * Static class to manage the device's vibration. It will return itself if it is tried to be instantiated.
1098 * @namespace
1099 */
1100CB_Device.Vibration = function() { return CB_Device.Vibration; };
1101{
1102 /**
1103 * Tells whether the [Vibration API]{@link https://developer.mozilla.org/docs/Web/API/Vibration_API} (or compatible one as [Apache Cordova's Vibration plugin]{@link https://github.com/apache/cordova-plugin-vibration}) is available or not.
1104 * @function
1105 * @returns {boolean}
1106 */
1107 CB_Device.Vibration.isSupported = function()
1108 {
1109 return (window.navigator &amp;&amp; "vibrate" in navigator &amp;&amp; typeof(navigator.vibrate) === "function");
1110 }
1111
1112
1113 /**
1114 * Makes the device vibrate using the [Vibration API]{@link https://developer.mozilla.org/docs/Web/API/Vibration_API} (or compatible one as [Apache Cordova's Vibration plugin]{@link https://github.com/apache/cordova-plugin-vibration}).
1115 * @function
1116 * @param {integer|array} [vibration] - The vibration pattern which can be either a single integer value or an array of integers. Following the same rules as the first parameter of the native [vibrate]{@link https://developer.mozilla.org/docs/Web/API/Navigator/vibrate} function.
1117 * @returns {undefined|false} Returns false in the case that [Vibration API]{@link https://developer.mozilla.org/docs/Web/API/Vibration_API} (or compatible one as [Apache Cordova's Vibration plugin]{@link https://github.com/apache/cordova-plugin-vibration}) cannot be used or undefined otherwise.
1118 */
1119 CB_Device.Vibration.start = function(vibration)
1120 {
1121 navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;
1122 if (navigator.vibrate)
1123 {
1124 return navigator.vibrate(vibration);
1125 }
1126 return false;
1127 }
1128
1129
1130 /**
1131 * Makes the device stop vibrating using the [Vibration API]{@link https://developer.mozilla.org/docs/Web/API/Vibration_API} (or compatible one as [Apache Cordova's Vibration plugin]{@link https://github.com/apache/cordova-plugin-vibration}).
1132 * @function
1133 * @returns {undefined|false} Returns false in the case that [Vibration API]{@link https://developer.mozilla.org/docs/Web/API/Vibration_API} (or compatible one as [Apache Cordova's Vibration plugin]{@link https://github.com/apache/cordova-plugin-vibration}) cannot be used or undefined otherwise.
1134 */
1135 CB_Device.Vibration.stop = function()
1136 {
1137 return CB_Device.Vibration.start(0);
1138 }
1139
1140} //End of the static class CB_Device.Vibration.
1141
1142
1143
1144/**
1145 * Static class to manage the device's ambient light sensor. It will return itself if it is tried to be instantiated.
1146 * @namespace
1147 * @todo Normalize more differences between web clients.
1148 */
1149CB_Device.AmbientLight = function() { return CB_Device.AmbientLight; };
1150{
1151 /**
1152 * Tells whether the [Ambient Light Sensor API]{@link https://w3.org/TR/ambient-light/} or the [Ambient Light Sensor Events ("ondevicelight")]{@link https://developer.mozilla.org/en-US/docs/Web/API/Ambient_Light_Events} or ["onlightlevel" event]{@link https://modernweb.com/introduction-to-the-ambient-light-api/} are supported or not.
1153 * @function
1154 * @returns {boolean}
1155 */
1156 CB_Device.AmbientLight.isSupported = function()
1157 {
1158 return (typeof(AmbientLightSensor) !== "undefined" || "ondevicelight" in window || "onlightlevel" in window);
1159 }
1160
1161
1162 /**
1163 * Sets the event to get the ambient light or removes it. Uses the [Ambient Light Sensor API]{@link https://w3.org/TR/ambient-light/} or the [Ambient Light Sensor Events ("ondevicelight")]{@link https://developer.mozilla.org/en-US/docs/Web/API/Ambient_Light_Events} or ["onlightlevel" event]{@link https://modernweb.com/introduction-to-the-ambient-light-api/}.
1164 &lt;br/>
1165 The given "eventFunction" will receive the event object as the first parameter but this event object will vary depending on the way to get the ambient light which is supported by the client (if any):
1166 &lt;br />
1167 First choice, if available, uses the [Ambient Light Sensor API]{@link https://w3.org/TR/ambient-light/} and "event.value" will contain the units in lux.
1168 &lt;br />
1169 Second choice, if available, uses the [Ambient Light Sensor Events ("ondevicelight")]{@link https://developer.mozilla.org/en-US/docs/Web/API/Ambient_Light_Events} and "event.value" will contain the units in lux.
1170 &lt;br />
1171 Third choice, if available, uses the ["onlightlevel" event]{@link https://modernweb.com/introduction-to-the-ambient-light-api/} and "event.value" will be "" (an empty string), "dim", "normal" or "bright" instead of a number.
1172 * @function
1173 * @param {function|null} eventFunction - The function that will be called when the event is fired. The event object received will already be normalized by the {@link CB_Device.AmbientLight.normalizeEvent} function automatically. Despite of this, due to the big differences between different clients, the event object received as the first parameter will vary depending on the way to get the ambient light which is supported by the client (if any). If a null value is used, the event will be removed.
1174 * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not.
1175 * @param {float} [useCapture=false] - Defines whether the event we want to add will use capture or not. This parameter will be effective only if the current client supports the [addEventListener]{@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener} method and will be used as its third parameter.
1176 * @param {function} [callbackError] - Callback that will be called if there is any error getting the ambient light. Only used by the [Ambient Light Sensor API]{@link https://w3.org/TR/ambient-light/} (if available).
1177 * @returns {undefined|false} Returns false in the case that no way to get the ambient light is available or undefined otherwise.
1178 */
1179 CB_Device.AmbientLight.onChange = function(eventFunction, keepOldFunction, useCapture, callbackError)
1180 {
1181 if (typeof(AmbientLightSensor) !== "undefined")
1182 {
1183 var sensor = new AmbientLightSensor();
1184 sensor.start();
1185 sensor.onerror = callbackError;
1186 //if ("onchange" in sensor) { return CB_Device.AmbientLight._setEvent("change", function(e) { if (typeof(eventFunction) === "function") { e.value = event.reading &amp;&amp; typeof(event.reading.illuminance) !== "undefined" ? event.reading.illuminance : e.value; eventFunction.call(sensor, e); } }, keepOldFunction, useCapture, sensor); } //event.reading.illuminance will contain the units in lux.
1187 //else { return CB_Device.AmbientLight._setEvent("reading", function(e) { if (typeof(eventFunction) === "function") { e.value = sensor ? sensor.illuminance : e.value; eventFunction.call(sensor, e); } }, keepOldFunction, useCapture, sensor); } //sensor.illuminance will contain the units in lux.
1188 if ("onchange" in sensor) { return CB_Device.AmbientLight._setEvent("change", eventFunction, keepOldFunction, useCapture, sensor, sensor); } //event.reading.illuminance will contain the units in lux.
1189 else { return CB_Device.AmbientLight._setEvent("reading", eventFunction, keepOldFunction, useCapture, sensor, sensor); } //sensor.illuminance will contain the units in lux.
1190 }
1191 else if ("ondevicelight" in window)
1192 {
1193 return CB_Device.AmbientLight._setEvent("devicelight", eventFunction, keepOldFunction, useCapture, window); //event.value will contain the units in lux.
1194 }
1195 else if ("onlightlevel" in window)
1196 {
1197 return CB_Device.AmbientLight._setEvent("lightlevel", eventFunction, keepOldFunction, useCapture, window); //event.value will be "" (an empty string), "dim", "normal" or "bright" instead of a number!
1198 }
1199
1200 //if (typeof(callbackError) === "function") { callbackError(); }
1201 return false;
1202 }
1203
1204
1205 //Sets a function to execute when a desired event is fired:
1206 CB_Device.AmbientLight._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture, target, sensor)
1207 {
1208 var wrapperFunction = eventFunction;
1209 if (typeof(eventFunction) === "function")
1210 {
1211 wrapperFunction = function(e)
1212 {
1213 e = CB_Device.AmbientLight.normalizeEvent(e, eventName, sensor);
1214 return eventFunction(e);
1215 };
1216 }
1217 CB_Device._setEvent(eventName, wrapperFunction, keepOldFunction, useCapture, target);
1218 }
1219
1220
1221 /**
1222 * Normalizes the data gotten from the the [Ambient Light Sensor API]{@link https://w3.org/TR/ambient-light/} or the [Ambient Light Sensor Events ("ondevicelight")]{@link https://developer.mozilla.org/en-US/docs/Web/API/Ambient_Light_Events} or ["onlightlevel" event]{@link https://modernweb.com/introduction-to-the-ambient-light-api/} to try to match the [Ambient Light Sensor API]{@link https://w3.org/TR/ambient-light/} and follow always the same rules as much as possible.
1223 * @function
1224 * @param {Event} e - The event object that we want to normalize.
1225 * @param {('change'|'reading'|'devicelight'|'lightlevel')} eventName - The name of the event that we want to normalize. Case sensitive.
1226 * @param {AmbientLightSensor} [sensor] - [AmbientLightSensor]{@link https://w3.org/TR/ambient-light/#ambient-light-sensor-interface} object used by the [Ambient Light Sensor API]{@link https://w3.org/TR/ambient-light/}.
1227 * @returns {Event} Returns the given event object again but normalized (if possible).
1228 * @todo Normalize more differences between web clients.
1229 */
1230 CB_Device.AmbientLight.normalizeEvent = function(e, eventName, sensor)
1231 {
1232 e = CB_Events.normalize(e);
1233 //Normalizes ambient light sensor data:
1234 /*
1235 if (typeof(AmbientLightSensor) !== "undefined" &amp;&amp; e &amp;&amp; e.reading &amp;&amp; typeof(e.reading.illuminance) !== "undefined")
1236 {
1237 if (typeof(e.value) === "undefined" || e.value === null)
1238 {
1239 e.value = e.reading.illuminance;
1240 }
1241 }
1242 */
1243 if (typeof(AmbientLightSensor) !== "undefined" &amp;&amp; typeof(sensor) !== "undefined" &amp;&amp; sensor !== null)
1244 {
1245 if (eventName === "change")
1246 {
1247 //e.value = (event.reading &amp;&amp; typeof(event.reading.illuminance) !== "undefined") ? event.reading.illuminance : e.value; //event.reading.illuminance will contain the units in lux.
1248 e.value = (e.reading &amp;&amp; typeof(e.reading.illuminance) !== "undefined") ? e.reading.illuminance : e.value; //e.reading.illuminance will contain the units in lux.
1249 }
1250 else if (eventName === "reading")
1251 {
1252 e.value = sensor ? sensor.illuminance : e.value; //sensor.illuminance will contain the units in lux.
1253 }
1254 }
1255 return e;
1256 }
1257
1258
1259} //End of the static class CB_Device.AmbientLight.
1260
1261
1262/**
1263 * Static class to manage the device's proximity sensor. It will return itself if it is tried to be instantiated.
1264 * @namespace
1265 * @todo Normalize more differences between web clients.
1266 */
1267CB_Device.Proximity = function() { return CB_Device.Proximity; };
1268{
1269 /**
1270 * Tells whether the [Proximity Sensor API]{@link https://w3.org/TR/proximity/} or the Proximity Sensor Events as ["ondeviceproximity"]{@link https://developer.mozilla.org/en-US/docs/Web/API/Ambient_Light_Events} or ["onuserproximity"]{@link https://developer.mozilla.org/en-US/docs/Web/API/UserProximityEvent} are supported or not.
1271 * @function
1272 * @returns {boolean}
1273 */
1274 CB_Device.Proximity.isSupported = function()
1275 {
1276 return (typeof(ProximitySensor) !== "undefined" || "ondeviceproximity" in window || "onuserproximity" in window);
1277 }
1278
1279
1280 /**
1281 * Sets the event to get the proximity or removes it. Uses the [Proximity Sensor API]{@link https://w3.org/TR/proximity/} or the Proximity Sensor Events as ["ondeviceproximity"]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/ondeviceproximity} or ["onuserproximity"]{@link https://developer.mozilla.org/en-US/docs/Web/API/UserProximityEvent}.
1282 &lt;br/>
1283 The given "eventFunction" will receive the event object as the first parameter but this event object will vary depending on the way to get the proximity which is supported by the client (if any) and the "detectNear" parameter. It will use the following logic order:
1284 &lt;br />
1285 If "detectNear" is not set to true, [Proximity Sensor API]{@link https://w3.org/TR/proximity/} is used as the first option (if available) and "event.value" will contain the units in centimeters (depending on the implementation, "event.near" will also be present, containing a boolean depending on whether an object is near or not).
1286 &lt;br />
1287 If "detectNear" is not set to true, [Proximity Sensor Events ("ondeviceproximity")]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/ondeviceproximity} is used as the second option (if available) and "event.value" will contain the units in centimeters.
1288 &lt;br />
1289 If "detectNear" is set to true, ["onuserproximity" event]{@link https://developer.mozilla.org/en-US/docs/Web/API/UserProximityEvent} is the unique option used (if available) and "event.near" will be a boolean which tell us whether something is near or not.
1290 * @function
1291 * @param {function|null} eventFunction - The function that will be called when the event is fired. The event object received will already be normalized by the {@link CB_Device.Proximity.normalizeEvent} function automatically. Despite of this, due to the big differences between different clients, the event object received as the first parameter will vary depending on the way to get the proximity which is supported by the client (if any). If a null value is used, the event will be removed.
1292 * @param {boolean} [detectNear=false] - Defines whether we want to detect when a physical object is nearby. If it is set to true, it will use the ["onuserproximity" event]{@link https://developer.mozilla.org/en-US/docs/Web/API/UserProximityEvent}.
1293 * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not.
1294 * @param {float} [useCapture=false] - Defines whether the event we want to add will use capture or not. This parameter will be effective only if the current client supports the [addEventListener]{@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener} method and will be used as its third parameter.
1295 * @param {function} [callbackError] - Callback that will be called if there is any error getting the proximity. Only used by the [Proximity Sensor API]{@link https://w3.org/TR/proximity/} (if available).
1296 * @returns {undefined|false} Returns false in the case that no way to get the proximity is available or undefined otherwise.
1297 */
1298 CB_Device.Proximity.onChange = function(eventFunction, detectNear, keepOldFunction, useCapture, callbackError)
1299 {
1300 if (!detectNear)
1301 {
1302 if (typeof(ProximitySensor) !== "undefined")
1303 {
1304 var sensor = new ProximitySensor();
1305 sensor.start();
1306 sensor.onerror = callbackError;
1307 //if ("onchange" in sensor) { return CB_Device._setEvent("change", function(e) { if (typeof(eventFunction) === "function") { e.value = event.reading &amp;&amp; typeof(event.reading.distance) !== "undefined" ? event.reading.distance : e.value; eventFunction.call(sensor, e); } }, keepOldFunction, useCapture, sensor); } //event.reading.distance will contain the units in centimeters.
1308 //else { return CB_Device._setEvent("reading", function(e) { if (typeof(eventFunction) === "function") { e.value = sensor ? sensor.distance : e.value; e.near = sensor ? sensor.near : e.near; eventFunction.call(sensor, e); } }, keepOldFunction, useCapture, sensor); } //sensor.distance will contain the units in centimeters and sensor.near will be a boolean telling whether an object is near or not.
1309 if ("onchange" in sensor) { return CB_Device.Proximity._setEvent("change", eventFunction, keepOldFunction, useCapture, sensor, sensor); } //event.reading.distance will contain the units in centimeters.
1310 else { return CB_Device.Proximity._setEvent("reading", eventFunction, keepOldFunction, useCapture, sensor, sensor); } //sensor.distance will contain the units in centimeters and sensor.near will be a boolean telling whether an object is near or not.
1311 }
1312 else if ("ondeviceproximity" in window)
1313 {
1314 return CB_Device.Proximity._setEvent("deviceproximity", eventFunction, keepOldFunction, useCapture, window); //event.value will contain the units in centimeters.
1315 }
1316 }
1317 else
1318 {
1319 if ("onuserproximity" in window)
1320 {
1321 return CB_Device.Proximity._setEvent("userproximity", eventFunction, keepOldFunction, useCapture, window); //event.near will be received (boolean).
1322 }
1323 }
1324
1325 //if (typeof(callbackError) === "function") { callbackError(); }
1326 return false;
1327 }
1328
1329
1330 //Sets a function to execute when a desired event is fired:
1331 CB_Device.Proximity._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture, target, sensor)
1332 {
1333 var wrapperFunction = eventFunction;
1334 if (typeof(eventFunction) === "function")
1335 {
1336 wrapperFunction = function(e)
1337 {
1338 e = CB_Device.Proximity.normalizeEvent(e, eventName, sensor);
1339 return eventFunction(e);
1340 };
1341 }
1342 CB_Device._setEvent(eventName, wrapperFunction, keepOldFunction, useCapture, target);
1343 }
1344
1345
1346 /**
1347 * Normalizes the data gotten from the the [Proximity Sensor API]{@link https://w3.org/TR/proximity/} or the Proximity Sensor Events as ["ondeviceproximity"]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/ondeviceproximity} or ["onuserproximity"]{@link https://developer.mozilla.org/en-US/docs/Web/API/UserProximityEvent} to try to match the [Proximity Sensor API]{@link https://w3.org/TR/proximity/} and follow always the same rules as much as possible.
1348 * @function
1349 * @param {Event} e - The event object that we want to normalize.
1350 * @param {('change'|'reading'|'deviceproximity'|'userproximity')} eventName - The name of the event that we want to normalize. Case sensitive.
1351 * @param {ProximitySensor} [sensor] - [ProximitySensor]{@link https://w3.org/TR/proximity/#proximity-sensor-interface} object used by the [Proximity Sensor API]{@link https://w3.org/TR/proximity/}.
1352 * @returns {Event} Returns the given event object again but normalized (if possible).
1353 * @todo Normalize more differences between web clients.
1354 */
1355 CB_Device.Proximity.normalizeEvent = function(e, eventName, sensor)
1356 {
1357 e = CB_Events.normalize(e);
1358 /*
1359 //Normalizes proximity sensor data:
1360 if (typeof(ProximitySensor) !== "undefined" &amp;&amp; e &amp;&amp; event.reading &amp;&amp; typeof(event.reading.distance) !== "undefined")
1361 {
1362 if (typeof(e.value) === "undefined" || e.value === null)
1363 {
1364 e.value = event.reading.distance;
1365 }
1366 }
1367 */
1368 if (typeof(ProximitySensor) !== "undefined" &amp;&amp; typeof(sensor) !== "undefined" &amp;&amp; sensor !== null)
1369 {
1370 if (eventName === "change")
1371 {
1372 //e.value = (event.reading &amp;&amp; typeof(event.reading.distance) !== "undefined") ? event.reading.distance : e.value; //event.reading.distance will contain the units in centimeters.
1373 e.value = (e.reading &amp;&amp; typeof(e.reading.distance) !== "undefined") ? e.reading.distance : e.value; //e.reading.distance will contain the units in centimeters.
1374 }
1375 else if (eventName === "reading")
1376 {
1377 e.value = sensor ? sensor.distance : e.value; //sensor.distance will contain the units in centimeters.
1378 e.near = sensor ? sensor.near : e.near; //sensor.near will be a boolean telling whether an object is near or not.
1379 }
1380 }
1381
1382 return e;
1383 }
1384
1385
1386} //End of the static class CB_Device.Proximity.</pre>
1387 </article>
1388</section>
1389
1390
1391
1392
1393
1394 </div>
1395 </div>
1396
1397 <div class="clearfix"></div>
1398
1399
1400
1401</div>
1402</div>
1403
1404
1405 <div class="modal fade" id="searchResults">
1406 <div class="modal-dialog">
1407 <div class="modal-content">
1408 <div class="modal-header">
1409 <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
1410 <h4 class="modal-title">Search results</h4>
1411 </div>
1412 <div class="modal-body"></div>
1413 <div class="modal-footer">
1414 <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
1415 </div>
1416 </div><!-- /.modal-content -->
1417 </div><!-- /.modal-dialog -->
1418 </div>
1419
1420
1421<footer>
1422
1423
1424 <span class="copyright">
1425 <a href="printable/" target="_blank">See a more printer-friendly version</a><hr /><span style="color:#000000">© <address style="display:inline; font-style:normal;"><a href="https://crossbrowdy.com/" target="_blank">CrossBrowdy</a> API documentation</address> by <a href="https://joanalbamaldonado.com/" target="_blank">Joan Alba Maldonado</a> - <a href="https://creativecommons.org/licenses/by/4.0/" target="_blank">Creative Commons Attribution 4.0 International</a><br />DocStrap Copyright © 2012-2015 The contributors to the JSDoc3 and DocStrap projects.</span>
1426 </span>
1427
1428<span class="jsdoc-message">
1429 Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a>
1430
1431 on Mon Feb 3rd 2020
1432
1433 using the <a href="https://github.com/docstrap/docstrap">DocStrap template</a>.
1434</span>
1435</footer>
1436
1437<script src="scripts/docstrap.lib.js"></script>
1438<script src="scripts/toc.js"></script>
1439
1440 <script type="text/javascript" src="scripts/fulltext-search-ui.js"></script>
1441
1442
1443<script>
1444$( function () {
1445 $( "[id*='$']" ).each( function () {
1446 var $this = $( this );
1447
1448 $this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) );
1449 } );
1450
1451 $( ".tutorial-section pre, .readme-section pre, pre.prettyprint.source" ).each( function () {
1452 var $this = $( this );
1453
1454 var example = $this.find( "code" );
1455 exampleText = example.html();
1456 var lang = /{@lang (.*?)}/.exec( exampleText );
1457 if ( lang && lang[1] ) {
1458 exampleText = exampleText.replace( lang[0], "" );
1459 example.html( exampleText );
1460 lang = lang[1];
1461 } else {
1462 var langClassMatch = example.parent()[0].className.match(/lang\-(\S+)/);
1463 lang = langClassMatch ? langClassMatch[1] : "javascript";
1464 }
1465
1466 if ( lang ) {
1467
1468 $this
1469 .addClass( "sunlight-highlight-" + lang )
1470 .addClass( "linenums" )
1471 .html( example.html() );
1472
1473 }
1474 } );
1475
1476 Sunlight.highlightAll( {
1477 lineNumbers : true,
1478 showMenu : true,
1479 enableDoclinks : true
1480 } );
1481
1482 $.catchAnchorLinks( {
1483 navbarOffset: 10
1484 } );
1485 $( "#toc" ).toc( {
1486 anchorName : function ( i, heading, prefix ) {
1487 return $( heading ).attr( "id" ) || ( prefix + i );
1488 },
1489 selectors : "#toc-content h1,#toc-content h2,#toc-content h3,#toc-content h4",
1490 showAndHide : false,
1491 smoothScrolling: true
1492 } );
1493
1494 $( "#main span[id^='toc']" ).addClass( "toc-shim" );
1495 $( '.dropdown-toggle' ).dropdown();
1496
1497 $( "table" ).each( function () {
1498 var $this = $( this );
1499 $this.addClass('table');
1500 } );
1501
1502} );
1503</script>
1504
1505
1506
1507<!--Navigation and Symbol Display-->
1508
1509<script>
1510 $( function () {
1511 $( '#main' ).localScroll( {
1512 offset : { top : 60 } //offset by the height of your header (give or take a few px, see what works for you)
1513 } );
1514 $( "dt.name" ).each( function () {
1515 var $this = $( this ).find("h4");
1516 var icon = $( "<i/>" ).addClass( "icon-plus-sign" ).addClass( "pull-right" ).addClass( "icon-white" );
1517 var dt = $(this);
1518 var children = dt.next( "dd" );
1519
1520 dt.prepend( icon ).css( {cursor : "pointer"} );
1521 dt.addClass( "member-collapsed" ).addClass( "member" );
1522
1523
1524 children.hide();
1525
1526 dt.children().on( "click", function () {
1527 children = dt.next( "dd" );
1528 children.slideToggle( "fast", function () {
1529
1530 if ( children.is( ":visible" ) ) {
1531 icon.addClass( "icon-minus-sign" ).removeClass( "icon-plus-sign" ).removeClass( "icon-white" );
1532 dt.addClass( "member-open" ).animate( "member-collapsed" );
1533 } else {
1534 icon.addClass( "icon-plus-sign" ).removeClass( "icon-minus-sign" ).addClass( "icon-white" );
1535 dt.addClass( "member-collapsed" ).removeClass( "member-open" );
1536 }
1537 } );
1538 } );
1539
1540 } );
1541 } );
1542</script>
1543
1544
1545<!--Google Analytics-->
1546
1547
1548
1549 <script type="text/javascript">
1550 $(document).ready(function() {
1551 SearcherDisplay.init();
1552 });
1553 </script>
1554
1555
1556</body>
1557</html>