UNPKG

3.48 MBHTMLView Raw
1<html>
2<head>
3</head>
4<body style="background: transparent;">
5 <script src="scripts/docstrap.lib.js"></script>
6 <script src="scripts/lunr.min.js"></script>
7 <script src="scripts/fulltext-search.js"></script>
8
9 <script type="text/x-docstrap-searchdb">
10 {"CrossBrowdy.js.html":{"id":"CrossBrowdy.js.html","title":"Source: CrossBrowdy.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBrowdy.js // CrossBrowdy by Joan Alba Maldonado (workindalian@gmail.com). /** * @file Main CrossBrowdy file. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. * @todo Clear all timeouts before creating them (just in case). */ //CrossBrowdy constants and variables: /** * Keeps the name of the script (the main script will use this name with the \".js\" extension). Case sensitive. * @constant * @type {string} * @default */ var CB_NAME = \"CrossBrowdy\"; /** * CrossBrowdy version. * @constant * @type {string} */ var CB_VERSION = \"0.99.96.31\"; /** * Keeps the CrossBrowdy \"this\" context. * @constant * @type {Object} */ var CB_this = this; /** * Two-dimensional object defined by the user with the desired options for CrossBrowdy and its modules. The options supported are the ones used by the {@link CB_Configuration} object. &lt;br&gt; First-level indexes should belong to the module name (or to \"CrossBrowdy\", for general options) and second-level indexes should belong to the option name. &lt;br&gt; Example: &lt;br&gt; { CrossBrowdy: { CB_console_ALLOW_ALERTS: false }, CrossBase: { SLCANVAS_LOAD : true, FLASHCANVAS_LOAD : true } } * @constant CB_OPTIONS * @type {Object} * @default undefined */ /** * Static class to manage the configuration. It will be overwritten with the values defined in {@link CB_OPTIONS} (if any). &lt;br&gt; First-level indexes should belong to the module name and second-level indexes should belong to the option name. &lt;br&gt; Follows the same format as {@link CB_OPTIONS}. * @namespace */ var CB_Configuration = {}; /** Property that contains an object with the options for the main script. * @namespace CB_Configuration.CrossBrowdy */ CB_Configuration[CB_NAME] = { /** * Default path of the script (path can be changed when {@link CB_init} is called) * @memberof CB_Configuration.CrossBrowdy * @constant * @type {string} * @default {@link CB_NAME} + \"/\" */ SCRIPT_PATH_DEFAULT: \"../\" + CB_NAME + \"/\", /** * Defines whether to show the splash screen in the beginning by default or not. * @memberof CB_Configuration.CrossBrowdy * @constant * @type {boolean} * @default */ SHOW_SPLASH_SCREEN_DEFAULT: true, /** * Defines whether to register statistics or not. If it is enabled, the URL defined in {@link CB_Configuration.CrossBrowdy.STATS_URL} will be called (by including it as a JavaScript file) as soon as CrossBrowdy gets called (might not be ready yet). * This parameter do not do anything else, just includes your desired URL (defined in {@link CB_Configuration.CrossBrowdy.STATS_URL}) as a JavaScript file when CrossBrowdy is called. * @memberof CB_Configuration.CrossBrowdy * @constant * @type {boolean} * @default false */ STATS: false, /** * URL to register the statistics if {@link CB_Configuration.CrossBrowdy.STATS} is enabled. When {@link CB_Configuration.CrossBrowdy.STATS} is enabled, this URL will be included as a JavaScript file as soon as CrossBrowdy gets called (might not be ready yet). * The URL will be called (included in the document as a JavaScript file) adding three parameters: \"cb\" parameter with the CrossBrowdy version as the value, \"time\" with a timestamp which belongs to the current time of the client and \"url\" parameter with the current URL visited by the user as the value. * @memberof CB_Configuration.CrossBrowdy * @constant * @type {string} * @default */ STATS_URL: \"https://crossbrowdy.com/_stats/CB_stats.php\", /** * Defines whether to allow the use of alert()'s as a fallback when using {@link CB_console} and neither the [console]{@link https://developer.mozilla.org/en-US/docs/Web/API/Console} object nor a DOM element with \"CB_console\" ID are found. * @memberof CB_Configuration.CrossBrowdy * @constant * @type {boolean} * @default */ CB_console_ALLOW_ALERTS: true, /** * Default milliseconds before firing the timeout callback for the {@link CB_includeJSFile} function. * @memberof CB_Configuration.CrossBrowdy * @constant * @type {int} * @default */ CB_includeJSFile_TIMEOUT_MS_DEFAULT: 90000 }; /** * It will contain the CrossBrowdy path when it finally loads. * @var * @readonly * @type {string} * @default {@link CB_scriptPathCalculate}(); */ var CB_scriptPath = CB_scriptPathCalculate(); //Can be modified later. //Applies the options set by the user (if any): CB_applyOptions(CB_NAME, CB_this); //Needed modules: /** * Static class that contains all the modules and the tools to manage them. * @namespace */ var CB_Modules = {}; CB_Modules.modules = {}; /** * Enum which defines possible module statuses. * @memberof CB_Modules * @readonly * @enum {integer} CB_Modules.STATUSES */ CB_Modules.STATUSES = { /** The module has failed to load. */ FAILED: -1, /** The module has an unkwnown status. */ UNKNOWN : 0, /** The module is not loaded yet. Default status. */ UNLOADED : 1, /** The module is being loading. */ LOADING : 2, /** The module has loaded successfully (coudl be not ready yet). */ LOADED : 3, /** The module has loaded successfully and it is ready to be used. */ READY : 4 }; /** * Callback that is called before loading a file and should return true if we want to load the file or false otherwise. * @memberof CB_Modules * @callback CB_Modules.neededFile_LOAD_CHECKER * @param {string} filepath - Filepath of the needed file (including the filename). * @param {CB_Modules.NEEDED_FILE} neededFile - Object that contains the needed file. * @returns {boolean} - Returns true if we want to load the file or false otherwise. */ /** * Object that contains a needed file for a module. * @memberof CB_Modules * @typedef {Object} CB_Modules.NEEDED_FILE * @property {boolean} [load=false] - Defines whether to load the file or not. * @property {boolean} [mandatory=false] - Defines whether the file is mandatory. If the file is not mandatory, its module could be declared as loaded successfully before the file is loaded (and maybe never will). * @property {boolean} [absolutePath=false] - Defines whether the path of the file is relative to the path of the main script or absolute. * @property {CB_Modules.neededFile_LOAD_CHECKER} [loadChecker] - Callback that will be called when the file tries to be loaded and should return true if the file needs to be loaded. * @property {string} [id] - Desired string to identify the file. * @property {array} [requires] - Array of strings with the IDs of the files that must be loaded before loading this file. The file will not be loaded until the required files are loaded first. */ /** * Object that contains the needed files for a module. Each property will represent a needed file. * @memberof CB_Modules * @typedef {Object} CB_Modules.NEEDED_FILES * @property {CB_Modules.NEEDED_FILE} path_to_the_file - Object that contains a needed file for a module. The property name must be either the path to the file or a variable containing it. Tto use a variable, the name of the property must start with \"VALUEOF_\" and continue with the name of the variable. In the case that the variable is an object, each property must be separated by a dot (\".\"). */ /** * Object that contains a needed module for a parent module. * @memberof CB_Modules * @typedef {Object} CB_Modules.NEEDED_MODULE * @property {string} name - Name of the module. * @property {CB_Modules.NEEDED_FILES} neededFiles - Object containing the needed files. */ /** * Callback for the different events of a module. * @memberof CB_Modules * @callback CB_Modules.CALLBACK * @param {string} scriptPath - The value for the \"scriptPath\" parameter used by {@link CB_init} when it was called. */ /** * Object that contains a module. * @memberof CB_Modules * @typedef {Object} CB_Modules.MODULE * @property {string} name - Name of the module. * @property {CB_Modules.STATUSES} status - Module status. * @property {CB_Modules.CALLBACK} onCall - Callback for when the module is called to be loaded. Being \"this\" the {@link CB_Modules.MODULE} object itself. * @property {CB_Modules.CALLBACK} onLoad - Callback for when the module loads successfully. Being \"this\" the {@link CB_Modules.MODULE} object itself. * @property {CB_Modules.CALLBACK} onReady - Callback for when the module is totally ready. Being \"this\" the {@link CB_Modules.MODULE} object itself. * @property {CB_Modules.CALLBACK} onFail - Callback for when the module fails to load. Being \"this\" the {@link CB_Modules.MODULE} object itself. NOT IMPLEMENTED YET. * @property {CB_Modules.NEEDED_FILES} neededFiles - Object containing the needed files. * @property {array} neededModules - Array of {@link CB_Modules.NEEDED_MODULE} objects, containing the needed modules. * @property {string} credits - Credits of the module. */ //Main module basic configuration: /** * Contains all the modules, one per property. * @var CB_Modules.modules * @type {Object} * @property {CB_Modules.MODULE} name_of_the_module - Object that contains the module data. The property name must be the name of the module. */ CB_Modules.modules[CB_NAME] = { //Name of the module: \"name\" : CB_NAME, //Status (UNKNOWN, UNLOADED, LOADING, LOADED, READY or FAILED): \"status\" : CB_Modules.STATUSES.UNLOADED, //Function to call as soon as the module is called (before loading its scripts): \"onCall\" : function(scriptPathGiven) { if (CB_Configuration[CB_NAME].STATS) { CB_sendStats(); } //If we want, includes the file for statistics purposes. CB_Modules.setStatus(CB_NAME, CB_Modules.STATUSES.LOADED); }, //Callback function to call when the module has been loaded successfully: \"onLoad\" : function(scriptPathGiven) { CB_Modules.setStatus(CB_NAME, CB_Modules.STATUSES.READY); }, //Callback function to call when the module is ready: \"onReady\" : function(scriptPathGiven) { CB_scriptPath = scriptPathGiven; //The path given was correct so we set it. CB_ready = true; //Set as it's ready. }, //Callback function to call when module has not been loaded successfully: //\"onFail\" =&gt; null, //Needed files: \"neededFiles\" : null, //Format: \"needed_file\" : { load: needs_to_be_loaded, [mandatory: needed_to_begin_CrossBrowdy], [absolutePath: relative_to_CrossBrowdy_path_or_absolute], [loadChecker: function that will be called and return true if the file needs to be loaded], [id: file_identifier_string], [requires: array_with_required_ids_of_files_required] } //Needed modules: \"neededModules\" : [ { \"name\" : \"CrossBase\", //Format: \"needed_file\" : { load: needs_to_be_loaded, [mandatory: needed_to_begin_CrossBrowdy], [absolutePath: relative_to_CrossBrowdy_path_or_absolute], [loadChecker: function that will be called and return true if the file needs to be loaded], [id: file_identifier_string], [requires: array_with_required_ids_of_files_required] } \"neededFiles\" : { \"CrossBase/CrossBase.js\" : { load: true, mandatory: true } } } ], //Credits: \"credits\" : \"[CB] \" + CB_NAME + \" \" + CB_VERSION + \" by Joan Alba Maldonado&lt;br /&gt;\" }; //Sets default credits: /** * Default credits. * @var * @readonly * @type {string} * @default */ var CB_CREDITS_DEFAULT = \"\"; CB_addCredits(CB_Modules.modules[CB_NAME][\"credits\"]); //If now() static function not available, uses getTime() method: if (!Date.now) { Date.now = function() { return new Date().getTime(); }; } /** * Attaches the given credits to the default ones (to {@link CB_CREDITS_DEFAULT}). * @function * @param {string} credits - Path to the JS file. * @returns {string} Returns the default credits after attaching the given ones. */ function CB_addCredits(credits) { return CB_CREDITS_DEFAULT += credits; } /** * Alias for the \"console\" function which fallbacks to a DOM element with \"CB_console\" id (its CSS \"style\" attribute will be modified if needed, which means that its \"display\" property will be set to \"block\" if it is \"none\" and its \"visibility\" property to \"visible\" regardless its previous value) or even to an alert when it is not available (\"alert\" will only be used as a fallback in the case that the {@link CB_console_ALLOW_ALERTS} parameter is set to true). * @function * @param {string} message - Message to display * @todo When \"console\" is not available and it gets polyfilled, allow more parameters (use \"arguments\"). */ var CB_console; if (typeof(console) !== \"undefined\" &amp;&amp; typeof(console.log) !== \"undefined\") { if (typeof(console.log.apply) !== \"undefined\") { CB_console = function() { console.log.apply(console, arguments); }; } else { CB_console = console.log; } } else { CB_console = function(message) //TODO: allow more parameters (use \"arguments\"). { message += \"\"; var CB_consoleElement = document.getElementById(\"CB_console\"); if (CB_consoleElement !== null) { CB_consoleElement.style.visibility = \"visible\"; if (CB_consoleElement.style.display === \"none\") { CB_consoleElement.style.display = \"block\"; } CB_consoleElement.innerHTML += message.replace(/\\n/gi, \"&lt;br /&gt;\") + \"&lt;br /&gt;\"; CB_consoleElement.scrollTop = CB_consoleElement.scrollHeight; } else if (CB_Configuration[CB_NAME].CB_console_ALLOW_ALERTS) { alert(message); } }; console = { log : CB_console }; } var CB_filesRequested = {}; var CB_filesLoaded = []; var CB_filesLoadedIds = {}; /** * Callback for when the file is included successfully or fails to load. * @callback CB_includeJSFile_CALLBACK * @param {string} filepath - The 'filepath' parameter when {@link CB_includeJSFile} was called (if any). * @param {CB_includeJSFile_CALLBACK} callbackOk - The 'callbackOk' parameter when {@link CB_includeJSFile} was called (if any). * @param {CB_includeJSFile_CALLBACK} callbackError - The 'callbackError' parameter when {@link CB_includeJSFile} was called (if any). * @param {integer} timeoutMs - The 'timeoutMs' parameter when {@link CB_includeJSFile} was called (if any). * @param {boolean} asynchronously - The 'asynchronously' parameter when {@link CB_includeJSFile} was called (if any). */ /** * Includes a JavaScript file to the current document. * @function * @param {string} filepath - Path to the JS file. * @param {CB_includeJSFile_CALLBACK} [callbackOk] - Callback for when the file is included successfully. * @param {CB_includeJSFile_CALLBACK} [callbackError] - Callback for when there is any error including the file or it cannot be included after the defined timeout. * @param {integer} [timeoutMs={@link CB_Configuration.CrossBrowdy.CB_includeJSFile_TIMEOUT_MS_DEFAULT}] - Timeout in milliseconds to consider that the inclusion of the file has failed. * @param {boolean} [asynchronously=true] - Defines whether to load the file asynchronously or not. * @param {string} [fileId] - Internal usage recommended only. * @param {array} [fileRequires] - Internal usage recommended only. * @param {boolean} [notMandatory=false] - Internal usage recommended only. * @returns {Object|null|false} Returns null when the script file cannot be loaded yet as some required file has still not been loaded. Returns false when neither the 'HEAD' tag nor the document body can be found. Otherwise, returns an object whose two properties are 'scriptElement' (with the [SCRIPT]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script} element just created) and 'timeoutFailure' (with the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} ID created to check whether the file cannot be loaded after the given time). */ function CB_includeJSFile(filepath, callbackOk, callbackError, timeoutMs, asynchronously, fileId, fileRequires, notMandatory) { //If the file requires another one and it has still not loaded, calls the function again after a while: if (fileRequires &amp;&amp; typeof(fileRequires.length) !== \"undefined\" &amp;&amp; fileRequires.length &gt; 0) { for (var x = 0; x &lt; fileRequires.length; x++) { if (!CB_filesLoadedIds[fileRequires[x]]) { setTimeout(function() { CB_includeJSFile(filepath, callbackOk, callbackError, timeoutMs, asynchronously, fileId, fileRequires, notMandatory); }, 10); return null; } } } //If not given, uses the default timeout: timeoutMs = timeoutMs || CB_Configuration[CB_NAME].CB_includeJSFile_TIMEOUT_MS_DEFAULT //If not given, uses the default value for the 'asynchronously' parameter: if (asynchronously !== false) { asynchronously = true; } //Stores the file as not loaded in the array: if (!notMandatory) { CB_filesRequested[filepath] = true; } //var parentElement = document.getElementsByTagName(\"head\") || document.head || document.getElementsByTagName(\"body\") || document.body || document.documentElement; var parentElement = CB_getElementsByTagName(\"head\"); if (parentElement.length === 0) { parentElement = document.head || CB_getElementsByTagName(\"body\"); } if (parentElement.length === 0) { parentElement = document.body || document.documentElement || null; } if (parentElement &amp;&amp; typeof(parentElement[0]) === \"undefined\") { parentElement = [parentElement]; } if (typeof(parentElement) === \"undefined\" || parentElement === null || typeof(parentElement[0]) === \"undefined\" || parentElement[0] === null) { CB_console(\"[ERROR] Neither &lt;HEAD&gt; tag nor document body could be found! (CB_includeJSFile)\"); if (typeof(callbackError) === \"function\") { callbackError(filepath, callbackOk, callbackError, timeoutMs, asynchronously); } return false; } parentElement = parentElement[0]; var scriptTag = document.createElement(\"script\"); scriptTag.src = filepath; scriptTag.language = \"javascript\"; scriptTag.type = \"text/javascript\"; scriptTag.async = asynchronously; parentElement.appendChild(scriptTag); var onLoadExecuted = false; var onLoad = function() { this.onreadystatechange = this.onload = null; setTimeout ( function() { if (onErrorExecuted || onLoadExecuted) { return; } //Exists if the timeout has already been executed. onLoadExecuted = true; //Stores the file as already loaded in the array: CB_filesRequested[filepath] = false; CB_filesLoaded[CB_filesLoaded.length] = filepath; if (fileId) { CB_filesLoadedIds[fileId] = true; } //If defined, calls the OK function: if (typeof(callbackOk) === \"function\") { callbackOk(filepath, callbackOk, callbackError, timeoutMs, asynchronously); } }, 10 ); }; if (scriptTag.readyState) { scriptTag.onreadystatechange = function() { if (this.readyState === \"loaded\" || this.readyState === \"complete\") { onLoad(); } }; } else { scriptTag.onload = onLoad; } var onErrorExecuted = false; var onError = function() { if (onErrorExecuted || onLoadExecuted) { return; } //Exists if the onLoad has been already executed. onErrorExecuted = true; //Stores the file as failed to load in the array: CB_filesRequested[filepath] = null; if (typeof(callbackError) === \"function\") { callbackError(filepath, callbackOk, callbackError, timeoutMs, asynchronously); } }; scriptTag.onerror = onError; //Starts counting for the timeout: var callbackErrorTimeout = setTimeout(onError, timeoutMs); return { scriptElement: scriptTag, timeoutFailure: callbackErrorTimeout }; } /** * Callback for when the script is loaded successfully. Without parameters. * @callback CB_includeRequiredFileErrorCallback * @param {string} filepath - The 'filepath' parameter when {@link CB_includeJSFile} was called internally (if any). * @param {CB_includeJSFile_CALLBACK} callbackOk - The 'callbackOk' parameter when {@link CB_includeJSFile} was called internally (if any). * @param {CB_includeJSFile_CALLBACK} callbackError - The 'callbackError' parameter when {@link CB_includeJSFile} was called internally (if any). * @param {integer} timeoutMs - The 'timeoutMs' parameter when {@link CB_includeJSFile} was called internally (if any). * @param {boolean} asynchronously - The 'asynchronously' parameter when {@link CB_includeJSFile} was called (if any). * @param {object} filesRequested - Object whose indexes are all the filepaths of the script files requested so far and the value is true when the file is still loading (or to be loaded in the future), false if it was loaded successfully (the most likely) or null if it failed to load. * @param {array} filesLoaded - Numeric array whose values are the filepaths of the script files loaded successfully so far. */ //Function executed when a required file cannot be loaded (because of an error or timeout): CB_Modules._includeRequiredFileError = function(filepath, callbackOk, callbackError, timeoutMs, asynchronously) { CB_console(\"[CB] [ERROR] Script file failed to load: \" + filepath); if (typeof(CB_initOnErrorLoadingFile) === \"function\") { CB_initOnErrorLoadingFile(filepath, callbackOk, callbackError, timeoutMs, asynchronously, CB_filesRequested, CB_filesLoaded); } } //Function that includes all required files: CB_Modules._includeAllRequiredFiles = function(CB_scriptPathGiven, neededFiles, callbackOk) { //Parses the neededFiles object to turn variable keys into the real value of those variables: var currentValue = null; var allIndexes = null; var allIndexesLength = 0; var x = 0; for (var currentFile in neededFiles) { if (currentFile.substring(0, 8) === \"VALUEOF_\") { allIndexes = currentFile.substring(8).split(\".\"); allIndexesLength = allIndexes.length; currentValue = CB_this;//window; for (var x = 0; x &lt; allIndexesLength; x++) { if (typeof(currentValue[allIndexes[x]]) !== \"undefined\" &amp;&amp; currentValue[allIndexes[x]] !== null) { currentValue = currentValue[allIndexes[x]]; } else { break; } } if (typeof(currentValue) !== \"string\" &amp;&amp; !(currentValue instanceof String)) { currentValue = \"\"; } if (currentValue !== \"\") { neededFiles[currentValue] = { load: neededFiles[currentFile].load, loadChecker: neededFiles[currentFile].loadChecker, mandatory: neededFiles[currentFile].mandatory, id: neededFiles[currentFile].id, requires: neededFiles[currentFile].requires }; } neededFiles[currentFile].load = false; //It contains the key without parsing, so we set as we don't need it to load it to ignore it. neededFiles[currentFile].disabled = true; //Disables it. } } //Includes all files needed: var neededFilesPending = 0; for (currentFile in neededFiles) { if (neededFiles[currentFile].disabled) { continue; } //Performs the load checker that can change the load property (if any): if (typeof(neededFiles[currentFile].loadChecker) === \"function\" &amp;&amp; neededFiles[currentFile].load) { neededFiles[currentFile].load = neededFiles[currentFile].loadChecker(currentFile, neededFiles[currentFile]); } //If the file needs to be loaded, we load it: if (neededFiles[currentFile].load) { new function(currentFile) //Creates a new scope because we are in a loop. { var functionWhenLoad = null; if (neededFiles[currentFile].mandatory) //Only increases and decreases counter for mandatory files. { neededFilesPending++; functionWhenLoad = function(filepath, callbackOk, callbackError, timeoutMs) { neededFilesPending--; if (typeof(neededFiles) !== \"undefined\" &amp;&amp; neededFiles !== null &amp;&amp; typeof(neededFiles[currentFile]) !== \"undefined\" &amp;&amp; neededFiles[currentFile] !== null) { neededFiles[currentFile].load = false; //We have loaded it and don't need to load it more. } }; } var scriptPath = CB_scriptPathGiven; if (neededFiles[currentFile].absolutePath) { scriptPath = \"\"; } CB_includeJSFile(scriptPath + currentFile, functionWhenLoad, CB_Modules._includeRequiredFileError, undefined, undefined, neededFiles[currentFile].id, neededFiles[currentFile].requires); }(currentFile); } } //Interval that will check when all the modules has been loaded: var allRequiredFilesLoaded = function() { if (neededFilesPending &lt;= 0 &amp;&amp; typeof(callbackOk) === \"function\") { callbackOk(); } else if (typeof(callbackOk) === \"function\") { setTimeout(allRequiredFilesLoaded, 1); } }; allRequiredFilesLoaded(); } //Function that includes all required modules: CB_Modules._includeAllRequiredModules = function(CB_scriptPathGiven, modules, callbackOk) { if (typeof(modules) === \"undefined\" || modules === null) { return; } var modulesLength = modules.length; var neededModulesPending = 0; for (var x = 0; x &lt; modulesLength; x++) { if (typeof(modules[x].name) !== \"undefined\" &amp;&amp; typeof(modules[x].neededFiles) !== \"undefined\" &amp;&amp; modules[x].neededFiles) { neededModulesPending++; new function(moduleName) //Closure to keep moduleName value for every loop. { CB_Modules._includeAllRequiredFiles ( CB_scriptPathGiven, modules[x][\"neededFiles\"], function() { setTimeout ( function() { CB_Modules._initializeModule(CB_scriptPathGiven, moduleName); neededModulesPending--; }, 10 ); } ); }(modules[x].name); } } //Interval that will check when all the modules has been loaded: var allRequiredModulesLoaded = function() { if (neededModulesPending &lt;= 0 &amp;&amp; typeof(callbackOk) === \"function\") { callbackOk(); } else if (typeof(callbackOk) === \"function\") { setTimeout(allRequiredModulesLoaded, 1); } }; allRequiredModulesLoaded(); } //Tells the number of required files loaded: CB_Modules._numberFilesLoaded = function(neededFiles, onlyMandatory) { //Checks all files needed: var numberNeededFilesLoaded = 0; for (var currentFile in neededFiles) { //Checks whether the needed file has been loaded: if (neededFiles[currentFile].load) { if (!onlyMandatory || neededFiles[currentFile].mandatory) { numberNeededFilesLoaded++; } } } return numberNeededFilesLoaded; } //Checks whether all required files have been loaded: CB_Modules._allFilesLoaded = function(neededFiles, onlyMandatory) { //Checks all files needed: var allFilesNeededIncluded = true; for (var currentFile in neededFiles) { //If the file has not been included yet, exits the bucle: if (neededFiles[currentFile].load) { if (!onlyMandatory || neededFiles[currentFile].mandatory) { allFilesNeededIncluded = false; break; } } } return allFilesNeededIncluded; } //Checks whether all required modules have been loaded: CB_Modules._allModulesLoaded = function(neededModules, onlyMandatory) { if (typeof(neededModules) === \"undefined\" || neededModules === null) { return true; } var allModulesNeededIncluded = true; var neededModulesLength = neededModules.length; for (var x = 0; x &lt; neededModulesLength; x++) { if (typeof(neededModules[x].name) !== \"undefined\" &amp;&amp; typeof(neededModules[x].neededFiles) !== \"undefined\" &amp;&amp; neededModules[x].neededFiles) { if (!CB_Modules._allFilesLoaded(neededModules[x].neededFiles, onlyMandatory)) { allModulesNeededIncluded = false; break; } } } return allModulesNeededIncluded; } //Checks whether a given module is ready or not: CB_Modules._moduleReady = function(moduleName) { return (CB_Modules._getModuleStatus(moduleName) === CB_Modules.STATUSES.READY); } //Checks whether all required modules are ready: CB_Modules._allModulesReady = function(neededModules) { if (typeof(neededModules) === \"undefined\" || neededModules === null) { return true; } var allModulesNeededReady = true; var neededModulesLength = neededModules.length; for (var x = 0; x &lt; neededModulesLength; x++) { if (typeof(neededModules[x].name) !== \"undefined\" &amp;&amp; typeof(neededModules[x].neededFiles) !== \"undefined\" &amp;&amp; neededModules[x].neededFiles) { if (!CB_Modules._moduleReady(neededModules[x].name)) { allModulesNeededReady = false; break; } } } return allModulesNeededReady; } //Returns the status of a given module: CB_Modules._getModuleStatus = function(moduleName) { if (typeof(CB_Modules.modules[moduleName]) !== \"undefined\" &amp;&amp; typeof(CB_Modules.modules[moduleName].status) !== \"undefined\") { return CB_Modules.modules[moduleName].status; } else { return CB_Modules.STATUSES.UNKNOWN; } } /** * Sets a status for a given module. * @memberof CB_Modules * @function * @param {string} moduleName - Name of the module. * @param {integer} status - The desired status. Must be a value that exists in the {@link CB_Modules.STATUSES} enum. * @returns {boolean} It will return true if succeeded or false otherwise. */ CB_Modules.setStatus = function(moduleName, status) { if (typeof(CB_Modules.modules[moduleName]) !== \"undefined\") { CB_Modules.modules[moduleName].status = status; } } //Function that initializes a module: //var CB_allFilesLoadedInterval; //Interval that checks if CrossBrowdy is ready or not. CB_Modules._initializeModule = function(CB_scriptPathGiven, moduleName) { //It the module still does not exist (status is unknown), tries to load it again after some time: if (CB_Modules._getModuleStatus(moduleName) === CB_Modules.STATUSES.UNKNOWN) { setTimeout(function() { CB_Modules._initializeModule(CB_scriptPathGiven, moduleName); }, 1); return; } CB_Modules.setStatus(moduleName, CB_Modules.STATUSES.LOADING); if (typeof(CB_Modules.modules[moduleName][\"onCall\"]) === \"function\") { CB_Modules.modules[moduleName][\"onCall\"].call(CB_Modules.modules[moduleName], CB_scriptPathGiven); } //Applies default path if it was not sent: if (typeof(CB_scriptPathGiven) === \"undefined\" || CB_scriptPathGiven === null) { CB_scriptPathGiven = CB_scriptPathCalculate(); } //Includes required files: CB_Modules._includeAllRequiredFiles(CB_scriptPathGiven, CB_Modules.modules[moduleName][\"neededFiles\"]); //Includes required modules: CB_Modules._includeAllRequiredModules(CB_scriptPathGiven, CB_Modules.modules[moduleName][\"neededModules\"]); //Show credits in console: CB_console(CB_credits(CB_Modules.modules[moduleName][\"credits\"], false)); //Interval that checks if CrossBrowdy is ready (and initializes the static objects): var onLoadProcessed = false; var onReadyProcessed = false; var CB_allFilesLoadedCheck = function() { var loopAgain = true; //If all files needed are loaded (mandatory files only): if (CB_Modules._allFilesLoaded(CB_Modules.modules[moduleName][\"neededFiles\"], true)) { //If all needed modules are loaded (mandatory module files only): if (CB_Modules._allModulesLoaded(CB_Modules.modules[moduleName][\"neededModules\"], true)) { //If defined, executes the onLoad function of the module: if (!onLoadProcessed &amp;&amp; typeof(CB_Modules.modules[moduleName][\"onLoad\"]) === \"function\") { onLoadProcessed = true; CB_Modules.modules[moduleName][\"onLoad\"].call(CB_Modules.modules[moduleName], CB_scriptPathGiven); } //If all needed modules are ready: if (CB_Modules._allModulesReady(CB_Modules.modules[moduleName][\"neededModules\"])) { //If the module itself is ready: if (CB_Modules._moduleReady(moduleName)) { //If defined, executes the onReady function of the module: if (!onReadyProcessed &amp;&amp; typeof(CB_Modules.modules[moduleName][\"onReady\"]) === \"function\") { onReadyProcessed = true; CB_Modules.modules[moduleName][\"onReady\"].call(CB_Modules.modules[moduleName], CB_scriptPathGiven); } loopAgain = false; } } } } if (loopAgain) { setTimeout(CB_allFilesLoadedCheck, 1); } }; CB_allFilesLoadedCheck(); } /** * Returns a {@link CB_Modules.MODULE} object for module management. * @memberof CB_Modules * @function * @param {string} moduleName - Name of the desired module. * @returns {CB_Modules.MODULE|null} If found, it will return the {@link CB_Modules.MODULE} object desired. Otherwise, it will return null. */ CB_Modules.get = function(moduleName) { if (typeof(CB_Modules.modules[moduleName]) !== \"undefined\") { return CB_Modules.modules[moduleName]; } return null; } /** * Gets the value of a desired module property (or returns null). * @memberof CB_Modules * @function * @param {string} moduleName - Name of the desired module. * @param {string} property - Name of the desired property. * @returns {*|null} If found, it will return the value of the desired module property. Otherwise, it will return null. */ CB_Modules.getProperty = function(moduleName, property) { var module = CB_Modules.get(moduleName); if (module !== null &amp;&amp; typeof(module[property]) !== \"undefined\") { return module[property]; } return null; } /** * Modifies a desired property of a given module. * @memberof CB_Modules * @function * @param {string} moduleName - Name of the module which contains the property to modify. * @param {string} property - Name of the property to modify. * @param {*} value - Value desired for the property. * @param {('array'|'object'|'scalar')} [type='scalar'] Type that the property uses. If it is \"array\", the given \"value\" will be attached at the end of the array (all in a new single index if the \"iterateArray\" parameter is set to false, or each value in a new index otherwise). If it is \"object\", the given \"value\" and the given \"property\" to modify will be treated as objects and the members of the \"value\" will be copied one by one (overwriting previous members in the case they existed). If it is \"scalar\" or any other, the given \"property\" value will be replaced with the given \"value\". * @param {boolean} [iterateArray=false] - If is set to true and the given \"type\" is \"array\", the given \"value\" will be considered an array and will be iterated to copy each of its values to a new index in the destiny. Otherwise, if it is set to false and the given \"type\" is \"array\", the given \"value\" will be attached at the end of the array in a new single index. * @returns {boolean} It will return true if succeeded or false otherwise. */ CB_Modules.editProperty = function(moduleName, property, value, type, iterateArray) { if (typeof(moduleName) === \"undefined\" || moduleName === null || moduleName === \"\") { return false; } if (typeof(property) === \"undefined\" || property === null || property === \"\") { return false; } if (typeof(type) === \"undefined\" || type === null) { type = \"scalar\"; } type += \"\"; type = type.toLowerCase(); var modified = false; var module = CB_Modules.get(moduleName); if (module !== null) { var propertyValue = CB_Modules.getProperty(moduleName, property); if (type === \"array\") { if (propertyValue === null) { module[property] = []; } if (!iterateArray) { module[property][module[property].length] = value; modified = true; } else { var valueLength = value.length; for (var x = 0; x &lt; valueLength; x++) { module[property][module[property].length] = value[x]; } if (x &gt; 0) { modified = true; } } } else if (type === \"object\") { if (propertyValue === null) { module[property] = {}; } for (var propertyName in value) { module[property][propertyName] = value[propertyName]; modified = true; } } else { if (propertyValue === null) { module[property] = null; } module[property] = value; modified = true; } } return modified; } /** * Attaches one module to another one. * @memberof CB_Modules * @function * @param {string} moduleNameParent - Name of the parent module where the new child module will be attached to. * @param {string} moduleName - Name of the new child module which will be attached to the given parent. * @param {CB_Modules.NEEDED_FILES} neededFiles - The \"neededFiles\" parameter for the new child module. * @returns {boolean} It will return true if succeeded or false otherwise. */ CB_Modules.addNeededModule = function(moduleNameParent, moduleName, neededFiles) { return CB_Modules.editProperty(moduleNameParent, \"neededModules\", { \"name\" : moduleName, \"neededFiles\" : neededFiles }, \"array\"); } /** * Attaches files to a module. * @memberof CB_Modules * @function * @param {string} moduleName - Name of the module which will contain the new files. * @param {CB_Modules.NEEDED_FILES} neededFiles - The \"neededFiles\" parameter for the module. * @returns {boolean} It will return true if succeeded or false otherwise. */ CB_Modules.addNeededFiles = function(moduleName, neededFiles) { return CB_Modules.editProperty(moduleName, \"neededFiles\", neededFiles, \"object\"); } function CB_getElementsByTagName(tagName) { if (!tagName) { return []; } var elementsFound = []; if (typeof(document.getElementsByTagName) !== \"undefined\" &amp;&amp; document.getElementsByTagName !== null) { elementsFound = document.getElementsByTagName(tagName); } else if (document.querySelectorAll) { elementsFound = document.querySelectorAll(tagName); } else if (document.querySelectorAll) { elementsFound = document.querySelectorAll(tagName); } else if (typeof(document.all) !== \"undefined\" &amp;&amp; document.all !== null) { elementsFound = document.all.tags(tagName); } else if (document.layers) { var allElements = document.layers; //Obtains all elements with the given tag name: var allElementsLength = allElements.length; var elementCurrent; for (var x = 0; x &lt; allElementsLength; x++) { elementCurrent = allElements[x]; if (elementCurrent !== null &amp;&amp; typeof(elementCurrent.tagName) !== \"undefined\") { if (CB_trim(elementCurrent.tagName).toLowerCase() === tagName) { elementsFound.push(elementCurrent); } } } //elementsFound = document.layers[tagName]; } return elementsFound; } var CB_scriptPathCalculateLastReturn = CB_this.CB_scriptPathCalculateLastReturn || null; /** * Tries to calculate and returns the path where the script is located. * @function * @returns {string} If it cannot be calculated, it will returns the value of {@link CB_Configuration[CB_NAME].SCRIPT_PATH_DEFAULT}. */ function CB_scriptPathCalculate() { if (typeof(CB_scriptPathCalculateLastReturn) !== \"undefined\" &amp;&amp; CB_scriptPathCalculateLastReturn !== null) { return CB_scriptPathCalculateLastReturn; } //Gets the \"SCRIPT\" DOM elements: var scriptElements = CB_getElementsByTagName(\"script\"); var scriptFileName = CB_NAME + \".js\"; for (var x = 0, scriptElementsLength = scriptElements.length; x &lt; scriptElementsLength; x++) { if (scriptElements[x].src &amp;&amp; scriptElements[x].src.length) { var src = scriptElements[x].src; if (src === scriptFileName || src.substring(src.length - scriptFileName.length - 1, src.length + 1) === \"/\" + scriptFileName) { CB_scriptPathCalculateLastReturn = src.substring(0, src.length - scriptFileName.length); return CB_scriptPathCalculateLastReturn; } } } return CB_Configuration[CB_NAME].SCRIPT_PATH_DEFAULT; } var CB_ready = false; //Defines weather CrossBrowdy is ready or not. var CB_initWait = true; var CB_initWaitMs = 50; var CB_readyInterval; //Interval that will execute the main function when CrossBrowdy is ready. var CB_deviceReady = false; var CB_initOnErrorLoadingFile; //Function to call if any required file fails to load. /** * Callback for when the script is loaded successfully. Without parameters. * @callback CB_init_CALLBACK */ /** * Starts CrossBrowdy. * @function * @param {CB_init_CALLBACK} [mainFunction] - Callback for when CrossBrowdy is loaded successfully. Recommended. * @param {string} [scriptPath={@link CB_scriptPathCalculate}()] - Path where the main script is located. If not provided (it is undefined or null), it will try to calculate it calling the {@link CB_scriptPathCalculate} function internally. * @param {CB_includeRequiredFileErrorCallback} [onErrorLoadingFile] - Function to call when any of the required files fails to load (because of an error or because its timeout was fired). It could be called more than once, for each file which failed loading. If a function is provided, it will be stored in the global 'CB_initOnErrorLoadingFile' variable. * @param {boolean} [showSplashScreen={@link CB_Configuration.CrossBrowdy.SHOW_SPLASH_SCREEN_DEFAULT}] - Defines whether to show the splash screen or not. */ function CB_init(mainFunction, scriptPath, onErrorLoadingFile, showSplashScreen) { //If Cordova is detected, exits this function and it will be called again when the device is ready: if ((typeof(window.cordova) !== \"undefined\") &amp;&amp; !CB_deviceReady &amp;&amp; document.addEventListener) { document.addEventListener(\"deviceready\", function() { CB_deviceReady = true; CB_init(mainFunction, scriptPath, onErrorLoadingFile, showSplashScreen) }, false); return; } //Applies the options set by the user (if any): CB_applyOptions(CB_NAME, CB_this); if (typeof(showSplashScreen) === \"undefined\" || showSplashScreen === null) { showSplashScreen = CB_Configuration[CB_NAME].SHOW_SPLASH_SCREEN_DEFAULT; } //If defined, shows splash screen: if (showSplashScreen) { CB_showSplashScreen(); } //Executes this same function only after some milliseconds (avoids problems with Internet Explorer and excanvas): if (CB_initWait) { setTimeout(function() { CB_initWait = false; CB_init(mainFunction, scriptPath, onErrorLoadingFile, showSplashScreen); }, CB_initWaitMs); return; } //Applies default path if it was not sent: if (typeof(scriptPath) === \"undefined\" || scriptPath === null) { scriptPath = CB_scriptPathCalculate(); //scriptPath = CB_Configuration[CB_NAME].SCRIPT_PATH_DEFAULT; } //If given, sets the callback when a required file fails to load: if (typeof(onErrorLoadingFile) === \"function\") { CB_initOnErrorLoadingFile = onErrorLoadingFile; } //Initializes the main module: CB_Modules._initializeModule(scriptPath, CB_NAME); //If defined, the main function will be executed when CrossBrowdy is ready: if (typeof(mainFunction) === \"function\") { var CB_readyExecute = function() { var loopAgain = true; if (CB_ready) { setTimeout(mainFunction, 1); //Calls the function given. if (showSplashScreen) { CB_hideSplashScreen = true; } //If showing, hides splash screen. loopAgain = false; } if (loopAgain) { setTimeout(CB_readyExecute, 1); } }; CB_readyExecute(); } } //Function that applies the given options: function CB_applyOptions(moduleName)//, containerObject) { if (typeof(CB_OPTIONS) !== \"undefined\" &amp;&amp; typeof(CB_OPTIONS[moduleName]) !== \"undefined\") { for (var option in CB_OPTIONS[moduleName]) { CB_Configuration[moduleName][option] = CB_OPTIONS[moduleName][option]; } } } /** * Returns the credits with the desired format. * @function * @param {string} [credits={@link CB_CREDITS_DEFAULT}] - Desired credits to be shown. * @param {boolean} [html=true] - Strips all HTML tags (if any) when it is false. * @param {boolean} [showPrefix=true] - Defines whether to show the \"[CB]\" prefix for every line or not (it will remove all \"[CB]\" occurrences if it is false). * @returns {string} */ function CB_credits(credits, html, showPrefix) { if (typeof(html) === \"undefined\" || html === null) { html = true; } if (typeof(showPrefix) === \"undefined\" || showPrefix === null) { showPrefix = true; } if (typeof(credits) === \"undefined\" || credits === null || credits === \"\") { credits = CB_CREDITS_DEFAULT; } if (!html) { if (typeof(CB_br2nl) !== \"undefined\") { credits = CB_br2nl(credits); } else { credits = credits.replace(/&lt;br \\/&gt;/gi, \"\\n\"); } credits = credits.replace(/&lt;[^&gt;]*&gt;?/gm, ''); } if (!showPrefix) { credits = credits.replace(/\\[CB\\]/gi, \"\"); } return credits; } //Show a splash screen: var CB_showSplashScreenInterval; //Checks when the body is ready to show the splash screen. var CB_hideSplashScreen = false; var CB_showSplashScreenExecuted = false; function CB_showSplashScreen() { if (CB_showSplashScreenExecuted) { return; } CB_showSplashScreenExecuted = true; var CB_showSplashScreenShow = function() { var loopAgain = true; //var bodyTag = document.getElementsByTagName(\"body\"); var bodyTag = CB_getElementsByTagName(\"body\"); if (typeof(bodyTag) !== \"undefined\" &amp;&amp; bodyTag !== null &amp;&amp; typeof(bodyTag[0]) !== \"undefined\" &amp;&amp; bodyTag[0] !== null) { bodyTag = bodyTag[0]; if (!CB_hideSplashScreen &amp;&amp; document.getElementById(\"CB_splashScreenDiv\") === null) { var splashScreenDivPosition = \"fixed\"; var additionalCSS = \"\"; //if (window.navigator.appName === \"Microsoft Internet Explorer\") if (navigator.userAgent.indexOf(\"MSIE\") !== -1 &amp;&amp; (navigator.appVersion.indexOf(\"MSIE 5\") !== -1 || navigator.appVersion.indexOf(\"MSIE 6\") !== -1 || navigator.appVersion.indexOf(\"MSIE 7\") !== -1 || navigator.appVersion.indexOf(\"MSIE 8\") !== -1)) { /* if (typeof(document.compatMode) !== \"undefined\" &amp;&amp; document.compatMode === \"BackCompat\" || typeof(document.documentMode) !== \"undefined\" &amp;&amp; document.documentMode == 5) { additionalCSS = \" _position:absolute; _top:expression(eval(document.body.scrollTop));\"; } else if (navigator.appVersion.indexOf(\"MSIE 8\") === -1) { splashScreenDivPosition = \"absolute\"; } */ //If it is not IE8 (but IE5, IE6 or IE7) or it is in quirks mode (\"fixed\" property is not supported in IE8 when it is in quirks mode): if (navigator.appVersion.indexOf(\"MSIE 8\") === -1 || typeof(document.compatMode) !== \"undefined\" &amp;&amp; document.compatMode === \"BackCompat\" || typeof(document.documentMode) !== \"undefined\" &amp;&amp; document.documentMode == 5) { splashScreenDivPosition = \"absolute\"; //additionalCSS = \" _position:absolute; _top: expression(eval(document.compatMode &amp;&amp; document.compatMode=='CSS1Compat') ? documentElement.scrollTop +(documentElement.clientHeight-this.clientHeight) : document.body.scrollTop +(document.body.clientHeight-this.clientHeight));\"; additionalCSS = \" _position:absolute; _top: expression(eval(document.compatMode &amp;&amp; document.compatMode=='CSS1Compat') ? documentElement.scrollTop : document.body.scrollTop);\"; additionalCSS += \" _left: expression(eval(document.compatMode &amp;&amp; document.compatMode=='CSS1Compat') ? documentElement.scrollLeft : document.body.scrollLeft);\"; } bodyTag.style.width = bodyTag.style.height = \"100%\"; } var splashScreenDiv = '\\ &lt;div id=\"CB_splashScreenDiv\" onmousedown=\"return false;\" style=\"position:' + splashScreenDivPosition + '; top:0px; left:0px; width:100%; height:100%; background-color:#cccccc; z-index:999; opacity:0.95; transition:opacity 1000ms; -moz-transition:opacity 1000ms; -webkit-transition:opacity 1000ms; -o-transition:opacity 1000ms; -khtml-transition:opacity 1000ms; -ms-transition:opacity 1000ms;' + additionalCSS + '\"&gt;\\ &lt;table style=\"padding:0px; border:#ffffff solid 10px; width:100%; height:100%;\"&gt;\\ &lt;tr&gt;\\ &lt;td align=\"center\" style=\"text-align:center; font-size:13px; font-family:terminal; color:#ffffff;\"&gt;\\ &lt;table style=\"width:100%; height:30px; background:#aa0000; margin:0px; padding:0px; width:100%; height:30px; line-height:30px; border:0px;\"&gt;\\ &lt;tr&gt;\\ &lt;td align=\"center\" valign=\"middle\" style=\"text-align:center; font-size:25px; font-family:terminal; color:#ffffff;\"&gt;\\ CrossBrowdy&lt;span style=\"font-size:10px;\"&gt;' + CB_VERSION + '&lt;/span&gt;\\ &lt;/td&gt;\\ &lt;/tr&gt;\\ &lt;/table&gt;\\ &lt;div style=\"font-family:arial; font-size:9px; line-height:10px; color:#696969; text-align:center;\"&gt;\\ &lt;div style=\"display:block; width:55%; text-align:left; margin:0px auto 0px auto;\"&gt;\\ &lt;div style=\"font-family:verdana; text-align:center;\" id=\"CB_splashScreenDivCredits\"&gt;' + CB_credits(CB_Modules.modules[CB_NAME][\"credits\"], true, false).replace(/&lt;br \\/&gt;/i, \"\").replace(/&lt;br \\/&gt;/gi, \". \").replace(/- /i, \"&lt;/div&gt;\").replace(/- /gi, \"\") + '&lt;/div&gt;\\ &lt;/div&gt;\\ * &lt;span id=\"CB_splashScreenDivLoadingBlink\" style=\"color:#000000;\"&gt;Loading...&lt;/span&gt; *\\ &lt;br /&gt;\\ &lt;div id=\"CB_splashScreenDivLoader\" style=\"color:#ffffff; text-align:center;\"&gt;&lt;/div&gt;\\ &lt;/td&gt;\\ &lt;/tr&gt;\\ &lt;/table&gt;\\ &lt;/div&gt;\\ '; bodyTag.innerHTML += splashScreenDiv; } else if (CB_hideSplashScreen &amp;&amp; document.getElementById(\"CB_splashScreenDiv\") !== null) { var CB_splashScreenDiv = document.getElementById(\"CB_splashScreenDiv\"); CB_splashScreenDiv.style.opacity = 0; setTimeout(function() { CB_splashScreenDiv.style.visibility = \"hidden\"; }, 1000); loopAgain = false; } if (document.getElementById(\"CB_splashScreenDivLoadingBlink\") !== null) { document.getElementById(\"CB_splashScreenDivLoadingBlink\").style.visibility = (document.getElementById(\"CB_splashScreenDivLoadingBlink\").style.visibility === \"visible\") ? \"hidden\" : \"visible\"; } if (document.getElementById(\"CB_splashScreenDivLoader\") !== null) { var loader = \"\"; for (var file in CB_filesRequested) { if (CB_filesRequested[file]) { loader += '&lt;span style=\"color:#aa00aa;\"&gt;Loading&lt;/span&gt; ' + file; } else if (CB_filesRequested[file] === null) { loader += '&lt;span style=\"color:#aa0000; font-weight:bold;\"&gt;ERROR LOADING&lt;/span&gt; ' + file; } //else { loader += file + ' &lt;span style=\"color:#0000aa;\"&gt;Loaded!&lt;/span&gt;'; } loader += \"&lt;br /&gt;\"; } //if (typeof(CB_filesLoaded[CB_filesLoaded.length - 1]) !== \"undefined\") { loader += CB_filesLoaded[CB_filesLoaded.length - 1] + ' &lt;span style=\"color:#aa0000;\"&gt;Loaded&lt;/span&gt;'; } document.getElementById(\"CB_splashScreenDivLoader\").innerHTML = loader; } } if (loopAgain) { setTimeout(CB_showSplashScreenShow, 1); } }; CB_showSplashScreenShow(); } //Sends the statistics: var CB_statsStored = false; function CB_sendStats() { //Gets the information: //var OS = \"\"; var version = CB_VERSION; var url = typeof(window.location) !== \"undefined\" ? window.location : \"\"; var time = Date.now(); if (typeof(encodeURIComponent) !== \"undefined\") { version = encodeURIComponent(version); url = encodeURIComponent(url); time = encodeURIComponent(time); } else if (typeof(escape) !== \"undefined\") { version = escape(version); url = escape(url); time = escape(time); } /* txt = \"&lt;p&gt;Browser CodeName: \" + navigator.appCodeName + \"&lt;/p&gt;\"; txt+= \"&lt;p&gt;Browser Name: \" + navigator.appName + \"&lt;/p&gt;\"; txt+= \"&lt;p&gt;Browser Version: \" + navigator.appVersion + \"&lt;/p&gt;\"; txt+= \"&lt;p&gt;Cookies Enabled: \" + navigator.cookieEnabled + \"&lt;/p&gt;\"; txt+= \"&lt;p&gt;Browser Language: \" + navigator.language + \"&lt;/p&gt;\"; txt+= \"&lt;p&gt;Browser Online: \" + navigator.onLine + \"&lt;/p&gt;\"; txt+= \"&lt;p&gt;Platform: \" + navigator.platform + \"&lt;/p&gt;\"; txt+= \"&lt;p&gt;User-agent header: \" + navigator.userAgent + \"&lt;/p&gt;\"; txt+= \"&lt;p&gt;User-agent language: \" + navigator.systemLanguage + \"&lt;/p&gt;\"; */ //Sends the information by including the statistics file: CB_includeJSFile(CB_Configuration[CB_NAME].STATS_URL + \"?cb=\" + version + \"&amp;time=\" + time + \"&amp;url=\" + url, undefined, undefined, undefined, true, undefined, undefined, true); } × Search results Close "},"CrossBase_general_CB_Arrays.js.html":{"id":"CrossBase_general_CB_Arrays.js.html","title":"Source: CrossBase/general/CB_Arrays.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/general/CB_Arrays.js /** * @file Arrays management. Contains the {@link CB_Arrays} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage arrays. It will return itself if it is tried to be instantiated. * @namespace * @borrows CB_lastIndexOf as lastIndexOf * @borrows CB_indexOf as indexOf * @borrows CB_forEach as forEach * @borrows CB_isArray as isArray * @borrows CB_sizeOf as sizeOf * @borrows CB_replaceAll as replaceAll * @borrows CB_trim as trim * @borrows CB_rtrim as rtrim * @borrows CB_ltrim as ltrim * @borrows CB_combineArraysOrObjects as combine */ var CB_Arrays = function() { return CB_Arrays; }; { CB_Arrays.initialized = false; //It will tells whether the object has been initialized or not. //Initializes all values: CB_Arrays.init = function() { if (CB_Arrays.initialized) { return CB_Arrays; } //The object has been initialized: CB_Arrays.initialized = true; //TODO. return CB_Arrays; } CB_Arrays.lastIndexOf = function(array, searchElement, fromIndex) { return CB_lastIndexOf(array, searchElement, fromIndex, false); } //Returns the first index of a given element in an array (starting from an index if desired): CB_Arrays.indexOf = function(array, searchElement, fromIndex) { return CB_indexOf(array, searchElement, fromIndex, false); } //Tells whether an variable given is an array or not: CB_Arrays.isArray = function(variable) { return CB_isArray(variable, false); } /** * Alias for {@link CB_Arrays.sizeOf}. * @function CB_Arrays.sizeof * @see {@link CB_Arrays.sizeOf} */ /** * Alias for {@link CB_Arrays.sizeOf}. * @function CB_Arrays.count * @see {@link CB_Arrays.sizeOf} */ //Returns the size of an object given (does not need to be an array!): CB_Arrays.sizeOf = CB_Arrays.sizeof = CB_Arrays.count = function(object, onlyOwn) { return CB_sizeof(object, onlyOwn); } //Returns the given array of strings with the desired occurrences replaced. Calls itself recursively and calls the CB_replaceAll function internally. CB_Arrays.replaceAll = function(stringOrArray, stringOrArrayFind, stringReplace, caseInsensitive) //Either \"stringOrArray\" or \"stringOrArrayFind\" can also be an array of arrays of strings (as many levels as you wish). { return CB_replaceAll(stringOrArray, stringOrArrayFind, stringReplace, caseInsensitive); } //Trims all the strings that contains a given array (undesired strings can be set or otherwise will be spaces, etc.): CB_Arrays.trim = function(array, undesiredStrings) { return CB_trim(array, undesiredStrings); } //Trims all the strings from the right side that contains a given array (undesired strings can be set or otherwise will be spaces, etc.): CB_Arrays.rtrim = function(array, undesiredStrings) { return CB_rtrim(array, undesiredStrings); } //Trims all the strings from the left side that contains a given array (undesired strings can be set or otherwise will be spaces, etc.): CB_Arrays.ltrim = function(array, undesiredStrings) { return CB_ltrim(array, undesiredStrings); } //Returns a combined array or object from two arrays or objects: CB_Arrays.combine = function(arrayOrObjectA, arrayOrObjectB, avoidDuplicatedValuesInArray) { return CB_combineArraysOrObjects(arrayOrObjectA, arrayOrObjectB, avoidDuplicatedValuesInArray); } //Performs a desired function for each element of a given array (changing the value of \"this\" if desired): CB_Arrays.forEach = function(array, fun, thisObject) { return CB_forEach(array, fun, thisObject, false); } /** * Callback that is used for each iteration when looping the array. Being \"this\" the value itself. * @memberof CB_Arrays * @callback CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK * @param {*} item - Element (item) which belongs to the index which is being checked in the current iteration of the given array. * @param {integer} index - Index which is being checked in the current iteration. * @param {array} array - Whole array which is being looped. * @param {integer} delay - The \"delayBetweenEach\" used for this loop. * @returns {number} When used as a function to calculate the delay, it should return the delay desired as a number. */ /** * Callback that is used when finishes all iterations after looping the array. Being \"this\" the array itself. * @memberof CB_Arrays * @callback CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK * @param {array} array - Whole array which was being looped. * @param {integer} itemsAffected - The number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null). * @param {integer} delayMaximum - The maximum \"delay\" used. */ /** * Object used by the {@link CB_Arrays#executeFunctionAll} method when the \"returnSetTimeoutsArray\" parameter is set to true. * @memberof CB_Arrays * @typedef {Object} CB_Arrays.executeFunctionAll_OBJECT * @property {*} item - The element affected. * @property {integer} setTimeoutReturningValue - The returning value of calling the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} internally or null if it was not called, depending on the \"delayBetweenEach\" parameter. * @property {number} setTimeoutDelay - The value used as the second parameter when calling the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} internally or zero if it was not called, depending on the \"delayBetweenEach\" parameter. */ /** * Alias for {@link CB_Arrays#executeFunctionAll}. * @function CB_Arrays#executeAll * @see {@link CB_Arrays#executeFunctionAll} */ /** * Alias for {@link CB_Arrays#executeFunctionAll}. * @function CB_Arrays#forEachDelay * @see {@link CB_Arrays#executeFunctionAll} */ /** * Performs a desired action, using the provided function, on all the existing elements of a given array. Elements which are undefined or null will be skipped without calling the \"functionEach\" function. * @function * @param {array} array - A numeric array containing the elements that we want to loop. * @param {CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} functionEach - Function that will be called for each element of the given array. As the first parameter it receives the element of the \"array\" provided being looped, as the second parameter the position of this element in the \"array\" provided, the third parameter is the array being looped and the fourth parameter will be the \"delayBetweenEach\" being used, being \"this\" the element itself. * @param {number|CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} [delayBetweenEach=0] - If a value greater than zero is used, it will be used as the delay desired between each call to the \"functionEach\" function (calling them using the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function internally). If not provided or the value is 0 (zero) or lower, each call to the \"functionEach\" function will be performed immediately one after the other. If a function is provided, it will be called with the same parameters as the \"functionEach\" function and its returning value will be used as the delay (executed every loop for each item). * @param {boolean} [returnSetTimeoutsArray=false] - Defines whether we want the method to return an integer or a numeric array with information of each [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} call. Returning an array with information of each [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} call is only useful when the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function is called internally, which happens when the \"delayBetweenEach\" parameter is greater than 0 (zero). * @param {boolean} [delayBetweenEachAffectsFirst=false] - If set to true, the desired delay (if any) will also affect the first call to the \"functionEach\" function. * @param {CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK} [functionFinish] - Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. * @returns {integer|array} If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the elements given in the \"array\" parameter). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a {@link CB_Arrays.executeFunctionAll_OBJECT} object for each element given. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function. */ CB_Arrays.executeFunctionAll = CB_Arrays.executeAll = CB_Arrays.forEachDelay = function(array, functionEach, delayBetweenEach, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, functionFinish) { if (typeof(functionEach) !== \"function\" || !CB_isArray(array)) { if (typeof(functionFinish) === \"function\") { functionFinish.call(array, array, 0, 0); } return returnSetTimeoutsArray ? [] : 0; } if (typeof(delayBetweenEach) !== \"function\" &amp;&amp; (typeof(delayBetweenEach) === \"undefined\" || delayBetweenEach === null || isNaN(delayBetweenEach) || delayBetweenEach &lt; 0)) { delayBetweenEach = 0; } var setTimeoutsInformation = []; var arrayLength = array.length; var y = 0; var setTimeoutReturningValue = null; var setTimeoutDelay = 0; var delay; var setTimeoutDelayMax = 0; for (var x = 0; x &lt; arrayLength; x++) { //If the object exists: if (typeof(array[x]) !== \"undefined\" &amp;&amp; array[x] !== null) { delay = typeof(delayBetweenEach) === \"function\" ? delayBetweenEach() : delayBetweenEach; delay = parseInt(delay) || 0; //Executes the given function (\"this\" parameters will point to the current object): if (delay === 0) { functionEach.call(array[x], array[x], x, array, delay); //\"x\" is the position of the object in the array. } else { new function(x, delay) //Closure to get unique value of \"x\" variable for each loop. { setTimeoutDelay = delayBetweenEachAffectsFirst ? delay * (y + 1) : delay * y; setTimeoutReturningValue = setTimeout ( function() { functionEach.call(array[x], array[x], x, array, delay); //\"x\" is the position of the object in the array. }, setTimeoutDelay ); setTimeoutDelayMax = setTimeoutDelay &gt; setTimeoutDelayMax ? setTimeoutDelay : setTimeoutDelayMax; }(x, delay); } setTimeoutsInformation[setTimeoutsInformation.length] = { \"item\" : array[x], \"setTimeoutReturningValue\" : setTimeoutReturningValue, \"setTimeoutDelay\" : setTimeoutDelay }; y++; } } if (typeof(functionFinish) === \"function\") { if (setTimeoutDelayMax === 0) { functionFinish.call(array, array, y, setTimeoutDelayMax); } else { setTimeout(function() { functionFinish.call(array, array, y, setTimeoutDelayMax); }, setTimeoutDelayMax + 1); } } if (returnSetTimeoutsArray) { return setTimeoutsInformation; } else { return y; } } /** * Returns an array copied from the given one. It will also make a copy of the arrays found in the values (if any), calling itself recursively. * @function * @param {array} array - The array whose values we want to copy. * @returns {object} Returns an array copied from the given one. Returns an empty array if the given \"array\" was not an array. */ CB_Arrays.copy = function(array) { if (!CB_isArray(array)) { return []; } //Removes possible duplicated values or not desired: var newArray = []; for (var x = array.length - 1; x &gt;= 0; x--) { newArray[x] = CB_isArray(array[x]) ? CB_Arrays.copy(array[x]) : array[x]; } return newArray; } /** * Alias for {@link CB_Arrays.insertElement}. * @function CB_Arrays.insert * @see {@link CB_Arrays.insertElement} */ /** * Alias for {@link CB_Arrays.insertElement}. * @function CB_Arrays.insertElementByPosition * @see {@link CB_Arrays.insertElement} */ /** * Inserts an element in the desired position of a given an array. Elements which are placed after it will be moved a position to the right (increasing their index). * @function * @param {array} array - The array whose element we want to delete. * @param {integer} [index=0] - Position of the element in the given array that we want to remove. * @param {*} item - Element (item) which belongs to the index which is being checked in the current iteration of the given array. * @param {CB_Arrays.removeDuplicated_PURGE_FUNCTION} [onInsert] - Function to call if the element is inserted, after inserting it. * @returns {array} Returns the new array (with the element inserted if it was possible). If no valid array is given, it will return an empty array. */ CB_Arrays.insertElement = CB_Arrays.insertElementByPosition = CB_Arrays.insert = function(array, index, element, onInsert) { index = parseInt(index); index = isNaN(index) ? 0 : index; if (!CB_isArray(array)) { return []; } if (index &lt; 0) { index *= -1; } //It must be a positive integer. if (index &gt; array.length) { index = array.length; } array.splice(index, 0, element); if (typeof(onInsert) === \"function\") { onInsert.call(element, element, index, array); } return array; } /** * Callback that is used as the \"purgeFunction\" parameter of the {@link CB_Arrays.removeDuplicated} function. Being \"this\" the current element (item). It should return false when we want to keep the value or true otherwise. * @memberof CB_Arrays * @callback CB_Arrays.removeDuplicated_PURGE_FUNCTION * @param {*} item - Element (item) which belongs to the index which is being checked in the current iteration used in {@link CB_Arrays.removeDuplicated}. * @param {integer} index - Index which is being checked in the current iteration used in {@link CB_Arrays.removeDuplicated}. * @param {array} array - Whole array which is being checked. * @returns {boolean} It should return false when we want to keep the value or true otherwise. */ /** * Deletes duplicated and/or not desired values (with a checking function to purge) from a numeric array. Values can be of any type. Internally, loops through the given array backwards (from the last index to the first one). * @function * @param {array} array - The array whose values we want to purge. * @param {CB_Arrays.removeDuplicated_PURGE_FUNCTION} [purgeFunction] - Callback that will be called for each item, being \"this\" the current item. It should return false when we want to keep the value or true otherwise. If the \"ignoreDuplicated\" parameter is set to true, all duplicated elements will be removed regardless of the returning value of the \"purgeFunction\" function. * @param {boolean} [ignoreDuplicated=false] - If it is set to true, it will keep duplicated values (unless the given \"purgeFunction\" purge them). * @returns {array} Returns the array purged. If no valid array is given, it will return an empty array. */ CB_Arrays.removeDuplicated = function(array, purgeFunction, ignoreDuplicated) { if (!CB_isArray(array)) { return []; } //Removes possible duplicated values or not desired: var keysDuplicatedChecker = []; for (var x = array.length - 1; x &gt;= 0; x--) { //if (typeof(purgeFunction) === \"function\" &amp;&amp; purgeFunction(array[x]) || (typeof(purgeFunction) !== \"function\" || !ignoreDuplicated) &amp;&amp; CB_indexOf(keysDuplicatedChecker, array[x]) !== -1) if (typeof(purgeFunction) === \"function\" &amp;&amp; purgeFunction.call(array[x], array[x], x, array) || !ignoreDuplicated &amp;&amp; CB_indexOf(keysDuplicatedChecker, array[x]) !== -1) { array[x] = undefined; array.splice(x, 1); continue; } keysDuplicatedChecker[keysDuplicatedChecker.length] = array[x]; } return array; } /** * Alias for {@link CB_Arrays.removeElementByPosition}. * @function CB_Arrays.removeElementByIndex * @see {@link CB_Arrays.removeElementByPosition} */ /** * Deletes an element from an array which is placed in the desired position. Elements which were after it will be moved a position to the left (decreasing their index). * @function * @param {array} array - The array whose element we want to delete. * @param {integer} [index=0] - Position of the element in the given array that we want to remove. * @param {CB_Arrays.removeDuplicated_PURGE_FUNCTION} [onRemove] - Function to call if the element is removed, before removing it. * @returns {array} Returns the new array (with the element removed if it was possible). If no valid array is given, it will return an empty array. */ CB_Arrays.removeElementByPosition = CB_Arrays.removeElementByIndex = function(array, index, onRemove) { index = parseInt(index); index = isNaN(index) ? 0 : index; if (index &lt; 0) { index *= -1; } //It must be a positive integer. return CB_Arrays.removeDuplicated(array, function(value, position, array) { if (position === index) { if (typeof(onRemove) === \"function\") { onRemove.call(value, value, position, array); } return true; } return false; }, true); } /** * Deletes a given element from an array. All occurrences will be deleted. Elements which were after a removed element will be moved a position to the left (decreasing their index). * @function * @param {array} array - The array whose element we want to delete. * @param {*} [element=undefined] - The element we want to remove. All occurrences will be deleted. Note that it is type sensitive. * @param {CB_Arrays.removeDuplicated_PURGE_FUNCTION} [onRemove] - Function to call if the element is removed, before removing it. * @returns {array} Returns the new array (with the element removed if it was possible). If no valid array is given, it will return an empty array. */ CB_Arrays.removeElement = function(array, element) { return CB_Arrays.removeDuplicated(array, function(value, position, array) { if (value === element) { if (typeof(onRemove) === \"function\") { onRemove.call(value, value, position, array); } return true; } return false; }, true); } /** * Deletes the given elements from an array. All occurrences will be deleted. Elements which were after a removed element will be moved a position to the left (decreasing their index). * @function * @param {array} array - The array whose element we want to delete. * @param {array} elements - An array with the elements we want to remove. All occurrences will be deleted. Note that it is type sensitive. * @returns {array} Returns the new array (with the element removed if it was possible). If no valid array is given, it will return an empty array. */ CB_Arrays.removeElements = function(array, elements) { if (!CB_isArray(elements)) { elements = []; } return CB_Arrays.removeDuplicated(array, function(value, position, array) { return CB_Arrays.lastIndexOf(elements, value, position) !== -1; }, true); } /** * Sorts the values of an array (using the native [Array.sort]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort} method). * @function * @param {array} array - The array whose elements we want to sort. * @param {boolean} [reversed=false] - Defines whether to sort in the reverse order or not. Only applies when comparingFunction is not provided. * @param {function} [comparingFunction] - Comparing function with the same rules as the native [Array.sort]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort} method. If provided, the \"reversed\" parameter will be ignored. * @returns {array} Returns the array ordered. If another value which is not an array is given, it will be returned again. */ CB_Arrays.sort = function(array, reversed, comparingFunction) { if (typeof(array) === \"undefined\" || array === null || !CB_Arrays.isArray(array)) { return array; } if (typeof(comparingFunction) !== \"function\") { if (reversed) { comparingFunction = function(a, b) { return b-a; }; } else { comparingFunction = function(a, b) { return a-b; }; } } return array.sort(comparingFunction); } /** * Sorts an array using the [bubble sort (sinking sort) method]{@link https://en.wikipedia.org/wiki/Bubble_sort}. Internally, it uses the \"&gt;\" operator for comparing values as they will be treated as numbers. * @function * @param {array} array - The array whose elements we want to sort. * @param {boolean} [reversed=false] - Defines whether to sort in the reverse order or not. * @todo Think about accepting a comparing function (as the \"sort\" method). * @returns {array} Returns the array ordered. If another value which is not an array is given, it will be returned again. */ CB_Arrays.bsort = function(array, reversed, comparingFunction) //NOTE: think about accepting a comparing function. { if (typeof(array) === \"undefined\" || array === null || !CB_Arrays.isArray(array)) { return array; } var arrayLength = array.length; for (var x = 1; x &lt; arrayLength; x++) { for (var y = 0; y &lt; arrayLength-x; y++) { if (!reversed &amp;&amp; array[y] &gt; array[y+1] || reversed &amp;&amp; array[y] &lt; array[y+1]) { var aux = array[y]; array[y] = array[y+1]; array[y+1] = aux; } } } return array; } //Sorts an array using merge sort method: CB_Arrays.msort = function(array, reversed, comparingFunction) //NOTE: think about accepting a comparing function. { if (typeof(array) === \"undefined\" || array === null || !CB_Arrays.isArray(array)) { return array; } //TODO. array = CB_Arrays.sort(array, reversed, comparingFunction); //DELETE THIS! return array; } //Sorts an array using quick sort method: CB_Arrays.qsort = function(array, reversed, comparingFunction) //NOTE: think about accepting a comparing function. { if (typeof(array) === \"undefined\" || array === null || !CB_Arrays.isArray(array)) { return array; } //TODO. array = CB_Arrays.sort(array, reversed, comparingFunction); //DELETE THIS! return array; } //Sorts an array using selection sort method: CB_Arrays.ssort = function(array, reversed, comparingFunction) //NOTE: think about accepting a comparing function. { if (typeof(array) === \"undefined\" || array === null || !CB_Arrays.isArray(array)) { return array; } //TODO. array = CB_Arrays.sort(array, reversed, comparingFunction); //DELETE THIS! return array; } //Sorts an array using insertion sort method: CB_Arrays.isort = function(array, reversed, comparingFunction) //NOTE: think about accepting a comparing function. { if (typeof(array) === \"undefined\" || array === null || !CB_Arrays.isArray(array)) { return array; } //TODO. array = CB_Arrays.sort(array, reversed, comparingFunction); //DELETE THIS! return array; } //Sorts an array using cocktail sort (bidirectional bubble) method: CB_Arrays.csort = function(array, reversed, comparingFunction) //NOTE: think about accepting a comparing function. { if (typeof(array) === \"undefined\" || array === null || !CB_Arrays.isArray(array)) { return array; } //TODO. array = CB_Arrays.sort(array, reversed, comparingFunction); //DELETE THIS! return array; } } × Search results Close "},"CrossBase_general_CB_data.js.html":{"id":"CrossBase_general_CB_data.js.html","title":"Source: CrossBase/general/CB_data.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/general/CB_data.js /** * @file Data and related management. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. * @todo A function equivalent to htmlentities/htmlspecialchars (as in PHP). */ //If we want to extend the DOM, we do it: if (CB_Configuration[CB_BASE_NAME].EXTEND_DOM) { try { if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { CB_indexOf(this, searchElement, fromIndex, true); } } if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function(searchElement, fromIndex) { CB_lastIndexOf(this, searchElement, fromIndex, true); } } if (!Array.isArray) { Array.isArray = function() { return CB_isArray(this, true); } } //isArray is a method which is not in the prototype. //if (!Array.prototype.isArray) { Array.prototype.isArray = function() { return CB_isArray(this, true); } } if (!Array.prototype.forEach) { Array.prototype.forEach = function(callback, thisArg) { CB_forEach(this, callback, thisArg, true); } } if (!NodeList.prototype.forEach) { NodeList.prototype.forEach = Array.prototype.forEach; } if (!HTMLCollection.prototype.forEach) { HTMLCollection.prototype.forEach = Array.prototype.forEach; } } catch(E) {} } /** * Implementation of [Array.lastIndexOf]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf} method for browsers that do not support it natively. &lt;br&gt; Returns the last index of a given element that exists in an array (starting from a certain index if desired) or -1 if not found. * @function * @param {array} array - Desired array. * @param {*} searchElement - Element we want to search. Note that it is type sensitive. * @param {integer} [fromIndex=array.length - 1] - First index of the given array where the search will start. * @param {boolean} [extendedDOM=false] - Defines whether the function is being called by a native function which was extended. Internal usage recommended only. * @returns {integer} * @todo Implement the \"fromIndex\" in the polyfill. */ //* Polyfill source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf function CB_lastIndexOf(array, searchElement, fromIndex, extendedDOM) { 'use strict'; if (!extendedDOM) { if (array &amp;&amp; array.lastIndexOf) { return array.lastIndexOf.call(array, searchElement, fromIndex || array.length); } //It can be a string. if (Array.prototype.lastIndexOf) { return Array.prototype.lastIndexOf.call(array, searchElement, fromIndex || array.length); } } if (typeof(array) === \"undefined\" || array === null) { throw new TypeError(); } var n, k, t = Object(array), len = t.length &gt;&gt;&gt; 0; if (len === 0) { return -1; } n = len - 1; if (arguments.length &gt; 2 &amp;&amp; typeof(arguments[2]) !== \"undefined\" &amp;&amp; arguments[2] !== null &amp;&amp; !isNaN(arguments[2])) { n = Number(arguments[2]); if (n != n) { n = 0; } //if (n != n) { n = len - 1; } else if (n != 0 &amp;&amp; n != (1 / 0) &amp;&amp; n != -(1 / 0)) { n = (n &gt; 0 || -1) * Math.floor(Math.abs(n)); } } for (k = n &gt;= 0 ? Math.min(n, len - 1) : len - Math.abs(n); k &gt;= 0; k--) { if (k in t &amp;&amp; t[k] === searchElement) { return k; } } return -1; } /** * Implementation of [Array.indexOf]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf} method for arrays in browsers that do not support it natively. &lt;br&gt; Returns the first index of a given element that exists in an array (starting from a certain index if desired) or -1 if not found. * @function * @param {array} array - Desired array. * @param {*} searchElement - Element we want to search. Note that it is type sensitive. * @param {integer} [fromIndex=0] - First index of the given array where the search will start. * @param {boolean} [extendedDOM=false] - Defines whether the function is being called by a native function which was extended. Internal usage recommended only. * @returns {integer} */ //* Polyfill source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf function CB_indexOf(array, searchElement, fromIndex, extendedDOM) { if (!extendedDOM) { if (array &amp;&amp; array.indexOf) { return array.indexOf.call(array, searchElement, fromIndex); } //It can be a string. if (Array.prototype.indexOf) { return Array.prototype.indexOf.call(array, searchElement, fromIndex); } } if (typeof(array) === \"undefined\" || array === null) { throw new TypeError( '\"array\" is null or not defined' ); } var length = array.length &gt;&gt;&gt; 0; // Hack to convert object.length to a UInt32 fromIndex = +fromIndex || 0; if (Math.abs(fromIndex) === Infinity) { fromIndex = 0; } if (fromIndex &lt; 0) { fromIndex += length; if (fromIndex &lt; 0) { fromIndex = 0; } } for (;fromIndex &lt; length; fromIndex++) { if (array[fromIndex] === searchElement) { return fromIndex; } } return -1; } /** * Implementation of the [Array.forEach]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach} method for browsers that do not support it natively. &lt;br&gt; Executes a function for each element of a given array. * @function * @param {array} array - Desired array. * @param {function} callback - Function that will be executed for each element of the given array. Following the same rules as the native [Array.forEach]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach} method, it will receive three arguments: currentValue, currentIndex and the array given. * @param {*} [thisArg] - Value that will be passed as \"this\" every time the function is called. * @param {boolean} [extendedDOM=false] - Defines whether the function is being called by a native function which was extended. Internal usage recommended only. * @returns {array|undefined} If the \"extendedDOM\" parameter is set to false, returns the given \"array\" again. Otherwise, returns undefined. */ //* Polyfill source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach function CB_forEach(array, callback, thisArg, extendedDOM) { \"use strict\"; if (!extendedDOM) { if (array.forEach) { array.forEach.call(array, callback, thisArg); return array; } else if (Array.prototype.forEach) { Array.prototype.forEach.call(array, callback, thisArg); return array; } } if (array === void 0 || array === null) { throw new TypeError(); } if (typeof callback !== \"function\") { throw new TypeError(); } var t = Object(array); var len = t.length &gt;&gt;&gt; 0; //thisArg = arguments.length &gt;= 2 ? arguments[1] : void 0; for (var i = 0; i &lt; len; i++) { if (i in t) { callback.call(thisArg, t[i], i, t); } } return extendedDOM ? undefined : array; } /** * Implementation of [Array.isArray]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray} method for browsers that do not support it natively. &lt;br&gt; Returns whether a given element is an array or not. * @function * @param {*} element - The element we want to check. * @param {boolean} [extendedDOM=false] - Defines whether the function is being called by a native function which was extended. Internal usage recommended only. * @returns {boolean} * @todo Think about a parameter to check whether the given array is a typed array (for example, 'Uint8Array') or not. */ function CB_isArray(element, extendedDOM) { if (typeof(element) === \"undefined\" || element === null) { return false; } var isArray = false; if (Array) { if (Array.isArray &amp;&amp; !extendedDOM) { isArray = Array.isArray(element); } else { isArray = element instanceof Array; if (!isArray) //It could still be an Array from another frame. { isArray = (Object.prototype.toString.call(element) === '[object Array]'); } } } return isArray; } /** * Alias for {@link CB_sizeOf}. * @function CB_sizeof * @see {@link CB_sizeOf} */ /** * Returns the size of an object or array. * @function * @param {Object|array} element - The element whose size we want to know. It should be an object or an array. * @param {boolean} [onlyOwn=false] - If the \"element\" given is not an object, this parameter will be ignored. Otherwise, if it is set to true, it will only have into account the properties which the object has as their own property and have not been inherited (using the [Object.hasOwnProperty]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty} method). * @returns {integer} If an object is provided, the size will be the number of its properties. Otherwise, if an array is given, the size will be the numbers of its indexes ([Array.length]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length} property). */ function CB_sizeOf(object, onlyOwn) { var size = 0; if (CB_isArray(object) &amp;&amp; typeof(object.length) !== \"undefined\" &amp;&amp; object.length !== null &amp;&amp; !isNaN(object.length) &amp;&amp; object.length &gt; 0) { return object.length; } for (var key in object) { if (!onlyOwn || object.hasOwnProperty(key)) { size++; } } return size; } var CB_sizeof = CB_sizeOf; //Alias for the function. /** * Returns whether a given element is a string or not. * @function * @param {*} element - The element we want to check. * @returns {boolean} */ function CB_isString(element) { return (typeof(element) === \"string\" || element instanceof String); } /** * Returns back the given element if it is a string or an empty string otherwise. * @function * @param {*} element - The element that will be checked. * @returns {string} */ function CB_forceString(element) { if (!CB_isString(element)) { return \"\"; } else { return element; } } /** * Returns back the given element as a string if it could be parsed or an empty string otherwise. * @function * @param {*} element - The element that will be checked. * @returns {string} */ function CB_parseString(element) { if (typeof(element) === \"undefined\" || element === null || element === true || element === false || !CB_isString(element) &amp;&amp; isNaN(element)) { return \"\"; } else { return element + \"\"; } } /** * Trims a given string or array of strings (modifying the given array), taking off the desired strings or otherwise trimming spaces, tabs (\"\\t\"), new lines (\"\\n\") and carriage returns (\"\\r\"). Case sensitive. * @function * @param {string|array} element - The element that will be trimmed. It should be either a string or an array of strings. * @param {string|array} [undesiredStrings=[ \" \", \"\\n\", \"\\r\", \"\\t\" ]] - String or an array with the strings that we want to trim off the given element. * @returns {string|array} Returns the given element again if it was an string, a number (it will be casted to a string) or an array of strings, trimmed if it has been possible. If it was another type, returns an empty string. * @todo Accept a \"recursive\" parameter (boolean) to affect multiple levels (array of arrays of strings, etc.). * @todo Consider accepting objects instead of arrays in the \"element\" parameter. */ function CB_trim(element, undesiredStrings) { if (CB_isArray(element)) { for (var x = 0, elementLength = element.length; x &lt; elementLength; x++) { element[x] = CB_trim(element[x], undesiredStrings); } return element; } //else if (typeof(element) !== \"undefined\" &amp;&amp; element !== null &amp;&amp; !isNaN(element)) { return element; } else if (typeof(element) === \"undefined\" || element === null) { return \"\"; } else if (element === true || element === false) { return \"\"; } else if (!isNaN(element)) { element = element + \"\"; } else if (!CB_isString(element)) { return \"\"; } else if (typeof(element.trim) === \"function\") { //Only calls the native function when the \"undesiredStringFound\" parameter is the default one (it will not just trim blank spaces but also \"\\r\", \"\\n\"...): if (!CB_isArray(undesiredStrings) &amp;&amp; !CB_isString(undesiredStrings)) { return element.trim(); } } //return element.replace(/^\\s+|\\s+$/g, \"\"); element = CB_rtrim(element, undesiredStrings); element = CB_ltrim(element, undesiredStrings); return element; } /** * Trims the right side of a given string or array of strings (modifying the given array), taking off the desired strings or otherwise trimming spaces, tabs (\"\\t\"), new lines (\"\\n\") and carriage returns (\"\\r\"). Case sensitive. * @function * @param {string|array} element - The element that will be trimmed. It should be either a string or an array of strings. * @param {string|array} [undesiredStrings=[ \" \", \"\\n\", \"\\r\", \"\\t\" ]] - String or an array with the strings that we want to trim off the given element. * @returns {string|array} Returns the given element again if it was an string, a number (it will be casted to a string) or an array of strings, trimmed if it has been possible. If it was another type, returns an empty string. * @todo Accept a \"recursive\" parameter (boolean) to affect multiple levels (array of arrays of strings, etc.). * @todo Consider accepting objects instead of arrays in the \"element\" parameter. * @todo Think about optimizing (using a counter for the number of occurrences in the loop and trim all the occurrences when finished). */ function CB_rtrim(element, undesiredStrings) { if (CB_isArray(element)) { for (var x = 0, elementLength = element.length; x &lt; elementLength; x++) { element[x] = CB_rtrim(element[x], undesiredStrings); } return element; } //else if (typeof(element) !== \"undefined\" &amp;&amp; element !== null &amp;&amp; !isNaN(element)) { return element; } else if (typeof(element) === \"undefined\" || element === null) { return \"\"; } else if (element === true || element === false) { return \"\"; } else if (!isNaN(element)) { element = element + \"\"; } else if (!CB_isString(element)) { return \"\"; } if (CB_isString(undesiredStrings)) { undesiredStrings = [ undesiredStrings ]; } else if (!CB_isArray(undesiredStrings)) { undesiredStrings = [ \" \", \"\\n\", \"\\r\", \"\\t\" ]; //Only calls the native function when the \"undesiredStringFound\" parameter is the default one (it will not just trim blank spaces but also \"\\r\", \"\\n\"...): if (typeof(element.trimEnd) === \"function\") { return element.trimEnd(); } } //Loops through the undesired strings: var undesiredStringsLength = undesiredStrings.length; var undesiredStringFound = false; for (var x = 0; x &lt; undesiredStringsLength; x++) { //Trims undesired string at the end: while (element.substring(element.length - undesiredStrings[x].length, element.length) === undesiredStrings[x]) { element = element.substring(0, element.length - undesiredStrings[x].length); undesiredStringFound = true; } //If an undesired string has been found, we are looking for more than one undesired strings and the loop is at the end, starts the loop again: if (undesiredStringFound &amp;&amp; undesiredStringsLength &gt; 1 &amp;&amp; x + 1 === undesiredStringsLength) { undesiredStringFound = false; x = -1; } } return element; } /** * Trims the left side of a given string or array of strings (modifying the given array), taking off the desired strings or otherwise trimming spaces, tabs (\"\\t\"), new lines (\"\\n\") and carriage returns (\"\\r\"). Case sensitive. * @function * @param {string|array} element - The element that will be trimmed. It should be either a string or an array of strings. * @param {string|array} [undesiredStrings=[ \" \", \"\\n\", \"\\r\", \"\\t\" ]] - String or an array with the strings that we want to trim off the given element. * @returns {string|array} Returns the given element again if it was an string, a number (it will be casted to a string) or an array of strings, trimmed if it has been possible. If it was another type, returns an empty string. * @todo Accept a \"recursive\" parameter (boolean) to affect multiple levels (array of arrays of strings, etc.). * @todo Consider accepting objects instead of arrays in the \"element\" parameter. * @todo Think about optimizing (using a counter for the number of occurrences in the loop and trim all the occurrences when finished). */ function CB_ltrim(element, undesiredStrings) { if (CB_isArray(element)) { for (var x = 0, elementLength = element.length; x &lt; elementLength; x++) { element[x] = CB_ltrim(element[x], undesiredStrings); } return element; } //else if (typeof(element) !== \"undefined\" &amp;&amp; element !== null &amp;&amp; !isNaN(element)) { return element; } else if (typeof(element) === \"undefined\" || element === null) { return \"\"; } else if (element === true || element === false) { return \"\"; } else if (!isNaN(element)) { element = element + \"\"; } else if (!CB_isString(element)) { return \"\"; } if (CB_isString(undesiredStrings)) { undesiredStrings = [ undesiredStrings ]; } else if (!CB_isArray(undesiredStrings)) { undesiredStrings = [ \" \", \"\\n\", \"\\r\", \"\\t\" ]; //Only calls the native function when the \"undesiredStringFound\" parameter is the default one (it will not just trim blank spaces but also \"\\r\", \"\\n\"...): if (typeof(element.trimStart) === \"function\") { return element.trimStart(); } } //Loops through the undesired strings: var undesiredStringsLength = undesiredStrings.length; var undesiredStringFound = false; for (var x = 0; x &lt; undesiredStringsLength; x++) { //Trims undesired string at the beginning: while (element.substring(0, undesiredStrings[x].length) === undesiredStrings[x]) { element = element.substring(undesiredStrings[x].length, element.length); undesiredStringFound = true; } //If an undesired string has been found, we are looking for more than one undesired strings and the loop is at the end, starts the loop again: if (undesiredStringFound &amp;&amp; undesiredStringsLength &gt; 1 &amp;&amp; x + 1 === undesiredStringsLength) { undesiredStringFound = false; x = -1; } } return element; } /** * Alias for {@link CB_nl2br}. * @function CB_nlToBr * @see {@link CB_nl2br} */ /** * Changes new lines (\\n) for &amp;lt;br /&amp;gt;'s in a given string. * @function * @param {string} string - The string we want to modify. * @returns {string} Returns the string with all the occurrences replaced or an empty string if the element given was not a string. */ function CB_nl2br(string) { //If it is not a string, uses an empty string instead: if (!CB_isString(string)) { string = \"\"; } //Parses the variable to string type: string = string.toString(); string = string.replace(/\\n/gi, \"&lt;br /&gt;\"); return string; } var CB_nlToBr = CB_nl2br; //Alias for the function. /** * Alias for {@link CB_br2nl}. * @function CB_brToNl * @see {@link CB_br2nl} */ /** * Changes &amp;lt;br /&amp;gt;'s, &amp;lt;br/&amp;gt;'s and &amp;lt;br&amp;gt;'s for new lines (\\n) in a given string. * @function * @param {string} string - The string we want to modify. * @returns {string} Returns the string with all the occurrences replaced or an empty string if the element given was not a string. */ function CB_br2nl(string) { //If it is not a string, uses an empty string instead: if (!CB_isString(string)) { string = \"\"; } //Parses the variable to string type: string = string.toString(); string = string.replace(/&lt;br \\/&gt;/gi, \"\\n\"); string = string.replace(/&lt;br\\/&gt;/gi, \"\\n\"); string = string.replace(/&lt;br&gt;/gi, \"\\n\"); return string; } var CB_brToNl = CB_br2nl; //Alias for the function. /** * Tries to guess whether a given file path (absolute or relative) is a local address or not. It will be assumed as local if the path uses the \"file:\" protocol or the current script is running locally and the path does not use the \"http:\", \"https:\" or \"ftp:\" protocols. * @function * @param {string} filePath - The file path we want to check. * @returns {boolean} Returns whether the given file path is a local address or not. */ function CB_isFileLocal(filePath) { var isFileLocal = false; filePath = CB_trim(filePath); if (filePath !== \"\") { if (filePath.substring(0, 5) === \"file:\" || CB_Client.isRunningLocally() &amp;&amp; filePath.substring(0, 5) !== \"http:\" &amp;&amp; filePath.substring(0, 6) !== \"https:\" &amp;&amp; filePath.substring(0, 4) !== \"ftp:\") { isFileLocal = true; } } return isFileLocal; } /** * Processes a given string as a template and returns it rendered (if possible) with the values of the given JSON object. Tries to use [Handlebars]{@link https://handlebarsjs.com/} as the first choice but if is is not available it will just replace all occurrences with vanilla JavaScript. * @function * @param {string} str - The string we want to render. * @param {Object} [JSONObject=CB_JSONData] - The JSON object which contains the values. If not provided, it will try to use the global CB_JSONData object in the case it exists. * @param {boolean} [forceVanilla=false] - Forces vanilla JavaScript rendering instead of using [Handlebars]{@link https://handlebarsjs.com/}. * @param {integer} [depthLevelMax=10] - Maximum depth level allowed to read the object to render the string. Only applies when it is rendered by vanilla JavaScript. For performance purposes. * @returns {str} */ function CB_renderString(string, JSONObject, forceVanilla, depthLevelMax) { string = CB_trim(string); //If a JSON object is not given, uses the default one (if any): if (typeof(JSONObject) === \"undefined\" || JSONObject === null) { if (typeof(CB_JSONData) !== \"undefined\" &amp;&amp; CB_JSONData !== null) { JSONObject = CB_JSONData; } } //If we do not want vanilla JavaScript rendering and Handlebars is present, uses it: if (!forceVanilla &amp;&amp; typeof(Handlebars) !== \"undefined\" &amp;&amp; Handlebars !== null &amp;&amp; typeof(Handlebars.compile) === \"function\") { //Returns the template rendered: return Handlebars.compile(string)(JSONObject); //Using Handlebars. } //...otherwise, just replaces all occurrences in the given string: else { return CB_renderStringRecursively(string, JSONObject, false, depthLevelMax); } } //Renders a given string recursively with the given object and the given max level: function CB_renderStringRecursively(string, desiredObject, avoidRecursive, depthLevelMax, levelCurrent, pathCurrent) { if (typeof(desiredObject) === \"undefined\" || desiredObject === null) { return string; } if (typeof(depthLevelMax) === \"undefined\" || depthLevelMax === null || isNaN(depthLevelMax)) { depthLevelMax = 10; } if (typeof(levelCurrent) === \"undefined\" || levelCurrent === null || isNaN(levelCurrent)) { levelCurrent = 0; } if (typeof(pathCurrent) === \"undefined\" || pathCurrent === null) { pathCurrent = \"\"; } if (pathCurrent.substring(0, 1) === \".\") { pathCurrent = pathCurrent.substring(1); } for (var property in desiredObject) { if (CB_sizeof(desiredObject[property]) === 0 || CB_isString(desiredObject[property])) { string = string.replace(CB_regularExpressionString(\"{{\" + pathCurrent + (pathCurrent === \"\" ? \"\" : \".\") + property + \"}}\", true, false), desiredObject[property]); } else if (!avoidRecursive &amp;&amp; levelCurrent &lt; depthLevelMax) { string = CB_renderStringRecursively(string, desiredObject[property], avoidRecursive, depthLevelMax, ++levelCurrent, pathCurrent + \".\" + property); string = string.replace(CB_regularExpressionString(\"{{\" + pathCurrent + (pathCurrent === \"\" ? \"\" : \".\") + property + \"}}\", true, false), \"\"); //In the case is has not been found, clears it. } } return string; } /** * Tells whether a given email is valid or not. Not really precise. * @function * @param {string} email - Possible email that we want to validate. * @returns {boolean} */ //* Source: steve @ http://stackoverflow.com/questions/46155/validate-email-address-in-javascript function CB_isEmail(email) { return (CB_isString(email) &amp;&amp; email.indexOf(\"..\") === -1 &amp;&amp; /^((([a-z]|\\d|[!#\\$%&amp;'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&amp;'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i.test(email)); } /** * Returns the given number with the desired decimals and make it a string if we want to (so it will be able to have trailing zeros). Uses decimal numeral system only. It will perform ceiling round automatically if needed. * @function * @param {integer|float|string} number - The number that we want to format. It can be a string. * @param {integer} [decimals=2] - The number of decimals we want to allow. * @param {boolean} [stringify=false] - Set to true if we want it to return a string (filled with trailing zeros to reach the desired number of decimals). * @returns {integer|float|string} Returns zero in the case a non-valid number has been provided. * @todo Allow to define a minimum length for the integer part of the \"number\" parameter, so it will fill with leading zeros if needed (when \"stringify\" is set to true). Think about allowing to define a maximum too. */ function CB_numberFormat(number, decimals, stringify) { number = parseFloat(number); if (isNaN(number)) { return 0; } decimals = parseInt(decimals); if (isNaN(decimals) || decimals &lt; 0) { decimals = 2; } number *= Math.pow(10, decimals); number = parseInt(number + 0.5); //Ceil round. number /= Math.pow(10, decimals); if (stringify) { number = number + \"\"; //if (number.indexOf(\".\") === -1) { number += \".00\"; } //else if (number.substring(number.indexOf(\".\") + 1).length === 1) { number += \"0\"; } if (decimals &gt;= 1 &amp;&amp; number.indexOf(\".\") === -1) { number += \".\"; } while (number.substring(number.indexOf(\".\") + 1).length &lt; decimals) { number += \"0\"; } } return number; } /** * Alias for {@link CB_countDecimalPart}. * @function CB_countDecimals * @see {@link CB_countDecimalPart} */ /** * Alias for {@link CB_countDecimalPart}. * @function CB_countDecimalDigits * @see {@link CB_countDecimalPart} */ /** * Alias for {@link CB_countDecimalPart}. * @function CB_numberOfDecimals * @see {@link CB_countDecimalPart} */ /** * Alias for {@link CB_countDecimalPart}. * @function CB_numberOfDecimalDigits * @see {@link CB_countDecimalPart} */ /** * Returns the number of decimals of the given number. It also works with numbers in exponential notation (as for example '1e-13' which would be 0.0000000000001). * @function * @param {integer|float|string} number - The number whose decimals we want to count. It can be a string. * @returns {integer} Returns zero in the case a non-valid number has been provided. Otherwise, it returns the number of decimals counted. */ var CB_countDecimalPart = CB_countDecimalDigits = CB_countDecimals = CB_numberOfDecimals = CB_numberOfDecimalDigits = function(number) { number = parseFloat(number); if (isNaN(number)) { return 0; } number = Math.abs(number); if (number % 1 === 0) { return 0; } //First it tries \"fastest\" way (it does not work for numbers in exponential notation): var decimals = (number + \"\").split(\".\"); decimals = (typeof(decimals[1]) !== \"undefined\") ? decimals[1].length : 0; if (decimals &gt; 0) { return decimals; } //For float numbers that are represented in exponential notation (like '1e-13', for example): decimals = 0; var numberMultiplied = 0; while ((numberMultiplied = number * Math.pow(10, ++decimals)) % 1 !== 0); return decimals; } /** * Alias for {@link CB_countIntegerPart}. * @function CB_numberOfIntegerDigits * @see {@link CB_countIntegerPart} */ /** * Alias for {@link CB_countIntegerPart}. * @function CB_countIntegerDigits * @see {@link CB_countIntegerPart} */ /** * Returns the number of integer digits (the number of digits that belong to the integer part) of the given number. It also works with numbers in exponential notation (as for example '1e-13' which would be 0.0000000000001). * @function * @param {integer|float|string} number - The number whose integer digits (the digits that belong to the integer part) we want to count. It can be a string. * @returns {integer} Returns zero in the case a non-valid number has been provided. Otherwise, it returns the number of integer digits (the number of digits that belong to the integer part) counted. */ var CB_countIntegerPart = CB_countIntegerDigits = CB_numberOfIntegerDigits = function(number) { number = parseFloat(number); if (isNaN(number)) { return 0; } number = Math.abs(number); if (number &lt; 1) { return 0; } //First it tries \"fastest\" way (it does not work for numbers in exponential notation): var integers = (number + \"\").split(\".\"); integers = (typeof(integers[1]) !== \"undefined\") ? integers[0].length : 0; if (integers &gt; 0) { return integers; } //For float numbers that are represented in exponential notation (like '1e-13', for example): integers = 0; var numberMultiplied = 0; while ((numberMultiplied = number / Math.pow(10, ++integers)) &gt; 1); return integers; } /** * Returns the value of a desired path in an object or an empty string if it cannot be found. * @function * @param {Object} object - The object where we want to find the path. * @param {string} path - The path that will be search in the given object to retrieve the value. It should use the string defined in the \"splitString\" parameter to separate items. If it is empty or not provided, it will just return the given \"object\" again. * @param {string} [splitString=\".\"] - The string that will be used to separate one item from another one. By default, it will be a dot (\".\") so, for example, a given \"path\" with a value of \"hello.world\" will indicate the \"object.hello.world\" path. * @returns {*} Returns the value of a desired path in an object or an empty string if it cannot be found. If the \"path\" parameter is empty or not provided, it will just return the given \"object\" again. */ function CB_getValuePath(object, path, splitString) { if (CB_sizeof(object) === 0 || CB_isString(object)) { return \"\"; } path = CB_trim(path); if (path === \"\") { return object; } if (!CB_isString(splitString) || splitString.length &lt; 1) { splitString = \".\"; } var indexes = path.split(splitString); var indexesLength = indexes.length; var index; var value = object; for (var x = 0; x &lt; indexesLength; x++) { index = CB_trim(indexes[x]); value = CB_getValueIndex(value, index, \"\"); if (CB_sizeof(value) === 0 || CB_isString(value)) { break; } } return (x + 1 === indexesLength) ? value : \"\"; } var CB_setDatumDateObject = new Date(); /** * Stores a value using [Web Storage API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API} ([localStorage]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage}). It can use [localStorage]{@link https://github.com/mortzdk/localStorage} as a fallback or cookies instead. * @function * @param {string|number} index - The index where the value given will be stored. * @param {string|number} value - The value we want to store. It should be a string or a number. * @param {integer} [days] - The number of days after which the cookie will expire (in the case that cookies are used). It belongs to the \"expires=\" parameter of the cookie. If not provided, the parameter will not be used at all. * @param {string} [path] - The path where the cookie will be stored (in the case that cookies are used). It belongs to the \"path=\" parameter of the cookie. If not provided, the parameter will not be used at all. * @param {boolean} [forceCookie=false] - Forces to use cookies instead of [Web Storage API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API} ([localStorage]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage}). * @returns {boolean} Returns true if the value has been stored successfully (not totally reliable, it should be checked with {@link CB_getDatum} after a while). */ function CB_setDatum(index, value, days, path, forceCookie) { index += \"\"; value += \"\"; if (!forceCookie &amp;&amp; window.localStorage &amp;&amp; window.localStorage.setItem) { try { localStorage.setItem(index, value); return true; } catch(E) { } } if (typeof(document.cookie) !== \"undefined\" &amp;&amp; document.cookie !== null) { try { path = CB_trim(path); if (path !== \"\") { path = \";path=\" + escape(path); } var expires = \"\"; if (typeof(days) !== \"undefined\" &amp;&amp; days !== null &amp;&amp; !isNaN(days) &amp;&amp; days &gt;= 0 &amp;&amp; days &lt;= 365) { CB_setDatumDateObject.setTime(CB_setDatumDateObject.getTime() + (days * 24 * 60 * 60 * 1000)); expires = \";expires=\" + CB_setDatumDateObject.toUTCString(); } document.cookie = escape(index) + \"=\" + escape(value) + expires + path; return true; } catch(E) { } } return false; } /** * Stores a cookie. * @function * @param {string|number} index - The index where the value given will be stored. * @param {string|number} value - The value we want to store. It should be a string or a number. * @param {integer} [days] - The number of days after which the cookie will expire. It belongs to the \"expires=\" parameter of the cookie. If not provided, the parameter will not be used at all. * @param {string} [path] - The path where the cookie will be stored. It belongs to the \"path=\" parameter of the cookie. If not provided, the parameter will not be used at all. * @returns {boolean} Returns true if the value has been stored successfully (not totally reliable, it should be checked with {@link CB_getCookie} after a while). */ function CB_setCookie(index, value, days, path) { return CB_setDatum(index, value, days, path, true); } /** * Gets, from its index, a previous value stored. It will try to get it using [Web Storage API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API} ([localStorage]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage}). It can use [localStorage]{@link https://github.com/mortzdk/localStorage} as a fallback or cookies instead. * @function * @param {string} index - The index whose value we want to retrieve. * @param {boolean} [forceCookie=false] - Forces to use cookies instead of [Web Storage API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API} ([localStorage]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage}). * @param {boolean} [unescapeIndex=false] - Applies the unescape function to the value before returning it. Only applies when cookies are used. * @returns {string|null} Returns null when the value cannot be found. */ function CB_getDatum(index, forceCookie, unescapeIndex) { var itemFound = null; if (window.localStorage &amp;&amp; window.localStorage.getItem &amp;&amp; !forceCookie) { itemFound = localStorage.getItem(index); } if (itemFound === null &amp;&amp; typeof(document.cookie) !== \"undefined\" &amp;&amp; document.cookie !== null) { index += \"=\"; if (unescapeIndex) { index = unescape(index); } var cookies = document.cookie.split(\";\"); var cookies_length = cookies.length; for (var x = 0; x &lt; cookies_length; x++) { if (cookies[x].indexOf(index) !== -1) { return unescape(cookies[x].substring(cookies[x].indexOf(index) + index.length, cookies[x].length)); } } } return itemFound; } /** * Returns, from its index, a previous stored cookie. * @function * @param {string} index - The index whose value we want to retrieve. * @returns {string|null} Returns null when the value cannot be found. */ function CB_getCookie(index) { return CB_getDatum(index, true); } /** * Gets the value from a given object which belongs to the desired index or returns the value of \"returnValueOnFail\" if it cannot be found. * @function * @param {Object} object - The object from which we want to get the value. * @param {string} index - The index whose value we want to retrieve. * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that the property cannot be found. If not provided, undefined will be returned. * @returns {*} Returns the value from a given object which belongs to the desired index or the value of \"returnValueOnFail\" otherwise if it cannot be found. */ function CB_getValueIndex(object, index, returnValueOnFail) { if (typeof(object) !== \"undefined\" &amp;&amp; object !== null &amp;&amp; typeof(object[index]) !== \"undefined\" &amp;&amp; object[index] !== null) { return object[index]; } else { return returnValueOnFail; } } /** * Returns an object copied from the given one. * @function * @param {object} element - The element whose properties and values we want to copy. It should be an object. * @param {boolean} [onlyOwn=false] - If the \"element\" given is not an object, this parameter will be ignored. Otherwise, if it is set to true, it will only have into account the properties which the object has as their own property and have not been inherited (using the [Object.hasOwnProperty]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty} method). * @returns {object} Returns an object copied from the given one. Returns an empty object if the given \"element\" was not an object. */ function CB_copyObject(object, onlyOwn) { if (typeof(object) !== \"object\" || object === null) { return {}; } var newObject = {}; for (var key in object) { if (!onlyOwn || object.hasOwnProperty(key)) { newObject[key] = object[key]; } } return newObject; } /** * Gets the value of a desired property of a given JSON object. Uses the {@link CB_getValueIndex} function internally. * @function * @param {Object|string} JSONObject - The JSON object from which we want to get the value. If it is a string, it will try to parse it to create a real object from it. Used as the \"object\" parameter when calling the {@link CB_getValueIndex} function internally. * @param {string} property - The property whose value we want to retrieve. If not provided, the given object will be returned again. Used as the \"index\" parameter when calling the {@link CB_getValueIndex} function internally. * @param {*} [returnValueOnFail] - The value we want it to return in the case it cannot be parsed. If not provided, undefined will be returned. Used as the \"returnValueOnFail\" parameter when calling the {@link CB_getValueIndex} function internally. * @returns {*} Returns the given \"JSONObject\" again (after trying to parse it if it was a string, if possible) if the \"property\" value was not given. Returns the value from the given object which belongs to the desired property or the value of \"returnValueOnFail\" otherwise if it cannot be found. */ function CB_getJSONPropertyValue(JSONObject, property, returnValueOnFail) { if (CB_isString(JSONObject)) { JSONObject = CB_parseJSON(JSONObject, undefined, null); } //If a string is received, tries to parse it as a JSON object. if (typeof(property) === \"undefined\" || property === null) { return JSONObject; } return CB_getValueIndex(JSONObject, property, returnValueOnFail); /* if (typeof(JSONObject) === \"undefined\" || JSONObject === null) { //if (!property || returnObjectOnFail) { return JSONObject; } return returnValueOnFail; } //else if (property &amp;&amp; typeof(JSONObject[property]) !== \"undefined\" &amp;&amp; JSONObject[property] !== null) { return JSONObject[property]; } //else if (!property || returnObjectOnFail) { return JSONObject; } else if (typeof(JSONObject[property]) !== \"undefined\" &amp;&amp; JSONObject[property] !== null) { return JSONObject[property]; } else { return returnValueOnFail; } */ } /** * Tries to parse a given string to convert it into a JSON object. Internally it will use the native [JSON.parse]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse} method or otherwise use [JSON 3]{@link https://bestiejs.github.io/json3/} instead. * @function * @param {string} objectString - The JSON object we want to parse, in string format. First parameter when calling the [JSON.parse]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse} method (or equivalent) * @param {function} [reviver] - Second parameter when calling the [JSON.parse]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse} method (or equivalent). * @param {*} [returnValueOnFail] - The value we want it to return in the case it cannot be parsed. If not provided, undefined will be returned. * @param {boolean} [acceptUndefinedOrNull=false] - If it is set to true and the given objectString is undefined or null, an empty object ({}) will be used as the objectString. * @param {function} [onError] - Callback which will be called if it failed to be parsed (it will receive the \"objectString\" as the unique parameter). * @returns {*} Returns the object parsed from the given string or the value of \"returnValueOnFail\" otherwise (which will be undefined if not provided). */ function CB_parseJSON(objectString, reviver, returnValueOnFail, acceptUndefinedOrNull, onError) { if (typeof(objectString) === \"undefined\" || objectString === null) { if (acceptUndefinedOrNull) { objectString = '{}'; } } objectString = objectString + \"\"; try { return JSON.parse(objectString, reviver); } catch(E) { if (typeof(onError) === \"function\") { onError(objectString); } return returnValueOnFail; } } /** * Tries to create a JSON valid string from a given JSON object or value. Internally it will use the native [JSON.stringify]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify} method or otherwise use [JSON 3]{@link https://bestiejs.github.io/json3/} instead. * @function * @param {*} objectOrValue - The object or value that we want to stringify. First parameter when calling the [JSON.stringify]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify} method (or equivalent). * @param {function} [replacer] - Second parameter when calling the [JSON.stringify]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify} method (or equivalent). * @param {string|integer} [space] - Third parameter when calling the [JSON.stringify]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify} method (or equivalent). * @param {*} [returnValueOnFail] - The value we want it to return in the case it cannot be stringify. If not provided, undefined will be returned. * @param {boolean} [failIfUndefinedOrNull=false] - If it is set to true and the returning value is undefined or null, the value of \"returnValueOnFail\" will be returned. * @param {function} [onError] - Callback which will be called if it failed to be stringified (it will receive the \"objectOrValue\" as the unique parameter). * @returns {string} Returns the object stringified from the given object or value if possible or the value of \"returnValueOnFail\" otherwise (which will be undefined if not provided). Avoids returning undefined or null if \"failIfUndefinedOrNull\" is set to true, returning the value of \"returnValueOnFail\" instead. */ function CB_stringifyJSON(objectOrValue, replacer, space, returnValueOnFail, failIfUndefinedOrNull, onError) { try { var valueReturned = JSON.stringify(objectOrValue, replacer, space); if (failIfUndefinedOrNull &amp;&amp; (typeof(valueReturned) === \"undefined\" || valueReturned === null || valueReturned === \"null\")) { return returnValueOnFail; } return valueReturned; } catch(E) { if (typeof(onError) === \"function\") { onError(objectOrValue); } return returnValueOnFail; } } /** * Tries to combine two given values guessing the best way to do it and returns their combination. Using the following rules: &lt;br /&gt; If both values are either undefined or null, returns null. &lt;br /&gt; Otherwise, if both values are boolean, returns the AND operation for the two of them (a &amp;&amp; b). &lt;br /&gt; Otherwise, if either of the two is a string (not empty) and is not JSON valid, combines them as URL (GET) parameters using {@link CB_combineURIParameters}. &lt;br /&gt; Otherwise, if either of them is JSON valid, combines them as JSON using {@link CB_combineJSON} (passing the received avoidDuplicatedValuesInArray value as a parameter). &lt;br /&gt; Otherwise, combines them as arrays or objects using {@link CB_combineArraysOrObjects} (passing the received \"avoidDuplicatedValuesInArray\" value as a parameter). * @function * @param {*} [a=null|[]|{}] - First value. It can be optional if \"b\" is a valid value, defined and not null. * @param {*} [b=null|[]|{}] - Second value. It can be optional if \"a\" is a valid value, defined and not null. * @param {boolean} [avoidDuplicatedValuesInArray=false] - Parameter that will be used in the case that {@link CB_combineJSON} or {@link CB_combineArraysOrObjects} is called. * @param {boolean} [modifyArrayOrObjectA=false] - Parameter that will be used in the case that {@link CB_combineJSON} or {@link CB_combineArraysOrObjects} is called. If set to true, it will modify the original \"a\" array or object. * @returns {*} */ function CB_combineAutomatically(a, b, avoidDuplicatedValuesInArray, modifyArrayOrObjectA) { if ((typeof(a) === \"undefined\" || a === null) &amp;&amp; (typeof(b) === \"undefined\" || b === null)) { return null; } else if ((a === true || a === false) &amp;&amp; (b === true || b === false)) { return a &amp;&amp; b; } var aJSON = CB_parseJSON(a, undefined, null); var bJSON = CB_parseJSON(b, undefined, null); //If either of the two is a string (not empty) and is not JSON valid, combines them as URL (GET) parameters: if (CB_isString(a) &amp;&amp; CB_trim(a) !== \"\" &amp;&amp; aJSON === null || CB_isString(b) &amp;&amp; CB_trim(b) !== \"\" &amp;&amp; bJSON === null) { return CB_combineURIParameters(a, b); } //...otherwise, if either of them is JSON valid, combines them as JSON: else if (typeof(aJSON) !== \"undefined\" &amp;&amp; aJSON !== null &amp;&amp; aJSON !== true &amp;&amp; aJSON !== false || typeof(bJSON) !== \"undefined\" &amp;&amp; bJSON !== null &amp;&amp; bJSON !== true &amp;&amp; bJSON !== false) { return CB_combineJSON(a, b, avoidDuplicatedValuesInArray, modifyArrayOrObjectA); } //...otherwise, combines them as associative arrays or objects: else { return CB_combineArraysOrObjects(a, b, avoidDuplicatedValuesInArray, modifyArrayOrObjectA); } } /** * Alias for {@link CB_combineURIParameters}. * @function CB_combineURLParameters * @see {@link CB_combineURIParameters} */ /** * Combines two strings as URL (GET) parameters. If either \"parametersA\" or \"parametersB\" is not a string, internally it will use the native [JSON.stringify]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify} method if available or otherwise it will use [JSON 3]{@link https://bestiejs.github.io/json3/} instead. * @function * @param {string} parametersA - String with the desired parameter or parameters. It can be optional if \"parametersB\" is a valid string. It will trim any \"&amp;\" and \"?\" character at the beginning and at the end, and finally use \"&amp;\" to concatenate the two strings (if needed). * @param {string} parametersB - String with the desired parameter or parameters. It can be optional if \"parametersA\" is a valid string. It will trim any \"&amp;\" and \"?\" character at the beginning and at the end, and finally use \"&amp;\" to concatenate the two strings (if needed). * @returns {string} For example, if parametersA is \"parameter1=value1&amp;amp;parameter2=value2\" and parametersB is \"parameter3=value3&amp;amp;what=ever\" then it will return \"parameter1=value1&amp;amp;parameter2=value2&amp;amp;parameter3=value3&amp;amp;what=ever\". */ function CB_combineURIParameters(parametersA, parametersB) { if (typeof(parametersA) === \"undefined\" || parametersA === null) { parametersA = \"\"; } if (typeof(parametersB) === \"undefined\" || parametersB === null) { parametersB = \"\"; } if (!CB_isString(parametersA)) { parametersA = JSON.stringify(parametersA); if (!CB_isString(parametersA)) { parametersA = \"\"; } } if (!CB_isString(parametersB)) { parametersB = JSON.stringify(parametersB); if (!CB_isString(parametersB)) { parametersB = \"\"; } } if (parametersA !== \"\") { parametersA = CB_trim(CB_trim(parametersA), [\"&amp;\", \"?\"]); } if (parametersB !== \"\") { parametersB = CB_trim(CB_trim(parametersB), [\"&amp;\", \"?\"]); } return CB_trim(parametersA + \"&amp;\" + parametersB, \"&amp;\"); } var CB_combineURLParameters = CB_combineURIParameters; //Alias for the function. /** * Returns a combined array or object from two arrays or objects. Using the following rules: &lt;br /&gt; If they both are arrays (numeric indexes), it will keep all elements (attaching the elements of the second array after the elements of the first one). &lt;br /&gt; Otherwise, if either of them is not an array (it should be an associative array which is an object in JavaScript), it will merge the elements (overwritting those whose index is the same and keeping the ones from the second array/object): * @function * @param {array|Object|string|null|undefined} [arrayOrObjectA=[]|{}] - One of the arrays (numeric indexes) or associative arrays (object) that we want to combine. If a string is provided, it will try to convert it into a new object (the string should be a JSON-valid string). It can be optional if \"arrayOrObjectB\" is a valid value and neither null nor undefined. If not provided but the \"arrayOrObjectB\" is provided, it will be a new empty array if the \"arrayOrObjectB\" is an array or it will be an empty object otherwise. * @param {array|Object|string|null|undefined} [arrayOrObjectB=[]|{}] - One of the arrays (numeric indexes) or associative arrays (object) that we want to combine. If a string is provided, it will try to convert it into a new object (the string should be a JSON-valid string). It can be optional if \"arrayOrObjectA\" is a valid value and neither null nor undefined. If not provided but the \"arrayOrObjectA\" is provided, it will be a new empty array if the \"arrayOrObjectA\" is an array or it will be an empty object otherwise. * @param {boolean} avoidDuplicatedValuesInArray - Tells whether to avoid or allow items with duplicated values in the returned array or not. Only applies when both arrays to combine are numeric arrays. * @param {boolean} [modifyArrayOrObjectA=false] - Parameter that will be used in the case that {@link CB_combineJSON} or {@link CB_combineArraysOrObjects} is called. If set to true, it will modify the original \"arrayOrObjectA\" array or object. * @returns {array|Object} */ function CB_combineArraysOrObjects(arrayOrObjectA, arrayOrObjectB, avoidDuplicatedValuesInArray, modifyArrayOrObjectA) { if (typeof(arrayOrObjectA) === \"undefined\" || arrayOrObjectA === null || arrayOrObjectA === true || arrayOrObjectA === false) { arrayOrObjectA = CB_isArray(arrayOrObjectB) ? [] : {}; } if (typeof(arrayOrObjectB) === \"undefined\" || arrayOrObjectB === null || arrayOrObjectB === true || arrayOrObjectB === false) { arrayOrObjectB = CB_isArray(arrayOrObjectA) ? [] : {}; } if (CB_isString(arrayOrObjectA)) { arrayOrObjectA = CB_parseJSON(arrayOrObjectA, undefined, null); if (arrayOrObjectA === null) { arrayOrObjectA = CB_isArray(arrayOrObjectB) ? [] : {}; } } if (CB_isString(arrayOrObjectB)) { arrayOrObjectB = CB_parseJSON(arrayOrObjectB, undefined, null); if (arrayOrObjectB === null) { arrayOrObjectB = CB_isArray(arrayOrObjectA) ? [] : {}; } } var mergedObjectOrArray; //If they both are arrays, it will keep all elements (attaching the elements of the second array after the elements of the first one): if (CB_isArray(arrayOrObjectA) &amp;&amp; CB_isArray(arrayOrObjectB)) { if (modifyArrayOrObjectA) { mergedObjectOrArray = arrayOrObjectA; if (!avoidDuplicatedValuesInArray) { mergedObjectOrArray = CB_Arrays.removeDuplicated(mergedObjectOrArray, undefined, false); } } else { mergedObjectOrArray = []; var arrayOrObjectALength = arrayOrObjectA.length; for (var x = 0; x &lt; arrayOrObjectALength; x++) { if (!avoidDuplicatedValuesInArray || CB_indexOf(mergedObjectOrArray, arrayOrObjectA[x]) === -1) { mergedObjectOrArray[x] = arrayOrObjectA[x]; } } } var arrayOrObjectBLength = arrayOrObjectB.length; for (var x = 0; x &lt; arrayOrObjectBLength; x++) { if (!avoidDuplicatedValuesInArray || CB_indexOf(mergedObjectOrArray, arrayOrObjectB[x]) === -1) { mergedObjectOrArray[mergedObjectOrArray.length] = arrayOrObjectB[x]; } } } //...otherwise, if either of them is not an array, it will merge the elements (overwritting those whose index is the same and keeping the ones from the second object/array): else { if (modifyArrayOrObjectA) { mergedObjectOrArray = arrayOrObjectA; if (!avoidDuplicatedValuesInArray &amp;&amp; CB_isArray(arrayOrObjectA)) { mergedObjectOrArray = CB_Arrays.removeDuplicated(arrayOrObjectA, undefined, false); } } else { mergedObjectOrArray = {}; for (var propertyName in arrayOrObjectA) { mergedObjectOrArray[propertyName] = arrayOrObjectA[propertyName]; } } for (var propertyName in arrayOrObjectB) { mergedObjectOrArray[propertyName] = arrayOrObjectB[propertyName]; } } return mergedObjectOrArray; } /** * Alias for {@link CB_combineArraysOrObjects}. * @function CB_combineJSON * @see {@link CB_combineArraysOrObjects} */ var CB_combineJSON = CB_combineArraysOrObjects; /* function CB_combineJSON(JSONObjectA, JSONObjectB, avoidDuplicatedValuesInArray, modifyArrayOrObjectA) { return CB_combineArraysOrObjects(JSONObjectA, JSONObjectB, avoidDuplicatedValuesInArray, modifyArrayOrObjectA); } */ /** Object that contains different properties and methods that can be used as the \"baseSymbols\" parameter for the {@link CB_intToBase} and {@link CB_baseToInt} functions. Each property is a numeric array of characters. * @namespace * @type {Object} */ var CB_baseSymbols = { \"_getCache\" : { \"max\" : [] }, /** * Function that will return a numeric array of characters containing as many items as the desired base. Uses a cache internally. * @function * @param {integer} [base=256] - The desired base (number of items, each with a character, that the returning array will contain). Minimum value is 1. The maximum can differ one client to another but it is not recommended to exceed 4096 (or even lower, depending on the client, although some clients could support up to 63988 or even more). All arrays of bases lower than 87 use the symbols included also in base 87. * @returns {array} Returns a numeric array of characters containing as many items as the desired base. All arrays of bases lower than 87 use the symbols included also in base 87. When the base is greater than 87 and it is not not created by default (88 and 128), each item of the returning array will be the result of calling the [String.fromCharCode]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode} function from 0 to one number less than the desired base number. */ \"get\" : function(base) { if (typeof(base) === \"undefined\" || base === null || isNaN(base) || base &lt; 1) { base = 256; } if (CB_isArray(CB_baseSymbols[base]) &amp;&amp; CB_baseSymbols[base].length === base) { return CB_baseSymbols[base]; } else if (CB_isArray(CB_baseSymbols._getCache[base]) &amp;&amp; CB_baseSymbols._getCache[base].length === base) { return CB_baseSymbols._getCache[base]; } var baseSymbols = []; var _getCacheLength = CB_baseSymbols._getCache.max.length; //if (_getCacheLength === base) { return CB_baseSymbols._getCache.max; } for (var x = 0; x &lt; base &amp;&amp; x &lt; _getCacheLength; x++) { baseSymbols[x] = CB_baseSymbols._getCache.max[x]; } for (; x &lt; base; x++) { CB_baseSymbols._getCache.max[x] = baseSymbols[x] = String.fromCharCode(x); } CB_baseSymbols._getCache[base] = baseSymbols; return baseSymbols; }, /** * Alias for {@link CB_baseSymbols.128}. * @var CB_baseSymbols._128 * @see {@link CB_baseSymbols.128} */ \"_128\" : [], /** * Numeric array of characters with 128 symbols. These symbols (and also the ones from other bases with higher number) will be encoded by the [escape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape} function and also by the [encodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent} function and they will need to be encoded in HTML (not recommended for URI components or JavaScript strings or HTML code). * @type {array} * @default An array with each item being the result of calling the [String.fromCharCode]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode} function from 0 to 127 as its unique parameter. */ \"128\" : [], /** * Alias for {@link CB_baseSymbols.88}. * @var CB_baseSymbols._88 * @see {@link CB_baseSymbols.88} */ /** * Numeric array of characters with 88 symbols. These symbols will be encoded by the [escape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape} function and also by the [encodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent} function, but they will not need to be encoded in HTML (not recommended for URI components or JavaScript strings, but useful for HTML code). * @type {array} * @default */ \"88\" : [ \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \".\", \"~\", \"!\", \"'\", \"(\", \")\", \"*\", \"-\", \"_\", \"@\", \"\\\\\", \"/\", \"|\", \"[\", \"]\", \"{\", \"}\", \"$\", \"%\", \"=\", \"?\", \"^\", \":\", \";\", \",\", \"+\" ], /** * Alias for {@link CB_baseSymbols.87}. * @var CB_baseSymbols._87 * @see {@link CB_baseSymbols.87} */ /** * Numeric array of characters with 87 symbols. These symbols will be encoded by the [escape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape} function and also by the [encodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent} function but they will not need to be encoded neither in JavaScript strings nor in HTML (not recommended for URI components, but useful for JavaScript strings or HTML code). Includes all symbols from lower bases, respecting the same order (which is their value). * @type {array} * @default */ \"87\" : [ \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \".\", \"*\", \"-\", \"_\", \"~\", \"!\", \"'\", \"(\", \")\", \"@\", \"/\", \"|\", \"[\", \"]\", \"{\", \"}\", \"$\", \"%\", \"=\", \"?\", \"^\", \":\", \";\", \",\", \"+\" ], /** * Alias for {@link CB_baseSymbols.71}. * @var CB_baseSymbols._71 * @see {@link CB_baseSymbols.71} */ /** * Numeric array of characters with 71 symbols. These symbols will be encoded by the [escape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape} function but not by the [encodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent} function (not recommended for URI components in old clients, but useful for URI components in new clients with [encodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent} function support, for JavaScript strings or HTML code). Includes all symbols from lower bases, respecting the same order (which is their value). * @type {array} * @default */ \"71\" : [ \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \".\", \"*\", \"-\", \"_\", \"~\", \"!\", \"'\", \"(\", \")\"], /** * Alias for {@link CB_baseSymbols.66}. * @var CB_baseSymbols._66 * @see {@link CB_baseSymbols.66} */ /** * Numeric array of characters with 66 symbols. These symbols will not be encoded neither by the [escape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape} function nor by the [encodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent} function (recommended for URI components for any client, JavaScript strings or HTML code). Includes Includes all symbols from lower bases, respecting the same order (which is their value). * @type {array} * @default */ \"66\" : [ \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \".\", \"*\", \"-\", \"_\" ], /** * Alias for {@link CB_baseSymbols.64}. * @var CB_baseSymbols._64 * @see {@link CB_baseSymbols.64} */ /** * Numeric array of characters with 64 symbols (using 0 to 9, A to Z, a to z, \".\" and \"*\"). These symbols will not be encoded neither by the [escape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape} function nor by the [encodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent} function (recommended for URI components for any client, JavaScript strings or HTML code in the case that we do not want to use base 66 from the {@link CB_baseSymbols.66} property). Includes all symbols from lower bases, respecting the same order (which is their value). * @type {array} * @default */ \"64\" : [ \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \".\", \"*\" ], /** * Alias for {@link CB_baseSymbols.16}. * @var CB_baseSymbols._16 * @see {@link CB_baseSymbols.16} */ /** * Numeric array of characters with 16 symbols (using 0 to 9, A to F), hexadecimal system. These symbols will not be encoded neither by the [escape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape} function nor by the [encodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent} function (recommended for URI components for any client, JavaScript strings or HTML code). Includes all symbols from lower bases, respecting the same order (which is their value). * @type {array} * @default */ \"16\" : [ \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\" ], /** * Alias for {@link CB_baseSymbols.10}. * @var CB_baseSymbols._10 * @see {@link CB_baseSymbols.10} */ /** * Numeric array of characters with 10 symbols (using 0 to 9), decimal system. These symbols will not be encoded neither by the [escape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape} function nor by the [encodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent} function (recommended for URI components for any client, JavaScript strings or HTML code). Includes all symbols from lower bases, respecting the same order (which is their value). * @type {array} * @default */ \"10\" : [ \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\" ], /** * Alias for {@link CB_baseSymbols.8}. * @var CB_baseSymbols._8 * @see {@link CB_baseSymbols.8} */ /** * Numeric array of characters with 8 symbols (using 0 to 7), octal system. These symbols will not be encoded neither by the [escape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape} function nor by the [encodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent} function (recommended for URI components for any client, JavaScript strings or HTML code). Includes all symbols from lower bases, respecting the same order (which is their value). * @type {array} * @default */ \"8\" : [ \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\" ], /** * Alias for {@link CB_baseSymbols.2}. * @var CB_baseSymbols._8 * @see {@link CB_baseSymbols.2} */ /** * Numeric array of characters with 2 symbols (using 0 and 1), binary system. These symbols will not be encoded neither by the [escape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape} function nor by the [encodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent} function (recommended for URI components for any client, JavaScript strings or HTML code). * @type {array} * @default */ \"2\" : [ \"0\", \"1\" ] }; CB_baseSymbols._128 = CB_baseSymbols[\"128\"] = CB_baseSymbols.get(128); CB_baseSymbols._88 = CB_baseSymbols[\"88\"]; CB_baseSymbols._87 = CB_baseSymbols[\"87\"]; CB_baseSymbols._71 = CB_baseSymbols[\"71\"]; CB_baseSymbols._66 = CB_baseSymbols[\"66\"]; CB_baseSymbols._64 = CB_baseSymbols[\"64\"]; CB_baseSymbols._16 = CB_baseSymbols[\"16\"]; CB_baseSymbols._10 = CB_baseSymbols[\"10\"]; CB_baseSymbols._8 = CB_baseSymbols[\"8\"]; CB_baseSymbols._2 = CB_baseSymbols[\"2\"]; for (CB_baseSymbols._x = 3; CB_baseSymbols._x &lt; 87; CB_baseSymbols._x++) { if (typeof(CB_baseSymbols[CB_baseSymbols._x]) !== \"undefined\") { continue; } CB_baseSymbols[\"_\" + CB_baseSymbols._x] = CB_baseSymbols[CB_baseSymbols._x] = CB_baseSymbols._87.slice(0, CB_baseSymbols._x); } /** * Converts a given integer into a desired base. * @function * @param {integer|string} number - The integer that we want to convert to the desired base. For bigger numbers (up to 999999999999999934464 or even lower, depending on the client and the \"baseSymbols\" used), it is recommended to use a string which will allow to accept a slightly bigger number (up to 999999999999999999999999 or lower, depending on the client and the \"baseSymbols\" used). Really big numbers will not be codified properly even when passed as a string due to the limitations of JavaScript engines and maximum number allowed to be stored in a variable. * @param {array|integer} [baseSymbols={@link CB_baseSymbols.66}] - Array with the desired symbols, using only one per index (their value will correspond to their index). The base (radix) will be the total number of indexes. If an integer greater or equal than 2 is provided, it will try to use it as an index of the {@link CB_baseSymbols} object and use it if found or use it as a parameter to call the {@link CB_baseSymbols.get} function otherwise. If not provided or the integer is lower than 2, it will use base 66 (defined in the {@link CB_baseSymbols._66} property of the {@link CB_baseSymbols} object). It is recommended not to exceed 4096 (or even lower, depending on the client, although some clients could support up to 63988 or even more). The properties of the {@link CB_baseSymbols} object or the {@link CB_baseSymbols.get} function can be used for this parameter. * @param {boolean} [unsigned=false] - Determines whether to treat the input and output numbers as unsigned or not. * @param {string} [minusSymbol='-'|'0'] - Determines the minus symbol or string for the output, to mark negative numbers. If not provided, it will be '-' for bases equal or lower than 16 (hexadecimal) or '0' (zero character) otherwise. This parameter is ignored if the \"unsigned\" parameter is set to true. * @param {prefix} [prefix='0'|'0x'|''] - Determines the prefix for the output. If not provided, it will be '0' (zero character) for base 8 (octal), '0x' for base 16 (hexadecimal) or nothing (empty string) for all the others. Use an empty string to avoid using anything. * @returns {string} Returns an empty string in the case that the given number cannot be parsed as an integer. Otherwise, returns the given number in the desired base as a string. * @todo Think about allowing the \"number\" parameter to be a very long string, for bigger numbers (to exceed the limit for integers). Internally, it would need to perform operations comparisons, divisions, remainder calculation with strings, etc. * @todo Think about allowing to specify the base for the integer (now it is 16 if it begins with \"0x\", 8 if it begins with \"0\" and it is not a string or 10 otherwise, and newer clients can support '0b' for binaries, '0o' for octals, ). * @todo Think about accepting a decimal symbol to separate decimals and support float numbers. */ function CB_intToBase(number, baseSymbols, unsigned, minusSymbol, prefix) { number = parseInt(number); if (isNaN(number)) { return \"\"; } var isNegative = false; if (!unsigned &amp;&amp; number &lt; 0) { isNegative = true; } if (!CB_isArray(baseSymbols)) { if (typeof(baseSymbols) !== \"undefined\" &amp;&amp; baseSymbols !== null &amp;&amp; !isNaN(baseSymbols) &amp;&amp; baseSymbols &gt;= 2) { if (CB_isArray(CB_baseSymbols[baseSymbols])) { baseSymbols = CB_baseSymbols[baseSymbols]; } else { baseSymbols = CB_baseSymbols.get(baseSymbols); } } else { baseSymbols = CB_baseSymbols._66; } } baseRadix = baseSymbols.length; if (!unsigned &amp;&amp; isNegative &amp;&amp; (typeof(minusSymbol) === \"undefined\" || minusSymbol === null)) { minusSymbol = baseRadix &lt;= 16 ? \"-\" : \"0\"; } var total = \"\"; number = Math.abs(number); if (number &gt;= baseRadix) { total = CB_intToBase(number / baseRadix, baseSymbols, true, \"\", \"\"); number = parseInt(number % baseRadix); } total += baseSymbols[number]; if (typeof(prefix) === \"undefined\" || prefix === null) { if (baseRadix === 8) { prefix = \"0\"; } else if (baseRadix === 16) { prefix = \"0x\"; } else { prefix = null; } } if (prefix !== null) { total = prefix + total; } if (!unsigned &amp;&amp; isNegative) { total = minusSymbol + total; } return total; } /** * Converts a given number which is already in a desired base into an integer (decimal base). &lt;br /&gt; Note: It can return wrong values when the value exceeds the maximum allowed by a number in the client's JavaScript engine. It can also depend on the \"baseSymbols\" used. * @function * @param {string} number - A string containing the number which is already in the desired base and that we want to convert to an integer. * @param {array|integer} [baseSymbols={@link CB_baseSymbols.66}] - Array with the desired symbols, using only one per index (their value will correspond to their index). The base (radix) will be the total number of indexes. It should be the base which is already being used by the given number. If an integer greater or equal than 2 is provided, it will try to use it as an index of the {@link CB_baseSymbols} object and use it if found or use it as a parameter to call the {@link CB_baseSymbols.get} function otherwise. If not provided or the integer is lower than 2, it will use base 66 (defined in the {@link CB_baseSymbols._66} property of the {@link CB_baseSymbols} object). It is recommended not to exceed 4096 (or even lower, depending on the client, although some clients could support up to 63988 or even more). The properties of the {@link CB_baseSymbols} object or the {@link CB_baseSymbols.get} function can be used for this parameter. * @param {boolean} [unsigned=false] - Determines whether to treat the input and output numbers as unsigned or not. * @param {string} [minusSymbol='-'|'0'] - Determines the minus symbol or string for the input, to mark negative numbers. If not provided, it will be '-' for bases equal or lower than 16 (hexadecimal) or '0' (zero character) otherwise. This parameter is ignored if the \"unsigned\" parameter is set to true. * @param {prefix} [prefix='0'|'0x'|''] - Determines the prefix for the input. If not provided, it will be '0' (zero character) for base 8 (octal), '0x' for base 16 (hexadecimal) or nothing (empty string) for all the others. Use an empty string to avoid using anything. * @returns {integer} Returns the integer number in decimal base. * @todo Think about allowing to return a string, for bigger numbers (to exceed the limit for integers). Internally, it would need to perform operations comparisons, multiplications with strings, etc. * @todo Think about allowing to specify the base for the integer. * @todo Think about accepting a decimal symbol to separate decimals and support float numbers. */ function CB_baseToInt(number, baseSymbols, unsigned, minusSymbol, prefix) { number = \"\" + number; if (!CB_isArray(baseSymbols)) { if (typeof(baseSymbols) !== \"undefined\" &amp;&amp; baseSymbols !== null &amp;&amp; !isNaN(baseSymbols) &amp;&amp; baseSymbols &gt;= 2) { if (CB_isArray(CB_baseSymbols[baseSymbols])) { baseSymbols = CB_baseSymbols[baseSymbols]; } else { baseSymbols = CB_baseSymbols.get(baseSymbols); } } else { baseSymbols = CB_baseSymbols._66; } } var value = CB_indexOf(baseSymbols, number.substring(number.length-1)); if (value === -1) { return 0; } baseRadix = baseSymbols.length; var isNegative = false; if (!unsigned) { if (typeof(minusSymbol) === \"undefined\" || minusSymbol === null) { minusSymbol = baseRadix &lt;= 16 ? \"-\" : \"0\"; } else { minusSymbol = minusSymbol + \"\"; } if (number.substring(0, minusSymbol.length) === minusSymbol) { number = number.substring(minusSymbol.length); isNegative = true; } } if (typeof(prefix) === \"undefined\" || prefix === null) { if (baseRadix === 8) { prefix = \"0\"; } else if (baseRadix === 16) { prefix = \"0x\"; } else { prefix = null; } } if (prefix !== null &amp;&amp; prefix.length &amp;&amp; number.substring(0, prefix.length) === prefix) { number = number.substring(prefix.length); } number = number.substring(0, number.length - 1); if (number !== \"\") { value += CB_baseToInt(number, baseSymbols, true, \"\", \"\") * baseRadix; } if (isNegative &amp;&amp; value &gt; 0) { value *= -1; } return value; } /** * Converts a given number which is already in a desired base into another chosen base. &lt;br /&gt; Note: Uses {@link CB_baseToInt} and {@link CB_intToBase} internally. * @function * @param {string} number - A string containing the number which is already in the desired base and that we want to convert into the another chosen base. Used as the \"number\" parameter for calling both {@link CB_intToBase} and {@link CB_baseToInt} functions internally. * @param {array|integer} [baseSymbolsOrigin={@link CB_baseSymbols.66}] - Used as the \"baseSymbols\" parameter when calling the {@link CB_baseToInt} function internally. * @param {array|integer} [baseSymbolsDestiny={@link CB_baseSymbols.66}] - Used as the \"baseSymbols\" parameter when calling the {@link CB_intToBase} function internally. * @param {boolean} [unsigned=false] - Determines whether to treat the input and output numbers as unsigned or not. Used as the \"unsigned\" parameter for calling both {@link CB_intToBase} and {@link CB_baseToInt} functions internally. * @param {string} [minusSymbolOrigin='-'|'0'] - Used as the \"minusSymbol\" parameter when calling the {@link CB_baseToInt} function internally. * @param {string} [minusSymbolDestiny='-'|'0'] - Used as the \"minusSymbol\" parameter when calling the {@link CB_intToBase} function internally. * @param {prefix} [prefixOrigin='0'|'0x'|''] - Used as the \"prefix\" parameter when calling the {@link CB_baseToInt} function internally. * @param {prefix} [prefixDestiny='0'|'0x'|''] - Used as the \"prefix\" parameter when calling the {@link CB_intToBase} function internally. * @returns {string} Returns the returning value of the internal call to the {@link CB_intToBase} function. * @todo Think about accepting a decimal symbol to separate decimals and support float numbers. */ function CB_baseToBase(number, baseSymbolsOrigin, baseSymbolsDestiny, unsigned, minusSymbolOrigin, minusSymbolDestiny, prefixOrigin, prefixDestiny) { var numberDecimal = CB_baseToInt(number, baseSymbolsOrigin, unsigned, minusSymbolOrigin, prefixOrigin); return CB_intToBase(numberDecimal, baseSymbolsDestiny, unsigned, minusSymbolDestiny, prefixDestiny); } /** * Returns the string or array of strings with all the desired occurrences replaced. Calls itself recursively and calls the {@link CB_regularExpressionString} function internally. * @function * @param {string|array} stringOrArray - An string or an array of strings whose content we want to replace. It can also be an array of arrays of strings (as many levels as you wish). If an array is given, it will not be modified and a copy from it will be generated and returned with the occurrences replaced. * @param {string|array} stringOrArrayFind - An string or an array of strings (not a regular expressions) that we want to find to be replaced (special characters will be escaped). * @param {string} [stringReplace=\"\"] - The string that will replace \"stringFind\". If not provided, it will be replaced as an empty string (it will just remove the occurrences found). * @param {boolean} [caseInsensitive=false] - Defines whether we want to be case insensitive or not. * @returns {string|array} Returns the \"stringOrArray\" given with occurrences replaced. If the \"stringOrArray\" given was neither a string nor an array, it will be returned without being modified. */ function CB_replaceAll(stringOrArray, stringOrArrayFind, stringReplace, caseInsensitive) { if (CB_isArray(stringOrArray)) { var arrayCopy = []; for (var x = 0; x &lt; stringOrArray.length; x++) { arrayCopy[x] = CB_replaceAll(stringOrArray[x], stringOrArrayFind, stringReplace, caseInsensitive); } stringOrArray = arrayCopy; } else if (CB_isString(stringReplace)) { stringOrArrayFind = CB_isArray(stringOrArrayFind) ? stringOrArrayFind : [ stringOrArrayFind ]; for (var x = 0; x &lt; stringOrArrayFind.length; x++) { stringOrArray = (stringOrArray + \"\").replace(CB_regularExpressionString(stringOrArrayFind[x], true, caseInsensitive), stringReplace); } } return stringOrArray; //If it is neither a string nor an array, it will be returned without being modified. } /** * Returns a desired regular expression (escaping the string) using the native JavaScript's [RegExp]{@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp} from a given string. * @function * @param {string} string - The string (not a regular expression) that we want to use (special characters will be escaped). * @param {boolean} [allOccurrences=false] - Defines whether we want the regular expression returned to match all occurrences of the given string or only first found. * @param {boolean} [caseInsensitive=false] - Defines whether we want the regular expression returned to be case insensitive or not. * @returns {RegExp} Returns the desired regular expression (escaping the string) using the native JavaScript's [RegExp]{@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp} from a given string. */ //* Source: Cory Gross @ http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript function CB_regularExpressionString(string, allOccurrences, caseInsensitive) { var parameters = \"\"; if (allOccurrences) { parameters += \"g\"; } if (caseInsensitive) { parameters += \"i\"; } return new RegExp(string.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&amp;\"), parameters === \"\" ? undefined : parameters); } /** * Returns the \"LZString\" object (used by the [lz-string]{@link http://pieroxy.net/blog/pages/lz-string/index.html} library), if any. Useful for compressing/decompressing strings. * @function * @returns {Object} Returns the \"LZString\" object (used by the [lz-string]{@link http://pieroxy.net/blog/pages/lz-string/index.html} library) if available or null otherwise. */ function CB_getLZStringObject() { return (typeof(LZString) === \"object\") ? LZString : null; } /** * Returns the \"Base64String\" object (used by the base64-string library included in [lz-string]{@link http://pieroxy.net/blog/pages/lz-string/index.html}), if any. Useful for compressing/decompressing base64 code. * @function * @returns {Object} Returns the \"Base64String\" object (used by the base64-string library included in [lz-string]{@link http://pieroxy.net/blog/pages/lz-string/index.html}) if available or null otherwise. */ function CB_getBase64StringObject() { return (typeof(Base64String) === \"object\") ? Base64String : null; } × Search results Close "},"CrossBase_audiovisual_audio_CB_AudioDetector.js.html":{"id":"CrossBase_audiovisual_audio_CB_AudioDetector.js.html","title":"Source: CrossBase/audiovisual/audio/CB_AudioDetector.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/audiovisual/audio/CB_AudioDetector.js /** * @file Audio formats and audio APIs support detection. Contains the {@link CB_AudioDetector} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to detect audio API and formats supported. Possible audio APIs are \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). It will return itself if it is tried to be instantiated. * @namespace */ var CB_AudioDetector = function() { return CB_AudioDetector; }; { CB_AudioDetector.initialized = false; //It will tells whether the object has been initialized or not. //Initializes all values: CB_AudioDetector.init = function() { if (CB_AudioDetector.initialized) { return CB_AudioDetector; } //Sets that the object has already been initialized: CB_AudioDetector.initialized = true; //TODO. return CB_AudioDetector; } CB_AudioDetector._getSupportedAudioFormatsReturnCache = {}; /** * Returns an array of strings with the audio formats that are supported (from an array if it is given) by the current client and ordered by support level. Uses the {@link CB_AudioDetector.isAudioFormatSupported} function internally. * @function * @param {array} [audioFormats=CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_FORMATS] - An array of strings with the audio format or audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"') that we want to check. * @param {array} [supportLevels=['probably', 'maybe']] - An array with the support level or support levels allowed. Two possible levels: \"probably\" and \"maybe\". The \"probably\" audio formats are more likely to be supported than the \"maybe\" ones. * @param {boolean} [dataURI=false] - Specifies whether we want to check the support for data URI audios or just for normal audio files. * @returns {array} Returns an array of strings with the audio formats that are supported (from an array if it is given) and ordered by support level. */ CB_AudioDetector.getSupportedAudioFormats = function(audioFormats, supportLevels, dataURI) { //If not given any APIs, uses the default ones with the default order: if (typeof(audioFormats) === \"undefined\" || audioFormats === null || !CB_isArray(audioFormats)) { audioFormats = CB_Configuration[CB_BASE_NAME].CB_AudioFileCache_PREFERRED_AUDIO_FORMATS; } //If not given, it will return \"probably\" and \"maybe\" ones and in that order (\"probably\" are more likely to be supported than \"maybe\" ones): if (!CB_isArray(supportLevels)) { supportLevels = [\"probably\", \"maybe\"]; } //If it is not the first time, returns the same as the first time (from the cache): if (typeof(CB_AudioDetector._getSupportedAudioFormatsReturnCache[audioFormats]) !== \"undefined\" &amp;&amp; CB_AudioDetector._getSupportedAudioFormatsReturnCache[audioFormats] !== null) { if (typeof(CB_AudioDetector._getSupportedAudioFormatsReturnCache[audioFormats][supportLevels]) !== \"undefined\" &amp;&amp; CB_AudioDetector._getSupportedAudioFormatsReturnCache[audioFormats][supportLevels] !== null) { if (typeof(CB_AudioDetector._getSupportedAudioFormatsReturnCache[audioFormats][supportLevels][dataURI]) !== \"undefined\" &amp;&amp; CB_AudioDetector._getSupportedAudioFormatsReturnCache[audioFormats][supportLevels][dataURI] !== null) { return CB_AudioDetector._getSupportedAudioFormatsReturnCache[audioFormats][supportLevels][dataURI]; } } } var supportedAudioFormats = []; var audioFormatsLength = audioFormats.length; //Checks the different support levels by order of preference (\"probably\" are more likely to be supported than \"maybe\" ones): var supportLevelsLength = supportLevels.length; var y; for (var x = 0; x &lt; supportLevelsLength; x++) { for (y = 0; y &lt; audioFormatsLength; y++) { if (CB_AudioDetector.isAudioFormatSupported(audioFormats[y], dataURI) === supportLevels[x]) { if (CB_indexOf(supportedAudioFormats, audioFormats[y]) === -1) { supportedAudioFormats[supportedAudioFormats.length] = audioFormats[y]; } } } } //Stores the result in the cache for the next time: if (typeof(CB_AudioDetector._getSupportedAudioFormatsReturnCache[audioFormats]) === \"undefined\") { CB_AudioDetector._getSupportedAudioFormatsReturnCache[audioFormats] = {}; } if (typeof(CB_AudioDetector._getSupportedAudioFormatsReturnCache[audioFormats][supportLevels]) === \"undefined\") { CB_AudioDetector._getSupportedAudioFormatsReturnCache[audioFormats][supportLevels] = {}; } CB_AudioDetector._getSupportedAudioFormatsReturnCache[audioFormats][supportLevels][dataURI] = supportedAudioFormats; return supportedAudioFormats; } CB_AudioDetector._isAudioFormatSupportedReturnCache = {}; CB_AudioDetector._audioObject = null; /** * Returns the support level of a given audio format by the current client. * @function * @param {string} audioFormat - The audio format (it can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"') that we want to check. * @param {boolean} [dataURI=false] - Specifies whether we want to check the support for data URI audios or just for normal audio files. * @returns {string} Returns the support level of the given audio format (it will return \"probably\", \"maybe\" or an empty string which means not supported). The \"probably\" audio formats are more likely to be supported than the \"maybe\" ones. * @todo Think about using MediaSource.isTypeSupported(). * @todo Some web clients does not support data URIs for Audio element so we should take this into account. * @todo Take into account that data URIs may not be supported when WAAPI is being emulated. */ CB_AudioDetector.isAudioFormatSupported = function(audioFormat, dataURI) { audioFormat = CB_trim(audioFormat).toLowerCase(); //If it is not the first time, returns the same as the first time (from the cache): if (typeof(CB_AudioDetector._isAudioFormatSupportedReturnCache[audioFormat]) !== \"undefined\" &amp;&amp; CB_AudioDetector._isAudioFormatSupportedReturnCache[audioFormat] !== null) { if (typeof(CB_AudioDetector._isAudioFormatSupportedReturnCache[audioFormat][dataURI]) !== \"undefined\" &amp;&amp; CB_AudioDetector._isAudioFormatSupportedReturnCache[audioFormat][dataURI] !== null) { return CB_AudioDetector._isAudioFormatSupportedReturnCache[audioFormat][dataURI]; } } var isSupported = \"\"; //TODO: think about using MediaSource.isTypeSupported(). if (CB_AudioDetector.isAPISupported(\"AAPI\", false)) { if (CB_AudioDetector._audioObject === null) { CB_AudioDetector._audioObject = new Audio(); } //TODO: some web clients does not support data URIs for Audio element so we should take this into account. if (CB_AudioDetector._audioObject !== null &amp;&amp; typeof(CB_AudioDetector._audioObject.canPlayType) === \"function\") { isSupported = CB_AudioDetector._audioObject.canPlayType(audioFormat); } } //...otherwise, if SoundManager 2 is loaded and it is using Flash: else if (CB_AudioDetector.isAPISupported(\"SM2\", false) &amp;&amp; CB_AudioDetector.isSM2UsingFlash()) { //SoundManager 2 using Flash supports MP3 only and does not support data URIs: if (!dataURI &amp;&amp; audioFormat.substring(0, 10) === \"audio/mpeg\") { isSupported = \"maybe\"; } } //Stores the result in the cache for the next time: if (typeof(CB_AudioDetector._isAudioFormatSupportedReturnCache[audioFormat]) === \"undefined\") { CB_AudioDetector._isAudioFormatSupportedReturnCache[audioFormat] = {}; } CB_AudioDetector._isAudioFormatSupportedReturnCache[audioFormat][dataURI] = isSupported; return (\"\" + isSupported).toLowerCase(); } /** * Returns whether a given audio API exists or not (without keeping into account whether it is supported or not). All existing ones are defined in {@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS}. * @function * @param {string} audioAPI - The audio API that we want to check. All existing ones are defined in {@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS}. For example: \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @param {boolean} [sanitize=true] - If set to true, the \"audioAPI\" given will be trimmed and converted to upper case. * @returns {boolean} Returns whether the given audio API exists or not (without keeping into account whether it is supported or not). */ CB_AudioDetector.APIExists = function(audioAPI, sanitize) { if (typeof(sanitize) === \"undefined\" || sanitize === null) { sanitize = true; } if (sanitize) { audioAPI = CB_trim(audioAPI).toUpperCase(); } return (CB_indexOf(CB_Configuration[CB_BASE_NAME].CB_AudioFileCache_PREFERRED_AUDIO_APIS, audioAPI) !== -1); } CB_AudioDetector._getPreferredAPIReturnCache = {}; /** * Calculates and returns the preferred audio API (from an array if it is given) for the current client, if any. * @function * @param {array} [audioAPIs=CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS] - An array of strings with the audio APIs that we want to check, in order of preference. All existing ones are defined in {@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS}. For example: \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @param {boolean} [allowEmulation=!!CB_Configuration[CB_BASE_NAME].CB_AudioDetector_allowEmulation_DEFAULT] - If set to true, it will also detect as supported emulated audio APIs (as \"WAAPI\" using [waapisim.js]{@link https://github.com/g200kg/WAAPISim} instead of supported natively). * @param {boolean} [returnOnEmpty=undefined] - If set to true and no audio API is supported, it will return the value of this parameter instead of null. * @returns {string|*} Returns a string with the preferred audio API (from an array if it is given) for the current client, if any. If no audio API is supported, it will return the value set in the \"returnOnEmpty\" parameter. */ CB_AudioDetector.getPreferredAPI = function(audioAPIs, allowEmulation, returnOnEmpty) { audioAPIs = CB_AudioDetector.getSupportedAPIs(audioAPIs, allowEmulation); if (allowEmulation !== true &amp;&amp; allowEmulation !== false) { allowEmulation = !!CB_Configuration[CB_BASE_NAME].CB_AudioDetector_allowEmulation_DEFAULT; } //If it is not the first time, returns the same as the first time (from the cache): if (typeof(CB_AudioDetector._getPreferredAPIReturnCache[audioAPIs]) !== \"undefined\" &amp;&amp; CB_AudioDetector._getPreferredAPIReturnCache[audioAPIs] !== null) { if (typeof(CB_AudioDetector._getPreferredAPIReturnCache[audioAPIs][allowEmulation]) !== \"undefined\" &amp;&amp; CB_AudioDetector._getPreferredAPIReturnCache[audioAPIs][allowEmulation] !== null) { return CB_AudioDetector._getPreferredAPIReturnCache[audioAPIs][allowEmulation]; } else if (CB_AudioDetector._getPreferredAPIReturnCache[audioAPIs][allowEmulation] === null) { return returnOnEmpty; } } else { CB_AudioDetector._getPreferredAPIReturnCache[audioAPIs] = {}; } var preferredAPI = null; if (audioAPIs.length &gt; 0) { preferredAPI = audioAPIs[0]; } //Stores the result in the cache for the next time: CB_AudioDetector._getPreferredAPIReturnCache[audioAPIs][allowEmulation] = preferredAPI; if (preferredAPI === null) { preferredAPI = returnOnEmpty; } return preferredAPI; } CB_AudioDetector._getSupportedAPIsReturnCache = {}; /** * Calculates and returns an array with the audio APIs supported (from an array if it is given) for the current client, if any. * @function * @param {array} [audioAPIs=CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS] - An array of strings with the audio APIs that we want to check. All existing ones are defined in {@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS}. For example: \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @param {boolean} [allowEmulation=!!CB_Configuration[CB_BASE_NAME].CB_AudioDetector_allowEmulation_DEFAULT] - If set to true, it will also detect as supported emulated audio APIs (as \"WAAPI\" using [waapisim.js]{@link https://github.com/g200kg/WAAPISim} instead of supported natively). * @returns {array} Returns an array with the audio APIs supported (from an array if it is given) for the current client, if any. If no audio API is supported, an empty array will be returned. */ CB_AudioDetector.getSupportedAPIs = function(audioAPIs, allowEmulation) { //If not given any APIs, uses the default ones with the default order: if (typeof(audioAPIs) === \"undefined\" || audioAPIs === null || !CB_isArray(audioAPIs)) { audioAPIs = CB_Configuration[CB_BASE_NAME].CB_AudioFileCache_PREFERRED_AUDIO_APIS; } if (allowEmulation !== true &amp;&amp; allowEmulation !== false) { allowEmulation = !!CB_Configuration[CB_BASE_NAME].CB_AudioDetector_allowEmulation_DEFAULT; } //If it is not the first time, returns the same as the first time (from the cache): if (typeof(CB_AudioDetector._getSupportedAPIsReturnCache[audioAPIs]) !== \"undefined\" &amp;&amp; CB_AudioDetector._getSupportedAPIsReturnCache[audioAPIs] !== null) { if (typeof(CB_AudioDetector._getSupportedAPIsReturnCache[audioAPIs][allowEmulation]) !== \"undefined\" &amp;&amp; CB_AudioDetector._getSupportedAPIsReturnCache[audioAPIs][allowEmulation] !== null) { return CB_AudioDetector._getSupportedAPIsReturnCache[audioAPIs][allowEmulation]; } } else { CB_AudioDetector._getSupportedAPIsReturnCache[audioAPIs] = {}; } var supportedAudioAPIs = []; var audioAPIsLength = audioAPIs.length; for (var x = 0; x &lt; audioAPIsLength; x++) { if (CB_AudioDetector.isAPISupported(audioAPIs[x], allowEmulation)) { if (CB_indexOf(supportedAudioAPIs, audioAPIs[x]) === -1) { supportedAudioAPIs[supportedAudioAPIs.length] = audioAPIs[x]; } } } //Stores the result in the cache for the next time: CB_AudioDetector._getSupportedAPIsReturnCache[audioAPIs][allowEmulation] = supportedAudioAPIs; return supportedAudioAPIs; } CB_AudioDetector._isAPISupportedReturnCache = {}; /** * Tells whether a given audio API is supported or not by the current client. * @function * @param {string} audioAPI - The audio API that we want to check. All existing ones are defined in {@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS}. For example: \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @param {boolean} [allowEmulation=!!CB_Configuration[CB_BASE_NAME].CB_AudioDetector_allowEmulation_DEFAULT] - If set to true, it will detect as supported also emulated audio APIs (as \"WAAPI\" using [waapisim.js]{@link https://github.com/g200kg/WAAPISim} instead of supported natively). * @returns {boolean} Returns whether the given audio API is supported or not. * @todo Have into account allowEmulation and detect whether emulation is being used if so (for example, detect whether [waapisim.js]{@link https://github.com/g200kg/WAAPISim} is being used). */ CB_AudioDetector.isAPISupported = function(audioAPI, allowEmulation) { audioAPI = CB_trim(audioAPI).toUpperCase(); if (allowEmulation !== true &amp;&amp; allowEmulation !== false) { allowEmulation = !!CB_Configuration[CB_BASE_NAME].CB_AudioDetector_allowEmulation_DEFAULT; } //If it is not the first time, returns the same as the first time (from the cache): if (typeof(CB_AudioDetector._isAPISupportedReturnCache[audioAPI]) !== \"undefined\" &amp;&amp; CB_AudioDetector._isAPISupportedReturnCache[audioAPI] !== null) { if (typeof(CB_AudioDetector._isAPISupportedReturnCache[audioAPI][allowEmulation]) !== \"undefined\" &amp;&amp; CB_AudioDetector._isAPISupportedReturnCache[audioAPI][allowEmulation] !== null) { return CB_AudioDetector._isAPISupportedReturnCache[audioAPI][allowEmulation]; } } else { CB_AudioDetector._isAPISupportedReturnCache[audioAPI] = {}; } var isSupported = false; //TODO: Have into account allowEmulation and detect whether emulation is being used if so (for example, detect whether waapisim.js is being used). //Detects whether it is supported or not: if (audioAPI === \"WAAPI\") //Web Audio API. { isSupported = (allowEmulation || !CB_AudioDetector.isWAAPIUsingEmulation()) &amp;&amp; (typeof(window.AudioContext) !== \"undefined\" || typeof(window.webkitAudioContext) !== \"undefined\"); } else if (audioAPI === \"ACMP\") //Apache Cordova Media Plugin. { isSupported = (typeof(Media) !== \"undefined\"); } else if (audioAPI === \"AAPI\") //Audio API. { isSupported = (typeof(window.Audio) !== \"undefined\"); } else if (audioAPI === \"SM2\") //SoundManager 2. { //SM2 needs either Audio API or Flash: isSupported = CB_soundManager2Supported &amp;&amp; (CB_AudioDetector.isAPISupported(\"AAPI\", false) || CB_AudioDetector.isSM2UsingFlash() &amp;&amp; CB_Client.supportsFlash()); } //Stores the result in the cache for the next time: CB_AudioDetector._isAPISupportedReturnCache[audioAPI][allowEmulation] = isSupported; return isSupported; } /** * Tells whether \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}) is using emulation (through [WAAPISim]{@link https://github.com/g200kg/WAAPISim}) or not. * @function * @returns {boolean} Returns whether \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}) is using emulation (through [WAAPISim]{@link https://github.com/g200kg/WAAPISim}) or not. */ CB_AudioDetector.isWAAPIUsingEmulation = function() { return CB_Configuration[CB_BASE_NAME].WAAPISIM_LOAD; } /** * Tells whether [SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/} is using [Adobe Flash (formerly Macromedia Flash)]{@link https://en.wikipedia.org/wiki/Adobe_Flash_Player} to emulate sound or not. * @function * @returns {boolean} Returns whether [SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/} is using [Adobe Flash (formerly Macromedia Flash)]{@link https://en.wikipedia.org/wiki/Adobe_Flash_Player} to emulate sound or not. */ CB_AudioDetector.isSM2UsingFlash = function() { return (typeof(soundManager) !== \"undefined\" &amp;&amp; soundManager !== null &amp;&amp; typeof(soundManager.html5) !== \"undefined\" &amp;&amp; soundManager.html5 !== null &amp;&amp; soundManager.html5.usingFlash); } } //End of the static class CB_AudioDetector. × Search results Close "},"CrossBase_audiovisual_audio_CB_AudioFile.js.html":{"id":"CrossBase_audiovisual_audio_CB_AudioFile.js.html","title":"Source: CrossBase/audiovisual/audio/CB_AudioFile.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/audiovisual/audio/CB_AudioFile.js /** * @file Audio files management, including abstraction for different audio APIs. Possible audio APIs are \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). Contains the {@link CB_AudioFile} class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.) if the \"autoPlay\" option is set to true, as some clients may need this at least the first time in order to be able to play the audio. * @class * @classdesc Class to manage an audio file. Internally, it uses one audio API object which belongs to the audio API being used (when the audio API is changed, it keeps the old audio API objects just in case they are needed in the future when the audio API is changed again). Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @param {string} filePath - The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @param {string} [audioId='CB_AudioFile_' + CB_AudioFile._idUnique++] - Desired identifier for the audio object (can be a different element depending on the audio API used). If not provided, an automatic unique ID will be calculated. Note that it is not case sensitive and it should be unique for each object. * @param {CB_AudioFile.OPTIONS} [options={@link CB_AudioFile#DEFAULT_OPTIONS}] - Object with the desired options. * @param {string} [audioAPI=CB_AudioDetector.getPreferredAPI(undefined, false, null) || CB_AudioDetector.getPreferredAPI(undefined, true, null)] - The desired audio API to be used. If not provided, it will try to calculate the best one for the current client by calling the {@link CB_AudioDetector.getPreferredAPI} function internally. Audio API support will depend on the current client being used. All possible ones are defined in {@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS}. For example: \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the {@link CB_AudioFile} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile} object itself. * @returns {CB_AudioFile} Returns a new {@link CB_AudioFile} object. * @todo Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). Note that the \"id\" is not case sensitive and it should be unique for each object. * @todo Send the {@link CB_AudioFile} object itself as a parameter when calling both \"callbackOk\" and \"callbackError\". * @todo Think about allowing to define 'useXHR' and 'useCache' options (used by {@link CB_AudioFile_API.WAAPI} objects). * @todo Method getCopy and static method filterProperties (similar to the ones from {@link CB_GraphicSprites} and {@link CB_GraphicSpritesScene}). */ var CB_AudioFile = function(filePath, audioId, options, audioAPI, callbackOk, callbackError) { //Creates an instance of this object and returns it in the case that it is being called from an unexpected context: if (this === window || !(this instanceof CB_AudioFile)) { return new CB_AudioFile(filePath, audioId, options, audioAPI, callbackOk, callbackError); } //Constants: /** * Keeps the default volume. If the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT} property is true, this will keep the result of calling the {@link CB_Speaker.getVolume} function. Otherwise, it will use the value of the {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME} variable. * @constant * @type {number} * @default CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME */ CB_AudioFile.prototype.DEFAULT_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration[CB_BASE_NAME].CB_Speaker_DEFAULT_VOLUME; /** * Keeps the default options when an object is created. Format: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. * @constant * @type {CB_AudioFile.OPTIONS} * @default { autoLoad: true, autoPlay: false, loop: false, volume: [CB_AudioFile.prototype.DEFAULT_VOLUME]{@link CB_AudioFile#DEFAULT_VOLUME} } */ CB_AudioFile.prototype.DEFAULT_OPTIONS = { autoLoad: true, autoPlay: false, loop: false, volume: CB_AudioFile.prototype.DEFAULT_VOLUME }; //Properties and variables: /** * Defines whether the file loops by default when the audio is played or not. Its value will be modified automatically whenever the {@link CB_AudioFile#play} method is called, getting the value from the \"loop\" parameter (but only if contains a boolean). * @var * @readonly * @type {boolean} * @default [CB_AudioFile.prototype.DEFAULT_OPTIONS]{@link CB_AudioFile#DEFAULT_OPTIONS}.loop */ this.loop = CB_AudioFile.prototype.DEFAULT_OPTIONS.loop; /** * Stores the volume of this audio. Accepted values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is false or otherwise MAX_VOLUME is the returning value of the {@link CB_Speaker.getVolume} function. * @var * @readonly * @type {number} * @default [CB_AudioFile.prototype.DEFAULT_OPTIONS]{@link CB_AudioFile#DEFAULT_OPTIONS}.volume */ this.volume = CB_AudioFile.prototype.DEFAULT_OPTIONS.volume; /** * Stores the identifier for the audio file. * @var * @readonly * @type {string} * @default 'CB_AudioFile_' + CB_AudioFile._idUnique++ */ this.id = \"\"; /** * Stores the path of the audio file or the data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @var * @readonly * @type {string} * @default */ this.filePath = \"\"; /** * Defines the Audio API used for this audio file. Audio API support will depend on the current client being used. All possible ones are defined in {@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS}. For example: \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @var * @readonly * @type {string} * @default */ this.audioAPI = null; this._onStopFunction = null; //Function to call when the audio stops. //Fake AudioFile[x] object: var that = this; CB_AudioFile._audioFileObject_prototype = CB_AudioFile._audioFileObject_prototype || { usingPrototype : true, status : CB_AudioFile.UNLOADED, paused : false, stopped : true, destructor : function() {}, getDuration : function() { return 0; }, checkPlaying : function(callbackOk, callbackError) { if (typeof(callbackError) === \"function\") { callbackError.call(that, \"audioFileObject is not loaded (using CB_AudioFile._audioFileObject_prototype)\"); } return false; }, play : function() {}, resume : function() {}, pause : function() {}, stop : function() {}, volume : this.DEFAULT_OPTIONS.volume, volumeBeforeMute : this.DEFAULT_OPTIONS.volume, setVolume : function(volume) { var MAX_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM ? CB_Speaker.getVolume() : 100; if (volume &gt; MAX_VOLUME) { volume = MAX_VOLUME; } else if (volume &lt; 0) { volume = 0; } this.volume = volume; return volume; }, mute : function() { this.volumeBeforeMute = this.volume; this.volume = 0; return 0; }, unmute : function() { this.volume = this.volumeBeforeMute; return this.volume; }, getCurrentTime : function() { return 0; }, onStop : function() { return false; }, getProgress : function() { return 0; } }; CB_AudioFile._audioFileObject_prototype.volume = CB_AudioFile.prototype.DEFAULT_OPTIONS.volume; //Updates the property because maybe the volume has changed. CB_AudioFile._audioFileObject_prototype.volumeBeforeMute = CB_AudioFile.prototype.DEFAULT_OPTIONS.volume; //Updates the property because maybe the volume has changed. /** * It will store the created audio file objects for the different audio APIs (for optimization purposes, to avoid creating more than one per API). Being each index the name of the audio API (\"WAAPI\", \"AAPI\", \"SM2\" or \"ACMP\"), their value will be an object which can be {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). Recommended for internal usage only. * @var * @type {Object} * @default */ this.audioFileObjects = {}; //It will store the created objects for the different audio APIs (for optimization purposes, to avoid creating more than one per API). /** * It will store the current audio file object for the current audio API. The {@link CB_AudioFile#load} method will set the value of this property only after the audio file object (stored in its value) is loaded properly. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). When no audio API object is being set, it will contain a fake object with same methods and properties (defined in {@link CB_AudioFile._audioFileObject_prototype}). Recommended for internal usage only. * @var * @type {CB_AudioFile_API.WAAPI | CB_AudioFile_API.SM2 | CB_AudioFile_API.ACMP | CB_AudioFile_API.AAPI | Object} * @default */ this.audioFileObject = CB_AudioFile._audioFileObject_prototype; /** * Stores the last audio file object created or reused, for the current API being used. The {@link CB_AudioFile#load} method will set the value of this property before knowing whether the audio file object (stored in its value) will be loaded properly or not. Used by the {@link CB_AudioFile#load} and {@link CB_AudioFile#getProgress} methods. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). When no audio API object is being set, it will contain a fake object with same methods and properties (defined in {@link CB_AudioFile._audioFileObject_prototype}). Recommended for internal usage only. * @var * @type {CB_AudioFile_API.WAAPI | CB_AudioFile_API.SM2 | CB_AudioFile_API.ACMP | CB_AudioFile_API.AAPI | Object} * @default */ this.audioFileObjectLast = CB_AudioFile._audioFileObject_prototype; this._loadingAudioFileObject = false; //Tells when the audio object is being loading. //Variables to keep same parameters when API is changed: this._avoidDelayedPlayLast = null; this._allowedRecursiveDelayLast = null; //this._onPlayStartLast = undefined; this._onLoadErrorLast = null; //Calls the constructor of the object when creates an instance: return this._init(filePath, audioId, options, audioAPI, callbackOk, callbackError); } /** * Object with the options for an audio file. The format is the following one: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. * @memberof CB_AudioFile * @typedef {Object} CB_AudioFile.OPTIONS * @property {boolean} [autoLoad={@link CB_AudioFile#DEFAULT_OPTIONS}.autoLoad] - Value which will be used as the \"autoLoad\" parameter when calling the {@link CB_AudioFile#setAudioAPI} method internally (when the constructor is called). * @property {boolean} [autoPlay={@link CB_AudioFile#DEFAULT_OPTIONS}.autoPlay] - Value which will be used as the \"autoPlay\" parameter when calling the {@link CB_AudioFile#setAudioAPI} method internally (when the constructor is called). * @property {boolean} [loop={@link CB_AudioFile#DEFAULT_OPTIONS}.loop] - Value that will be used for the {@link CB_AudioFile#loop} property. * @property {number} [volume={@link CB_AudioFile#DEFAULT_OPTIONS}.volume] - The desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise) that will be used for the {@link CB_AudioFile#volume} property. */ //Static properties and constants: CB_AudioFile._idUnique = 0; //Counter to make the id unique. /** * Status value for an audio file which is unloaded. Can be used to compare the value returned by the {@link CB_AudioFile#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default 0 */ CB_AudioFile.UNLOADED = 0; /** * Status value for an audio file which is loading. Can be used to compare the value returned by the {@link CB_AudioFile#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFile.LOADING = 1; /** * Status value for an audio file which has been not checked yet. Can be used to compare the value returned by the {@link CB_AudioFile#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFile.UNCHECKED = 2; /** * Status value for an audio file which is being checked currently. Can be used to compare the value returned by the {@link CB_AudioFile#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFile.CHECKING = 3; /** * Status value for an audio file which has been loaded. Can be used to compare the value returned by the {@link CB_AudioFile#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFile.LOADED = 4; /** * Status value for an audio file which failed to be loaded or failed for any other reason. Can be used to compare the value returned by the {@link CB_AudioFile#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFile.FAILED = 5; /** * Status value for an audio file which has been aborted. This will happen when the audio file has been destroyed with the {@link CB_AudioFile#destructor} method. Can be used to compare the value returned by the {@link CB_AudioFile#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFile.ABORTED = 6; //Constructor: CB_AudioFile.prototype._init = function(filePath, audioId, options, audioAPI, callbackOk, callbackError) { //If not given, defines the default parameters: if (typeof(audioId) === \"undefined\" || audioId === null) { audioId = \"CB_AudioFile_\" + CB_AudioFile._idUnique++; } //Uses the file path as default id. if (typeof(options) === \"undefined\" || options === null) { options = this.DEFAULT_OPTIONS; } else { if (typeof(options.loop) === \"undefined\" || options.loop === null) { options.loop = this.DEFAULT_OPTIONS.loop; } if (typeof(options.autoLoad) === \"undefined\" || options.autoLoad === null) { options.autoLoad = this.DEFAULT_OPTIONS.autoLoad; } if (typeof(options.autoPlay) === \"undefined\" || options.autoPlay === null) { options.autoPlay = this.DEFAULT_OPTIONS.autoPlay; } if (typeof(options.volume) === \"undefined\" || options.volume === null) { options.volume = this.DEFAULT_OPTIONS.volume; } } //Sets the audio ID: this.id = CB_trim(audioId).toUpperCase(); //Sets the file path: this.filePath = filePath; //Sets whether it will loop or not: this.loop = options.loop; //Sets the volume: //this.volume = options.volume; this.setVolume(options.volume); //Sets the audio API and proceeds according to the options received: this.setAudioAPI(audioAPI, options.autoLoad, options.autoPlay, callbackOk, callbackError); //Will load the audio too. //Returns the object: return this; } /** * Destroys the audio file object and frees memory. Sets its current status to ABORTED ({@link CB_AudioFile.ABORTED} value). * @function * @param {boolean} [stopSound=false] - If set to true, it will also call the \"stop\" method of the internal audio file object for the current API (stored in the {@link CB_AudioFile#audioFileObject} property). This method has the same parameters as the {@link CB_AudioFile#stop} method. * @param {boolean} [keepStoppedUnaltered=false] - Used internally as the \"keepStoppedUnaltered\" parameter to call the \"stop\" method of the internal audio file object for the current API (stored in the {@link CB_AudioFile#audioFileObject} property). This method has the same parameters as the {@link CB_AudioFile#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. * @param {boolean} [avoidOnStop=false] - Used internally as the \"avoidOnStop\" parameter to call the \"stop\" method of the internal audio file object for the current API (stored in the {@link CB_AudioFile#audioFileObject} property). This method has the same parameters as the {@link CB_AudioFile#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. * @param {boolean} [forceOnStop=false] - Used internally as the \"forceOnStop\" parameter to call the \"stop\" method of the internal audio file object for the current API (stored in the {@link CB_AudioFile#audioFileObject} property). This method has the same parameters as the {@link CB_AudioFile#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. */ CB_AudioFile.prototype.destructor = function(stopSound, keepStoppedUnaltered, avoidOnStop, forceOnStop) { this.audioFileObject.destructor(stopSound, keepStoppedUnaltered, avoidOnStop, forceOnStop); this.audioFileObject = CB_AudioFile._audioFileObject_prototype; this.audioFileObject.status = CB_AudioFile.ABORTED; } /** * Sets the desired audio API. This method will also be called automatically by the constructor. If the \"autoLoad\" parameter is set to true, it will call the {@link CB_AudioFile#load} method internally, changing the audio API on-the-fly, and the audio will try to continue playing if it was playing at the moment of calling this method. Check the {@link CB_AudioFile#load} method documentation for more information. If the \"autoLoad\" parameter is set to true, it is recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. The audio API used will be stored in the {@link CB_AudioFile#audioAPI} property. * @function * @param {string} [audioAPI=CB_AudioDetector.getPreferredAPI(undefined, false, null) || CB_AudioDetector.getPreferredAPI(undefined, true, null)] - The desired audio API to be used. If not provided, it will try to calculate the best one for the current client by calling the {@link CB_AudioDetector.getPreferredAPI} function internally. Audio API support will depend on the current client being used. All possible ones are defined in {@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS}. For example: \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). Used internally as the \"audioAPI\" parameter when calling the {@link CB_AudioFile#load} method internally (only when the \"autoLoad\" parameter is set to true). * @param {string} [autoLoad=true] - If set to false, it will not call the {@link CB_AudioFile#load} method internally and will only set the {@link CB_AudioFile#audioAPI} property (not recommended). * @param {string} [autoPlay=false] - Used internally as the \"autoPlay\" parameter when calling the {@link CB_AudioFile#load} method internally (only when the \"autoLoad\" parameter is set to true). * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the {@link CB_AudioFile} object itself. Used internally as the \"callbackOk\" parameter when calling the {@link CB_AudioFile#load} method internally (only when the \"autoLoad\" parameter is set to true). * @param {function} [callbackError] - Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile} object itself. Used internally as the \"callbackError\" parameter when calling the {@link CB_AudioFile#load} method internally (only when the \"autoLoad\" parameter is set to true). * @param {string} [ignoreOldValues=false] - Used internally as the \"ignoreOldValues\" parameter when calling the {@link CB_AudioFile#load} method internally (only when the \"autoLoad\" parameter is set to true). * @param {string} [filePath={@link CB_AudioFile#filePath}] - Used internally as the \"filePath\" parameter when calling the {@link CB_AudioFile#load} method internally (only when the \"autoLoad\" parameter is set to true). * @param {string} [forceReload=false] - Used internally as the \"forceReload\" parameter when calling the {@link CB_AudioFile#load} method internally (only when the \"autoLoad\" parameter is set to true). * @returns {string} Returns the desired audio API that has been tried to set, in upper case (successfully or not). * @todo Think about using the \"forceReload\" just after the \"callbackError\" to match the parameter order of the \"load\" method of all the audio API objects. */ CB_AudioFile.prototype.setAudioAPI = function(audioAPI, autoLoad, autoPlay, callbackOk, callbackError, ignoreOldValues, filePath, forceReload) { if (typeof(audioAPI) === \"undefined\" || audioAPI === null) //Uses the preferred API as default. { audioAPI = CB_AudioDetector.getPreferredAPI(undefined, false, null) || CB_AudioDetector.getPreferredAPI(undefined, true, null); } audioAPI = CB_trim(audioAPI).toUpperCase(); if (!CB_AudioDetector.APIExists(audioAPI)) { if (typeof(callbackError) === \"function\") { callbackError.call(this, \"Audio API given does not exist (\" + audioAPI + \").\"); } return audioAPI; } if (typeof(autoLoad) === \"undefined\" || autoLoad === null) { autoLoad = true; } //Since AJAX doesn't allow to load local files, if the file is local we can't use WAAPI: //if (CB_isFileLocal(this.filePath)) { if (audioAPI === \"WAAPI\") { audioAPI = \"SM2\"; } } //Uses SM2 instead. //If it is the same audio API as the current one, we don't need to do more: if (this.audioAPI === audioAPI) { if (typeof(callbackOk) === \"function\") { callbackOk.call(this); } return audioAPI; } //First time is undefined, so we accept any first value: if (typeof(this.audioAPI) === \"undefined\") { this.audioAPI = audioAPI; } //We (re)load the audio file if we want to (NOTE: audioAPI will change only if the object is created and loaded successfully): if (autoLoad) { this.load(filePath ? filePath : this.filePath, audioAPI, autoPlay, callbackOk, callbackError, ignoreOldValues, forceReload); } //...otherwise, we just change the audioAPI property: else { this.audioAPI = audioAPI; } return audioAPI; } /** * Loads the desired audio file with the desired options. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. This method will be called automatically if the \"autoLoad\" option was set to true when calling the {@link CB_AudioFile#setAudioAPI} method. The audio API used will be stored in the {@link CB_AudioFile#audioAPI} property. * When this method is called, if the \"status\" property of the audio API object already has the \"LOADED\" status (defined in the {@link CB_AudioFile.LOADED} constant) and the \"forceReload\" parameter is not set to true, it will exit calling the given \"callbackOk\" function (if any) immediately. Otherwise, regardless the status, the status will be set to \"LOADING\" (defined in the {@link CB_AudioFile.LOADING} constant). After it, it will reach the \"UNCHECKED\" (defined in the {@link CB_AudioFile.UNCHECKED} constant). If the \"autoPlay\" parameter is not set to true, this will be the final status (and it will be necessary to call the \"checkPlaying\" method of the audio API object after it). After it and only if the \"autoPlay\" is set to true, as the \"checkPlaying\" method of the audio API object will be called internally, it will have the \"CHECKING\" status (defined in the {@link CB_AudioFile.CHECKING} constant) and finally the \"LOADED\" status (defined in the {@link CB_AudioFile.LOADED} constant) if all goes well. * Although it is not recommended to do so, if this method is called when the audio API object has the \"UNCHECKED\" status (defined in the {@link CB_AudioFile.UNCHECKED} constant), it will call the \"checkPlaying\" method of the audio API object internally. * Internally, it can use the {@link CB_AudioFile#audioFileObjects} property as a cache. * @function * @param {string} [filePath={@link CB_AudioFile#filePath}] - The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @param {string} [audioAPI={@link CB_AudioFile#audioAPI}] - The desired audio API to be used. If not provided, it will try to use the previously-set one (in the {@link CB_AudioFile#audioAPI} property). All possible ones are defined in {@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS}. For example: \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @param {string} [autoPlay=false] - If set to true, it will start playing the audio automatically (by calling the {@link CB_AudioFile#play} method internally) unless the \"ignoreOldValues\" parameter is set to false and the previous audio was playing or paused. If set to true and the \"status\" property of the audio API object reaches to the \"UNCHECKED\" status (defined in the {@link CB_AudioFile.UNCHECKED} constant), it will also call internally the \"checkPlaying\" method of the audio API object before anything. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the {@link CB_AudioFile} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile} object itself. * @param {string} [ignoreOldValues=false] - If set to true, it will ignore the old values of the previous used audio API object. This means that it will neither continue playing if it was playing (changing the audio API on-the-fly) nor keep the paused status if it was paused nor copy its \"loop\" property to the new audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @param {string} [forceReload=false] - Used internally as the \"forceReload\" parameter when calling the \"load\" method of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @returns {CB_AudioFile_API.WAAPI|CB_AudioFile_API.SM2|CB_AudioFile_API.ACMP|CB_AudioFile_API.AAPI|null} Returns the used audio API object or null otherwise. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @todo Think about using the \"forceReload\" just after the \"callbackError\" to match the parameter order of the \"load\" method of all the audio API objects. */ CB_AudioFile.prototype.load = function(filePath, audioAPI, autoPlay, callbackOk, callbackError, ignoreOldValues, forceReload) { //Defines the default parameters: if (typeof(audioAPI) === \"undefined\" || audioAPI === null) { audioAPI = this.audioAPI; //Uses the previously set Audio API as default. //if (typeof(audioAPI) === \"undefined\" || audioAPI === null) { audioAPI = CB_AudioDetector.getPreferredAPI(undefined, false, null) || CB_AudioDetector.getPreferredAPI(undefined, true, null); } //Uses the preferred API as default. } audioAPI = CB_trim(audioAPI).toUpperCase(); filePath = filePath || this.filePath; var that = this; var callbackErrorFunction = function(error) { that._loadingAudioFileObject = false; //The audio object is not being loaded anymore. that.audioFileObjectLast = that.audioFileObject; //If we are using the prototype (no real audio object adopted), and the audio API requested has been set or the audio API was never set (first time), status is failed: if (that.audioFileObject.usingPrototype &amp;&amp; (audioAPI === that.audioAPI || that.audioAPI === null)) //This way, we avoid setting as FAILED if the audio API has not been changed. { that.audioFileObject.status = CB_AudioFile.FAILED; } //Calls the error function (if any): if (typeof(callbackError) === \"function\") { callbackError.call(that, error); } }; //Creates the audio object depending on the API chosen: if (typeof(CB_AudioFile_API) !== \"undefined\" &amp;&amp; typeof(CB_AudioFile_API[audioAPI]) !== \"undefined\") { this._loadingAudioFileObject = true; //The audio object is being loaded. var callbackOkFunction = function() { //If there is an object already: var wasPlaying = false; var wasPaused = false; //If we wanto to play automatically and the status of the new object is unchecked, checks the file and the function will be called when finishes: if (autoPlay &amp;&amp; audioFileObject.status === CB_AudioFile.UNCHECKED &amp;&amp; typeof(audioFileObject.checkPlaying) !== \"undefined\") { audioFileObject.checkPlaying(callbackOkFunction, callbackErrorFunction, false, false, false); return; } //If we do not want to ignore old values and the previous audio file object used was not a prototype (it was a real one): if (!ignoreOldValues &amp;&amp; typeof(that.audioFileObject.usingPrototype) === \"undefined\") { //If the status of the new object is unchecked, checks the file and the function will be called when finishes: if (audioFileObject.status === CB_AudioFile.UNCHECKED &amp;&amp; typeof(audioFileObject.checkPlaying) !== \"undefined\") { audioFileObject.checkPlaying(callbackOkFunction, callbackErrorFunction, false, false, false); return; } //var status = that.getStatus(); var status = that.audioFileObject.status; //audioFileObject.status = LOADED; //If the audio was LOADED: if (status === CB_AudioFile.LOADED) { //Stores the startAt: audioFileObject.lastStartAt = that.audioFileObject.lastStartAt; //Stores the stopAt: audioFileObject.lastStopAt = that.audioFileObject.lastStopAt; //Stores loop: that.loop = audioFileObject.loop = that.audioFileObject.loop; //If the sound is playing, pauses it: if (that.isPlaying()) { //Stops it: that.pause(); wasPlaying = true; } else if (that.audioFileObject.paused) { wasPaused = true; } //Stores the pause time (if any): audioFileObject.pauseTime = that.audioFileObject.pauseTime; //If it was using WAAPI and not now, we need to substract the startTime: /* if (that.audioAPI === \"WAAPI\" &amp;&amp; audioAPI !== \"WAAPI\" &amp;&amp; typeof(that.audioFileObject.startTime) !== \"undefined\" &amp;&amp; that.audioFileObject.startTime !== null &amp;&amp; !isNaN(that.audioFileObject.startTime)) { audioFileObject.pauseTime -= that.audioFileObject.startTime * 1000; } */ } } //If we changed the API (this means the object will have changed too): if (that.audioAPI !== audioAPI) { //Stops and destroys previous object (if any) and declares it as ABORTED: //////that.destructor(true, false, true); //Stops the object (avoiding to fire onStop) and destroys the object (sets status as ABORTED). } //Stores the volume: that.volume = audioFileObject.volume = that.getVolume(); //Stores the new audio object: that.audioFileObject = audioFileObject; //If it was playing, continues playing from the same point: if (!ignoreOldValues &amp;&amp; (wasPlaying || wasPaused)) { that.audioFileObject.stopped = false; that.audioFileObject.paused = true; //that.resume(that.loop); //that.resume(that.loop, that._avoidDelayedPlayLast, that._allowedRecursiveDelayLast, that._onPlayStartLast, that._onLoadErrorLast); that.resume(that.loop, that._avoidDelayedPlayLast, that._allowedRecursiveDelayLast, null, that._onLoadErrorLast); if (wasPaused) { that.pause(); } } //...otherwise, if we wanted to play automatically, we start playing: else if (autoPlay) { that.play(); } //Now the new API can be accepted: that.audioAPI = audioAPI; //Sets the file path: that.filePath = filePath; //Set the desired onStop event (if any): /////////that.onStop(that.onStopFunction, false); that.onStop(that._onStopFunction, false); that._loadingAudioFileObject = false; //The audio object has been loaded already. //Calls the OK function (if any): if (typeof(callbackOk) === \"function\") { callbackOk.call(that); } }; //Creates a new CB_AudioFile[x] object or uses the existing one (if available): var audioFileObject; if (typeof(this.audioFileObjects[audioAPI]) !== \"undefined\" &amp;&amp; this.audioFileObjects[audioAPI] !== null) { //Gets the existing object: audioFileObject = this.audioFileObjects[audioAPI]; //Sets the desired options: ////if (typeof(this.id) === \"undefined\" || this.id === null) { audioFileObject.id = filePath; } //Uses the file path as default id. if (typeof(this.id) === \"undefined\" || this.id === null) { audioFileObject.id = CB_trim(\"CB_AudioFile_\" + CB_AudioFile._idUnique++).toUpperCase(); } //Uses the file path as default id. else { audioFileObject.id = this.id; } audioFileObject.loop = this.loop; //audioFileObject.setVolume(this.volume); //audioFileObject.setVolume(0); //Sets volume to zero to prevent hearing the sound in some web clients when checkPlaying is called. if (CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING) { audioFileObject.mute(); } //Sets volume to zero to prevent hearing the sound in some web clients when checkPlaying is called. //Calls the load method of the object (load method also calls the destructor method): audioFileObject.load(filePath, false, callbackOkFunction, callbackErrorFunction, forceReload); } else { //Creates the new object and stores it (sets volume to zero to prevent hearing the sound in some web clients when checkPlaying is called): //audioFileObject = new CB_AudioFile_API[audioAPI](filePath, this.id, { autoLoad: true, autoPlay: autoPlay, loop: this.loop, volume: this.volume }, callbackOkFunction, callbackErrorFunction); this.DEFAULT_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration[CB_BASE_NAME].CB_Speaker_DEFAULT_VOLUME; audioFileObject = new CB_AudioFile_API[audioAPI](filePath, this.id, { autoLoad: true, autoPlay: false, loop: this.loop, volume: CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING ? 0 : this.DEFAULT_VOLUME }, callbackOkFunction, callbackErrorFunction); this.audioFileObjects[audioAPI] = audioFileObject; } this.audioFileObjectLast = this.audioFileObjects[audioAPI]; return audioFileObject; } else { callbackErrorFunction(\"CB_AudioFile_API['\" + audioAPI + \"'] not found\"); return null; } } /** * Checks whether the audio can be played or not. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Also recommended to use before calling the {@link CB_AudioFile#play} method the first time. Internally, uses the \"checkPlaying\" method of the used audio API object. The checking action will only be performed if the value of the \"status\" property of the used audio API object belongs to the {@link CB_AudioFile.UNCHECKED} or to the {@link CB_AudioFile.CHECKING} value. After checking, if the audio can be played, the \"status\" property of the used audio API object will get the value of {@link CB_AudioFile.LOADED}. Otherwise, if it cannot be played, the \"status\" property of the used audio API object will get the value of {CB_AudioFile.FAILED}. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been checked successfully, being \"this\" the {@link CB_AudioFile} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been checked successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile} object itself. * @param {boolean} [ignoreStatus=false] - If set to false and the audio status is neither \"UNCHECKED\" nor \"CHECKING\", it will fail calling the \"callbackError\" function (if any). If set to true, it will try to perform the checking action regardless the status of the audio. * @param {boolean} [ignoreQueue=false] - If set to false and there is already the maximum number of audio files being checked (defined internally, depending on the audio API), the function will exit and it will call itself automatically again and again until the checking process can be performed (when its queue turn has been reached). This is done for performance purposes. Some audio APIs will ignore this parameter as they do not use checking queues. * @param {boolean} [useCache=false] - If set to true (not recommended) and the same audio file was checked previously, it will not perform the checking process again and it will do the same as the previous call. Some audio APIs will ignore this parameter as they do not use cache. * @returns {boolean} Returns false if the checking could not be performed and failed. If it returns true, it can mean either the checking has been processed successfully or it will fail in the future, so it is recommended to ignore the returning value and use the callback functions instead. */ CB_AudioFile.prototype.checkPlaying = function(callbackOk, callbackError, ignoreStatus, ignoreQueue, useCache) { var that = this; return this.audioFileObject.checkPlaying ( function() { if (typeof(callbackOk) === \"function\") { callbackOk.call(that); } }, //callbackOk. function(error) { if (typeof(callbackError) === \"function\") { callbackError.call(that, error); } }, //callbackError. ignoreStatus, ignoreQueue, useCache ); } /** * Tells the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. Internally, uses the \"getDuration\" method of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @returns {number} Returns the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. */ CB_AudioFile.prototype.getDuration = function() { return this.audioFileObject.getDuration(); } /** * Plays the audio. Internally, uses the \"play\" method of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @param {number} [startAt=0 | {@link CB_AudioFile_API.WAAPI#lastStartAt} | {@link CB_AudioFile_API.SM2#lastStartAt} | {@link CB_AudioFile_API.ACMP#lastStartAt} | {@link CB_AudioFile_API.AAPI#lastStartAt} | stopAt] - Time in milliseconds where we want the audio to start at. If not provided or it is not a valid number, it will use zero (0) as default which belongs to the beginning of the audio. If the value provided is greater than the \"stopAt\" provided, it will use the value set in the \"lastStartAt\" property of the used audio API object (which belongs to the \"startAt\" value the last time that the \"play\" method was called). If, even using the \"lastStartAt\" value is still greather than the \"stopAt\" provided, it will use the same value as the \"stopAt\" which means it will not play and will stop immediately. Used internally as the \"startAt\" parameter to call the \"play\" method of the audio API object. * @param {number} [stopAt={@link CB_AudioFile_API.WAAPI#getDuration}() | {@link CB_AudioFile_API.SM2#getDuration}() | {@link CB_AudioFile_API.ACMP#getDuration}() | {@link CB_AudioFile_API.AAPI#getDuration}()] - Time in milliseconds where we want the audio to stop at. If not provided or it is not a valid number, it will use the returning value of the \"getDuration\" method of the used audio API object (which should belong to the total duration of the audio, if it was calculated correctly). Used internally as the \"stopAt\" parameter to call the \"play\" method of the audio API object. * @param {boolean} [loop={@link CB_AudioFile#loop}] - Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the {@link CB_AudioFile#onStop} method) will not be called. Used internally as the \"loop\" parameter to call the \"play\" method of the audio API object. * @param {boolean} [avoidDelayedPlay=false] - If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the \"stop\" method of the used audio API object will be called immediately. Used internally as the \"avoidDelayedPlay\" parameter to call the \"play\" method of the audio API object. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the \"stop\" method of the used audio API object will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). Used internally as the \"allowedRecursiveDelay\" parameter to call the \"play\" method of the audio API object. * @param {function} [onPlayStart] - Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the {@link CB_AudioFile} object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. Used internally as the \"onPlayStart\" parameter to call the \"play\" method of the audio API object. * @param {function} [onLoadError] - Function to be called if the audio cannot be played successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile} object. Used internally as the \"onLoadError\" parameter to call the \"play\" method of the audio API object. * @param {boolean} [isResume=false] - If set to true (not recommended) and it is a looping audio, the next loop will use the value of the \"lastStartAt\" property of the audio API object as the \"startAt\" parameter when it calls the \"play\" method again automatically (internally). Recommended for internal usage only. Used internally as the \"isResume\" parameter to call the \"play\" method of the audio API object. * @returns {boolean|integer} Returns the returning value of the \"play\" method of the audio API object. It returns false if the duration is 0 (\"startAt\" and \"stopAt\" are the same number), returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). */ CB_AudioFile.prototype.play = function(startAt, stopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, isResume) { if (typeof(loop) === \"undefined\" || loop === null) { loop = this.loop; } //If not set, uses the default (or last one used). else { this.loop = loop; } //...otherwise, stores the new setting given. //Backups the parameters given: this._avoidDelayedPlayLast = avoidDelayedPlay; this._allowedRecursiveDelayLast = allowedRecursiveDelay; //this._onPlayStartLast = onPlayStart; this._onLoadErrorLast = onLoadError; var that = this; //Plays the sound: return this.audioFileObject.play ( startAt, stopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, function(startAt, stopAt, startAtNextLoop, loop, avoidDelayedPlay, allowedRecursiveDelay, startPlayingTime) { if (typeof(onPlayStart) === \"function\") { onPlayStart.call(that, startAt, stopAt, startAtNextLoop, loop, avoidDelayedPlay, allowedRecursiveDelay, startPlayingTime); } }, function (error) { if (typeof(onPlayStart) === \"function\") { onLoadError.call(that, error); } }, isResume, false ); } /** * Resumes the audio (after being paused), starting from the same point it was paused previously. Internally, uses the \"resume\" method of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @param {boolean} [loop={@link CB_AudioFile#loop}] - Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the {@link CB_AudioFile#onStop} method) will not be called. Used internally as the \"loop\" parameter to call the \"resume\" method of the audio API object. * @param {boolean} [avoidDelayedPlay=false] - If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the \"stop\" method of the used audio API object will be called immediately. Used internally as the \"avoidDelayedPlay\" parameter to call the \"resume\" method of the audio API object. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the \"stop\" method of the used audio API object will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). Used internally as the \"allowedRecursiveDelay\" parameter to call the \"resume\" method of the audio API object. * @param {function} [onPlayStart] - Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the {@link CB_AudioFile} object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. Used internally as the \"onPlayStart\" parameter to call the \"resume\" method of the audio API object. * @param {function} [onLoadError] - Function to be called if the audio cannot be played successfully. It will not be called if the audio is not paused or is stopped. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile} object. Used internally as the \"onLoadError\" parameter to call the \"resume\" method of the audio API object. * @returns {boolean|integer} Returns the returning value of the \"resume\" method of the audio API object. It returns false if the audio is not paused or it is stopped, returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). */ //CB_AudioFile.prototype.resume = function(stopAt, loop, /*startAtNextLoop,*/ allowOverlapping) CB_AudioFile.prototype.resume = function(loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError) { /////////if (typeof(loop) === \"undefined\" || loop === null) { loop = this.DEFAULT_OPTIONS.loop; } if (typeof(loop) === \"undefined\" || loop === null) { loop = this.loop; } //If not set, uses the default (or last one used). this.loop = loop; //return this.audioFileObject.resume(stopAt, loop, /*startAtNextLoop,*/ allowOverlapping); //Backups the parameters given: this._avoidDelayedPlayLast = avoidDelayedPlay; this._allowedRecursiveDelayLast = allowedRecursiveDelay; //this._onPlayStartLast = onPlayStart; this._onLoadErrorLast = onLoadError; var that = this; //Resumes the sound: return this.audioFileObject.resume ( loop, avoidDelayedPlay, allowedRecursiveDelay, //////function() { if (typeof(onPlayStart) === \"function\") { onPlayStart.call(that); } }, function(startAt, stopAt, startAtNextLoop, loop, avoidDelayedPlay, allowedRecursiveDelay, startPlayingTime) { if (typeof(onPlayStart) === \"function\") { onPlayStart.call(that, startAt, stopAt, startAtNextLoop, loop, avoidDelayedPlay, allowedRecursiveDelay, startPlayingTime); } }, function (error) { if (typeof(onPlayStart) === \"function\") { onLoadError.call(that, error); } } ); } /** * Pauses the audio when it is being played. Internally, uses the \"pause\" method of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @param {function} [onPause] - Function without parameters to be called when the audio is paused successfully, being \"this\" the {@link CB_AudioFile} object. Used internally as the \"onPause\" parameter (with a wrapper function) to call the \"pause\" method of the audio API object. * @param {boolean} [keepPausedUnaltered=false] - If set to true (not recommended), the \"paused\" property of the audio API object will not be set to true and it will remain with its current value. Used internally as the \"keepPausedUnaltered\" parameter to call the \"pause\" method of the audio API object. * @returns {boolean} Returns the returning value of the \"pause\" method of the audio API object. It returns false if the audio is already paused or it is stopped or if it cannot be paused. Returns true otherwise. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). */ CB_AudioFile.prototype.pause = function(onPause, keepPausedUnaltered) { var that = this; return this.audioFileObject.pause(function() { if (typeof(onPause) === \"function\") { onPause.call(that); } }, keepPausedUnaltered); } /** * Stops the audio. Internally, uses the \"stop\" method of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @param {boolean} [keepStoppedUnaltered=false] - If set to true (not recommended), the \"stopped\" property of the audio API object will not be set to true and it will remain with its current value. Used internally as the \"keepStoppedUnaltered\" parameter to call the \"stop\" method of the audio API object. * @param {boolean} [avoidOnStop=false] - If set to false and there is an \"onStop\" function defined (through the {@link CB_AudioFile#onStop} method), it will be called after stopping the audio (or after trying to do it, at least) but only if either the \"forceOnStop\" parameter is set to true or if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. If set to true, the \"onStop\" function (if any) will not be called at all. Used internally as the \"avoidOnStop\" parameter to call the \"stop\" method of the audio API object. * @param {boolean} [forceOnStop=false] - If it is set to true and the \"avoidOnStop\" parameter is set to false and there is an \"onStop\" function defined (through the {@link CB_AudioFile#onStop} method), it will be called regardless the audio was stopped before or not. If set to false, the \"onStop\" function (if any) will only be called if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. This parameter will be ignored if the \"avoidOnStop\" parameter is set to true. Used internally as the \"forceOnStop\" parameter to call the \"stop\" method of the audio API object. * @returns {boolean} Returns the returning value of the \"stop\" method of the audio API object. It returns false if the stopping action cannot be performed at all (this could happen with the internal audio API has not been loaded properly, for example). Returns true otherwise (this only means that it has been tried to be stopped but it could not be successfully). Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). */ CB_AudioFile.prototype.stop = function(keepStoppedUnaltered, avoidOnStop, forceOnStop) { return this.audioFileObject.stop(keepStoppedUnaltered, avoidOnStop, forceOnStop); } /** * Returns the volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise) that was set before the audio was muted. Internally, uses the \"volumeBeforeMute\" property of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @returns {number} Returns the volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise) that was set before the audio was muted. If the audio was not muted before, it will contain the default volume used in the \"volume\" property of the used audio API object. */ CB_AudioFile.prototype.getVolumeBeforeMute = function() { return this.audioFileObject.volumeBeforeMute; } /** * Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). Internally, uses the \"volume\" property of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). */ CB_AudioFile.prototype.getVolume = function() { this.volume = this.audioFileObject.volume; return this.volume; } /** * Sets the desired volume for the audio file (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). Internally, uses the \"setVolume\" method of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @param {number} [volume={@link CB_Speaker.getVolume()} | {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME}] - Desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). Used internally as the \"volume\" parameter to call the \"setVolume\" method of the audio API object. * @param {boolean} [forceSetVolumeProperty=false] - If set to true (not recommended), it will change the \"volume\" property of the used audio API object even when the volume failed to be changed. Used internally as the \"forceSetVolumeProperty\" parameter to call the \"setVolume\" method of the audio API object. * @param {function} [onSetVolume] - Callback function which will be called if it has been possible to set the volume (or at least it was possible to try it). It will not receive any parameters, being \"this\" the {@link CB_AudioFile} object. Used internally as the \"onSetVolume\" parameter (with a wrapper function) to call the \"setVolume\" method of the audio API object. * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). */ CB_AudioFile.prototype.setVolume = function(volume, forceSetVolumeProperty, onSetVolume) { var that = this; this.volume = this.audioFileObject.setVolume(volume, forceSetVolumeProperty, function() { if (typeof(onSetVolume) === \"function\") { onSetVolume.call(that); } }, false); return this.volume; } /** * Mutes the audio file. Internally, uses the \"mute\" method of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @param {function} [onMute] - Callback function which will be called if it has been possible to mute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the {@link CB_AudioFile} object. Used internally as the \"onMute\" parameter (with a wrapper function) to call the \"mute\" method of the audio API object. * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). If all goes well, the returning value should be zero (0). Note that, even when it returns a zero (0) value, this does not always mean that the mute has been applied successfully. */ CB_AudioFile.prototype.mute = function(onMute) { var that = this; this.volume = this.audioFileObject.mute(function() { if (typeof(onMute) === \"function\") { onMute.call(that); } }); return this.volume; } /** * Restores audio after muting it (unmutes it). Internally, uses the \"unmute\" method of the used audio API object which uses its own \"volumeBeforeMute\" property. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @param {function} [onUnmute] - Callback function which will be called if it has been possible to unmute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the {@link CB_AudioFile} object. Used internally as the \"onUnmute\" parameter (with a wrapper function) to call the \"unmute\" method of the audio API object. * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). */ CB_AudioFile.prototype.unmute = function(onUnmute) { var that = this; this.volume = this.audioFileObject.unmute(function() { if (typeof(onUnmute) === \"function\") { onUnmute.call(that); } }); return this.volume; } /** * Gets the current time (in milliseconds) which belongs to the position where the audio is currently playing or where it has been paused. Note that some audio APIs and clients could give wrong values. Internally, uses the \"getCurrentTime\" method of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @returns {number} Returns the current time (in milliseconds). Note that some audio APIs and clients could give wrong values. */ CB_AudioFile.prototype.getCurrentTime = function() { return this.audioFileObject.getCurrentTime(); } /** * Gets the current status of the audio file. * @function * @param {boolean} [realStatus=false] - If set to true, it will return the \"status\" property of the used audio API object instead of the \"status\" property of the current CB_AudioFile object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @returns {number} Returns the current status of the audio file. It is a number, which should match the value of the CB_AudioFile.UNLOADED (still unloaded), CB_AudioFile.LOADING (loading), CB_AudioFile.UNCHECKED (not checked by calling the \"checkPlaying\" method yet), CB_AudioFile.CHECKING (being checked by the \"checkPlaying\" method), CB_AudioFile.LOADED (loaded), CB_AudioFile.FAILED (failed loading or failed to play or by any other reason) or CB_AudioFile.ABORTED (aborted because it was destroyed with the \"destructor\" method) property. */ CB_AudioFile.prototype.getStatus = function(realStatus) { if (this._loadingAudioFileObject &amp;&amp; !realStatus) { return CB_AudioFile.LOADING; } return this.audioFileObject.status; } /** * Gets the current status of the audio file, as a string. * @function * @param {boolean} [realStatus=false] - If set to true, it will have in mind the \"status\" property of the used audio API object instead of the \"status\" property of the current CB_AudioFile object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @returns {string} Returns the current status of the audio file, as a string. Possible return values are \"UNLOADED\", \"LOADING\", \"UNCHECKED\", \"CHECKING\", \"LOADED\", \"FAILED\", \"ABORTED\" or \"UNKNOWN (UNKNOWN_STATUS)\" (where \"UNKNOWN_STATUS\" will be a value from the \"status\" property not recognized as any possible status). */ CB_AudioFile.prototype.getStatusString = function(realStatus) { var status = this.getStatus(realStatus); var statuses = [ \"UNLOADED\", \"LOADING\", \"UNCHECKED\", \"CHECKING\", \"LOADED\", \"FAILED\", \"ABORTED\" ]; if (typeof(statuses[status]) !== \"undefined\") { return statuses[status]; } else { return \"UNKNOWN (\" + status + \")\"; } } /** * Tells whether the audio file is playing or not. Internally, uses the {@link CB_AudioFile#isStopped} and {@link CB_AudioFile#isPaused} methods. * @function * @returns {boolean} Returns whether the audio file is playing or not. */ CB_AudioFile.prototype.isPlaying = function() { return (!this.isStopped() &amp;&amp; !this.isPaused()); } /** * Tells whether the audio is paused or not. Internally, uses the \"paused\" property of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @returns {boolean} Returns whether the audio is paused or not. */ CB_AudioFile.prototype.isPaused = function() { return this.audioFileObject.paused; } /** * Tells whether the audio file is stopped or not. Internally, uses the \"stopped\" property of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @returns {boolean} Returns whether the audio file is stopped or not. */ CB_AudioFile.prototype.isStopped = function() { return this.audioFileObject.stopped; } /* //Returns the bytes loaded of the file: CB_AudioFile.prototype.getBytesLoaded = function() { return this.audioFileObject.getBytesLoaded(); } //Returns the total bytes of the file: CB_AudioFile.prototype.getBytesTotal = function() { return this.audioFileObject.getBytesTotal(); } */ /** * Sets a function to execute when the audio file stops playing or removes it. Internally, uses the \"onStop\" method of the used audio API object (wrapping the given function). * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. No parameters will be received, being \"this\" the {@link CB_AudioFile} object. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @returns {boolean} Returns whether the event has been set or not (removed). */ CB_AudioFile.prototype.onStop = function(callbackFunction, keepOldFunction) { //If not set, it keeps old function by default: if (typeof(keepOldFunction) === \"undefined\" || keepOldFunction === null) { keepOldFunction = true; } if (typeof(callbackFunction) !== \"function\") { this._onStopFunction = null; return false; } var that = this; //If we don't want to keep the old function: if (!keepOldFunction) { this._onStopFunction = callbackFunction; } //...otherwise if we want to keep the old function, we keep it: else { //Stores old function: var oldFunction = this._onStopFunction; //Stores old function of eventFunctionHolder. this._onStopFunction = function() { if (typeof(oldFunction) === \"function\") { oldFunction.call(that); } callbackFunction.call(that); }; } ////return this.audioFileObject.onStop(callbackFunction, false); //We have already kept the function (if desired). return this.audioFileObject.onStop(function() { if (typeof(that._onStopFunction) === \"function\") { that._onStopFunction.call(that); } }, false); //We have already kept the function (if desired). } /** * Tells the last \"startAt\" parameter value used by the {@link CB_AudioFile#play} or the {@link CB_AudioFile#resume} method (or used by the equivalents methods of the same name from the used audio API object). Internally, uses the \"lastStartAt\" property of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @param {boolean} [numeric=false] - If set to true, it will sanitize the returning value by returning zero instead of undefined, null or any other non-numeric value. * @returns {number|*} Returns the last \"startAt\" value used by the {@link CB_AudioFile#play} or the {@link CB_AudioFile#resume} method (or used by the equivalents methods of the same name from the used audio API object). If we want it to be numeric always, the \"numeric\" parameter should be set to true. */ CB_AudioFile.prototype.getStartAt = function(numeric) { var value = undefined; if (typeof(this.audioFileObject.lastStartAt) !== \"undefined\") { value = this.audioFileObject.lastStartAt; } if (numeric &amp;&amp; (typeof(value) === \"undefined\" || value === null || isNaN(value))) { value = 0; } return value; } /** * Tells the last \"stopAt\" parameter value used by the {@link CB_AudioFile#play} or the {@link CB_AudioFile#resume} method (or used by the equivalents methods of the same name from the used audio API object). Internally, uses the \"lastStopAt\" property of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @param {boolean} [numeric=false] - If set to true, it will sanitize the returning value by returning zero instead of undefined, null or any other non-numeric value. * @returns {number|*} Returns the last \"stopAt\" value used by the {@link CB_AudioFile#play} or the {@link CB_AudioFile#resume} method (or used by the equivalents methods of the same name from the used audio API object). If we want it to be numeric always, the \"numeric\" parameter should be set to true. */ CB_AudioFile.prototype.getStopAt = function(numeric) { var value = undefined; if (typeof(this.audioFileObject.lastStopAt) !== \"undefined\") { value = this.audioFileObject.lastStopAt; } if (numeric &amp;&amp; (typeof(value) === \"undefined\" || value === null || isNaN(value))) { value = 0; } return value; } /** * Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Internally, uses the \"getProgress\" method of the used audio API object. Possible internal audio API objects are {@link CB_AudioFile_API.WAAPI} object for \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), {@link CB_AudioFile_API.SM2} object for \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), {@link CB_AudioFile_API.ACMP} object for \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or {@link CB_AudioFile_API.AAPI} object for \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @function * @returns {number} Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. */ CB_AudioFile.prototype.getProgress = function() { return this.audioFileObjectLast.getProgress(); } × Search results Close "},"CrossBase_audiovisual_audio_CB_AudioFile_API_AAPI.js.html":{"id":"CrossBase_audiovisual_audio_CB_AudioFile_API_AAPI.js.html","title":"Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js /** * @file Audio files management using \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). Contains the {@link CB_AudioFile_API.AAPI} class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ //We need a limit to prevent Firefox error (\"Media resource [URI] could not be decoded\") since many calls to play() method would fail: if (typeof(CB_AudioFile_API_AAPI_SM2_beingLoading) === \"undefined\") { var CB_AudioFile_API_AAPI_SM2_beingLoading = 0; } //Counts how many objects are loading. if (typeof(CB_AudioFile_API_AAPI_SM2_maximumLoading) === \"undefined\") { var CB_AudioFile_API_AAPI_SM2_maximumLoading = 5; } //Maximum of objects that can be loading at the same time. if (typeof(CB_AudioFile_API_AAPI_SM2_beingChecking) === \"undefined\") { var CB_AudioFile_API_AAPI_SM2_beingChecking = 0; } //Counts how many objects are loading. if (typeof(CB_AudioFile_API_AAPI_SM2_maximumChecking) === \"undefined\") { var CB_AudioFile_API_AAPI_SM2_maximumChecking = CB_AudioFile_API_AAPI_SM2_maximumLoading; } //Maximum of objects that can be loading at the same time. //Class to manage an audio file with AAPI (Audio API): if (typeof(CB_AudioFile_API) === \"undefined\") { var CB_AudioFile_API = {}; } /** * The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.) if the \"autoPlay\" option is set to true, as some web clients may need this at least the first time in order to be able to play the audio. * @class CB_AudioFile_API.AAPI * @memberof! &lt;global&gt; * @classdesc Class to manage an audio file using \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). Used by the {@link CB_AudioFile} class internally and it shares most of its properties and methods. Recommended for internal usage only. * @param {string} filePath - The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @param {string} [audioId='CB_AUDIOFILE_AAPI_' + CB_AudioFile_API.AAPI._idUnique++] - Desired identifier for the audio object. If not provided, an automatic unique ID will be calculated. Note that it is not case sensitive and it should be unique for each object. * @param {CB_AudioFile_API.AAPI.OPTIONS} [options=CB_AudioFile_API.AAPI#DEFAULT_OPTIONS] - Object with the desired options. * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the {@link CB_AudioFile_API.AAPI} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if could be determined), being \"this\" the {@link CB_AudioFile_API.AAPI} object itself. * @returns {CB_AudioFile_API.AAPI} Returns a new {@link CB_AudioFile_API.AAPI} object. * @todo Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). Note that the \"id\" is not case sensitive and it should be unique for each object. * @todo Method getCopy and static method filterProperties (similar to the ones from {@link CB_GraphicSprites} and {@link CB_GraphicSpritesScene}). */ CB_AudioFile_API[\"AAPI\"] = function(filePath, audioId, options, callbackOk, callbackError) { //Creates an instance of this object and returns it in the case that it is being called from an unexpected context: if (this === window || !(this instanceof CB_AudioFile_API[\"AAPI\"])) { return new CB_AudioFile_API[\"AAPI\"](filePath, audioId, options, callbackOk, callbackError); } //Constants: /** * Keeps the default volume. If the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT} property is true, this will keep the result of calling the {@link CB_Speaker.getVolume} function. Otherwise, it will use the value of the {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME} variable. * @constant CB_AudioFile_API.AAPI#DEFAULT_VOLUME * @type {number} * @default CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME */ CB_AudioFile_API[\"AAPI\"].prototype.DEFAULT_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration[CB_BASE_NAME].CB_Speaker_DEFAULT_VOLUME; /** * Keeps the default options when an object is created. Format: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. * @constant CB_AudioFile_API.AAPI#DEFAULT_OPTIONS * @type {CB_AudioFile_API.AAPI.OPTIONS} * @default { autoLoad: true, autoPlay: false, loop: false, volume: [CB_AudioFile_API.AAPI.prototype.DEFAULT_VOLUME]{@link CB_AudioFile_API.AAPI#DEFAULT_VOLUME} } */ CB_AudioFile_API[\"AAPI\"].prototype.DEFAULT_OPTIONS = { autoLoad: true, autoPlay: false, loop: false, volume: CB_AudioFile_API[\"AAPI\"].prototype.DEFAULT_VOLUME }; //Properties and variables: /** * Tells whether the file is unloaded ({@link CB_AudioFile.UNLOADED}), loading ({@link CB_AudioFile.LOADING}), unchecked ({@link CB_AudioFile.UNCHECKED}), checking ({@link CB_AudioFile.CHECKING}), loaded ({@link CB_AudioFile.LOADED}), failed ({@link CB_AudioFile.FAILED}) or aborted ({@link CB_AudioFile.ABORTED}). * @var CB_AudioFile_API.AAPI#status * @readonly * @type {integer} * @default {@link CB_AudioFile.UNLOADED} */ this.status = CB_AudioFile.UNLOADED; /** * Defines whether the file loops by default when the audio is played or not. Its value will be modified automatically whenever the {@link CB_AudioFile_API.AAPI#play} method is called, getting the value from the \"loop\" parameter (but only if contains a boolean). * @var CB_AudioFile_API.AAPI#loop * @readonly * @type {boolean} * @default [CB_AudioFile_API.AAPI.prototype.DEFAULT_OPTIONS]{@link CB_AudioFile_API.AAPI#DEFAULT_OPTIONS}.loop */ this.loop = CB_AudioFile_API[\"AAPI\"].prototype.DEFAULT_OPTIONS.loop; /** * Stores the volume of this audio. Accepted values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is false or otherwise MAX_VOLUME is the returning value of the {@link CB_Speaker.getVolume} function. * @var CB_AudioFile_API.AAPI#volume * @readonly * @type {number} * @default [CB_AudioFile_API.AAPI.prototype.DEFAULT_OPTIONS]{@link CB_AudioFile_API.AAPI#DEFAULT_OPTIONS}.volume */ this.volume = CB_AudioFile_API[\"AAPI\"].prototype.DEFAULT_OPTIONS.volume; /** * Stores the volume of this audio before it was muted (to restore it later). Valid values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is false or otherwise MAX_VOLUME is the returning value of the {@link CB_Speaker.getVolume} function. * @var CB_AudioFile_API.AAPI#volumeBeforeMute * @readonly * @type {number} * @default {@link CB_AudioFile_API.AAPI#volume} */ this.volumeBeforeMute = this.volume; /** * Stores the identifier for the audio file. * @var CB_AudioFile_API.AAPI#id * @readonly * @type {string} * @default 'CB_AUDIOFILE_AAPI_' + CB_AudioFile_API.AAPI._idUnique++ */ this.id = \"\"; /** * Stores the path of the audio file or the data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @var CB_AudioFile_API.AAPI#filePath * @readonly * @type {string} * @default */ this.filePath = \"\"; /** * Tells whether the audio is paused or not. * @var CB_AudioFile_API.AAPI#paused * @readonly * @type {boolean} * @default false */ this.paused = false; /** * Stores the time (in milliseconds) when the audio has been paused. * @var CB_AudioFile_API.AAPI#pauseTime * @readonly * @type {number} * @default */ this.pauseTime = 0; /** * Tells whether the audio is stopped or not. * @var CB_AudioFile_API.AAPI#stopped * @readonly * @type {boolean} * @default true */ this.stopped = true; /** * Function to call when the audio stops. * @var CB_AudioFile_API.AAPI#onStopFunction * @readonly * @type {function} * @default */ this.onStopFunction = null; /** * Stores the last \"startAt\" parameter value used by the {@link CB_AudioFile_API.AAPI#play} or the {@link CB_AudioFile_API.AAPI#resume} method. * @var CB_AudioFile_API.AAPI#lastStartAt * @readonly * @type {number} * @default */ this.lastStartAt = null; /** * Stores the last \"stopAt\" parameter value used by the {@link CB_AudioFile_API.AAPI#play} or the {@link CB_AudioFile_API.AAPI#resume} method. * @var CB_AudioFile_API.AAPI#lastStopAt * @readonly * @type {number} * @default */ this.lastStopAt = null; /** * Stores the [HTMLAudioElement]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement} object of the audio, used by the \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @var CB_AudioFile_API.AAPI#audioObject * @readonly * @type {HTMLAudioElement} * @default */ this.audioObject = null; //Internal properties: this._timeoutWhenStop = null; //Keeps the timeout that is executed when the audio has finished playing (to either stop or loop). this._id_internal = null; //Internal id. this._recursiveCallTimeout = null; this._onReadyTimeout = null; this._stopAfterPlayingTimeout = null; this._onCanplaythroughHandlerLast = null; this._onErrorHandlerLast = null; this._loadingCounterIncreased = false; this._checkPlayingTimeout = null; this._checkPlayingFinishingTimeout = null; this._recursiveCallCheckingTimeout = null; this._checkingCounterIncreased = false; this._onPlayingErrorFunctionExecuted = false; this._lastDuration = null; //Calls the constructor of the object when creates an instance: return this._init(filePath, audioId, options, callbackOk, callbackError); } /** * Object with the options for an audio file. The format is the following one: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. * @memberof CB_AudioFile_API.AAPI * @typedef {Object} CB_AudioFile_API.AAPI.OPTIONS * @property {boolean} [autoLoad={@link CB_AudioFile_API.AAPI#DEFAULT_OPTIONS}.autoLoad] - If set to false, it will not call the {@link CB_AudioFile_API.AAPI#load} method internally when the constructor is called (not recommended). * @property {boolean} [autoPlay={@link CB_AudioFile_API.AAPI#DEFAULT_OPTIONS}.autoPlay] - Value which will be used as the \"autoPlay\" parameter when calling the {@link CB_AudioFile_API.AAPI#load} method internally, only when the \"autoLoad\" is set to true (when the constructor is called). * @property {boolean} [loop={@link CB_AudioFile_API.AAPI#DEFAULT_OPTIONS}.loop] - Value that will be used for the {@link CB_AudioFile_API.AAPI#loop} property. * @property {number} [volume={@link CB_AudioFile_API.AAPI#DEFAULT_OPTIONS}.volume] - The desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise) that will be used for the {@link CB_AudioFile_API.AAPI#volume} property. */ //Static properties: CB_AudioFile_API[\"AAPI\"]._counter = 0; //Internal counter. CB_AudioFile_API[\"AAPI\"]._idUnique = 0; //Counter to make the id unique. //Constructor: CB_AudioFile_API[\"AAPI\"].prototype._init = function(filePath, audioId, options, callbackOk, callbackError) { //If not given, defines the default parameters: if (typeof(audioId) === \"undefined\" || audioId === null) { audioId = \"CB_AUDIOFILE_AAPI_\" + CB_AudioFile_API[\"AAPI\"]._idUnique++; } //Uses the file path as default id. if (typeof(options) === \"undefined\" || options === null) { options = this.DEFAULT_OPTIONS; } else { if (typeof(options.loop) === \"undefined\" || options.loop === null) { options.loop = this.DEFAULT_OPTIONS.loop; } if (typeof(options.autoLoad) === \"undefined\" || options.autoLoad === null) { options.autoLoad = this.DEFAULT_OPTIONS.autoLoad; } if (typeof(options.autoPlay) === \"undefined\" || options.autoPlay === null) { options.autoPlay = this.DEFAULT_OPTIONS.autoPlay; } if (typeof(options.volume) === \"undefined\" || options.volume === null) { options.volume = this.DEFAULT_OPTIONS.volume; } } //Sets the audio ID: this.id = CB_trim(audioId).toUpperCase(); //Sets the internal id: if (typeof(this._id_internal) === \"undefined\" || this._id_internal === null) { this._id_internal = CB_AudioFile_API[\"AAPI\"]._counter++; } //Sets the file path: this.filePath = filePath; //Proceeds according to the options sent: this.loop = options.loop; this.volume = options.volume; this.volumeBeforeMute = this.volume; if (options.autoLoad) { var that = this; setTimeout ( function() { that.load(that.filePath, options.autoPlay, callbackOk, callbackError); }, 10 ); } //Returns the object: return this; } /** * Destroys the audio file object and frees memory. Sets its current {@link CB_AudioFile_API.AAPI#status} property to ABORTED ({@link CB_AudioFile.ABORTED} value). * @function CB_AudioFile_API.AAPI#destructor * @param {boolean} [stopSound=false] - If set to true, it will also call the {@link CB_AudioFile_API.AAPI#stop} method. * @param {boolean} [keepStoppedUnaltered=false] - Used internally as the \"keepStoppedUnaltered\" parameter to call the {@link CB_AudioFile_API.AAPI#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. * @param {boolean} [avoidOnStop=false] - Used internally as the \"avoidOnStop\" parameter to call the {@link CB_AudioFile_API.AAPI#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. * @param {boolean} [forceOnStop=false] - Used internally as the \"forceOnStop\" parameter to call the {@link CB_AudioFile_API.AAPI#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. */ CB_AudioFile_API[\"AAPI\"].prototype.destructor = function(stopSound, keepStoppedUnaltered, avoidOnStop, forceOnStop) { this._lastDuration = null; //if (typeof(this.audioObject) === \"undefined\" || this.audioObject === null) { this.status = CB_AudioFile.ABORTED; return; } if (stopSound) { this.stop(keepStoppedUnaltered, avoidOnStop, forceOnStop); } //this.onerror = this.oncanplaythrough = null; //this.audioObject.src = \"\"; //this.audioObject.load(); CB_Elements.remove(this.audioObject); //if (this.status === CB_AudioFile.LOADING) if (this._loadingCounterIncreased) { this._loadingCounterIncreased = false; CB_AudioFile_API_AAPI_SM2_beingLoading--; //Decreases the counter of the objects which are loading. if (CB_AudioFile_API_AAPI_SM2_beingLoading &lt; 0) { CB_AudioFile_API_AAPI_SM2_beingLoading = 0; } } if (this._checkingCounterIncreased) { this._checkingCounterIncreased = false; CB_AudioFile_API_AAPI_SM2_beingChecking--; //Decreases the counter of the objects which are checking. if (CB_AudioFile_API_AAPI_SM2_beingChecking &lt; 0) { CB_AudioFile_API_AAPI_SM2_beingChecking = 0; } } this.status = CB_AudioFile.ABORTED; } /** * Loads the desired audio file with the desired options. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. This method will be called automatically by the constructor if the \"autoLoad\" option was set to true in its given \"options\" parameter. * When this method is called, if the {@link CB_AudioFile_API.AAPI#status} property already has the \"LOADED\" status (defined in the {@link CB_AudioFile.LOADED} constant) and the \"forceReload\" parameter is not set to true, it will exit calling the given \"callbackOk\" function (if any) immediately. Otherwise, regardless the status, the status will be set to \"LOADING\" (defined in the {@link CB_AudioFile.LOADING} constant). After it, it will reach the \"UNCHECKED\" (defined in the {@link CB_AudioFile.UNCHECKED} constant). If the \"autoPlay\" parameter is not set to true, this will be the final status (and it will be necessary to call the {@link CB_AudioFile_API.AAPI#checkPlaying} method after it). After it and only if the \"autoPlay\" is set to true, as the {@link CB_AudioFile_API.AAPI#checkPlaying} method will be called internally, it will have the \"CHECKING\" status (defined in the {@link CB_AudioFile.CHECKING} constant) and finally the \"LOADED\" status (defined in the {@link CB_AudioFile.LOADED} constant) if all goes well. * @function CB_AudioFile_API.AAPI#load * @param {string} [filePath={@link CB_AudioFile_API.AAPI#filePath}] - The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @param {string} [autoPlay=false] - If set to true, it will start playing the audio automatically (by calling the {@link CB_AudioFile_API.AAPI#play} method internally). If set to true and the {@link CB_AudioFile_API.AAPI#status} property reaches to the \"UNCHECKED\" status (defined in the {@link CB_AudioFile.UNCHECKED} constant), it will also call internally the {@link CB_AudioFile_API.AAPI#checkPlaying} method. * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the {@link CB_AudioFile_API.AAPI} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.AAPI} object itself. * @param {boolean} [forceReload=false] - If set to false, the \"filePath\" has not been changed from the previously used and the {@link CB_AudioFile_API.AAPI#status} property belongs to the \"LOADED\" status (defined in the {@link CB_AudioFile.LOADED} constant), it will exit the method without loading the audio file again (calling the \"callbackOk\" function, if any). * @returns {CB_AudioFile_API.AAPI|null} Returns the audio API object (if it was possible to create) or null otherwise. */ CB_AudioFile_API[\"AAPI\"].prototype.load = function(filePath, autoPlay, callbackOk, callbackError, forceReload) { clearTimeout(this._stopAfterPlayingTimeout); clearTimeout(this._checkPlayingTimeout); clearTimeout(this._onReadyTimeout); clearTimeout(this._recursiveCallTimeout); clearTimeout(this._checkPlayingFinishingTimeout); filePath = filePath || this.filePath; //If the status is LOADED and the file path give is the same as the current one, just exits: if (!forceReload &amp;&amp; this.status === CB_AudioFile.LOADED &amp;&amp; this.filePath === filePath) { if (typeof(callbackOk) === \"function\") { callbackOk.call(this); } return this; } this.status = CB_AudioFile.LOADING; //The file is loading. var that = this; //If the maximum of objects loading is reached, calls the function again after some time and exits: //if (CB_AudioFile_API_AAPI_SM2_beingLoading &gt;= CB_AudioFile_API_AAPI_SM2_maximumLoading) if (autoPlay &amp;&amp; CB_AudioFile_API_AAPI_SM2_beingLoading &gt;= CB_AudioFile_API_AAPI_SM2_maximumLoading) { this._recursiveCallTimeout = setTimeout(function() { that.load(filePath, autoPlay, callbackOk, callbackError, forceReload); }, 10); return this; } //Destroys previous object (if any): this.destructor(true, false, true); //Also stops the sound (if any) and prevents firing onStop. this.status = CB_AudioFile.LOADING; //The file is loading. if (!this._loadingCounterIncreased) { this._loadingCounterIncreased = true; CB_AudioFile_API_AAPI_SM2_beingLoading++; //Increases the counter of the objects which are loading (destructor has decreased 1). } this.filePath = filePath; var callbackFunctionError = function(error, ignoreFailed) { //Prevents the execution of the function after the oncanplaythrough event has fired: ////if (onReadyFunctionExecuted) { return; } //Prevents the execution of the function if the object has been declared as LOADED: if (that.status === CB_AudioFile.LOADED || that.status === CB_AudioFile.UNCHECKED || that.status === CB_AudioFile.CHECKING) { return; } CB_Events.remove(that.audioObject, \"canplaythrough\", onCanplaythroughHandler, false); CB_Events.remove(that.audioObject, \"error\", onErrorHandler, false); if (that.status === CB_AudioFile.ABORTED) { return; } //If it is has been aborted, we exit. //If it has already failed before, exits: if (!ignoreFailed &amp;&amp; that.status === CB_AudioFile.FAILED) { return; } if (that._loadingCounterIncreased) { that._loadingCounterIncreased = false; CB_AudioFile_API_AAPI_SM2_beingLoading--; //Decreases the counter of the objects which are loading. if (CB_AudioFile_API_AAPI_SM2_beingLoading &lt; 0) { CB_AudioFile_API_AAPI_SM2_beingLoading = 0; } } that.status = CB_AudioFile.FAILED; //File failed to load. autoPlay = false; //var fileName = filePath; if (filePath.substring(0, 5).toLowerCase() === \"data:\") { filePath = filePath.substring(0, 15) + \"[...]\" + filePath.substring(filePath.length - 2); } error = \"Error message for \" + filePath + \" file: \" + error; if (typeof(callbackError) === \"function\") { callbackError.call(that, error); } //Calls the Error function back. }; try { //If the Audio object doesn't exist, creates it: if (typeof(this.audioObject) === \"undefined\" || this.audioObject === null) { if (typeof(window.Audio) === \"undefined\") { callbackFunctionError(\"Audio API not found\"); return null; } this.audioObject = new Audio(filePath); /////////this.audioObject.src = filePath; } //...otherwise, it updates its source (to avoid creating more than one Audio object): else { CB_Events.remove(this.audioObject, \"canplaythrough\", this._onCanplaythroughHandlerLast, false); CB_Events.remove(this.audioObject, \"error\", this._onErrorHandlerLast, false); this.audioObject.src = filePath; } var audioObjectOnReadyFunction = function() { CB_Events.remove(that.audioObject, \"canplaythrough\", onCanplaythroughHandler, false); CB_Events.remove(that.audioObject, \"error\", onErrorHandler, false); onReadyFunction(); //Prepares the sound to be playable (and plays it automatically if we want to). }; //Adds oncanplaythrough event: var onCanplaythroughHandler = this._onCanplaythroughHandlerLast = function() { that._onReadyTimeout = setTimeout(audioObjectOnReadyFunction, 1500); //Gives time to onerror event to be fired before canplaythrough event. }; CB_Events.add ( this.audioObject, \"canplaythrough\", onCanplaythroughHandler, false, true, true ); //Adds onerror event: var onErrorHandler = this._onErrorHandlerLast = function() { callbackFunctionError(\"Could not be loaded (onerror event fired)\"); }; CB_Events.add ( this.audioObject, \"error\", onErrorHandler, false, true, true ); //Loads the sound: this.audioObject.load(); //Makes the sound seekable for some iOS versions (strange bug) and forces Firefox for Android to fire canplaythrough event (strange bug too): var previousVolume = this.volume; if (CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING) { this.setVolume(0); this.audioObject.muted = true; } var possiblePromise = this.audioObject.play(); //In the case the play method returned a Promise (newer clients), it adds the error event to the catch: var isPromise = false; if (possiblePromise &amp;&amp; typeof(possiblePromise[\"catch\"]) !== \"undefined\") { isPromise = true; possiblePromise[\"catch\"](function(error) { callbackFunctionError(\"Error caught in Promise (load method): \" + error); }); //Calls the Error function back. } this._stopAfterPlayingTimeout = setTimeout(function() { that.audioObject.pause(); }, isPromise ? 50 : 1); //If it is a Promise, prevents the 'The play() request was interrupted by a call to pause()' error on Chrome. //Plays the sound during some time because otherwise some web clients, as WebView used by Cordova on Android, receive duration 0 (strange bug): var onReadyFunctionExecuted = false; var onReadyFunction = function() { //Prevents the execution of the function more than once: if (onReadyFunctionExecuted) { return; } onReadyFunctionExecuted = true; //Prevents to be executed after the onerror event has fired: if (that.status === CB_AudioFile.FAILED) { return; } //Function to execute when all is OK: var allIsFine = function() { if (that.status === CB_AudioFile.ABORTED) { return; } //If it is has been aborted, we exit. if (that._loadingCounterIncreased) { that._loadingCounterIncreased = false; CB_AudioFile_API_AAPI_SM2_beingLoading--; //Decreases the counter of the objects which are loading. if (CB_AudioFile_API_AAPI_SM2_beingLoading &lt; 0) { CB_AudioFile_API_AAPI_SM2_beingLoading = 0; } } //Restores the volume: that.audioObject.muted = false; that.setVolume(previousVolume); if (typeof(callbackOk) === \"function\") { callbackOk.call(that); } //Calls the OK function back. //Plays automatically if we want to: if (autoPlay) { that.play(); } }; that.status = CB_AudioFile.UNCHECKED; //The file is still unchecked. //If we want to play automatically, checks if the currentTime changes (some web clients cannot play if the user did not fire an event to call the play function): if (autoPlay) { that.checkPlaying(function() { allIsFine(); }, function(error) { callbackFunctionError(error, true); }, false, false); } else { allIsFine(); } }; } catch(E) { callbackFunctionError(E); return null; } return this; } /** * Checks whether the audio can be played or not. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. Also recommended to use before calling the {@link CB_AudioFile_API.AAPI#play} method the first time. The checking action will only be performed if the value of the {@link CB_AudioFile_API.AAPI#status} property belongs to the {@link CB_AudioFile.UNCHECKED} or to the {@link CB_AudioFile.CHECKING} value. After checking, if the audio can be played, the {@link CB_AudioFile_API.AAPI#status} of the object will get the value of {@link CB_AudioFile.LOADED}. Otherwise, if it cannot be played, the {@link CB_AudioFile_API.AAPI#status} property will get the value of {CB_AudioFile.FAILED}. * @function CB_AudioFile_API.AAPI#checkPlaying * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been checked successfully, being \"this\" the {@link CB_AudioFile_API.AAPI} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been checked successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.AAPI} object itself. * @param {boolean} [ignoreStatus=false] - If set to false and the {@link CB_AudioFile_API.AAPI#status} property does not belong neither to the \"UNCHECKED\" status (defined in the {@link CB_AudioFile.UNCHECKED} constant) nor to the \"CHECKING\" status (defined in the {@link CB_AudioFile.CHECKING} constant), it will fail calling the \"callbackError\" function (if any). If set to true, it will try to perform the checking action regardless the status of the audio. * @param {boolean} [ignoreQueue=false] - If set to false and there is already the maximum number of audio files being checked (defined internally), the function will exit and it will call itself automatically again and again until the checking process can be performed (when its queue turn has been reached). This is done for performance purposes. * @param {boolean} [useCache=false] - This parameter will be ignored in this audio API. * @returns {boolean} Returns false if the checking could not be performed and failed. If it returns true, it can mean either the checking has been processed successfully or it will fail in the future, so it is recommended to ignore the returning value and use the callback functions instead. */ CB_AudioFile_API[\"AAPI\"].prototype.checkPlaying = function(callbackOk, callbackError, ignoreStatus, ignoreQueue, useCache) { /////clearTimeout(this._recursiveCallCheckingTimeout); if (!ignoreStatus &amp;&amp; this.status !== CB_AudioFile.UNCHECKED &amp;&amp; this.status !== CB_AudioFile.CHECKING) { if (typeof(callbackError) === \"function\") { callbackError.call(this, \"Cannot check if status is not unchecked or checking (status is \" + this.status + \")\"); } return false; } this.status = CB_AudioFile.CHECKING; var that = this; //If we do not use cache the maximum of objects checking is reached or we use cache but the file path is checking, calls the function again after some time and exits: if (!ignoreQueue &amp;&amp; CB_AudioFile_API_AAPI_SM2_beingChecking &gt;= CB_AudioFile_API_AAPI_SM2_maximumChecking) { this._recursiveCallCheckingTimeout = setTimeout(function() { that.checkPlaying(callbackOk, callbackError, ignoreStatus, useCache); }, 10); return true; } //////this.status = CB_AudioFile.CHECKING; if (!this._checkingCounterIncreased) { this._checkingCounterIncreased = true; CB_AudioFile_API_AAPI_SM2_beingChecking++; //Increases the counter of the objects which are checking. } var previousVolume = this.volume; var finishedChecking = function(ok, error, keepStatus) { //Stops the file: that.audioObject.pause(); //Restores the volume: that._checkPlayingFinishingTimeout = //Timeout to prevent hearing the sound in some web clients. setTimeout ( function() { that.audioObject.muted = false; that.setVolume(previousVolume); //If the file is ok: if (ok) { if (!keepStatus) { that.status = CB_AudioFile.LOADED; } if (typeof(callbackOk) === \"function\") { callbackOk.call(that); } } //...otherwise, if the file has failed: else { if (!keepStatus) { that.status = CB_AudioFile.FAILED; } if (typeof(callbackError) === \"function\") { callbackError.call(that, error); } } }, 10 ); if (that._checkingCounterIncreased) { that._checkingCounterIncreased = false; CB_AudioFile_API_AAPI_SM2_beingChecking--; //Decreases the counter of the objects which are checking. if (CB_AudioFile_API_AAPI_SM2_beingChecking &lt; 0) { CB_AudioFile_API_AAPI_SM2_beingChecking = 0; } } }; try { //Plays the sound during some time to let some web clients get the duration correctly (strange bug): if (CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING) { this.setVolume(0); this.audioObject.muted = true; } var possiblePromise = this.audioObject.play(); //In the case the play method returned a Promise (newer clients), it adds the error event to the catch: if (possiblePromise &amp;&amp; typeof(possiblePromise[\"catch\"]) !== \"undefined\") { possiblePromise[\"catch\"](function(error) { finishedChecking(false, \"Error caught in Promise (checkPlaying method): \" + error); }); //Calls the Error function back. } var durationDetected = this.getDuration(); var timesCurrentTimeChecked = 0; clearTimeout(this._checkPlayingTimeout); clearTimeout(this._checkPlayingFinishingTimeout); var checkFunction = function(callbackOk, callbackError) { clearTimeout(that._checkPlayingTimeout); //If it is has been aborted, we exit: if (that.status === CB_AudioFile.ABORTED || that.status === CB_AudioFile.FAILED) { finishedChecking(false, \"Audio file object is \" + (that.status === CB_AudioFile.ABORTED ? \"ABORTED\" : \"FAILED\") + \".\", true); return; } try { that.status = CB_AudioFile.CHECKING; //If the duration has changed, it calls the function again because it means the audio is still loading (otherwise, Firefox has issues with data URIs and detects a shorter duration): var durationDetectedNow = that.getDuration(); if (durationDetected !== durationDetectedNow) { durationDetected = durationDetectedNow; that._checkPlayingTimeout = setTimeout(function() { checkFunction(callbackOk, callbackError); }, CB_Configuration[CB_BASE_NAME].CB_AudioFile_AUTOPLAY_SILENTLY_ON_LOAD_MS); return; } //If the current time is still 0: if (that.audioObject.currentTime == 0) { //We give it some opportunities more to change current time: if (timesCurrentTimeChecked &lt; 1000) { timesCurrentTimeChecked++; if (timesCurrentTimeChecked % 20 === 0) { that.audioObject.pause(); try { that.audioObject.currentTime = 0; } catch(E) {} //Avoid Firefox complain about using an object which is no longer available. var possiblePromise = that.audioObject.play(); //In the case the play method returned a Promise (newer clients), it adds the error event to the catch: if (possiblePromise &amp;&amp; typeof(possiblePromise[\"catch\"]) !== \"undefined\") { possiblePromise[\"catch\"](function(error) { finishedChecking(false, \"Error caught in Promise (checkPlaying method in CheckFunction): \" + error); }); //Calls the Error function back. } /* try { if (that.audioObject.currentTime != 0) { that.audioObject.currentTime = 0.00000000001; //Executed after play method because otherwise Safari Mobile does not change currentTime. } } catch(E) {} */ } that._checkPlayingTimeout = setTimeout(function() { checkFunction(callbackOk, callbackError); }, 1); return; } //...if all opportunities failed, we declare it as FAILED and exits: else { finishedChecking(false, \"currentTime does not change (it is \" + that.audioObject.currentTime + \").\"); return; } } //Only updates the currentTime to 0 if it is not zero already (because otherwise some web clients will fail or have a wrong behaviour): if (that.audioObject.currentTime != 0) { that.audioObject.currentTime = 0; } //If the duration is zero, we declare it as FAILED and exits: if (that.getDuration() === 0) { finishedChecking(false, \"Duration is zero\"); return; } finishedChecking(true); } catch(E) { finishedChecking(false, E); } }; this._checkPlayingTimeout = setTimeout(function() { checkFunction(callbackOk, callbackError); }, CB_Configuration[CB_BASE_NAME].CB_AudioFile_AUTOPLAY_SILENTLY_ON_LOAD_MS); return true; } catch(E) { finishedChecking(false, E); return false; } } /** * Tells the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. * @function CB_AudioFile_API.AAPI#getDuration * @returns {number} Returns the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. */ CB_AudioFile_API[\"AAPI\"].prototype.getDuration = function() { var duration; if (typeof(this.audioObject) !== \"undefined\" &amp;&amp; this.audioObject !== null) { duration = this.audioObject.duration * 1000; } if (typeof(duration) === \"undefined\" || duration === null || isNaN(duration) || duration &lt; 0) { duration = 0; } return duration; } //Executed when there is an error playing: CB_AudioFile_API[\"AAPI\"].prototype._onPlayingErrorFunction = function(onPlayingErrorFunction) { CB_Events.remove(this.audioObject, \"error\", onPlayingErrorFunction, false); if (this._onPlayingErrorFunctionExecuted) { return; } this._onPlayingErrorFunctionExecuted = true; this.status = CB_AudioFile.FAILED; //Declares it as failed. this.stop(false, false, true); //Also fires onStop event. }; //Executed when the sound stops playing: CB_AudioFile_API[\"AAPI\"].prototype._checkWhenStopFunction = function(e, finished, startAtNextLoop, stopAt, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, checkWhenStopFunction, whenStopFunction, flags) { //If we are using timeupdadte event (finished is undefined) but whenStopFunction has been executed (ended event or timeout has been executed), exits: //if (!finished &amp;&amp; whenStopFunctionExecuted) { return; } //If the sound has been stopped or paused or the stop time has changed: if (this.stopped || this.paused || this.lastStopAt !== stopAt) { //Removes the events: clearTimeout(this._timeoutWhenStop); this._onPlayingErrorFunctionExecuted = true; CB_Events.remove(this.audioObject, \"timeupdate\", checkWhenStopFunction, false); CB_Events.remove(this.audioObject, \"ended\", whenStopFunction, false); } //...otherwise, if the stop time has been reached: else if (finished || this.getCurrentTime() &gt;= stopAt - 1) //Allows 1 ms of margin (because in some web clients, currentTime will never reach the total duration). { //Removes the event: clearTimeout(this._timeoutWhenStop); CB_Events.remove(this.audioObject, \"timeupdate\", checkWhenStopFunction, false); CB_Events.remove(this.audioObject, \"ended\", whenStopFunction, false); //if (finished) { this.audioObject.pause(); this.audioObject.currentTime = 0; this.audioObject.play(); this.audioObject.currentTime = 0; this.audioObject.pause(); } //If we want to loop, loops again: if (this.loop) //Only allows one loop per time. { if (!flags.loopPerformed) { flags.loopPerformed = true; //this.stop(true); //Stops the sound without setting its property as stopped. this.play(startAtNextLoop, stopAt, true, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, false, true); //Plays again the sound. } } //...otherwise, if we don't want to loop, we stop at the given position (ms): else { this._onPlayingErrorFunctionExecuted = true; this.stop(); } //Stops the sound. } }; /** * Plays the audio. * @function CB_AudioFile_API.AAPI#play * @param {number} [startAt=0 | {@link CB_AudioFile_API.AAPI#lastStartAt} | stopAt] - Time in milliseconds where we want the audio to start at. If not provided or it is not a valid number, it will use zero (0) as default which belongs to the beginning of the audio. If the value provided is greater than the \"stopAt\" provided, it will use the value set in the {@link CB_AudioFile_API.AAPI#lastStartAt} property (which belongs to the \"startAt\" value the last time that this method was called). If, even using the {@link CB_AudioFile_API.AAPI#lastStartAt} value is still greather than the \"stopAt\" provided, it will use the same value as the \"stopAt\" which means it will not play and will stop immediately. * @param {number} [stopAt={@link CB_AudioFile_API.AAPI#getDuration}()] - Time in milliseconds where we want the audio to stop at. If not provided or it is not a valid number, it will use the returning value of the {@link CB_AudioFile_API.AAPI#getDuration} method (which should belong to the total duration of the audio, if it was calculated correctly). * @param {boolean} [loop={@link CB_AudioFile_API.AAPI#loop}] - Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the {@link CB_AudioFile_API.AAPI#onStop} method) will not be called. * @param {boolean} [avoidDelayedPlay=false] - If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the \"stop\" method will be called immediately. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the {@link CB_AudioFile_API.AAPI#stop} method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). * @param {function} [onPlayStart] - Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the {@link CB_AudioFile_API.AAPI} object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. * @param {function} [onLoadError] - Function to be called if the audio cannot be played successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.AAPI} object. * @param {boolean} [isResume=false] - If set to true (not recommended) and it is a looping audio, the next loop will use the value of the {@link CB_AudioFile_API.AAPI#lastStartAt} property as the \"startAt\" parameter when it calls this method again automatically (internally). Recommended for internal usage only. * @param {boolean} [isLooping=false] - Used to determine whether this method was called automatically again by itself because it is looping the audio. Recommended for internal usage only. * @param {integer} [startPlayingTime] - Contains the time when the audio should start playing. Recommended for internal usage only. * @returns {boolean|integer} It returns false if the duration is 0 (\"startAt\" and \"stopAt\" are the same number), returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. */ CB_AudioFile_API[\"AAPI\"].prototype.play = function(startAt, stopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, isResume, isLooping, startPlayingTime) { var that = this; var duration = this.getDuration(); if (typeof(startPlayingTime) === \"undefined\" || startPlayingTime === null) { startPlayingTime = CB_Device.getTiming(); } var onPlayingErrorFunction = function() { that._onPlayingErrorFunction.call(that, onPlayingErrorFunction); }; //If the sound is not ready yet, calls the function again but later: if (this.status !== CB_AudioFile.LOADED || duration === 0) //Duration must be greater than zero. { this.stopped = true; this.paused = false; CB_Events.remove(this.audioObject, \"error\", onPlayingErrorFunction, false); //If it has not failed or aborted: if (this.status !== CB_AudioFile.FAILED &amp;&amp; this.status !== CB_AudioFile.ABORTED) //It must be UNLOADED, LOADING, LOADED, UNCHECKED or CHECKING. { //Function that calls the play method recursively (unless the maximum time allowed has expired): var playLaterFunctionCalled = false; var playLaterFunction = function() { if (playLaterFunctionCalled) { return; } playLaterFunctionCalled = true; //If the recursive delay is not null and is a valid number: if (typeof(allowedRecursiveDelay) === \"undefined\" || allowedRecursiveDelay === null || isNaN(allowedRecursiveDelay) || allowedRecursiveDelay &lt; 0) { allowedRecursiveDelay = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT; //We use default value. } var timeNow = CB_Device.getTiming(); //If the time expired is less or equal to the delay allowed: if (timeNow - startPlayingTime &lt;= allowedRecursiveDelay) { //Calls play method again: that.play(startAt, stopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, isResume, isLooping, startPlayingTime); } //...otherwise, just stops the sound: /////else { that.stop(false, false); } //Sets as stopped and fires onStop function (if any). else { that.stop(false, false, true); } //Sets as stopped and fires onStop function (if any). }; //Function to execute when the sound loads successfully (or finishes checking successfully): var onLoad = function() { //If we allow delayed play, plays the sound: if (!avoidDelayedPlay) { playLaterFunction(); } //...otherwise, just stops the sound (to fire onStop function): //////else { that.stop(false, false); } //Sets as stopped and fires onStop function (if any). else { that.stop(false, false, true); } //Sets as stopped and fires onStop function (if any). }; //If it is UNLOADED or we had a duration before but not now and it is not LOADING, loads the file again: if (this.status === CB_AudioFile.UNLOADED || this.status !== CB_AudioFile.LOADING &amp;&amp; this._lastDuration !== null &amp;&amp; duration === 0) { this.load(this.filePath, false, onLoad, onLoadError, true); } //...otherwise, if it is UNCHECKED, we call the checking function: else if (this.status === CB_AudioFile.UNCHECKED) { this.checkPlaying(onLoad, onLoadError, false, true, false); } //...otherwise, if it is not CHECKING (it must be LOADING or LOADED with duration 0 from the beginning), we will not reload the sound: else if (this.status !== CB_AudioFile.CHECKING) { //If we allow delayed play, calls the play method again but after some time: if (!avoidDelayedPlay) { setTimeout(playLaterFunction, 1); } //...otherwise, just stops the sound (to fire onStop function): //////else { this.stop(false, false); } //Sets as stopped and fires onStop function (if any). else { this.stop(false, false, true); } //Sets as stopped and fires onStop function (if any). } } return -1; } this._lastDuration = duration; //Defines the default parameters: if (CB_trim(startAt) === \"\") { startAt = 0; } //Starts at the beginning as default. if (CB_trim(stopAt) === \"\") { stopAt = 0; } //If it is not a number, default is zero. if (typeof(loop) === \"undefined\" || loop === null) { loop = this.loop; } //If not set, uses the default (or last one used). else { this.loop = loop; } //...otherwise, stores the new setting given. //Sanitizes startAt and stopAt: startAt = parseFloat(startAt); stopAt = parseFloat(stopAt); if (startAt &lt; 0) { startAt = 0; } if (stopAt &lt;= 0 || stopAt &gt; duration) { stopAt = duration; } //If the stopAt is not correct, plays until the end of the file. if (startAt &gt; stopAt) { startAt = this.lastStartAt; } //In the case start time is than stop time, starts as the previous time. if (startAt &gt; stopAt || isNaN(startAt)) { startAt = stopAt; } //If the duration is zero (startAt and stopAt are equal), exits: if (startAt === stopAt) { this.stop(); return false; } //Next loop (if any) it will start at the same time by default: var startAtNextLoop = startAt; //If it is a resume, next loop we should start from the previous startAt used: if (isResume) { startAtNextLoop = this.lastStartAt; } //...otherwise, if it is not a resume, stores the startAt used: else { this.lastStartAt = startAt; } this.lastStopAt = stopAt; //Stores stopAt used. //Adds the events to check when the file reaches the stop time: this.audioObject.loop = false; //We will use our own way to loop, so we don't need the normal way. var flags = { \"loopPerformed\" : false }; var checkWhenStopFunction = function(e, finished) { that._checkWhenStopFunction.call(that, e, finished, startAtNextLoop, stopAt, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, checkWhenStopFunction, whenStopFunction, flags); }; var whenStopFunctionExecuted = false; var whenStopFunction = function(e) { //Just allows executing the function once: if (whenStopFunctionExecuted) { return; } whenStopFunctionExecuted = true; checkWhenStopFunction.call(that, e, true); }; CB_Events.add(this.audioObject, \"ended\", whenStopFunction, false, true, true); this._onPlayingErrorFunctionExecuted = false; CB_Events.remove(this.audioObject, \"error\", onPlayingErrorFunction, false); CB_Events.add(this.audioObject, \"error\", onPlayingErrorFunction, false); clearTimeout(this._timeoutWhenStop); //Clears the previous timeout (if any). //If we want to use timeout: if (CB_Configuration[CB_BASE_NAME].CB_AudioFile_AAPI_USE_TIMEOUT_TO_DETECT_STOPAT) { //If it is not a loop (it is the first call to the play method) or we do not want to loop: if (!isLooping || !loop) { CB_symmetricCallClear(\"AAPI_AUDIO_FILE\" + this._id_internal); } //We clean the cache of setTimeoutSynchronized for the loop function. var msToFinish = stopAt - startAt; this._timeoutWhenStop = CB_symmetricCall(whenStopFunction, msToFinish, \"AAPI_AUDIO_FILE\" + this._id_internal); } //...otherwise, we use timeupdate: else { CB_Events.add(this.audioObject, \"timeupdate\", checkWhenStopFunction, false, true, true); } //If it is looping or does not allow overlapping and it is not paused, stops the possible previous sound (although AAPI would never overlap normally): //if (isLooping || !allowOverlapping &amp;&amp; !this.paused) { this.stop(true); } //Stops the sound without setting its property as stopped. this.stop(true, true); //Stops the sound without setting its property as stopped. //Applies the current volume: this.setVolume(this.volume); //If defined, starts at the given position (ms): var currentTime = startAt / 1000; //Only updates the currentTime to 0 if it is not zero already (because otherwise some web clients will fail or have a wrong behaviour): if (currentTime !== 0 || this.audioObject.currentTime != 0) { this.audioObject.currentTime = currentTime; } //Plays the file: var possiblePromise = this.audioObject.play(); //In the case the play method returned a Promise (newer clients), it adds the error event to the catch: if (possiblePromise &amp;&amp; typeof(possiblePromise[\"catch\"]) !== \"undefined\") { possiblePromise[\"catch\"] ( function(error) { that.status = CB_AudioFile.FAILED; onLoadError(false, \"Error caught in Promise (play method): \" + error); } ); } //If defined, starts at the given position (ms): ////////if (currentTime === 0) { currentTime = 0.001; } //Safari Mobile works wrong the second loop if it we set currentTime to 0, so we add 0.00000000001 (strange bug). //Only updates the currentTime to 0 if it is not zero already (because otherwise some web clients will fail or have a wrong behaviour): ///////if (this.audioObject.currentTime !== currentTime &amp;&amp; (currentTime !== 0 || this.audioObject.currentTime != 0)) if (currentTime !== 0 || this.audioObject.currentTime != 0) { this.audioObject.currentTime = currentTime + 0.00000000001; //Executed after play method because otherwise Safari Mobile does not change currentTime. } //The sound is neither paused nor stopped: this.paused = this.stopped = false; //If it is the first time (not a loop) and there is a function to call when the play starts, we call it: if (!isLooping &amp;&amp; typeof(onPlayStart) === \"function\") { onPlayStart.call(this, startAt, stopAt, startAtNextLoop, loop, avoidDelayedPlay, allowedRecursiveDelay, startPlayingTime); onPlayStart = null; } //Prevents execution again. return true; } /** * Resumes the audio (after being paused), starting from the same point it was paused previously. * @function CB_AudioFile_API.AAPI#resume * @param {boolean} [loop={@link CB_AudioFile_API.AAPI#loop}] - Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the {@link CB_AudioFile_API.AAPI#onStop} method) will not be called. * @param {boolean} [avoidDelayedPlay=false] - If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the {@link CB_AudioFile_API.AAPI#stop} method will be called immediately. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the {@link CB_AudioFile_API.AAPI#stop} method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). * @param {function} [onPlayStart] - Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the {@link CB_AudioFile_API.AAPI} object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. * @param {function} [onLoadError] - Function to be called if the audio cannot be played successfully. It will not be called if the audio is not paused or is stopped. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.AAPI} object. * @returns {boolean|integer} Returns the returning value of the {@link CB_AudioFile_API.AAPI#play} method which is called internally. It returns false if the audio is not paused or it is stopped, returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. */ CB_AudioFile_API[\"AAPI\"].prototype.resume = function(loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError) { //If it not paused or it is stopped, exits the function: if (!this.paused || this.stopped) { return false; } var startAt = this.pauseTime; //If it has been paused after the stop time (happens sometimes when the sound was nearly to finish): if (startAt &gt;= this.lastStopAt) { startAt = this.lastStopAt - 1; //We will begin just 1 millisecond before (otherwise the play method would begin again from lastStartAt). } return this.play(startAt, this.lastStopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, true, false); } /** * Pauses the audio when it is being played. * @function CB_AudioFile_API.AAPI#pause * @param {function} [onPause] - Function without parameters to be called when the audio is paused successfully, being \"this\" the {@link CB_AudioFile_API.AAPI} object. * @param {boolean} [keepPausedUnaltered=false] - If set to true (not recommended), the {@link CB_AudioFile_API.AAPI#paused} property will not be set to true and it will remain with its current value. * @returns {boolean} It returns false if the audio is already paused or it is stopped or if it cannot be paused. Returns true otherwise. */ CB_AudioFile_API[\"AAPI\"].prototype.pause = function(onPause, keepPausedUnaltered) { //If it already paused or stopped, exits the function: if (this.paused || this.stopped) { return false; } if (typeof(this.audioObject) !== \"undefined\" &amp;&amp; this.audioObject !== null) { clearTimeout(this._timeoutWhenStop); //Prevents that the file is set as stopped or to be executed again. this.audioObject.pause(); this.pauseTime = this.getCurrentTime(); if (!keepPausedUnaltered) { this.paused = true; } if (typeof(onPause) === \"function\") { onPause.call(this); } return true; } return false; } /** * Stops the audio. * @function CB_AudioFile_API.AAPI#stop * @param {boolean} [keepStoppedUnaltered=false] - If set to true (not recommended), the {@link CB_AudioFile_API.AAPI#stopped} property will not be set to true and it will remain with its current value. * @param {boolean} [avoidOnStop=false] - If set to false and there is an \"onStop\" function defined (through the {@link CB_AudioFile_API.AAPI#onStop} method), it will be called after stopping the audio (or after trying to do it, at least) but only if either the \"forceOnStop\" parameter is set to true or if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. If set to true, the \"onStop\" function (if any) will not be called at all. * @param {boolean} [forceOnStop=false] - If it is set to true and the \"avoidOnStop\" parameter is set to false and there is an \"onStop\" function defined (through the {@link CB_AudioFile_API.AAPI#onStop} method), it will be called regardless the audio was stopped before or not. If set to false, the \"onStop\" function (if any) will only be called if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. This parameter will be ignored if the \"avoidOnStop\" parameter is set to true. * @returns {boolean} It returns false if the stopping action cannot be performed at all (this could happen when the audio has not been loaded properly, for example). Returns true otherwise (this only means that it has been tried to be stopped but it could not be successfully). */ CB_AudioFile_API[\"AAPI\"].prototype.stop = function(keepStoppedUnaltered, avoidOnStop, forceOnStop) { if (typeof(this.audioObject) !== \"undefined\" &amp;&amp; this.audioObject !== null) { ///////clearTimeout(this._timeoutWhenStop); //Prevents that the file is set as stopped or to be executed again. this.audioObject.pause(); //Only updates the currentTime to 0 if it is not zero already (because otherwise some web clients will fail or have a wrong behaviour): if (this.audioObject.currentTime != 0) { this.audioObject.currentTime = 0; } var stoppedBefore = this.stopped; if (!keepStoppedUnaltered) { this.stopped = true; } this.paused = false; //If it is stopped, it is not paused. //If we do not want to avoid onStop, it was not stopped before but it is now and onStop has a valid function assigned, we execute it: if (!avoidOnStop &amp;&amp; (!stoppedBefore &amp;&amp; this.stopped || forceOnStop) &amp;&amp; typeof(this.onStopFunction) === \"function\") { this.onStopFunction.call(this); } return true; } return false; } /** * Sets the desired volume for the audio file (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). * @function CB_AudioFile_API.AAPI#setVolume * @param {number} [volume={@link CB_Speaker.getVolume()} | {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME}] - Desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). * @param {boolean} [forceSetVolumeProperty=false] - If set to true (not recommended), it will change the {@link CB_AudioFile_API.AAPI#volume} property even when the volume failed to be changed. * @param {function} [onSetVolume] - Callback function which will be called if it has been possible to set the volume (or at least it was possible to try it). It will not receive any parameters, being \"this\" the {@link CB_AudioFile_API.AAPI} object. * @param {boolean} [saveForUnmute=false] - If set to true (not recommended), it will save internally the current volume before setting it so it will restore the same volume again after calling the {@link CB_AudioFile_API.AAPI#unmute} method. Internal usage only recommended. * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). */ CB_AudioFile_API[\"AAPI\"].prototype.setVolume = function(volume, forceSetVolumeProperty, onSetVolume, saveForUnmute) { //Defines the default parameters: volume = parseInt(volume); if (isNaN(volume)) { this.DEFAULT_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration[CB_BASE_NAME].CB_Speaker_DEFAULT_VOLUME; volume = this.DEFAULT_VOLUME; } //Sets the volume within their limits if it is beyond them: var MAX_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM ? CB_Speaker.getVolume() : 100; if (volume &gt; MAX_VOLUME) { volume = MAX_VOLUME; } else if (volume &lt; 0) { volume = 0; } if (typeof(this.audioObject) !== \"undefined\" &amp;&amp; this.audioObject !== null) { this.audioObject.volume = volume / 100; if ((saveForUnmute || volume === 0) &amp;&amp; this.volume &gt; 0) { this.volumeBeforeMute = this.volume; } //Also saves the previous volume if the desired one is zero (muted). this.volume = volume; if (typeof(onSetVolume) === \"function\") { onSetVolume.call(this); } } if (forceSetVolumeProperty) { this.volume = volume; } return this.volume; } /** * Mutes the audio file. * @function CB_AudioFile_API.AAPI#mute * @param {function} [onMute] - Callback function which will be called if it has been possible to mute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the {@link CB_AudioFile_API.AAPI} object. * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). If all goes well, the returning value should be zero (0). Note that, even when it returns a zero (0) value, this does not always mean that the mute has been applied successfully. */ CB_AudioFile_API[\"AAPI\"].prototype.mute = function(onMute) { //Only mutes the sound if it is not muted already: if (this.volume &gt; 0) { //Mutes the audio: this.setVolume(0, false, onMute, true); //It modifies this.volumeBeforeMute. } return this.volume; } /** * Restores audio after muting it (unmutes it). * @function CB_AudioFile_API.AAPI#unmute * @param {function} [onUnmute] - Callback function which will be called if it has been possible to unmute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the {@link CB_AudioFile_API.AAPI} object. * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). */ CB_AudioFile_API[\"AAPI\"].prototype.unmute = function(onUnmute) { //Only unmutes if it is still muted: if (this.volume === 0) { //Restores the volume before muting: this.setVolume(this.volumeBeforeMute, false, onUnmute); } return this.volume; } /** * Gets the current time (in milliseconds) which belongs to the position where the audio is currently playing or where it has been paused. Note that some audio APIs and clients could give wrong values. * @function CB_AudioFile_API.AAPI#getCurrentTime * @returns {number} Returns the current time (in milliseconds). Note that some audio APIs and clients could give wrong values. */ CB_AudioFile_API[\"AAPI\"].prototype.getCurrentTime = function() { var currentTime; if (this.status !== CB_AudioFile.LOADED) { return 0; } if (typeof(this.audioObject) !== \"undefined\" &amp;&amp; this.audioObject !== null) { currentTime = this.audioObject.currentTime * 1000; } if (typeof(currentTime) === \"undefined\" || currentTime === null || isNaN(currentTime) || currentTime &lt; 0) { currentTime = 0; } return currentTime; } /** * Sets a function to execute when the audio file stops playing or removes it. * @function CB_AudioFile_API.AAPI#onStop * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. No parameters will be received, being \"this\" the {@link CB_AudioFile_API.AAPI} object. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @returns {boolean} Returns whether the event has been set or not (removed). */ CB_AudioFile_API[\"AAPI\"].prototype.onStop = function(callbackFunction, keepOldFunction) { //If not set, it keeps old function by default: if (typeof(keepOldFunction) === \"undefined\" || keepOldFunction === null) { keepOldFunction = true; } if (typeof(callbackFunction) !== \"function\") { this.onStopFunction = null; return false; } //If we don't want to keep the old function: if (!keepOldFunction) { this.onStopFunction = callbackFunction; } //...otherwise if we want to keep the old function, we keep it: else { var that = this; //Stores old function: var oldFunction = this.onStopFunction; //Stores old function of eventFunctionHolder. this.onStopFunction = function() { if (typeof(oldFunction) === \"function\") { oldFunction.call(that); } callbackFunction.call(that); }; } return true; } /** * Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. * @function CB_AudioFile_API.AAPI#getProgress * @returns {number} Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. */ CB_AudioFile_API[\"AAPI\"].prototype.getProgress = function() { if (this.status === CB_AudioFile.LOADED || this.status === CB_AudioFile.UNCHECKED || this.status === CB_AudioFile.CHECKING) { return 100; } else if (this.status === CB_AudioFile.UNLOADED) { return 0; } var progress = 0; //Calculates the progress (only if it is LOADING, FAILED or ABORTED): if (typeof(this.audioObject) !== \"undefined\" &amp;&amp; this.audioObject !== null &amp;&amp; typeof(this.audioObject.buffered) !== \"undefined\") { var duration = this.getDuration() / 1000; var bufferedLength = this.audioObject.buffered.length; var secondsBuffered = 0; for (var x = 0; x &lt; bufferedLength; x++) { secondsBuffered += this.audioObject.buffered.end(x) - this.audioObject.buffered.start(x); } if (duration === 0) { if (secondsBuffered &gt; 0) { return 100; } else { return 0; } } else { progress = secondsBuffered / duration * 100; } if (progress &gt; 100) { progress = 100; } else if (progress &lt; 0) { progress = 0; } } return progress; } × Search results Close "},"CrossBase_audiovisual_audio_CB_AudioFile_API_ACMP.js.html":{"id":"CrossBase_audiovisual_audio_CB_AudioFile_API_ACMP.js.html","title":"Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js /** * @file Audio files management using \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}). Contains the {@link CB_AudioFile_API.ACMP} class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ //Class to manage an audio file with ACMP (Apache Cordova Media Plugin): if (typeof(CB_AudioFile_API) === \"undefined\") { var CB_AudioFile_API = {}; } /** * The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.) if the \"autoPlay\" option is set to true, as some web clients may need this at least the first time in order to be able to play the audio. * @class CB_AudioFile_API.ACMP * @memberof! &lt;global&gt; * @classdesc Class to manage an audio file using \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}). Used by the {@link CB_AudioFile} class internally and it shares most of its properties and methods. Recommended for internal usage only. * @param {string} filePath - The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @param {string} [audioId='CB_AUDIOFILE_ACMP_' + CB_AudioFile_API.ACMP._idUnique++] - Desired identifier for the audio object. If not provided, an automatic unique ID will be calculated. Note that it is not case sensitive and it should be unique for each object. * @param {CB_AudioFile_API.ACMP.OPTIONS} [options=CB_AudioFile_API.ACMP#DEFAULT_OPTIONS] - Object with the desired options. * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the {@link CB_AudioFile_API.ACMP} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if could be determined), being \"this\" the {@link CB_AudioFile_API.ACMP} object itself. * @returns {CB_AudioFile_API.ACMP} Returns a new {@link CB_AudioFile_API.ACMP} object. * @todo Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). Note that the \"id\" is not case sensitive and it should be unique for each object. * @todo Method getCopy and static method filterProperties (similar to the ones from {@link CB_GraphicSprites} and {@link CB_GraphicSpritesScene}). */ CB_AudioFile_API[\"ACMP\"] = function(filePath, audioId, options, callbackOk, callbackError) { //Creates an instance of this object and returns it in the case that it is being called from an unexpected context: if (this === window || !(this instanceof CB_AudioFile_API[\"ACMP\"])) { return new CB_AudioFile_API[\"ACMP\"](filePath, audioId, options, callbackOk, callbackError); } //Constants: /** * Keeps the default volume. If the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT} property is true, this will keep the result of calling the {@link CB_Speaker.getVolume} function. Otherwise, it will use the value of the {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME} variable. * @constant CB_AudioFile_API.ACMP#DEFAULT_VOLUME * @type {number} * @default CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME */ CB_AudioFile_API[\"ACMP\"].prototype.DEFAULT_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration[CB_BASE_NAME].CB_Speaker_DEFAULT_VOLUME; /** * Keeps the default options when an object is created. Format: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. * @constant CB_AudioFile_API.ACMP#DEFAULT_OPTIONS * @type {CB_AudioFile_API.ACMP.OPTIONS} * @default { autoLoad: true, autoPlay: false, loop: false, volume: [CB_AudioFile_API.ACMP.prototype.DEFAULT_VOLUME]{@link CB_AudioFile_API.ACMP#DEFAULT_VOLUME} } */ CB_AudioFile_API[\"ACMP\"].prototype.DEFAULT_OPTIONS = { autoLoad: true, autoPlay: false, loop: false, volume: CB_AudioFile_API[\"ACMP\"].prototype.DEFAULT_VOLUME }; //Properties and variables: /** * Tells whether the file is unloaded ({@link CB_AudioFile.UNLOADED}), loading ({@link CB_AudioFile.LOADING}), unchecked ({@link CB_AudioFile.UNCHECKED}), checking ({@link CB_AudioFile.CHECKING}), loaded ({@link CB_AudioFile.LOADED}), failed ({@link CB_AudioFile.FAILED}) or aborted ({@link CB_AudioFile.ABORTED}). * @var CB_AudioFile_API.ACMP#status * @readonly * @type {integer} * @default {@link CB_AudioFile.UNLOADED} */ this.status = CB_AudioFile.UNLOADED; /** * Defines whether the file loops by default when the audio is played or not. Its value will be modified automatically whenever the {@link CB_AudioFile_API.ACMP#play} method is called, getting the value from the \"loop\" parameter (but only if contains a boolean). * @var CB_AudioFile_API.ACMP#loop * @readonly * @type {boolean} * @default [CB_AudioFile_API.ACMP.prototype.DEFAULT_OPTIONS]{@link CB_AudioFile_API.ACMP#DEFAULT_OPTIONS}.loop */ this.loop = CB_AudioFile_API[\"ACMP\"].prototype.DEFAULT_OPTIONS.loop; /** * Stores the volume of this audio. Accepted values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is false or otherwise MAX_VOLUME is the returning value of the {@link CB_Speaker.getVolume} function. * @var CB_AudioFile_API.ACMP#volume * @readonly * @type {number} * @default [CB_AudioFile_API.ACMP.prototype.DEFAULT_OPTIONS]{@link CB_AudioFile_API.ACMP#DEFAULT_OPTIONS}.volume */ this.volume = CB_AudioFile_API[\"ACMP\"].prototype.DEFAULT_OPTIONS.volume; /** * Stores the volume of this audio before it was muted (to restore it later). Valid values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is false or otherwise MAX_VOLUME is the returning value of the {@link CB_Speaker.getVolume} function. * @var CB_AudioFile_API.ACMP#volumeBeforeMute * @readonly * @type {number} * @default {@link CB_AudioFile_API.ACMP#volume} */ this.volumeBeforeMute = this.volume; /** * Stores the identifier for the audio file. * @var CB_AudioFile_API.ACMP#id * @readonly * @type {string} * @default 'CB_AUDIOFILE_ACMP_' + CB_AudioFile_API.ACMP._idUnique++ */ this.id = \"\"; /** * Stores the path of the audio file or the data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @var CB_AudioFile_API.ACMP#filePath * @readonly * @type {string} * @default */ this.filePath = \"\"; /** * Tells whether the audio is paused or not. * @var CB_AudioFile_API.ACMP#paused * @readonly * @type {boolean} * @default false */ this.paused = false; /** * Stores the time (in milliseconds) when the audio has been paused. * @var CB_AudioFile_API.ACMP#pauseTime * @readonly * @type {number} * @default */ this.pauseTime = 0; /** * Tells whether the audio is stopped or not. * @var CB_AudioFile_API.ACMP#stopped * @readonly * @type {boolean} * @default true */ this.stopped = true; /** * Function to call when the audio stops. * @var CB_AudioFile_API.ACMP#onStopFunction * @readonly * @type {function} * @default */ this.onStopFunction = undefined; /** * Stores the last \"startAt\" parameter value used by the {@link CB_AudioFile_API.ACMP#play} or the {@link CB_AudioFile_API.ACMP#resume} method. * @var CB_AudioFile_API.ACMP#lastStartAt * @readonly * @type {number} * @default */ this.lastStartAt = null; /** * Stores the last \"stopAt\" parameter value used by the {@link CB_AudioFile_API.ACMP#play} or the {@link CB_AudioFile_API.ACMP#resume} method. * @var CB_AudioFile_API.ACMP#lastStopAt * @readonly * @type {number} * @default */ this.lastStopAt = null; /** * Stores the [Media]{@link https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-media/} object of the audio, used by the \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}). * @var CB_AudioFile_API.ACMP#mediaObject * @readonly * @type {Object} * @default */ this.mediaObject = undefined; /** * Stores the current position (in seconds) where the audio is playing (returned by the [getCurrentPosition]{@link https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-media/} method), used by the \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}). * @var CB_AudioFile_API.ACMP#position * @readonly * @type {number} * @default */ this.position = 0; //Internal properties: this._mediaObjectSwap = null; //Media object for swapping (used for ACMP). Necessary due ACMP issues when looping a sprite near the end of the audio file. this._positionSwap = 0; //Keeps the current position (in seconds) for the swap object. this._timeoutWhenStop = null; //Keeps the timeout that is executed when the audio has finished playing (to either stop or loop). this._id_internal = null; //Internal id. this._checkDurationTimeout = null; this._swapChecked = false; this._updatePositionLoopExecuted = false; this._checkPlayingTimeout = null; this._checkPlayingFinishingTimeout = null; //this._recursiveCallCheckingTimeout = null; this._lastDuration = null; //this._resuming = false; //Calls the constructor of the object when creates an instance: return this._init(filePath, audioId, options, callbackOk, callbackError); } /** * Object with the options for an audio file. The format is the following one: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. * @memberof CB_AudioFile_API.ACMP * @typedef {Object} CB_AudioFile_API.ACMP.OPTIONS * @property {boolean} [autoLoad={@link CB_AudioFile_API.ACMP#DEFAULT_OPTIONS}.autoLoad] - If set to false, it will not call the {@link CB_AudioFile_API.ACMP#load} method internally when the constructor is called (not recommended). * @property {boolean} [autoPlay={@link CB_AudioFile_API.ACMP#DEFAULT_OPTIONS}.autoPlay] - Value which will be used as the \"autoPlay\" parameter when calling the {@link CB_AudioFile_API.ACMP#load} method internally, only when the \"autoLoad\" is set to true (when the constructor is called). * @property {boolean} [loop={@link CB_AudioFile_API.ACMP#DEFAULT_OPTIONS}.loop] - Value that will be used for the {@link CB_AudioFile_API.ACMP#loop} property. * @property {number} [volume={@link CB_AudioFile_API.ACMP#DEFAULT_OPTIONS}.volume] - The desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise) that will be used for the {@link CB_AudioFile_API.ACMP#volume} property. */ //Static properties: CB_AudioFile_API[\"ACMP\"]._counter = 0; //Internal counter. CB_AudioFile_API[\"ACMP\"]._idUnique = 0; //Counter to make the id unique. //Constructor: CB_AudioFile_API[\"ACMP\"].prototype._init = function(filePath, audioId, options, callbackOk, callbackError) { //If not given, defines the default parameters: if (typeof(audioId) === \"undefined\" || audioId === null) { audioId = \"CB_AUDIOFILE_ACMP_\" + CB_AudioFile_API[\"ACMP\"]._idUnique++; } //Uses the file path as default id. if (typeof(options) === \"undefined\" || options === null) { options = this.DEFAULT_OPTIONS; } else { if (typeof(options.loop) === \"undefined\" || options.loop === null) { options.loop = this.DEFAULT_OPTIONS.loop; } if (typeof(options.autoLoad) === \"undefined\" || options.autoLoad === null) { options.autoLoad = this.DEFAULT_OPTIONS.autoLoad; } if (typeof(options.autoPlay) === \"undefined\" || options.autoPlay === null) { options.autoPlay = this.DEFAULT_OPTIONS.autoPlay; } if (typeof(options.volume) === \"undefined\" || options.volume === null) { options.volume = this.DEFAULT_OPTIONS.volume; } } //Sets the audio ID: this.id = CB_trim(audioId).toUpperCase(); //Sets the internal id: if (typeof(this._id_internal) === \"undefined\" || this._id_internal === null) { this._id_internal = CB_AudioFile_API[\"ACMP\"]._counter++; } //Sets the file path: this.filePath = filePath; //Proceeds according to the options sent: this.loop = options.loop; this.volume = options.volume; this.volumeBeforeMute = this.volume; if (options.autoLoad) { var that = this; setTimeout ( function() { that.load(that.filePath, options.autoPlay, callbackOk, callbackError); }, 10 ); } //Returns the object: return this; } /** * Destroys the audio file object and frees memory. Sets its current {@link CB_AudioFile_API.ACMP#status} property to ABORTED ({@link CB_AudioFile.ABORTED} value). * @function CB_AudioFile_API.ACMP#destructor * @param {boolean} [stopSound=false] - If set to true, it will also call the {@link CB_AudioFile_API.ACMP#stop} method. * @param {boolean} [keepStoppedUnaltered=false] - Used internally as the \"keepStoppedUnaltered\" parameter to call the {@link CB_AudioFile_API.ACMP#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. * @param {boolean} [avoidOnStop=false] - Used internally as the \"avoidOnStop\" parameter to call the {@link CB_AudioFile_API.ACMP#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. * @param {boolean} [forceOnStop=false] - Used internally as the \"forceOnStop\" parameter to call the {@link CB_AudioFile_API.ACMP#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. */ CB_AudioFile_API[\"ACMP\"].prototype.destructor = function(stopSound, keepStoppedUnaltered, avoidOnStop, forceOnStop) { try { if (typeof(this._mediaObjectSwap) !== \"undefined\" &amp;&amp; this._mediaObjectSwap !== null) { this._mediaObjectSwap.release(); CB_Elements.remove(this.mediaObject); } } catch(E) {} this._lastDuration = null; if (typeof(this.mediaObject) === \"undefined\" || this.mediaObject === null) { this.status = CB_AudioFile.ABORTED; return; } if (stopSound) { this.stop(keepStoppedUnaltered, avoidOnStop, forceOnStop); } try { this.mediaObject.release(); CB_Elements.remove(this.mediaObject); } catch(E) {} this.status = CB_AudioFile.ABORTED; } /** * Loads the desired audio file with the desired options. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. This method will be called automatically by the constructor if the \"autoLoad\" option was set to true in its given \"options\" parameter. * When this method is called, if the {@link CB_AudioFile_API.ACMP#status} property already has the \"LOADED\" status (defined in the {@link CB_AudioFile.LOADED} constant) and the \"forceReload\" parameter is not set to true, it will exit calling the given \"callbackOk\" function (if any) immediately. Otherwise, regardless the status, the status will be set to \"LOADING\" (defined in the {@link CB_AudioFile.LOADING} constant). After it, it will reach the \"UNCHECKED\" (defined in the {@link CB_AudioFile.UNCHECKED} constant). If the \"autoPlay\" parameter is not set to true, this will be the final status (and it will be necessary to call the {@link CB_AudioFile_API.ACMP#checkPlaying} method after it). After it and only if the \"autoPlay\" is set to true, as the {@link CB_AudioFile_API.ACMP#checkPlaying} method will be called internally, it will have the \"CHECKING\" status (defined in the {@link CB_AudioFile.CHECKING} constant) and finally the \"LOADED\" status (defined in the {@link CB_AudioFile.LOADED} constant) if all goes well. * @function CB_AudioFile_API.ACMP#load * @param {string} [filePath={@link CB_AudioFile_API.ACMP#filePath}] - The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @param {string} [autoPlay=false] - If set to true, it will start playing the audio automatically (by calling the {@link CB_AudioFile_API.ACMP#play} method internally). If set to true and the {@link CB_AudioFile_API.ACMP#status} property reaches to the \"UNCHECKED\" status (defined in the {@link CB_AudioFile.UNCHECKED} constant), it will also call internally the {@link CB_AudioFile_API.ACMP#checkPlaying} method. * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the {@link CB_AudioFile_API.ACMP} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.ACMP} object itself. * @param {boolean} [forceReload=false] - If set to false, the \"filePath\" has not been changed from the previously used and the {@link CB_AudioFile_API.ACMP#status} property belongs to the \"LOADED\" status (defined in the {@link CB_AudioFile.LOADED} constant), it will exit the method without loading the audio file again (calling the \"callbackOk\" function, if any). * @returns {CB_AudioFile_API.ACMP|null} Returns the audio API object (if it was possible to create) or null otherwise. */ CB_AudioFile_API[\"ACMP\"].prototype.load = function(filePath, autoPlay, callbackOk, callbackError, forceReload) { clearTimeout(this._checkDurationTimeout); clearTimeout(this._checkPlayingTimeout); clearTimeout(this._checkPlayingFinishingTimeout); filePath = filePath || this.filePath; //If the status is LOADED and the file path give is the same as the current one, just exits: if (!forceReload &amp;&amp; this.status === CB_AudioFile.LOADED &amp;&amp; this.filePath === filePath) { if (typeof(callbackOk) === \"function\") { callbackOk.call(this); } return this; } //Destroys previous object (if any): this.destructor(true, false, true); //Also stops the sound (if any) and prevents firing onStop. this.status = CB_AudioFile.LOADING; //The file is loading. this.filePath = filePath; var that = this; var anyCallbackFunctionCalled = false; this._swapChecked = false; this.position = this._positionSwap = 0; var callbackFunctionError = function(error) { if (that.status === CB_AudioFile.ABORTED) { return; } //If it is has been aborted, we exit. //If the success function has been called already (sound is loaded), ignores the fail: if (anyCallbackFunctionCalled) { return; } anyCallbackFunctionCalled = true; that.status = CB_AudioFile.FAILED; //File failed to load. autoPlay = false; //var fileName = filePath; if (filePath.substring(0, 5).toLowerCase() === \"data:\") { filePath = filePath.substring(0, 15) + \"[...]\" + filePath.substring(filePath.length - 2); } if (!CB_isString(error) &amp;&amp; typeof(error) !== \"undefined\" &amp;&amp; (typeof(error.message) !== \"undefined\" || typeof(error.code) !== \"undefined\")) { error = \"Error for \" + filePath + \" file: \" + error.message + \" [code: \" + error.code + \"]\"; } else { error = \"Error for \" + filePath + \" file: \" + error; } try { if (typeof(that.mediaObject) !== \"undefined\" &amp;&amp; that.mediaObject !== null) { that.mediaObject.release(); } if (typeof(that._mediaObjectSwap) !== \"undefined\" &amp;&amp; that._mediaObjectSwap !== null) { that._mediaObjectSwap.release(); } } catch(E) {} if (typeof(callbackError) === \"function\") { callbackError.call(that, error); } //Calls the Error function back. }; try { var timesChecked = 0; var callbackFunctionSuccess = function() { if (that.status === CB_AudioFile.ABORTED) { return; } //If it is has been aborted, we exit. //If the success function has been called already (sound is loaded), exits: if (anyCallbackFunctionCalled) { return; } //Success callback is called all the time the file plays successfully in ACMP, so we need to call callbackOk just once: if (that.status !== CB_AudioFile.LOADED) { //Checks for the duration and fails after some attempts: if (that.getDuration() === 0) { if (++timesChecked &lt; 1000) { that._checkDurationTimeout = setTimeout(callbackFunctionSuccess, 1); } else { callbackFunctionError(\"Duration is zero\"); } return; } anyCallbackFunctionCalled = true; //Function to execute when all is OK: var allIsFine = function() { if (that.status === CB_AudioFile.ABORTED) { return; } //If it is has been aborted, we exit. //Restores the volume: that.setVolume(previousVolume); var checkSwapFinished = function() { if (typeof(callbackOk) === \"function\") { callbackOk.call(that); } //Calls the OK function back. //Plays automatically if we want to: if (autoPlay) { that.play(); } }; //Function that checks swap object: var checkSwapObject = function() { //If the swap object has been created successfully: if (that._mediaObjectSwap !== null &amp;&amp; !that._swapChecked) { var updatePositionSwap = function() { var callAgain = true; if (!that._swapChecked &amp;&amp; typeof(that._mediaObjectSwap) !== \"undefined\" &amp;&amp; that._mediaObjectSwap !== null) { that._mediaObjectSwap.getCurrentPosition ( function(positionSwap) { that._positionSwap = positionSwap; if (isNaN(that._positionSwap) || that._positionSwap &lt; 0) { that._positionSwap = 0; } } ); setTimeout(updatePositionSwap, 1); } else { that._positionSwap = 0; } }; updatePositionSwap(); that.checkPlaying(checkSwapFinished, function() { that._mediaObjectSwap = null; checkSwapFinished(); }, false, false, false, true); } }; //Creates the second mediaObject for swapping: var swapFunctionCalled = false; that._mediaObjectSwap = new Media ( filePath, function() { if (swapFunctionCalled) { return; } swapFunctionCalled = true; //Checks the swap object: checkSwapObject(); }, function() { if (swapFunctionCalled) { return; } swapFunctionCalled = true; try { if (typeof(that._mediaObjectSwap) !== \"undefined\" &amp;&amp; that._mediaObjectSwap !== null) { that._mediaObjectSwap.release(); } } catch(E) {} that._mediaObjectSwap = null; } ); that._mediaObjectSwap.play(); //Needs to be played to fire events. that._mediaObjectSwap.stop(); }; that.status = CB_AudioFile.UNCHECKED; //The file is still unchecked. //If we want to play automatically, checks if the currentTime changes (some web clients cannot play if the user did not fire an event to call the play function): if (autoPlay) { that.checkPlaying(function() { allIsFine(); }, function(error) { callbackFunctionError(error, true); }, false, false, false); } else { allIsFine(); } } }; if (typeof(Media) === \"undefined\") { callbackFunctionError(\"Apache Cordova Media plugin not found\"); return null; } this.mediaObject = new Media(filePath, callbackFunctionSuccess, callbackFunctionError); var previousVolume = this.volume; if (CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING) { this.setVolume(0); } //Media object needs to be played to fire events, so we call play method and stop it immediately: this.mediaObject.play(); //this.mediaObject.seekTo(0); this.mediaObject.stop(); //Starts the interval that will update the position all the time: if (!this._updatePositionLoopExecuted) { this._updatePositionLoopExecuted = true; var updatePosition = function() { if (typeof(that.mediaObject) !== \"undefined\" &amp;&amp; that.mediaObject !== null) { that.mediaObject.getCurrentPosition ( function(position) { that.position = position; if (isNaN(that.position) || that.position &lt; 0) { that.position = 0; } } ); } else { that.position = 0; } setTimeout(updatePosition, 1); }; updatePosition(); } } catch(E) { callbackFunctionError(E); return null; } return this; } /** * Checks whether the audio can be played or not. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. Also recommended to use before calling the {@link CB_AudioFile_API.ACMP#play} method the first time. The checking action will only be performed if the value of the {@link CB_AudioFile_API.ACMP#status} property belongs to the {@link CB_AudioFile.UNCHECKED} or to the {@link CB_AudioFile.CHECKING} value. After checking, if the audio can be played, the {@link CB_AudioFile_API.ACMP#status} of the object will get the value of {@link CB_AudioFile.LOADED}. Otherwise, if it cannot be played, the {@link CB_AudioFile_API.ACMP#status} property will get the value of {CB_AudioFile.FAILED}. * @function CB_AudioFile_API.ACMP#checkPlaying * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been checked successfully, being \"this\" the {@link CB_AudioFile_API.ACMP} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been checked successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.ACMP} object itself. * @param {boolean} [ignoreStatus=false] - If set to false and the {@link CB_AudioFile_API.ACMP#status} property does not belong neither to the \"UNCHECKED\" status (defined in the {@link CB_AudioFile.UNCHECKED} constant) nor to the \"CHECKING\" status (defined in the {@link CB_AudioFile.CHECKING} constant), it will fail calling the \"callbackError\" function (if any). If set to true, it will try to perform the checking action regardless the status of the audio. * @param {boolean} [ignoreQueue=false] - This parameter will be ignored in this audio API. * @param {boolean} [useCache=false] - This parameter will be ignored in this audio API. * @param {boolean} [isSwapObject=false] - Defines whether the [Media]{@link https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-media/} object to check is a swap object or the normal one (a swap object is stored internally as it is necessary due ACMP issues when looping a sprite near the end of the audio file). Internal usage only recommended. * @returns {boolean} Returns false if the checking could not be performed and failed. If it returns true, it can mean either the checking has been processed successfully or it will fail in the future, so it is recommended to ignore the returning value and use the callback functions instead. */ CB_AudioFile_API[\"ACMP\"].prototype.checkPlaying = function(callbackOk, callbackError, ignoreStatus, ignoreQueue, useCache, isSwapObject) { /////clearTimeout(this._recursiveCallCheckingTimeout); if (!ignoreStatus &amp;&amp; this.status !== CB_AudioFile.UNCHECKED &amp;&amp; this.status !== CB_AudioFile.CHECKING) { if (typeof(callbackError) === \"function\") { callbackError.call(this, \"Cannot check if status is not unchecked or checking (status is \" + this.status + \")\"); } return false; } var that = this; var mediaObject = this.mediaObject; if (isSwapObject) { mediaObject = this._mediaObjectSwap; } else { this.status = CB_AudioFile.CHECKING; } var previousVolume = this.volume; var finishedChecking = function(ok, error, keepStatus) { if (isSwapObject) { that._swapChecked = true; } //Stops the file: mediaObject.pause(); //Restores the volume: that._checkPlayingFinishingTimeout = //Timeout to prevent hearing the sound in some web clients. setTimeout ( function() { that.setVolume(previousVolume, false, null, false, isSwapObject ? that._mediaObjectSwap : null); //If the file is ok: if (ok) { if (!keepStatus &amp;&amp; !isSwapObject) { that.status = CB_AudioFile.LOADED; } if (typeof(callbackOk) === \"function\") { callbackOk.call(that); } } //...otherwise, if the file has failed: else { if (!keepStatus &amp;&amp; !isSwapObject) { that.status = CB_AudioFile.FAILED; } if (typeof(callbackError) === \"function\") { callbackError.call(that, error); } } }, 10 ); }; try { //Plays the sound during some time to let some web clients get the duration correctly (strange bug): if (CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING) { this.setVolume(0, false, null, false, isSwapObject ? this._mediaObjectSwap : null); } mediaObject.play(); var durationDetected = this.getDuration(isSwapObject ? this._mediaObjectSwap : null); var timesCurrentTimeChecked = 0; clearTimeout(this._checkPlayingTimeout); clearTimeout(this._checkPlayingFinishingTimeout); var checkFunction = function(callbackOk, callbackError) { clearTimeout(that._checkPlayingTimeout); //If it is has been aborted, we exit: if (that.status === CB_AudioFile.ABORTED || that.status === CB_AudioFile.FAILED) { finishedChecking(false, \"Audio file object is \" + (that.status === CB_AudioFile.ABORTED ? \"ABORTED\" : \"FAILED\") + \".\", true); return; } try { if (!isSwapObject) { that.status = CB_AudioFile.CHECKING; } //If the duration has changed, it calls the function again because it means the audio is still loading (otherwise, Firefox has issues with data URIs and detects a shorter duration): var durationDetectedNow = that.getDuration(isSwapObject ? that._mediaObjectSwap : null); if (durationDetected !== durationDetectedNow) { durationDetected = durationDetectedNow; that._checkPlayingTimeout = setTimeout(function() { checkFunction(callbackOk, callbackError); }, CB_Configuration[CB_BASE_NAME].CB_AudioFile_AUTOPLAY_SILENTLY_ON_LOAD_MS); return; } //If the current time is still 0: if (!isSwapObject &amp;&amp; that.position == 0 || isSwapObject &amp;&amp; that._positionSwap == 0) { //We give it some opportunities more to change current time: if (timesCurrentTimeChecked &lt; 100) { timesCurrentTimeChecked++; if (timesCurrentTimeChecked % 20 === 0) { mediaObject.pause(); mediaObject.play(); try { mediaObject.seekTo(0); } catch(E) {} //Executed after play method because otherwise Intel XDK emulator and Android WebView kit does not perform seekTo. } that._checkPlayingTimeout = setTimeout(function() { checkFunction(callbackOk, callbackError); }, 1); return; } //...if all opportunities failed, we declare it as FAILED and exits: else { finishedChecking(false, \"position does not change (it is \" + (isSwapObject ? that._positionSwap : that.position) + \").\"); return; } } //Only updates the currentTime to 0 if it is not zero already (because otherwise some web clients will fail or have a wrong behaviour): if (!isSwapObject &amp;&amp; that.position != 0 || isSwapObject &amp;&amp; that._positionSwap != 0) { mediaObject.seekTo(0); } //If the duration is zero, we declare it as FAILED and exits: if (that.getDuration(isSwapObject ? that._mediaObjectSwap : null) === 0) { finishedChecking(false, \"Duration is zero\"); return; } finishedChecking(true); } catch(E) { finishedChecking(false, E); } }; checkFunction(callbackOk, callbackError); return true; } catch(E) { finishedChecking(false, E); return false; } } /** * Tells the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. * @function CB_AudioFile_API.ACMP#getDuration * @param {Object} [mediaObject={@link CB_AudioFile_API.ACMP#mediaObject}] - [Media]{@link https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-media/} object whose audio duration we want to check. Used internally to check either normal or swap [Media]{@link https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-media/} object (a swap object is stored internally as it is necessary due ACMP issues when looping a sprite near the end of the audio file). Internal usage only recommended. * @returns {number} Returns the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. */ CB_AudioFile_API[\"ACMP\"].prototype.getDuration = function(mediaObject) { var duration; if (typeof(mediaObject) === \"undefined\" || mediaObject === null) { mediaObject = this.mediaObject; } if (typeof(mediaObject) !== \"undefined\" &amp;&amp; mediaObject !== null &amp;&amp; typeof(mediaObject.getDuration) !== \"undefined\" &amp;&amp; mediaObject.getDuration !== null) { duration = mediaObject.getDuration() * 1000; } if (typeof(duration) === \"undefined\" || duration === null || isNaN(duration) || duration &lt; 0) { duration = 0; } return duration; } /** * Plays the audio. * @function CB_AudioFile_API.ACMP#play * @param {number} [startAt=0 | {@link CB_AudioFile_API.ACMP#lastStartAt} | stopAt] - Time in milliseconds where we want the audio to start at. If not provided or it is not a valid number, it will use zero (0) as default which belongs to the beginning of the audio. If the value provided is greater than the \"stopAt\" provided, it will use the value set in the {@link CB_AudioFile_API.ACMP#lastStartAt} property (which belongs to the \"startAt\" value the last time that this method was called). If, even using the {@link CB_AudioFile_API.ACMP#lastStartAt} value is still greather than the \"stopAt\" provided, it will use the same value as the \"stopAt\" which means it will not play and will stop immediately. * @param {number} [stopAt={@link CB_AudioFile_API.ACMP#getDuration}()] - Time in milliseconds where we want the audio to stop at. If not provided or it is not a valid number, it will use the returning value of the {@link CB_AudioFile_API.ACMP#getDuration} method (which should belong to the total duration of the audio, if it was calculated correctly). * @param {boolean} [loop={@link CB_AudioFile_API.ACMP#loop}] - Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the {@link CB_AudioFile_API.ACMP#onStop} method) will not be called. * @param {boolean} [avoidDelayedPlay=false] - If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the \"stop\" method will be called immediately. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the {@link CB_AudioFile_API.ACMP#stop} method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). * @param {function} [onPlayStart] - Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the {@link CB_AudioFile_API.ACMP} object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. * @param {function} [onLoadError] - Function to be called if the audio cannot be played successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.ACMP} object. * @param {boolean} [isResume=false] - If set to true (not recommended) and it is a looping audio, the next loop will use the value of the {@link CB_AudioFile_API.ACMP#lastStartAt} property as the \"startAt\" parameter when it calls this method again automatically (internally). Recommended for internal usage only. * @param {boolean} [isLooping=false] - Used to determine whether this method was called automatically again by itself because it is looping the audio. Recommended for internal usage only. * @param {integer} [startPlayingTime] - Contains the time when the audio should start playing. Recommended for internal usage only. * @returns {boolean|integer} It returns false if the duration is 0 (\"startAt\" and \"stopAt\" are the same number), returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. */ CB_AudioFile_API[\"ACMP\"].prototype.play = function(startAt, stopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, isResume, isLooping, startPlayingTime) { var that = this; var duration = this.getDuration(); if (typeof(startPlayingTime) === \"undefined\" || startPlayingTime === null) { startPlayingTime = CB_Device.getTiming(); } //If the sound is not ready yet, calls the function again but later: /*if (this.status !== CB_AudioFile.LOADED || this.getDuration() === 0) //Duration must be greater than zero. { this.stopped = true; this.paused = false; //If it has not failed or aborted, calls the function again but later: if (this.status !== CB_AudioFile.FAILED &amp;&amp; this.status !== CB_AudioFile.ABORTED) { setTimeout(function() { that.play(startAt, stopAt, loop, allowOverlapping, avoidDelayedPlay, onLoadError, isResume, isLooping); }, 1); } //...otherwise, if it has failed, sets it as stopped: //else { this.stopped = true; } return -1; }*/ if (this.status !== CB_AudioFile.LOADED || duration === 0) //Duration must be greater than zero. { this.stopped = true; this.paused = false; //If it has not failed or aborted: if (this.status !== CB_AudioFile.FAILED &amp;&amp; this.status !== CB_AudioFile.ABORTED) //It must be UNLOADED, LOADING, LOADED, UNCHECKED or CHECKING. { //Function that calls the play method recursively (unless the maximum time allowed has expired): var playLaterFunctionCalled = false; var playLaterFunction = function() { if (playLaterFunctionCalled) { return; } playLaterFunctionCalled = true; //If the recursive delay is not null and is a valid number: if (typeof(allowedRecursiveDelay) === \"undefined\" || allowedRecursiveDelay === null || isNaN(allowedRecursiveDelay) || allowedRecursiveDelay &lt; 0) { allowedRecursiveDelay = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT; //We use default value. } var timeNow = CB_Device.getTiming(); //If the time expired is less or equal to the delay allowed: if (timeNow - startPlayingTime &lt;= allowedRecursiveDelay) { //Calls play method again: that.play(startAt, stopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, isResume, isLooping, startPlayingTime); } //...otherwise, just stops the sound: //////else { that.stop(false, false); } //Sets as stopped and fires onStop function (if any). else { that.stop(false, false, true); } //Sets as stopped and fires onStop function (if any). }; //Function to execute when the sound loads successfully: var onLoad = function() { //If we allow delayed play, plays the sound: if (!avoidDelayedPlay) { playLaterFunction(); } //...otherwise, just stops the sound (to fire onStop function): ///////else { that.stop(false, false); } //Sets as stopped and fires onStop function (if any). else { that.stop(false, false, true); } //Sets as stopped and fires onStop function (if any). }; //If it is UNLOADED or we had a duration before but not now and it is not LOADING, loads the file again: if (this.status === CB_AudioFile.UNLOADED || this.status !== CB_AudioFile.LOADING &amp;&amp; this._lastDuration !== null &amp;&amp; duration === 0) { this.load(this.filePath, false, onLoad, onLoadError, true); } //...otherwise, if it is UNCHECKED, we call the checking function: else if (this.status === CB_AudioFile.UNCHECKED) { this.checkPlaying(onLoad, onLoadError, false, true, false); } //...otherwise, if it is not CHECKING (it must be LOADING or LOADED with duration 0 from the beginning), we will not reload the sound: else if (this.status !== CB_AudioFile.CHECKING) { //If we allow delayed play, calls the play method again but after some time: if (!avoidDelayedPlay) { setTimeout(playLaterFunction, 1); } //...otherwise, just stops the sound (to fire onStop function): ///////else { this.stop(false, false); } //Sets as stopped and fires onStop function (if any). else { this.stop(false, false, true); } //Sets as stopped and fires onStop function (if any). } } return -1; } this._lastDuration = duration; //Defines the default parameters: if (CB_trim(startAt) === \"\") { startAt = 0; } //Starts at the beginning as default. if (CB_trim(stopAt) === \"\") { stopAt = 0; } //If it is not a number, default is zero. if (typeof(loop) === \"undefined\" || loop === null) { loop = this.loop; } //If not set, uses the default (or last one used). else { this.loop = loop; } //...otherwise, stores the new setting given. //Sanitizes startAt and stopAt: startAt = parseFloat(startAt); stopAt = parseFloat(stopAt); if (startAt &lt; 0) { startAt = 0; } if (stopAt &lt;= 0 || stopAt &gt; duration) { stopAt = duration; } //If the stopAt is not correct, plays until the end of the file. if (startAt &gt; stopAt) { startAt = this.lastStartAt; } //In the case start time is than stop time, starts as the previous time. if (startAt &gt; stopAt || isNaN(startAt)) { startAt = stopAt; } //If the duration is zero (startAt and stopAt are equal), exits: if (startAt === stopAt) { this.stop(); return false; } //Next loop (if any) it will start at the same time by default: var startAtNextLoop = startAt; //If it is a resume, next loop we should start from the previous startAt used: if (isResume) { startAtNextLoop = this.lastStartAt; } //...otherwise, if it is not a resume, stores the startAt used: else { this.lastStartAt = startAt; } this.lastStopAt = stopAt; //Stores stopAt used. //Adds the event to check when the file reaches the stop time: var whenStopFunction = function() { //Removes the event and timeout: clearTimeout(that._timeoutWhenStop); //Clears the previous timeout. //If the sound has been stopped or paused or the stop time has changed, exits: if (that.stopped || that.paused || that.lastStopAt !== stopAt) { return; } //...otherwise, if the stop time has not been reached yet, calls the function again after a while: //else if (that.getCurrentTime() &lt; stopAt) { setTimeout(whenStopFunction, 1); return; } //If we want to loop, loops again: if (that.loop) { if (that._mediaObjectSwap !== null &amp;&amp; that._swapChecked) { var temp = that.mediaObject; that.stop(true, true); that.mediaObject = that._mediaObjectSwap; that._mediaObjectSwap = temp; } //that.stop(true); //Stops the sound without setting its property as stopped. that.play(startAtNextLoop, stopAt, true, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, false, true); //Plays again the sound. } //...otherwise, if we don't want to loop, we stop: else { that.stop(); } }; //Clears the previous timeout (if any): clearTimeout(this._timeoutWhenStop); //If it is looping or does not allow overlapping and it is not paused, stops the possible previous sound: //if (isLooping || !allowOverlapping &amp;&amp; !this.paused) { this.stop(true); } //Stops the sound without setting its property as stopped. //if (isLooping || !allowOverlapping) { this.stop(true); } //Stops the sound without setting its property as stopped. //Stop because otherwise Android with WebView takes long time to perform play again if stopAt is near the total duration (so next loop would take long time to start): this.stop(true, true); //Stops the sound without setting its property as stopped. //If defined, starts at the given position (ms): ////this.mediaObject.seekTo(startAt); //Applies the current volume: this.setVolume(this.volume); //If it is not a loop (it is the first call to the play method) or we do not want to loop: if (!isLooping || !loop) { CB_symmetricCallClear(\"ACMP_AUDIO_FILE\" + this._id_internal); } //We clean the cache of setTimeoutSynchronized for the loop function. //Plays the file: //this.mediaObject.play({ numberOfLoops: 9999999999 }); //We will use our own way to loop, so we don't need the normal way. this.mediaObject.play(); //We will use our own way to loop, so we don't need the normal way. this.mediaObject.seekTo(startAt); //Executed after play method because otherwise Intel XDK emulator and Android WebView kit does not perform seekTo. //Sets the event and timeout for when the sound finishes: var msToFinish = stopAt - startAt; this._timeoutWhenStop = CB_symmetricCall(whenStopFunction, msToFinish, \"ACMP_AUDIO_FILE\" + this._id_internal); //The sound is neither paused nor stopped: this.paused = this.stopped = false; //If it is the first time (not a loop) and there is a function to call when the play starts, we call it: if (!isLooping &amp;&amp; typeof(onPlayStart) === \"function\") { onPlayStart.call(this, startAt, stopAt, startAtNextLoop, loop, avoidDelayedPlay, allowedRecursiveDelay, startPlayingTime); onPlayStart = null; } //Prevents execution again. return true; } /** * Resumes the audio (after being paused), starting from the same point it was paused previously. * @function CB_AudioFile_API.ACMP#resume * @param {boolean} [loop={@link CB_AudioFile_API.ACMP#loop}] - Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the {@link CB_AudioFile_API.ACMP#onStop} method) will not be called. * @param {boolean} [avoidDelayedPlay=false] - If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the {@link CB_AudioFile_API.ACMP#stop} method will be called immediately. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the {@link CB_AudioFile_API.ACMP#stop} method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). * @param {function} [onPlayStart] - Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the {@link CB_AudioFile_API.ACMP} object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. * @param {function} [onLoadError] - Function to be called if the audio cannot be played successfully. It will not be called if the audio is not paused or is stopped. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.ACMP} object. * @returns {boolean|integer} Returns the returning value of the {@link CB_AudioFile_API.ACMP#play} method which is called internally. It returns false if the audio is not paused or it is stopped, returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. */ CB_AudioFile_API[\"ACMP\"].prototype.resume = function(loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError) { //If it not paused or it is stopped, exits the function: if (!this.paused || this.stopped) { return false; } //this._resuming = true; var startAt = this.pauseTime; //If it has been paused after the stop time (happens sometimes when the sound was nearly to finish): if (startAt &gt;= this.lastStopAt) { startAt = this.lastStopAt - 1; //We will begin just 1 millisecond before (otherwise the play method would begin again from lastStartAt). } return this.play(startAt, this.lastStopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, true, false); } /** * Pauses the audio when it is being played. * @function CB_AudioFile_API.ACMP#pause * @param {function} [onPause] - Function without parameters to be called when the audio is paused successfully, being \"this\" the {@link CB_AudioFile_API.ACMP} object. * @param {boolean} [keepPausedUnaltered=false] - If set to true (not recommended), the {@link CB_AudioFile_API.ACMP#paused} property will not be set to true and it will remain with its current value. * @returns {boolean} It returns false if the audio is already paused or it is stopped or if it cannot be paused. Returns true otherwise. */ CB_AudioFile_API[\"ACMP\"].prototype.pause = function(onPause, keepPausedUnaltered) { //If it already paused or stopped, exits the function: if (this.paused || this.stopped) { return false; } //this._resuming = false; if (typeof(this.mediaObject) !== \"undefined\" &amp;&amp; this.mediaObject !== null) { clearTimeout(this._timeoutWhenStop); //Prevents that the file is set as stopped or to be executed again. this.mediaObject.pause(); this.pauseTime = this.getCurrentTime(); if (!keepPausedUnaltered) { this.paused = true; } if (typeof(onPause) === \"function\") { onPause.call(this); } return true; } return false; } /** * Stops the audio. * @function CB_AudioFile_API.ACMP#stop * @param {boolean} [keepStoppedUnaltered=false] - If set to true (not recommended), the {@link CB_AudioFile_API.ACMP#stopped} property will not be set to true and it will remain with its current value. * @param {boolean} [avoidOnStop=false] - If set to false and there is an \"onStop\" function defined (through the {@link CB_AudioFile_API.ACMP#onStop} method), it will be called after stopping the audio (or after trying to do it, at least) but only if either the \"forceOnStop\" parameter is set to true or if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. If set to true, the \"onStop\" function (if any) will not be called at all. * @param {boolean} [forceOnStop=false] - If it is set to true and the \"avoidOnStop\" parameter is set to false and there is an \"onStop\" function defined (through the {@link CB_AudioFile_API.ACMP#onStop} method), it will be called regardless the audio was stopped before or not. If set to false, the \"onStop\" function (if any) will only be called if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. This parameter will be ignored if the \"avoidOnStop\" parameter is set to true. * @returns {boolean} It returns false if the stopping action cannot be performed at all (this could happen when the audio has not been loaded properly, for example). Returns true otherwise (this only means that it has been tried to be stopped but it could not be successfully). */ CB_AudioFile_API[\"ACMP\"].prototype.stop = function(keepStoppedUnaltered, avoidOnStop, forceOnStop) { if (typeof(this.mediaObject) !== \"undefined\" &amp;&amp; this.mediaObject !== null) { ///////clearTimeout(this._timeoutWhenStop); //Prevents that the file is set as stopped or to be executed again. this.mediaObject.seekTo(0); this.mediaObject.stop(); var stoppedBefore = this.stopped; if (!keepStoppedUnaltered) { this.stopped = true; } this.paused = false; //If it is stopped, it is not paused. //If we do not want to avoid onStop, it was not stopped before but it is now and onStop has a valid function assigned, we execute it: if (!avoidOnStop &amp;&amp; (!stoppedBefore &amp;&amp; this.stopped || forceOnStop) &amp;&amp; typeof(this.onStopFunction) === \"function\") { this.onStopFunction.call(this); } return true; } return false; } /** * Sets the desired volume for the audio file (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). * @function CB_AudioFile_API.ACMP#setVolume * @param {number} [volume={@link CB_Speaker.getVolume()} | {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME}] - Desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). * @param {boolean} [forceSetVolumeProperty=false] - If set to true (not recommended), it will change the {@link CB_AudioFile_API.ACMP#volume} property even when the volume failed to be changed. * @param {function} [onSetVolume] - Callback function which will be called if it has been possible to set the volume (or at least it was possible to try it). It will not receive any parameters, being \"this\" the {@link CB_AudioFile_API.ACMP} object. * @param {boolean} [saveForUnmute=false] - If set to true (not recommended), it will save internally the current volume before setting it so it will restore the same volume again after calling the {@link CB_AudioFile_API.ACMP#unmute} method. Internal usage only recommended. * @param {Object} [mediaObject={@link CB_AudioFile_API.ACMP#mediaObject}] - [Media]{@link https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-media/} object whose volume we want to set. Used internally to affect either normal or swap [Media]{@link https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-media/} object (a swap object is stored internally as it is necessary due ACMP issues when looping a sprite near the end of the audio file). Internal usage only recommended. * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). */ CB_AudioFile_API[\"ACMP\"].prototype.setVolume = function(volume, forceSetVolumeProperty, onSetVolume, saveForUnmute, mediaObject) { //Defines the default parameters: volume = parseInt(volume); if (isNaN(volume)) { this.DEFAULT_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration[CB_BASE_NAME].CB_Speaker_DEFAULT_VOLUME; volume = this.DEFAULT_VOLUME; } //Sets the volume within their limits if it is beyond them: var MAX_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM ? CB_Speaker.getVolume() : 100; if (volume &gt; MAX_VOLUME) { volume = MAX_VOLUME; } else if (volume &lt; 0) { volume = 0; } var originalObject = false; if (typeof(mediaObject) === \"undefined\" || mediaObject === null) { mediaObject = this.mediaObject; originalObject = true; } if (typeof(mediaObject) !== \"undefined\" &amp;&amp; mediaObject !== null) { mediaObject.setVolume(volume / 100); if (originalObject) { if ((saveForUnmute || volume === 0) &amp;&amp; this.volume &gt; 0) { this.volumeBeforeMute = this.volume; } //Also saves the previous volume if the desired one is zero (muted). this.volume = volume; if (typeof(onSetVolume) === \"function\") { onSetVolume.call(this); } } } if (forceSetVolumeProperty) { this.volume = volume; } return this.volume; } /** * Mutes the audio file. * @function CB_AudioFile_API.ACMP#mute * @param {function} [onMute] - Callback function which will be called if it has been possible to mute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the {@link CB_AudioFile_API.ACMP} object. * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). If all goes well, the returning value should be zero (0). Note that, even when it returns a zero (0) value, this does not always mean that the mute has been applied successfully. */ CB_AudioFile_API[\"ACMP\"].prototype.mute = function(onMute) { //Only mutes the sound if it is not muted already: if (this.volume &gt; 0) { //Mutes the audio: this.setVolume(0, false, onMute, true); //It modifies this.volumeBeforeMute. } return this.volume; } /** * Restores audio after muting it (unmutes it). * @function CB_AudioFile_API.ACMP#unmute * @param {function} [onUnmute] - Callback function which will be called if it has been possible to unmute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the {@link CB_AudioFile_API.ACMP} object. * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). */ CB_AudioFile_API[\"ACMP\"].prototype.unmute = function(onUnmute) { //Only unmutes if it is still muted: if (this.volume === 0) { //Restores the volume before muting: this.setVolume(this.volumeBeforeMute, false, onUnmute); } return this.volume; } /** * Gets the current time (in milliseconds) which belongs to the position where the audio is currently playing or where it has been paused. Note that some audio APIs and clients could give wrong values. * @function CB_AudioFile_API.ACMP#getCurrentTime * @returns {number} Returns the current time (in milliseconds). Note that some audio APIs and clients could give wrong values. */ CB_AudioFile_API[\"ACMP\"].prototype.getCurrentTime = function() { var currentTime; /* if (typeof(this.mediaObject) !== \"undefined\" &amp;&amp; this.mediaObject !== null) { currentTime = this.mediaObject.position * 1000; } */ currentTime = this.position * 1000; if (typeof(currentTime) === \"undefined\" || currentTime === null || isNaN(currentTime) || currentTime &lt; 0) { currentTime = 0; } return currentTime; } /** * Sets a function to execute when the audio file stops playing or removes it. * @function CB_AudioFile_API.ACMP#onStop * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. No parameters will be received, being \"this\" the {@link CB_AudioFile_API.ACMP} object. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @returns {boolean} Returns whether the event has been set or not (removed). */ CB_AudioFile_API[\"ACMP\"].prototype.onStop = function(callbackFunction, keepOldFunction) { //If not set, it keeps old function by default: if (typeof(keepOldFunction) === \"undefined\" || keepOldFunction === null) { keepOldFunction = true; } if (typeof(callbackFunction) !== \"function\") { this.onStopFunction = null; return false; } //If we don't want to keep the old function: if (!keepOldFunction) { this.onStopFunction = callbackFunction; } //...otherwise if we want to keep the old function, we keep it: else { var that = this; //Stores old function: var oldFunction = this.onStopFunction; //Stores old function of eventFunctionHolder. this.onStopFunction = function() { if (typeof(oldFunction) === \"function\") { oldFunction.call(that); } callbackFunction.call(that); }; } return true; } /** * Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. * @function CB_AudioFile_API.ACMP#getProgress * @returns {number} Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. */ CB_AudioFile_API[\"ACMP\"].prototype.getProgress = function() { if (this.status === CB_AudioFile.LOADED || this.status === CB_AudioFile.UNCHECKED || this.status === CB_AudioFile.CHECKING) { return 100; } else if (this.status === CB_AudioFile.UNLOADED) { return 0; } var progress = 0; //Calculates the progress (only if it is LOADING, FAILED or ABORTED): //TODO: use onProgress method from Apache Cordova Media Plugin when it is finally available (it is not usable yet). return progress; } × Search results Close "},"CrossBase_audiovisual_audio_CB_AudioFile_API_SM2.js.html":{"id":"CrossBase_audiovisual_audio_CB_AudioFile_API_SM2.js.html","title":"Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js /** * @file Audio files management using \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}). Contains the {@link CB_AudioFile_API.SM2} class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ //We need a limit to prevent Firefox error (\"Media resource [URI] could not be decoded\") since many calls to play() method would fail: if (typeof(CB_AudioFile_API_AAPI_SM2_beingLoading) === \"undefined\") { var CB_AudioFile_API_AAPI_SM2_beingLoading = 0; } //Counts how many objects are loading. if (typeof(CB_AudioFile_API_AAPI_SM2_maximumLoading) === \"undefined\") { var CB_AudioFile_API_AAPI_SM2_maximumLoading = 5; } //Maximum of objects that can be loading at the same time. if (typeof(CB_AudioFile_API_AAPI_SM2_beingChecking) === \"undefined\") { var CB_AudioFile_API_AAPI_SM2_beingChecking = 0; } //Counts how many objects are loading. if (typeof(CB_AudioFile_API_AAPI_SM2_maximumChecking) === \"undefined\") { var CB_AudioFile_API_AAPI_SM2_maximumChecking = CB_AudioFile_API_AAPI_SM2_maximumLoading; } //Maximum of objects that can be loading at the same time. //Class to manage an audio file with SM2 (SoundManager 2): if (typeof(CB_AudioFile_API) === \"undefined\") { var CB_AudioFile_API = {}; } /** * The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.) if the \"autoPlay\" option is set to true, as some web clients may need this at least the first time in order to be able to play the audio. * @class CB_AudioFile_API.SM2 * @memberof! &lt;global&gt; * @classdesc Class to manage an audio file using \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}). Used by the {@link CB_AudioFile} class internally and it shares most of its properties and methods. Recommended for internal usage only. * @param {string} filePath - The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @param {string} [audioId='CB_AUDIOFILE_SM2_' + CB_AudioFile_API.SM2._idUnique++] - Desired identifier for the audio object. If not provided, an automatic unique ID will be calculated. Note that it is not case sensitive and it should be unique for each object. * @param {CB_AudioFile_API.SM2.OPTIONS} [options=CB_AudioFile_API.SM2#DEFAULT_OPTIONS] - Object with the desired options. * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the {@link CB_AudioFile_API.SM2} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if could be determined), being \"this\" the {@link CB_AudioFile_API.SM2} object itself. * @returns {CB_AudioFile_API.SM2} Returns a new {@link CB_AudioFile_API.SM2} object. * @todo Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). Note that the \"id\" is not case sensitive and it should be unique for each object. * @todo Method getCopy and static method filterProperties (similar to the ones from {@link CB_GraphicSprites} and {@link CB_GraphicSpritesScene}). */ CB_AudioFile_API[\"SM2\"] = function(filePath, audioId, options, callbackOk, callbackError) { //Creates an instance of this object and returns it in the case that it is being called from an unexpected context: if (this === window || !(this instanceof CB_AudioFile_API[\"SM2\"])) { return new CB_AudioFile_API[\"SM2\"](filePath, audioId, options, callbackOk, callbackError); } //Constants: /** * Keeps the default volume. If the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT} property is true, this will keep the result of calling the {@link CB_Speaker.getVolume} function. Otherwise, it will use the value of the {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME} variable. * @constant CB_AudioFile_API.SM2#DEFAULT_VOLUME * @type {number} * @default CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME */ CB_AudioFile_API[\"SM2\"].prototype.DEFAULT_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration[CB_BASE_NAME].CB_Speaker_DEFAULT_VOLUME; /** * Keeps the default options when an object is created. Format: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. * @constant CB_AudioFile_API.SM2#DEFAULT_OPTIONS * @type {CB_AudioFile_API.SM2.OPTIONS} * @default { autoLoad: true, autoPlay: false, loop: false, volume: [CB_AudioFile_API.SM2.prototype.DEFAULT_VOLUME]{@link CB_AudioFile_API.SM2#DEFAULT_VOLUME} } */ CB_AudioFile_API[\"SM2\"].prototype.DEFAULT_OPTIONS = { autoLoad: true, autoPlay: false, loop: false, volume: CB_AudioFile_API[\"SM2\"].prototype.DEFAULT_VOLUME }; //Properties and variables: /** * Tells whether the file is unloaded ({@link CB_AudioFile.UNLOADED}), loading ({@link CB_AudioFile.LOADING}), unchecked ({@link CB_AudioFile.UNCHECKED}), checking ({@link CB_AudioFile.CHECKING}), loaded ({@link CB_AudioFile.LOADED}), failed ({@link CB_AudioFile.FAILED}) or aborted ({@link CB_AudioFile.ABORTED}). * @var CB_AudioFile_API.SM2#status * @readonly * @type {integer} * @default {@link CB_AudioFile.UNLOADED} */ this.status = CB_AudioFile.UNLOADED; /** * Defines whether the file loops by default when the audio is played or not. Its value will be modified automatically whenever the {@link CB_AudioFile_API.SM2#play} method is called, getting the value from the \"loop\" parameter (but only if contains a boolean). * @var CB_AudioFile_API.SM2#loop * @readonly * @type {boolean} * @default [CB_AudioFile_API.SM2.prototype.DEFAULT_OPTIONS]{@link CB_AudioFile_API.SM2#DEFAULT_OPTIONS}.loop */ this.loop = CB_AudioFile_API[\"SM2\"].prototype.DEFAULT_OPTIONS.loop; /** * Stores the volume of this audio. Accepted values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is false or otherwise MAX_VOLUME is the returning value of the {@link CB_Speaker.getVolume} function. * @var CB_AudioFile_API.SM2#volume * @readonly * @type {number} * @default [CB_AudioFile_API.SM2.prototype.DEFAULT_OPTIONS]{@link CB_AudioFile_API.SM2#DEFAULT_OPTIONS}.volume */ this.volume = CB_AudioFile_API[\"SM2\"].prototype.DEFAULT_OPTIONS.volume; /** * Stores the volume of this audio before it was muted (to restore it later). Valid values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is false or otherwise MAX_VOLUME is the returning value of the {@link CB_Speaker.getVolume} function. * @var CB_AudioFile_API.SM2#volumeBeforeMute * @readonly * @type {number} * @default {@link CB_AudioFile_API.SM2#volume} */ this.volumeBeforeMute = this.volume; /** * Stores the identifier for the audio file. * @var CB_AudioFile_API.SM2#id * @readonly * @type {string} * @default 'CB_AUDIOFILE_SM2_' + CB_AudioFile_API.SM2._idUnique++ */ this.id = \"\"; /** * Stores the path of the audio file or the data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @var CB_AudioFile_API.SM2#filePath * @readonly * @type {string} * @default */ this.filePath = \"\"; /** * Tells whether the audio is paused or not. * @var CB_AudioFile_API.SM2#paused * @readonly * @type {boolean} * @default false */ this.paused = false; /** * Stores the time (in milliseconds) when the audio has been paused. * @var CB_AudioFile_API.SM2#pauseTime * @readonly * @type {number} * @default */ this.pauseTime = 0; /** * Tells whether the audio is stopped or not. * @var CB_AudioFile_API.SM2#stopped * @readonly * @type {boolean} * @default true */ this.stopped = true; /** * Function to call when the audio stops. * @var CB_AudioFile_API.SM2#onStopFunction * @readonly * @type {function} * @default */ this.onStopFunction = null; /** * Stores the last \"startAt\" parameter value used by the {@link CB_AudioFile_API.SM2#play} or the {@link CB_AudioFile_API.SM2#resume} method. * @var CB_AudioFile_API.SM2#lastStartAt * @readonly * @type {number} * @default */ this.lastStartAt = null; /** * Stores the last \"stopAt\" parameter value used by the {@link CB_AudioFile_API.SM2#play} or the {@link CB_AudioFile_API.SM2#resume} method. * @var CB_AudioFile_API.SM2#lastStopAt * @readonly * @type {number} * @default */ this.lastStopAt = null; /** * Stores the \"SMSound\" object (returned by the [createSound]{@link http://schillmania.com/projects/soundmanager2/doc/#soundmanager-createsound} method) of the audio, used by the \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}). * @var CB_AudioFile_API.SM2#soundObject * @readonly * @type {Object} * @default */ this.soundObject = null; //Internal properties: this._timeoutWhenStop = null; //Keeps the timeout that is executed when the audio has finished playing (to either stop or loop). this._id_internal = null; //Internal id. //this._resuming = false; this._recursiveCallTimeout = null; this._onReadyTimeout = null; this._onErrorFunctionTimeout = null; this._stopAfterPlayingTimeout = null; this._onLoadTimeout = null; this._loadingCounterIncreased = false; this._checkPlayingTimeout = null; this._checkPlayingFinishingTimeout = null; this._recursiveCallCheckingTimeout = null; this._checkingCounterIncreased = false; this._lastDuration = null; this._onPlayingErrorFunctionTimeout = null; this._onPlayingErrorFunctionExecuting = false; this._startPlayingTimeReal = 0; //Calls the constructor of the object when creates an instance: return this._init(filePath, audioId, options, callbackOk, callbackError); } /** * Object with the options for an audio file. The format is the following one: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. * @memberof CB_AudioFile_API.SM2 * @typedef {Object} CB_AudioFile_API.SM2.OPTIONS * @property {boolean} [autoLoad={@link CB_AudioFile_API.SM2#DEFAULT_OPTIONS}.autoLoad] - If set to false, it will not call the {@link CB_AudioFile_API.SM2#load} method internally when the constructor is called (not recommended). * @property {boolean} [autoPlay={@link CB_AudioFile_API.SM2#DEFAULT_OPTIONS}.autoPlay] - Value which will be used as the \"autoPlay\" parameter when calling the {@link CB_AudioFile_API.SM2#load} method internally, only when the \"autoLoad\" is set to true (when the constructor is called). * @property {boolean} [loop={@link CB_AudioFile_API.SM2#DEFAULT_OPTIONS}.loop] - Value that will be used for the {@link CB_AudioFile_API.SM2#loop} property. * @property {number} [volume={@link CB_AudioFile_API.SM2#DEFAULT_OPTIONS}.volume] - The desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise) that will be used for the {@link CB_AudioFile_API.SM2#volume} property. */ //Static properties: CB_AudioFile_API[\"SM2\"]._counter = 0; //Internal counter. CB_AudioFile_API[\"SM2\"]._idUnique = 0; //Counter to make the id unique (otherwise SM2 will never create an object with the same id after destroying it). //Constructor: CB_AudioFile_API[\"SM2\"].prototype._init = function(filePath, audioId, options, callbackOk, callbackError) { //If not given, defines the default parameters: if (typeof(audioId) === \"undefined\" || audioId === null) { audioId = \"CB_AUDIOFILE_SM2_\" + CB_AudioFile_API[\"SM2\"]._idUnique++; } //Uses the file path as default id. if (typeof(options) === \"undefined\" || options === null) { options = this.DEFAULT_OPTIONS; } else { if (typeof(options.loop) === \"undefined\" || options.loop === null) { options.loop = this.DEFAULT_OPTIONS.loop; } if (typeof(options.autoLoad) === \"undefined\" || options.autoLoad === null) { options.autoLoad = this.DEFAULT_OPTIONS.autoLoad; } if (typeof(options.autoPlay) === \"undefined\" || options.autoPlay === null) { options.autoPlay = this.DEFAULT_OPTIONS.autoPlay; } if (typeof(options.volume) === \"undefined\" || options.volume === null) { options.volume = this.DEFAULT_OPTIONS.volume; } } //Sets the audio ID: this.id = CB_trim(audioId).toUpperCase(); //Sets the internal id: if (typeof(this._id_internal) === \"undefined\" || this._id_internal === null) { this._id_internal = CB_AudioFile_API[\"SM2\"]._counter++; } //Sets the file path: this.filePath = filePath; //Proceeds according to the options sent: this.loop = options.loop; this.volume = options.volume; this.volumeBeforeMute = this.volume; if (options.autoLoad) { var that = this; setTimeout ( function() { that.load(that.filePath, options.autoPlay, callbackOk, callbackError); }, 10 ); } //Returns the object: return this; } /** * Destroys the audio file object and frees memory. Sets its current {@link CB_AudioFile_API.SM2#status} property to ABORTED ({@link CB_AudioFile.ABORTED} value). * @function CB_AudioFile_API.SM2#destructor * @param {boolean} [stopSound=false] - If set to true, it will also call the {@link CB_AudioFile_API.SM2#stop} method. * @param {boolean} [keepStoppedUnaltered=false] - Used internally as the \"keepStoppedUnaltered\" parameter to call the {@link CB_AudioFile_API.SM2#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. * @param {boolean} [avoidOnStop=false] - Used internally as the \"avoidOnStop\" parameter to call the {@link CB_AudioFile_API.SM2#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. * @param {boolean} [forceOnStop=false] - Used internally as the \"forceOnStop\" parameter to call the {@link CB_AudioFile_API.SM2#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. */ CB_AudioFile_API[\"SM2\"].prototype.destructor = function(stopSound, keepStoppedUnaltered, avoidOnStop, forceOnStop) { this._lastDuration = null; if (typeof(this.soundObject) === \"undefined\" || this.soundObject === null) { this.status = CB_AudioFile.ABORTED; return; } if (stopSound) { this.stop(keepStoppedUnaltered, avoidOnStop, forceOnStop); } if (typeof(this.soundObject.destruct) !== \"undefined\" &amp;&amp; this.soundObject.destruct !== null) { this.soundObject.destruct(); } CB_Elements.remove(this.soundObject); //if (this.status === CB_AudioFile.LOADING) if (this._loadingCounterIncreased) { this._loadingCounterIncreased = false; CB_AudioFile_API_AAPI_SM2_beingLoading--; //Decreases the counter of the objects which are loading. if (CB_AudioFile_API_AAPI_SM2_beingLoading &lt; 0) { CB_AudioFile_API_AAPI_SM2_beingLoading = 0; } } if (this._checkingCounterIncreased) { this._checkingCounterIncreased = false; CB_AudioFile_API_AAPI_SM2_beingChecking--; //Decreases the counter of the objects which are checking. if (CB_AudioFile_API_AAPI_SM2_beingChecking &lt; 0) { CB_AudioFile_API_AAPI_SM2_beingChecking = 0; } } this.status = CB_AudioFile.ABORTED; } /** * Loads the desired audio file with the desired options. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. This method will be called automatically by the constructor if the \"autoLoad\" option was set to true in its given \"options\" parameter. * When this method is called, if the {@link CB_AudioFile_API.SM2#status} property already has the \"LOADED\" status (defined in the {@link CB_AudioFile.LOADED} constant) and the \"forceReload\" parameter is not set to true, it will exit calling the given \"callbackOk\" function (if any) immediately. Otherwise, regardless the status, the status will be set to \"LOADING\" (defined in the {@link CB_AudioFile.LOADING} constant). After it, it will reach the \"UNCHECKED\" (defined in the {@link CB_AudioFile.UNCHECKED} constant). If the \"autoPlay\" parameter is not set to true, this will be the final status (and it will be necessary to call the {@link CB_AudioFile_API.SM2#checkPlaying} method after it). After it and only if the \"autoPlay\" is set to true, as the {@link CB_AudioFile_API.SM2#checkPlaying} method will be called internally, it will have the \"CHECKING\" status (defined in the {@link CB_AudioFile.CHECKING} constant) and finally the \"LOADED\" status (defined in the {@link CB_AudioFile.LOADED} constant) if all goes well. * @function CB_AudioFile_API.SM2#load * @param {string} [filePath={@link CB_AudioFile_API.SM2#filePath}] - The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @param {string} [autoPlay=false] - If set to true, it will start playing the audio automatically (by calling the {@link CB_AudioFile_API.SM2#play} method internally). If set to true and the {@link CB_AudioFile_API.SM2#status} property reaches to the \"UNCHECKED\" status (defined in the {@link CB_AudioFile.UNCHECKED} constant), it will also call internally the {@link CB_AudioFile_API.SM2#checkPlaying} method. * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the {@link CB_AudioFile_API.SM2} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.SM2} object itself. * @param {boolean} [forceReload=false] - If set to false, the \"filePath\" has not been changed from the previously used and the {@link CB_AudioFile_API.SM2#status} property belongs to the \"LOADED\" status (defined in the {@link CB_AudioFile.LOADED} constant), it will exit the method without loading the audio file again (calling the \"callbackOk\" function, if any). * @returns {CB_AudioFile_API.SM2|null} Returns the audio API object (if it was possible to create) or null otherwise. */ CB_AudioFile_API[\"SM2\"].prototype.load = function(filePath, autoPlay, callbackOk, callbackError, forceReload) { clearTimeout(this._checkPlayingTimeout); clearTimeout(this._onReadyTimeout); clearTimeout(this._onErrorFunctionTimeout); clearTimeout(this._stopAfterPlayingTimeout); clearTimeout(this._onLoadTimeout); clearTimeout(this._recursiveCallTimeout); clearTimeout(this._checkPlayingFinishingTimeout); filePath = filePath || this.filePath; //If the status is LOADED and the file path give is the same as the current one, just exits: if (!forceReload &amp;&amp; this.status === CB_AudioFile.LOADED &amp;&amp; this.filePath === filePath) { if (typeof(callbackOk) === \"function\") { callbackOk.call(this); } return this; } this.status = CB_AudioFile.LOADING; //The file is loading. var that = this; //If the maximum of objects loading is reached, calls the function again after some time and exits: //if (CB_AudioFile_API_AAPI_SM2_beingLoading &gt;= CB_AudioFile_API_AAPI_SM2_maximumLoading) if (autoPlay &amp;&amp; CB_AudioFile_API_AAPI_SM2_beingLoading &gt;= CB_AudioFile_API_AAPI_SM2_maximumLoading) { this._recursiveCallTimeout = setTimeout(function() { that.load(filePath, autoPlay, callbackOk, callbackError, forceReload); }, 10); return this; } if (typeof(this.soundObject) !== \"undefined\" &amp;&amp; this.soundObject !== null) { //this.soundObject.onload = function() { }; this.soundObject.onload = null; } //Destroys previous object (if any): this.destructor(true, false, true); //Also stops the sound (if any) and prevents firing onStop. this.status = CB_AudioFile.LOADING; //The file is loading. if (!this._loadingCounterIncreased) { this._loadingCounterIncreased = true; CB_AudioFile_API_AAPI_SM2_beingLoading++; //Increases the counter of the objects which are loading (destructor has decreased 1). } this.filePath = filePath; var callbackFunctionError = function(error, ignoreFailed) { //Prevents the execution of the function if the object has been declared as LOADED: if (that.status === CB_AudioFile.LOADED || that.status === CB_AudioFile.UNCHECKED || that.status === CB_AudioFile.CHECKING) { return; } if (that.status === CB_AudioFile.ABORTED) { return; } //If it is has been aborted, we exit. //If it has already failed before, exits: if (!ignoreFailed &amp;&amp; that.status === CB_AudioFile.FAILED) { return; } if (that._loadingCounterIncreased) { that._loadingCounterIncreased = false; CB_AudioFile_API_AAPI_SM2_beingLoading--; //Decreases the counter of the objects which are loading. if (CB_AudioFile_API_AAPI_SM2_beingLoading &lt; 0) { CB_AudioFile_API_AAPI_SM2_beingLoading = 0; } } that.status = CB_AudioFile.FAILED; //File failed to load. autoPlay = false; //var fileName = filePath; if (filePath.substring(0, 5).toLowerCase() === \"data:\") { filePath = filePath.substring(0, 15) + \"[...]\" + filePath.substring(filePath.length - 2); } error = \"Error message for \" + filePath + \" file: \" + error; if (typeof(callbackError) === \"function\") { callbackError.call(that, error); } //Calls the Error function back. }; try { if (typeof(soundManager) === \"undefined\") { callbackFunctionError(\"SoundManager 2 not found\"); return null; } //Creates an object and destroy it because otherwise in Intel XDK emulator and Android test with WebView does not work the second time (strange bug): this.soundObject = soundManager.createSound ( { id: \"fake_sound_sm2_\" + CB_AudioFile_API[\"SM2\"]._idUnique, url: filePath } ); this.destructor(); this.status = CB_AudioFile.LOADING; //The file is loading. var onLoadCalled = false; var onLoad = function(success) { onLoadCalled = true; clearTimeout(that._onLoadTimeout); //Cancels callbackError call (if any) in case onload has been called before with a wrong \"success\" (happens on Android with WebView): clearTimeout(that._onErrorFunctionTimeout); //if (this.readyState === 3) if (success) { //Prepares the sound to be playable (and plays it automatically if we want to): that._onReadyTimeout = setTimeout(onReadyFunction, 2000); //Gives time to onerror event to be fired before canplaythrough event. } else { //Gives a little bit of time because sometimes the onLoad function is called again (on Android with WebView sometimes the first call contains a wrong \"success\"): that._onErrorFunctionTimeout = setTimeout ( function() { callbackFunctionError(\"Sound could not be loaded\"); }, 1000 ); } }; //Creates the object: this.soundObject = soundManager.createSound ( { id: this.id + \"_\" + CB_AudioFile_API[\"SM2\"]._idUnique++, url: filePath, autoLoad: true, onload: onLoad } ); //Timeout to declare the sound as failed if the onload event is not fired before: this._onLoadTimeout = setTimeout(function() { if (!onLoadCalled) { callbackFunctionError(\"Sound's onload event timeout (not fired after \" + CB_Configuration[CB_BASE_NAME].CB_AudioFile_ONLOAD_TIMEOUT_MS + \" ms)\"); } }, CB_Configuration[CB_BASE_NAME].CB_AudioFile_ONLOAD_TIMEOUT_MS); //Makes the sound seekable for some iOS versions (strange bug) and forces Firefox for Android to fire canplaythrough event (strange bug too): var previousVolume = this.volume; //Stores the current volume. if (CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING) { this.setVolume(0); //Mutes the sound. } this.soundObject.play({ loops: 1 }); this._stopAfterPlayingTimeout = setTimeout(function() { that.soundObject.pause(); }, 1); //Plays the sound during some time because otherwise some web clients, as WebView used by Cordova on Android, receive duration 0 (strange bug): var onReadyFunctionExecuted = false; var onReadyFunction = function() { //Prevents the execution of the function more than once: if (onReadyFunctionExecuted) { return; } onReadyFunctionExecuted = true; //Prevents to be executed after the onerror event has fired: if (that.status === CB_AudioFile.FAILED) { return; } //Function to execute when all is OK: var allIsFine = function() { if (that.status === CB_AudioFile.ABORTED) { return; } //If it is has been aborted, we exit. if (that._loadingCounterIncreased) { that._loadingCounterIncreased = false; CB_AudioFile_API_AAPI_SM2_beingLoading--; //Decreases the counter of the objects which are loading. if (CB_AudioFile_API_AAPI_SM2_beingLoading &lt; 0) { CB_AudioFile_API_AAPI_SM2_beingLoading = 0; } } //Restores the volume: that.setVolume(previousVolume); if (typeof(callbackOk) === \"function\") { callbackOk.call(that); } //Calls the OK function back. //Plays automatically if we want to: if (autoPlay) { that.play(); } }; that.status = CB_AudioFile.UNCHECKED; //The file is still unchecked. //If we want to play automatically, checks if the currentTime changes (some web clients cannot play if the user did not fire an event to call the play function): if (autoPlay) { that.checkPlaying(function() { allIsFine(); }, function(error) { callbackFunctionError(error, true); }, false, false); } else { allIsFine(); } }; } catch(E) { callbackFunctionError(E); return null; } return this; } /** * Checks whether the audio can be played or not. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. Also recommended to use before calling the {@link CB_AudioFile_API.SM2#play} method the first time. The checking action will only be performed if the value of the {@link CB_AudioFile_API.SM2#status} property belongs to the {@link CB_AudioFile.UNCHECKED} or to the {@link CB_AudioFile.CHECKING} value. After checking, if the audio can be played, the {@link CB_AudioFile_API.SM2#status} of the object will get the value of {@link CB_AudioFile.LOADED}. Otherwise, if it cannot be played, the {@link CB_AudioFile_API.SM2#status} property will get the value of {CB_AudioFile.FAILED}. * @function CB_AudioFile_API.SM2#checkPlaying * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been checked successfully, being \"this\" the {@link CB_AudioFile_API.SM2} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been checked successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.SM2} object itself. * @param {boolean} [ignoreStatus=false] - If set to false and the {@link CB_AudioFile_API.SM2#status} property does not belong neither to the \"UNCHECKED\" status (defined in the {@link CB_AudioFile.UNCHECKED} constant) nor to the \"CHECKING\" status (defined in the {@link CB_AudioFile.CHECKING} constant), it will fail calling the \"callbackError\" function (if any). If set to true, it will try to perform the checking action regardless the status of the audio. * @param {boolean} [ignoreQueue=false] - If set to false and there is already the maximum number of audio files being checked (defined internally), the function will exit and it will call itself automatically again and again until the checking process can be performed (when its queue turn has been reached). This is done for performance purposes. * @param {boolean} [useCache=false] - This parameter will be ignored in this audio API. * @returns {boolean} Returns false if the checking could not be performed and failed. If it returns true, it can mean either the checking has been processed successfully or it will fail in the future, so it is recommended to ignore the returning value and use the callback functions instead. */ CB_AudioFile_API[\"SM2\"].prototype.checkPlaying = function(callbackOk, callbackError, ignoreStatus, ignoreQueue, useCache) { /////clearTimeout(this._recursiveCallCheckingTimeout); if (!ignoreStatus &amp;&amp; this.status !== CB_AudioFile.UNCHECKED &amp;&amp; this.status !== CB_AudioFile.CHECKING) { if (typeof(callbackError) === \"function\") { callbackError.call(this, \"Cannot check if status is not unchecked or checking (status is \" + this.status + \")\"); } return false; } this.status = CB_AudioFile.CHECKING; var that = this; //If we do not use cache the maximum of objects checking is reached or we use cache but the file path is checking, calls the function again after some time and exits: if (!ignoreQueue &amp;&amp; CB_AudioFile_API_AAPI_SM2_beingChecking &gt;= CB_AudioFile_API_AAPI_SM2_maximumChecking) { this._recursiveCallCheckingTimeout = setTimeout(function() { that.checkPlaying(callbackOk, callbackError, ignoreStatus, useCache); }, 10); return true; } ////this.status = CB_AudioFile.CHECKING; if (!this._checkingCounterIncreased) { this._checkingCounterIncreased = true; CB_AudioFile_API_AAPI_SM2_beingChecking++; //Increases the counter of the objects which are checking. } var previousVolume = this.volume; var finishedChecking = function(ok, error, keepStatus) { //Stops the file: that.soundObject.pause(); //Restores the volume: that._checkPlayingFinishingTimeout = //Timeout to prevent hearing the sound in some web clients. setTimeout ( function() { that.setVolume(previousVolume); //If the file is ok: if (ok) { if (!keepStatus) { that.status = CB_AudioFile.LOADED; } if (typeof(callbackOk) === \"function\") { callbackOk.call(that); } } //...otherwise, if the file has failed: else { if (!keepStatus) { that.status = CB_AudioFile.FAILED; } if (typeof(callbackError) === \"function\") { callbackError.call(that, error); } } }, 10 ); if (that._checkingCounterIncreased) { that._checkingCounterIncreased = false; CB_AudioFile_API_AAPI_SM2_beingChecking--; //Decreases the counter of the objects which are checking. if (CB_AudioFile_API_AAPI_SM2_beingChecking &lt; 0) { CB_AudioFile_API_AAPI_SM2_beingChecking = 0; } } }; try { //Plays the sound during some time to let some web clients get the duration correctly (strange bug): if (CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING) { this.setVolume(0); } this.soundObject.play({ loops: 1 }); var durationDetected = this.getDuration(); var timesCurrentTimeChecked = 0; clearTimeout(this._checkPlayingTimeout); clearTimeout(this._checkPlayingFinishingTimeout); var checkFunction = function(callbackOk, callbackError) { clearTimeout(that._checkPlayingTimeout); //If it is has been aborted, we exit: if (that.status === CB_AudioFile.ABORTED || that.status === CB_AudioFile.FAILED) { finishedChecking(false, \"Audio file object is \" + (that.status === CB_AudioFile.ABORTED ? \"ABORTED\" : \"FAILED\") + \".\", true); return; } try { that.status = CB_AudioFile.CHECKING; //If the duration has changed, it calls the function again because it means the audio is still loading (otherwise, Firefox has issues with data URIs and detects a shorter duration): var durationDetectedNow = that.getDuration(); if (durationDetected !== durationDetectedNow) { durationDetected = durationDetectedNow; that._checkPlayingTimeout = setTimeout(function() { checkFunction(callbackOk, callbackError); }, CB_Configuration[CB_BASE_NAME].CB_AudioFile_AUTOPLAY_SILENTLY_ON_LOAD_MS); return; } //If the current time is still 0: if (that.soundObject.position == 0) { //We give it some opportunities more to change current time: if (timesCurrentTimeChecked &lt; 1000) { timesCurrentTimeChecked++; if (timesCurrentTimeChecked % 20 === 0) { that.soundObject.pause(); try { that.soundObject.setPosition(0); } catch(E) {} //Avoid Firefox complain about using an object which is no longer available. that.soundObject.play({ loops: 1 }); /* try { if (that.soundObject.position != 0) { that.soundObject.setPosition(0.00000000001); //Executed after play method because otherwise Safari Mobile does not change currentTime. } } catch(E) {} */ } that._checkPlayingTimeout = setTimeout(function() { checkFunction(callbackOk, callbackError); }, 1); return; } //...if all opportunities failed, we declare it as FAILED and exits: else { finishedChecking(false, \"position does not change (it is \" + that.soundObject.position + \").\"); return; } } //Only updates the currentTime to 0 if it is not zero already (because otherwise some web clients will fail or have a wrong behaviour): if (that.soundObject.position != 0) { that.soundObject.setPosition(0); } //If the duration is zero, we declare it as FAILED and exits: if (that.getDuration() === 0) { finishedChecking(false, \"Duration is zero\"); return; } else if (that.soundObject.readyState === 2) { finishedChecking(false, \"readyState is 2 (failed/error)\"); return; } finishedChecking(true); } catch(E) { finishedChecking(false, E); } }; this._checkPlayingTimeout = setTimeout(function() { checkFunction(callbackOk, callbackError); }, CB_Configuration[CB_BASE_NAME].CB_AudioFile_AUTOPLAY_SILENTLY_ON_LOAD_MS); return true; } catch(E) { finishedChecking(false, E); return false; } } /** * Tells the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. * @function CB_AudioFile_API.SM2#getDuration * @returns {number} Returns the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. */ CB_AudioFile_API[\"SM2\"].prototype.getDuration = function() { var duration; if (typeof(this.soundObject) !== \"undefined\" &amp;&amp; this.soundObject !== null &amp;&amp; typeof(this.soundObject.duration) !== \"undefined\" &amp;&amp; this.soundObject.duration !== null) { duration = this.soundObject.duration; } if (typeof(duration) === \"undefined\" || duration === null || isNaN(duration) || duration &lt; 0) { duration = 0; } return duration; } //Executed when there is an error playing: CB_AudioFile_API[\"SM2\"].prototype._onPlayingErrorFunction = function() { this._onPlayingErrorFunctionExecuting = true; clearTimeout(this._onPlayingErrorFunctionTimeout); if (this.soundObject.readyState === 2 &amp;&amp; this.status === CB_AudioFile.LOADED) { this.status = CB_AudioFile.FAILED; //Declares it as failed. this.stop(false, false, true); //Also fires onStop event. } if (this.status === CB_AudioFile.LOADED) { var that = this; this._onPlayingErrorFunctionTimeout = setTimeout(function() { that._onPlayingErrorFunction.call(that); }, 1); } else { this._onPlayingErrorFunctionExecuting = false; } }; //Executed when the sound stops playing: CB_AudioFile_API[\"SM2\"].prototype._whenStopFunction = function(startAtNextLoop, stopAt, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, whenStopFunction, onPlayingErrorFunction, flags) { //Just allows executing the function once: if (flags.whenStopFunctionExecuted) { return; } flags.whenStopFunctionExecuted = true; //Removes the event and timeout: this.soundObject.clearOnPosition(stopAt, whenStopFunction); //Clears the event: clearTimeout(this._timeoutWhenStop); //Clears the previous timeout. //If the sound has been stopped or paused or the stop time has changed, exits: if (this.stopped || this.paused || this.lastStopAt !== stopAt) { return; } //...otherwise, if the stop time has not been reached yet, calls the function again after a while: //else if (this.getCurrentTime() &lt; stopAt) { setTimeout(whenStopFunction, 1); return; } //If the object has failed, just calls the error function and exits: if (this.soundObject.readyState === 2) { clearTimeout(this._onPlayingErrorFunctionTimeout); this._onPlayingErrorFunctionTimeout = setTimeout(onPlayingErrorFunction, 1); return; } //If we want to loop, loops again: if (this.loop) { //this.stop(true); //Stops the sound without setting its property as stopped. this.play(startAtNextLoop, stopAt, true, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, false, true); //Plays again the sound. } //...otherwise, if we don't want to loop, we stop: else { this.stop(); } }; /** * Plays the audio. * @function CB_AudioFile_API.SM2#play * @param {number} [startAt=0 | {@link CB_AudioFile_API.SM2#lastStartAt} | stopAt] - Time in milliseconds where we want the audio to start at. If not provided or it is not a valid number, it will use zero (0) as default which belongs to the beginning of the audio. If the value provided is greater than the \"stopAt\" provided, it will use the value set in the {@link CB_AudioFile_API.SM2#lastStartAt} property (which belongs to the \"startAt\" value the last time that this method was called). If, even using the {@link CB_AudioFile_API.SM2#lastStartAt} value is still greather than the \"stopAt\" provided, it will use the same value as the \"stopAt\" which means it will not play and will stop immediately. * @param {number} [stopAt={@link CB_AudioFile_API.SM2#getDuration}()] - Time in milliseconds where we want the audio to stop at. If not provided or it is not a valid number, it will use the returning value of the {@link CB_AudioFile_API.SM2#getDuration} method (which should belong to the total duration of the audio, if it was calculated correctly). * @param {boolean} [loop={@link CB_AudioFile_API.SM2#loop}] - Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the {@link CB_AudioFile_API.SM2#onStop} method) will not be called. * @param {boolean} [avoidDelayedPlay=false] - If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the \"stop\" method will be called immediately. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the {@link CB_AudioFile_API.SM2#stop} method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). * @param {function} [onPlayStart] - Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the {@link CB_AudioFile_API.SM2} object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. * @param {function} [onLoadError] - Function to be called if the audio cannot be played successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.SM2} object. * @param {boolean} [isResume=false] - If set to true (not recommended) and it is a looping audio, the next loop will use the value of the {@link CB_AudioFile_API.SM2#lastStartAt} property as the \"startAt\" parameter when it calls this method again automatically (internally). Recommended for internal usage only. * @param {boolean} [isLooping=false] - Used to determine whether this method was called automatically again by itself because it is looping the audio. Recommended for internal usage only. * @param {integer} [startPlayingTime] - Contains the time when the audio should start playing. Recommended for internal usage only. * @returns {boolean|integer} It returns false if the duration is 0 (\"startAt\" and \"stopAt\" are the same number), returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. */ CB_AudioFile_API[\"SM2\"].prototype.play = function(startAt, stopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, isResume, isLooping, startPlayingTime) { var that = this; var duration = this.getDuration(); if (typeof(startPlayingTime) === \"undefined\" || startPlayingTime === null) { startPlayingTime = CB_Device.getTiming(); } var onPlayingErrorFunction = function() { that._onPlayingErrorFunction.call(that); }; //If the sound is not ready yet, calls the function again but later: /*if (this.status !== CB_AudioFile.LOADED || this.getDuration() === 0) //Duration must be greater than zero. { this.stopped = true; this.paused = false; //If it has not failed or aborted, calls the function again but later: if (this.status !== CB_AudioFile.FAILED &amp;&amp; this.status !== CB_AudioFile.ABORTED) { setTimeout(function() { that.play(startAt, stopAt, loop, allowOverlapping, avoidDelayedPlay, onLoadError, isResume, isLooping); }, 1); } //...otherwise, if it has failed, sets it as stopped: //else { this.stopped = true; } return -1; }*/ if (this.status !== CB_AudioFile.LOADED || duration === 0 || this.soundObject.readyState === 2) //Duration must be greater than zero. { this.stopped = true; this.paused = false; //If it has not failed or aborted: if (this.status !== CB_AudioFile.FAILED &amp;&amp; this.status !== CB_AudioFile.ABORTED) //It must be UNLOADED, LOADING, LOADED, UNCHECKED or CHECKING. { //Function that calls the play method recursively (unless the maximum time allowed has expired): var playLaterFunctionCalled = false; var playLaterFunction = function() { if (playLaterFunctionCalled) { return; } playLaterFunctionCalled = true; //If the recursive delay is not null and is a valid number: if (typeof(allowedRecursiveDelay) === \"undefined\" || allowedRecursiveDelay === null || isNaN(allowedRecursiveDelay) || allowedRecursiveDelay &lt; 0) { allowedRecursiveDelay = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT; //We use default value. } var timeNow = CB_Device.getTiming(); //If the time expired is less or equal to the delay allowed: if (timeNow - startPlayingTime &lt;= allowedRecursiveDelay) { //Calls play method again: that.play(startAt, stopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, isResume, isLooping, startPlayingTime); } //...otherwise, just stops the sound: ///////else { that.stop(false, false); } //Sets as stopped and fires onStop function (if any). else { that.stop(false, false, true); } //Sets as stopped and fires onStop function (if any). }; //Function to execute when the sound loads successfully (or finishes checking successfully): var onLoad = function() { //If we allow delayed play, plays the sound: if (!avoidDelayedPlay) { playLaterFunction(); } //...otherwise, just stops the sound (to fire onStop function): ////////else { that.stop(false, false); } //Sets as stopped and fires onStop function (if any). else { that.stop(false, false, true); } //Sets as stopped and fires onStop function (if any). }; //If it is UNLOADED or we had a duration before but not now and it is not LOADING, loads the file again: if (this.status === CB_AudioFile.UNLOADED || this.status !== CB_AudioFile.LOADING &amp;&amp; this._lastDuration !== null &amp;&amp; duration === 0 || this.soundObject.readyState === 2) { this.load(this.filePath, false, onLoad, onLoadError, true); } //...otherwise, if it is UNCHECKED, we call the checking function: else if (this.status === CB_AudioFile.UNCHECKED) { this.checkPlaying(onLoad, onLoadError, false, true, false); } //...otherwise, if it is not CHECKING (it must be LOADING or LOADED with duration 0 from the beginning), we will not reload the sound: else if (this.status !== CB_AudioFile.CHECKING) { //If we allow delayed play, calls the play method again but after some time: if (!avoidDelayedPlay) { setTimeout(playLaterFunction, 1); } //...otherwise, just stops the sound (to fire onStop function): //////else { this.stop(false, false); } //Sets as stopped and fires onStop function (if any). else { this.stop(false, false, true); } //Sets as stopped and fires onStop function (if any). } } return -1; } this._lastDuration = duration; //Defines the default parameters: if (CB_trim(startAt) === \"\") { startAt = 0; } //Starts at the beginning as default. if (CB_trim(stopAt) === \"\") { stopAt = 0; } //If it is not a number, default is zero. if (typeof(loop) === \"undefined\" || loop === null) { loop = this.loop; } //If not set, uses the default (or last one used). else { this.loop = loop; } //...otherwise, stores the new setting given. //Sanitizes startAt and stopAt: startAt = parseFloat(startAt); stopAt = parseFloat(stopAt); if (startAt &lt; 0) { startAt = 0; } if (stopAt &lt;= 0 || stopAt &gt; duration) { stopAt = duration; } //If the stopAt is not correct, plays until the end of the file. if (startAt &gt; stopAt) { startAt = this.lastStartAt; } //In the case start time is than stop time, starts as the previous time. if (startAt &gt; stopAt || isNaN(startAt)) { startAt = stopAt; } //If the duration is zero (startAt and stopAt are equal), exits: if (startAt === stopAt) { this.stop(); return false; } //Next loop (if any) it will start at the same time by default: var startAtNextLoop = startAt; //If it is a resume, next loop we should start from the previous startAt used: if (isResume) { startAtNextLoop = this.lastStartAt; } //...otherwise, if it is not a resume, stores the startAt used: else { this.lastStartAt = startAt; } this.lastStopAt = stopAt; //Stores stopAt used. //Adds the event to check when the file reaches the stop time: var whenStopFunction = function() { that._whenStopFunction.call(that, startAtNextLoop, stopAt, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, whenStopFunction, onPlayingErrorFunction, flags); }; var flags = { \"whenStopFunctionExecuted\" : false }; //Clears the previous timeout (if any): clearTimeout(this._timeoutWhenStop); //If it is looping or does not allow overlapping and it is not paused, stops the possible previous sound: //if (isLooping || !allowOverlapping &amp;&amp; !this.paused) { this.stop(true); } //Stops the sound without setting its property as stopped. this.stop(true, true); //Stops the sound without setting its property as stopped. //Applies the current volume: this.setVolume(this.volume); //If it is not a loop (it is the first call to the play method) or we do not want to loop: if (!isLooping || !loop) { CB_symmetricCallClear(\"SM2_AUDIO_FILE\" + this._id_internal); } //We clean the cache of setTimeoutSynchronized for the loop function. //If defined, starts at the given position (ms): var currentTime = startAt; //Only updates the currentTime to 0 if it is not zero already (because otherwise some web clients will fail or have a wrong behaviour): if (currentTime !== 0 || this.soundObject.position != 0) { this.soundObject.setPosition(currentTime); } //this.soundObject.setPosition(startAt); //Plays the file: this.soundObject.play({ loops: 99999999, onfinish: whenStopFunction }); //We will use our own way to loop. Many loops (although seems that 2 would be enough) because Android WebView returns position as 0 the second loop if the file is played completely. //If defined, starts at the given position (ms): //Only updates the currentTime to 0 if it is not zero already (because otherwise some web clients will fail or have a wrong behaviour): if (currentTime !== 0 || this.soundObject.position != 0) { this.soundObject.setPosition(currentTime + 0.00000000001); } //this.soundObject.setPosition(startAt); //Executed after play method because otherwise Intel XDK emulator and Android WebView kit does not perform setPosition. //Sets the event and timeout for when the sound finishes: this.soundObject.onPosition(stopAt, whenStopFunction); var msToFinish = stopAt - startAt; this._timeoutWhenStop = CB_symmetricCall(whenStopFunction, msToFinish, \"SM2_AUDIO_FILE\" + this._id_internal); //The sound is neither paused nor stopped: this._startPlayingTimeReal = CB_Device.getTiming(); //Useful to calculate approximate currentTime when position returns 0 (SM2 bug). this.paused = this.stopped = false; //If it is has failed, calls the onPlayingError function: if (!this._onPlayingErrorFunctionExecuting) { clearTimeout(this._onPlayingErrorFunctionTimeout); this._onPlayingErrorFunctionTimeout = setTimeout(onPlayingErrorFunction, 1); } if (this.soundObject.readyState === 2) { return -1; } //If it is the first time (not a loop) and there is a function to call when the play starts, we call it: if (!isLooping &amp;&amp; typeof(onPlayStart) === \"function\") { onPlayStart.call(this, startAt, stopAt, startAtNextLoop, loop, avoidDelayedPlay, allowedRecursiveDelay, startPlayingTime); onPlayStart = null; } //Prevents execution again. return true; } /** * Resumes the audio (after being paused), starting from the same point it was paused previously. * @function CB_AudioFile_API.SM2#resume * @param {boolean} [loop={@link CB_AudioFile_API.SM2#loop}] - Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the {@link CB_AudioFile_API.SM2#onStop} method) will not be called. * @param {boolean} [avoidDelayedPlay=false] - If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the {@link CB_AudioFile_API.SM2#stop} method will be called immediately. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the {@link CB_AudioFile_API.SM2#stop} method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). * @param {function} [onPlayStart] - Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the {@link CB_AudioFile_API.SM2} object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. * @param {function} [onLoadError] - Function to be called if the audio cannot be played successfully. It will not be called if the audio is not paused or is stopped. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.SM2} object. * @returns {boolean|integer} Returns the returning value of the {@link CB_AudioFile_API.SM2#play} method which is called internally. It returns false if the audio is not paused or it is stopped, returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. */ CB_AudioFile_API[\"SM2\"].prototype.resume = function(loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError) { //If it not paused or it is stopped, exits the function: if (!this.paused || this.stopped) { return false; } //this._resuming = true; var startAt = this.pauseTime; //If it has been paused after the stop time (happens sometimes when the sound was nearly to finish): if (startAt &gt;= this.lastStopAt) { startAt = this.lastStopAt - 1; //We will begin just 1 millisecond before (otherwise the play method would begin again from lastStartAt). } return this.play(startAt, this.lastStopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, true, false); } /** * Pauses the audio when it is being played. * @function CB_AudioFile_API.SM2#pause * @param {function} [onPause] - Function without parameters to be called when the audio is paused successfully, being \"this\" the {@link CB_AudioFile_API.SM2} object. * @param {boolean} [keepPausedUnaltered=false] - If set to true (not recommended), the {@link CB_AudioFile_API.SM2#paused} property will not be set to true and it will remain with its current value. * @returns {boolean} It returns false if the audio is already paused or it is stopped or if it cannot be paused. Returns true otherwise. */ CB_AudioFile_API[\"SM2\"].prototype.pause = function(onPause, keepPausedUnaltered) { //If it already paused or stopped, exits the function: if (this.paused || this.stopped) { return false; } //this._resuming = false; if (typeof(this.soundObject) !== \"undefined\" &amp;&amp; this.soundObject !== null) { clearTimeout(this._timeoutWhenStop); //Prevents that the file is set as stopped or to be executed again. this.soundObject.pause(); this.pauseTime = this.getCurrentTime(); //Bug fix: sometimes SM2 returns position as 0 (getCurrentTime returns 0) and pauseTime is 0. if (this.pauseTime === 0) { var timeNow = CB_Device.getTiming(); var pauseTime = this.lastStartAt + (timeNow - this._startPlayingTimeReal); if (pauseTime &gt; this.lastStopAt) { pauseTime = this.lastStartAt; } this.pauseTime = pauseTime; } if (!keepPausedUnaltered) { this.paused = true; } if (typeof(onPause) === \"function\") { onPause.call(this); } return true; } return false; } /** * Stops the audio. * @function CB_AudioFile_API.SM2#stop * @param {boolean} [keepStoppedUnaltered=false] - If set to true (not recommended), the {@link CB_AudioFile_API.SM2#stopped} property will not be set to true and it will remain with its current value. * @param {boolean} [avoidOnStop=false] - If set to false and there is an \"onStop\" function defined (through the {@link CB_AudioFile_API.SM2#onStop} method), it will be called after stopping the audio (or after trying to do it, at least) but only if either the \"forceOnStop\" parameter is set to true or if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. If set to true, the \"onStop\" function (if any) will not be called at all. * @param {boolean} [forceOnStop=false] - If it is set to true and the \"avoidOnStop\" parameter is set to false and there is an \"onStop\" function defined (through the {@link CB_AudioFile_API.SM2#onStop} method), it will be called regardless the audio was stopped before or not. If set to false, the \"onStop\" function (if any) will only be called if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. This parameter will be ignored if the \"avoidOnStop\" parameter is set to true. * @returns {boolean} It returns false if the stopping action cannot be performed at all (this could happen when the audio has not been loaded properly, for example). Returns true otherwise (this only means that it has been tried to be stopped but it could not be successfully). */ CB_AudioFile_API[\"SM2\"].prototype.stop = function(keepStoppedUnaltered, avoidOnStop, forceOnStop) { if (typeof(this.soundObject) !== \"undefined\" &amp;&amp; this.soundObject !== null) { ///////clearTimeout(this._timeoutWhenStop); //Prevents that the file is set as stopped or to be executed again. this.soundObject.stop(); //Only updates the currentTime to 0 if it is not zero already (because otherwise some web clients will fail or have a wrong behaviour): if (this.soundObject.position != 0) { this.soundObject.setPosition(0); } var stoppedBefore = this.stopped; if (!keepStoppedUnaltered) { this.stopped = true; } this.paused = false; //If it is stopped, it is not paused. //If we do not want to avoid onStop, it was not stopped before but it is now and onStop has a valid function assigned, we execute it: if (!avoidOnStop &amp;&amp; (!stoppedBefore &amp;&amp; this.stopped || forceOnStop) &amp;&amp; typeof(this.onStopFunction) === \"function\") { this.onStopFunction.call(this); } return true; } return false; } /** * Sets the desired volume for the audio file (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). * @function CB_AudioFile_API.SM2#setVolume * @param {number} [volume={@link CB_Speaker.getVolume()} | {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME}] - Desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). * @param {boolean} [forceSetVolumeProperty=false] - If set to true (not recommended), it will change the {@link CB_AudioFile_API.SM2#volume} property even when the volume failed to be changed. * @param {function} [onSetVolume] - Callback function which will be called if it has been possible to set the volume (or at least it was possible to try it). It will not receive any parameters, being \"this\" the {@link CB_AudioFile_API.SM2} object. * @param {boolean} [saveForUnmute=false] - If set to true (not recommended), it will save internally the current volume before setting it so it will restore the same volume again after calling the {@link CB_AudioFile_API.SM2#unmute} method. Internal usage only recommended. * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). */ CB_AudioFile_API[\"SM2\"].prototype.setVolume = function(volume, forceSetVolumeProperty, onSetVolume, saveForUnmute) { //Defines the default parameters: volume = parseInt(volume); if (isNaN(volume)) { this.DEFAULT_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration[CB_BASE_NAME].CB_Speaker_DEFAULT_VOLUME; volume = this.DEFAULT_VOLUME; } //Sets the volume within their limits if it is beyond them: var MAX_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM ? CB_Speaker.getVolume() : 100; if (volume &gt; MAX_VOLUME) { volume = MAX_VOLUME; } else if (volume &lt; 0) { volume = 0; } if (typeof(this.soundObject) !== \"undefined\" &amp;&amp; this.soundObject !== null) { this.soundObject.setVolume(volume); if ((saveForUnmute || volume === 0) &amp;&amp; this.volume &gt; 0) { this.volumeBeforeMute = this.volume; } //Also saves the previous volume if the desired one is zero (muted). this.volume = volume; if (typeof(onSetVolume) === \"function\") { onSetVolume.call(this); } } if (forceSetVolumeProperty) { this.volume = volume; } return this.volume; } /** * Mutes the audio file. * @function CB_AudioFile_API.SM2#mute * @param {function} [onMute] - Callback function which will be called if it has been possible to mute the audio file (or at least it was possible to try it). * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). If all goes well, the returning value should be zero (0). Note that, even when it returns a zero (0) value, this does not always mean that the mute has been applied successfully. */ CB_AudioFile_API[\"SM2\"].prototype.mute = function(onMute) { //Only mutes the sound if it is not muted already: if (this.volume &gt; 0) { //Mutes the audio: this.setVolume(0, false, onMute, true); //It modifies this.volumeBeforeMute. } return this.volume; } /** * Restores audio after muting it (unmutes it). * @function CB_AudioFile_API.SM2#unmute * @param {function} [onUnmute] - Callback function which will be called if it has been possible to unmute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the {@link CB_AudioFile_API.SM2} object. * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). */ CB_AudioFile_API[\"SM2\"].prototype.unmute = function(onUnmute) { //Only unmutes if it is still muted: if (this.volume === 0) { //Restores the volume before muting: this.setVolume(this.volumeBeforeMute, false, onUnmute); } return this.volume; } /** * Gets the current time (in milliseconds) which belongs to the position where the audio is currently playing or where it has been paused. Note that some audio APIs and clients could give wrong values. * @function CB_AudioFile_API.SM2#getCurrentTime * @returns {number} Returns the current time (in milliseconds). Note that some audio APIs and clients could give wrong values. */ CB_AudioFile_API[\"SM2\"].prototype.getCurrentTime = function() { var currentTime; if (this.status !== CB_AudioFile.LOADED) { return 0; } if (typeof(this.soundObject) !== \"undefined\" &amp;&amp; this.soundObject !== null) { currentTime = this.soundObject.position; } if (typeof(currentTime) === \"undefined\" || currentTime === null || isNaN(currentTime) || currentTime &lt; 0) { currentTime = 0; } return currentTime; } /* //Returns the bytes loaded of the file: CB_AudioFile_API[\"SM2\"].prototype.getBytesLoaded = function() { var bytesLoaded; if (typeof(this.soundObject) !== \"undefined\" &amp;&amp; this.soundObject !== null) { bytesLoaded = this.soundObject.bytesLoaded; } if (typeof(bytesLoaded) === \"undefined\" || bytesLoaded === null || isNaN(bytesLoaded)) { bytesLoaded = 0; } return bytesLoaded; } //Returns the total bytes of the file: CB_AudioFile_API[\"SM2\"].prototype.getBytesTotal = function() { var bytesTotal; if (typeof(this.soundObject) !== \"undefined\" &amp;&amp; this.soundObject !== null) { bytesTotal = this.soundObject.bytesTotal; } if (typeof(bytesTotal) === \"undefined\" || bytesTotal === null || isNaN(bytesTotal)) { bytesTotal = 0; } return bytesTotal; } */ /** * Sets a function to execute when the audio file stops playing or removes it. * @function CB_AudioFile_API.SM2#onStop * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. No parameters will be received, being \"this\" the {@link CB_AudioFile_API.SM2} object. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @returns {boolean} Returns whether the event has been set or not (removed). */ CB_AudioFile_API[\"SM2\"].prototype.onStop = function(callbackFunction, keepOldFunction) { //If not set, it keeps old function by default: if (typeof(keepOldFunction) === \"undefined\" || keepOldFunction === null) { keepOldFunction = true; } if (typeof(callbackFunction) !== \"function\") { this.onStopFunction = null; return false; } //If we don't want to keep the old function: if (!keepOldFunction) { this.onStopFunction = callbackFunction; } //...otherwise if we want to keep the old function, we keep it: else { var that = this; //Stores old function: var oldFunction = this.onStopFunction; //Stores old function of eventFunctionHolder. this.onStopFunction = function() { if (typeof(oldFunction) === \"function\") { oldFunction.call(that); } callbackFunction.call(that); }; } return true; } /** * Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. * @function CB_AudioFile_API.SM2#getProgress * @returns {number} Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. */ CB_AudioFile_API[\"SM2\"].prototype.getProgress = function() { if (this.status === CB_AudioFile.LOADED || this.status === CB_AudioFile.UNCHECKED || this.status === CB_AudioFile.CHECKING) { return 100; } else if (this.status === CB_AudioFile.UNLOADED) { return 0; } var progress = 0; //Calculates the progress (only if it is LOADING, FAILED or ABORTED): if (typeof(this.soundObject) !== \"undefined\" &amp;&amp; this.soundObject !== null &amp;&amp; typeof(this.soundObject.buffered) !== \"undefined\") { var duration = this.getDuration(); var bufferedLength = this.soundObject.buffered.length; var secondsBuffered = 0; for (var x = 0; x &lt; bufferedLength; x++) { secondsBuffered += this.soundObject.buffered[x].end - this.soundObject.buffered[x].start; } if (duration === 0) { if (secondsBuffered &gt; 0) { return 100; } else { return 0; } } else { progress = secondsBuffered / duration * 100; } if (progress &gt; 100) { progress = 100; } else if (progress &lt; 0) { progress = 0; } } return progress; } × Search results Close "},"CrossBase_audiovisual_audio_CB_AudioFile_API_WAAPI.js.html":{"id":"CrossBase_audiovisual_audio_CB_AudioFile_API_WAAPI.js.html","title":"Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js /** * @file Audio files management using \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}). Contains the {@link CB_AudioFile_API.WAAPI} class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ //var CB_AudioFile_WAAPI_filePathsLoading = []; //Stores the file paths which are being loaded. //var CB_AudioFile_WAAPI_BuffersCache = {}; //Cache of buffers for every file path. //var CB_AudioFile_WAAPI_BuffersCacheMessage = {}; //Cache of buffers for every file path. //var CB_AudioFile_WAAPI_CheckedCache = {}; //Cache of results of checkPlaying method for every file path. //We need a limit to prevent out of memory error when many calls to play() are performed: var CB_AudioFile_API_WAAPI_beingLoading = 0; //Counts how many objects are loading. var CB_AudioFile_API_WAAPI_maximumLoading = 3; //Maximum of objects that can be loading at the same time. var CB_AudioFile_API_WAAPI_beingChecking = 0; //Counts how many objects are loading. var CB_AudioFile_API_WAAPI_maximumChecking = 75; //Maximum of objects that can be loading at the same time. //Class to manage an audio file with WAAPI (Web Audio API): if (typeof(CB_AudioFile_API) === \"undefined\") { var CB_AudioFile_API = {}; } /** * The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.) if the \"autoPlay\" option is set to true, as some web clients may need this at least the first time in order to be able to play the audio. * @class CB_AudioFile_API.WAAPI * @memberof! &lt;global&gt; * @classdesc Class to manage an audio file using \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}). Used by the {@link CB_AudioFile} class internally and it shares most of its properties and methods. Recommended for internal usage only. Uses [Base64Binary]{@link https://gist.github.com/htchaan/108b7aa6b71eb03e38019e64450ea095} internally. Some old clients can use this audio API thanks to [AudioContext-MonkeyPatch]{@link https://github.com/cwilso/AudioContext-MonkeyPatch} and [WAAPISim]{@link https://github.com/g200kg/WAAPISim}. * @param {string} filePath - The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @param {string} [audioId='CB_AUDIOFILE_WAAPI_' + CB_AudioFile_API.WAAPI._idUnique++] - Desired identifier for the audio object. If not provided, an automatic unique ID will be calculated. Note that it is not case sensitive and it should be unique for each object. * @param {CB_AudioFile_API.WAAPI.OPTIONS} [options=CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS] - Object with the desired options. * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the {@link CB_AudioFile_API.WAAPI} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if could be determined), being \"this\" the {@link CB_AudioFile_API.WAAPI} object itself. * @returns {CB_AudioFile_API.WAAPI} Returns a new {@link CB_AudioFile_API.WAAPI} object. * @todo Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). Note that the \"id\" is not case sensitive and it should be unique for each object. * @todo Method getCopy and static method filterProperties (similar to the ones from {@link CB_GraphicSprites} and {@link CB_GraphicSpritesScene}). */ CB_AudioFile_API[\"WAAPI\"] = function(filePath, audioId, options, callbackOk, callbackError) { //Creates an instance of this object and returns it in the case that it is being called from an unexpected context: if (this === window || !(this instanceof CB_AudioFile_API[\"WAAPI\"])) { return new CB_AudioFile_API[\"WAAPI\"](filePath, audioId, options, callbackOk, callbackError); } //Constants: /** * Keeps the default volume. If the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT} property is true, this will keep the result of calling the {@link CB_Speaker.getVolume} function. Otherwise, it will use the value of the {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME} variable. * @constant CB_AudioFile_API.WAAPI#DEFAULT_VOLUME * @type {number} * @default CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME */ CB_AudioFile_API[\"WAAPI\"].prototype.DEFAULT_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration[CB_BASE_NAME].CB_Speaker_DEFAULT_VOLUME; /** * Keeps the default options when an object is created. Format: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. * @constant CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS * @type {CB_AudioFile_API.WAAPI.OPTIONS} * @default { autoLoad: true, autoPlay: false, loop: false, volume: [CB_AudioFile_API.WAAPI.prototype.DEFAULT_VOLUME]{@link CB_AudioFile_API.WAAPI#DEFAULT_VOLUME} } */ CB_AudioFile_API[\"WAAPI\"].prototype.DEFAULT_OPTIONS = { autoLoad: true, autoPlay: false, loop: false, volume: CB_AudioFile_API[\"WAAPI\"].prototype.DEFAULT_VOLUME, useXHR: true, useCache: true }; //Default options when the file is created. //Properties and variables: /** * Tells whether the file is unloaded ({@link CB_AudioFile.UNLOADED}), loading ({@link CB_AudioFile.LOADING}), unchecked ({@link CB_AudioFile.UNCHECKED}), checking ({@link CB_AudioFile.CHECKING}), loaded ({@link CB_AudioFile.LOADED}), failed ({@link CB_AudioFile.FAILED}) or aborted ({@link CB_AudioFile.ABORTED}). * @var CB_AudioFile_API.WAAPI#status * @readonly * @type {integer} * @default {@link CB_AudioFile.UNLOADED} */ this.status = CB_AudioFile.UNLOADED; /** * Defines whether the file loops by default when the audio is played or not. Its value will be modified automatically whenever the {@link CB_AudioFile_API.WAAPI#play} method is called, getting the value from the \"loop\" parameter (but only if contains a boolean). * @var CB_AudioFile_API.WAAPI#loop * @readonly * @type {boolean} * @default [CB_AudioFile_API.WAAPI.prototype.DEFAULT_OPTIONS]{@link CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS}.loop */ this.loop = CB_AudioFile_API[\"WAAPI\"].prototype.DEFAULT_OPTIONS.loop; /** * Stores the volume of this audio. Accepted values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is false or otherwise MAX_VOLUME is the returning value of the {@link CB_Speaker.getVolume} function. * @var CB_AudioFile_API.WAAPI#volume * @readonly * @type {number} * @default [CB_AudioFile_API.WAAPI.prototype.DEFAULT_OPTIONS]{@link CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS}.volume */ this.volume = CB_AudioFile_API[\"WAAPI\"].prototype.DEFAULT_OPTIONS.volume; /** * Stores the volume of this audio before it was muted (to restore it later). Valid values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is false or otherwise MAX_VOLUME is the returning value of the {@link CB_Speaker.getVolume} function. * @var CB_AudioFile_API.WAAPI#volumeBeforeMute * @readonly * @type {number} * @default {@link CB_AudioFile_API.WAAPI#volume} */ this.volumeBeforeMute = this.volume; /** * Stores the identifier for the audio file. * @var CB_AudioFile_API.WAAPI#id * @readonly * @type {string} * @default 'CB_AUDIOFILE_WAAPI_' + CB_AudioFile_API.WAAPI._idUnique++ */ this.id = \"\"; /** * Stores the path of the audio file or the data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @var CB_AudioFile_API.WAAPI#filePath * @readonly * @type {string} * @default */ this.filePath = \"\"; /** * Tells whether the audio is paused or not. * @var CB_AudioFile_API.WAAPI#paused * @readonly * @type {boolean} * @default false */ this.paused = false; /** * Stores the time (in milliseconds) when the audio has been paused. * @var CB_AudioFile_API.WAAPI#pauseTime * @readonly * @type {number} * @default */ this.pauseTime = 0; /** * Tells whether the audio is stopped or not. * @var CB_AudioFile_API.WAAPI#stopped * @readonly * @type {boolean} * @default true */ this.stopped = true; /** * Function to call when the audio stops. * @var CB_AudioFile_API.WAAPI#onStopFunction * @readonly * @type {function} * @default */ this.onStopFunction = null; /** * Stores the last \"startAt\" parameter value used by the {@link CB_AudioFile_API.WAAPI#play} or the {@link CB_AudioFile_API.WAAPI#resume} method. * @var CB_AudioFile_API.WAAPI#lastStartAt * @readonly * @type {number} * @default */ this.lastStartAt = null; /** * Stores the last \"stopAt\" parameter value used by the {@link CB_AudioFile_API.WAAPI#play} or the {@link CB_AudioFile_API.WAAPI#resume} method. * @var CB_AudioFile_API.WAAPI#lastStopAt * @readonly * @type {number} * @default */ this.lastStopAt = null; /** * Stores the \"source\" ([AudioBufferSourceNode]{@link https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode} object) of the audio, used by the \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}). * @var CB_AudioFile_API.WAAPI#source * @readonly * @type {AudioBufferSourceNode} * @default */ this.source = null; /** * Stores the \"buffer\" ([AudioBuffer]{@link https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode/buffer} object) of the audio, used by the \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}). * @var CB_AudioFile_API.WAAPI#buffer * @readonly * @type {AudioBuffer} * @default */ this.buffer = null; /** * Stores the \"gain node\" ([GainNode]{@link https://developer.mozilla.org/en-US/docs/Web/API/GainNode} object created with the [createGain]{@link https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/createGain} method) of the audio, used by the \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}). * @var CB_AudioFile_API.WAAPI#gainNode * @readonly * @type {GainNode} * @default */ this.gainNode = null; /** * Progress of the loading process (or downloading through [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest}) the audio data, used by the \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}). Internal usage only recommended (use the {@link CB_AudioFile_API.WAAPI#getProgress} method instead to know the progress). * @var CB_AudioFile_API.WAAPI#progressDownloading * @readonly * @type {number} * @default 0 */ this.progressDownloading = 0; //Internal properties: this._startTime = 0; //Stores the time when the play starts (used for WAAPI). this._timeoutWhenStop = null; //Keeps the timeout that is executed when the audio has finished playing (to either stop or loop). this._id_internal = null; //Internal id. this._recursiveCallTimeout = null; this._checkCurrentTimeChangesTimeout = null; this._callbackFunctionOkTimeout = null; this._loadingCounterIncreased = false; this._checkPlayingFinishingTimeout = null; this._recursiveCallCheckingTimeout = null; this._checkingCounterIncreased = false; this._lastDuration = null; //Calls the constructor of the object when creates an instance: return this._init(filePath, audioId, options, callbackOk, callbackError); } /** * Object with the options for an audio file. The format is the following one: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. * @memberof CB_AudioFile_API.WAAPI * @typedef {Object} CB_AudioFile_API.WAAPI.OPTIONS * @property {boolean} [autoLoad={@link CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS}.autoLoad] - If set to false, it will not call the {@link CB_AudioFile_API.WAAPI#load} method internally when the constructor is called (not recommended). * @property {boolean} [autoPlay={@link CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS}.autoPlay] - Value which will be used as the \"autoPlay\" parameter when calling the {@link CB_AudioFile_API.WAAPI#load} method internally, only when the \"autoLoad\" is set to true (when the constructor is called). * @property {boolean} [loop={@link CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS}.loop] - Value that will be used for the {@link CB_AudioFile_API.WAAPI#loop} property. * @property {number} [volume={@link CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS}.volume] - The desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise) that will be used for the {@link CB_AudioFile_API.WAAPI#volume} property. */ //Static properties: CB_AudioFile_API[\"WAAPI\"]._counter = 0; //Internal counter. CB_AudioFile_API[\"WAAPI\"]._idUnique = 0; //Counter to make the id unique. CB_AudioFile_API[\"WAAPI\"]._cache = []; CB_AudioFile_API[\"WAAPI\"].audioContext = null; //Constructor: CB_AudioFile_API[\"WAAPI\"].prototype._init = function(filePath, audioId, options, callbackOk, callbackError) { //If not given, defines the default parameters: if (typeof(audioId) === \"undefined\" || audioId === null) { audioId = \"CB_AUDIOFILE_WAAPI_\" + CB_AudioFile_API[\"WAAPI\"]._idUnique++; } //Uses the file path as default id. if (typeof(options) === \"undefined\" || options === null) { options = this.DEFAULT_OPTIONS; } else { if (typeof(options.loop) === \"undefined\" || options.loop === null) { options.loop = this.DEFAULT_OPTIONS.loop; } if (typeof(options.autoLoad) === \"undefined\" || options.autoLoad === null) { options.autoLoad = this.DEFAULT_OPTIONS.autoLoad; } if (typeof(options.autoPlay) === \"undefined\" || options.autoPlay === null) { options.autoPlay = this.DEFAULT_OPTIONS.autoPlay; } if (typeof(options.volume) === \"undefined\" || options.volume === null) { options.volume = this.DEFAULT_OPTIONS.volume; } if (typeof(options.useXHR) === \"undefined\" || options.useXHR === null) { options.useXHR = this.DEFAULT_OPTIONS.useXHR; } if (typeof(options.useCache) === \"undefined\" || options.useCache === null) { options.useCache = this.DEFAULT_OPTIONS.useCache; } } //Sets the audio ID: this.id = CB_trim(audioId).toUpperCase(); //Sets the internal id: if (typeof(this._id_internal) === \"undefined\" || this._id_internal === null) { this._id_internal = CB_AudioFile_API[\"WAAPI\"]._counter++; } //Sets the file path: this.filePath = filePath; //Proceeds according to the options sent: this.loop = options.loop; this.volume = options.volume; this.volumeBeforeMute = this.volume; if (options.autoLoad) { var that = this; setTimeout ( function() { that.load(that.filePath, options.autoPlay, callbackOk, callbackError, null, options.useXHR, options.useCache); }, 10 ); } //Returns the object: return this; } /** * Destroys the audio file object and frees memory. Sets its current {@link CB_AudioFile_API.WAAPI#status} property to ABORTED ({@link CB_AudioFile.ABORTED} value). * @function CB_AudioFile_API.WAAPI#destructor * @param {boolean} [stopSound=false] - If set to true, it will also call the {@link CB_AudioFile_API.WAAPI#stop} method. * @param {boolean} [keepStoppedUnaltered=false] - Used internally as the \"keepStoppedUnaltered\" parameter to call the {@link CB_AudioFile_API.WAAPI#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. * @param {boolean} [avoidOnStop=false] - Used internally as the \"avoidOnStop\" parameter to call the {@link CB_AudioFile_API.WAAPI#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. * @param {boolean} [forceOnStop=false] - Used internally as the \"forceOnStop\" parameter to call the {@link CB_AudioFile_API.WAAPI#stop} method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. */ CB_AudioFile_API[\"WAAPI\"].prototype.destructor = function(stopSound, keepStoppedUnaltered, avoidOnStop, forceOnStop) { this._lastDuration = null; //if (typeof(this.audioObject) === \"undefined\" || this.audioObject === null) { this.status = CB_AudioFile.ABORTED; return; } if (stopSound) { this.stop(keepStoppedUnaltered, avoidOnStop, forceOnStop); } CB_Elements.remove(this.source); CB_Elements.remove(this.buffer); CB_Elements.remove(this.gainNode); //CB_Elements.remove(this.audioObject); //if (this.status === CB_AudioFile.LOADING) if (this._loadingCounterIncreased) { this._loadingCounterIncreased = false; CB_AudioFile_API_WAAPI_beingLoading--; //Decreases the counter of the objects which are loading. if (CB_AudioFile_API_WAAPI_beingLoading &lt; 0) { CB_AudioFile_API_WAAPI_beingLoading = 0; } } if (this._checkingCounterIncreased) { this._checkingCounterIncreased = false; CB_AudioFile_API_WAAPI_beingChecking--; //Decreases the counter of the objects which are checking. if (CB_AudioFile_API_WAAPI_beingChecking &lt; 0) { CB_AudioFile_API_WAAPI_beingChecking = 0; } } this.status = CB_AudioFile.ABORTED; } //Returns index of the cache of a given filepath or creates a new slot for it: CB_AudioFile_API[\"WAAPI\"].prototype._getCacheIndex = function(filePath) { var index = -1; var cacheLength = CB_AudioFile_API[\"WAAPI\"]._cache.length; for (var x = 0; x &lt; cacheLength; x++) { if (CB_AudioFile_API[\"WAAPI\"]._cache[x].filePath === filePath) { index = x; break; } } if (index === -1) { index = CB_AudioFile_API[\"WAAPI\"]._cache.length; CB_AudioFile_API[\"WAAPI\"]._cache[index] = []; CB_AudioFile_API[\"WAAPI\"]._cache[index].filePath = filePath; CB_AudioFile_API[\"WAAPI\"]._cache[index].loading = false; CB_AudioFile_API[\"WAAPI\"]._cache[index].buffer = null; CB_AudioFile_API[\"WAAPI\"]._cache[index].error = null; CB_AudioFile_API[\"WAAPI\"]._cache[index].checkResult = null; } return index; } /** * Loads the desired audio file with the desired options. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. Uses [Base64Binary]{@link https://gist.github.com/htchaan/108b7aa6b71eb03e38019e64450ea095} internally. This method will be called automatically by the constructor if the \"autoLoad\" option was set to true in its given \"options\" parameter. * When this method is called, if the {@link CB_AudioFile_API.WAAPI#status} property already has the \"LOADED\" status (defined in the {@link CB_AudioFile.LOADED} constant) and the \"forceReload\" parameter is not set to true, it will exit calling the given \"callbackOk\" function (if any) immediately. Otherwise, regardless the status, the status will be set to \"LOADING\" (defined in the {@link CB_AudioFile.LOADING} constant). After it, it will reach the \"UNCHECKED\" (defined in the {@link CB_AudioFile.UNCHECKED} constant). If the \"autoPlay\" parameter is not set to true, this will be the final status (and it will be necessary to call the {@link CB_AudioFile_API.WAAPI#checkPlaying} method after it). After it and only if the \"autoPlay\" is set to true, as the {@link CB_AudioFile_API.WAAPI#checkPlaying} method will be called internally, it will have the \"CHECKING\" status (defined in the {@link CB_AudioFile.CHECKING} constant) and finally the \"LOADED\" status (defined in the {@link CB_AudioFile.LOADED} constant) if all goes well. * @function CB_AudioFile_API.WAAPI#load * @param {string} [filePath={@link CB_AudioFile_API.WAAPI#filePath}] - The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. * @param {string} [autoPlay=false] - If set to true, it will start playing the audio automatically (by calling the {@link CB_AudioFile_API.WAAPI#play} method internally). If set to true and the {@link CB_AudioFile_API.WAAPI#status} property reaches the \"UNCHECKED\" status (defined in the {@link CB_AudioFile.UNCHECKED} constant), it will also call internally the {@link CB_AudioFile_API.WAAPI#checkPlaying} method. * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the {@link CB_AudioFile_API.WAAPI} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.WAAPI} object itself. * @param {boolean} [forceReload=false] - If set to false, the \"filePath\" has not been changed from the previously used and the {@link CB_AudioFile_API.WAAPI#status} property belongs to the \"LOADED\" status (defined in the {@link CB_AudioFile.LOADED} constant), it will exit the method without loading the audio file again (calling the \"callbackOk\" function, if any). * @param {boolean} [useXHR=[CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS]{@link CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS}.useXHR] - Defines whether to use or not [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} ([AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)}) to load the audio file. * @param {boolean} [useCache=[CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS]{@link CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS}.useCache] - Defines whether to try to use or not a cache for performance purposes. If set to true and the audio file was loaded before, it will try to use the cache (if possible) to accelerate the loading process. * @returns {CB_AudioFile_API.WAAPI|null} Returns the audio API object (if it was possible to create) or null otherwise. */ CB_AudioFile_API[\"WAAPI\"].prototype.load = function(filePath, autoPlay, callbackOk, callbackError, forceReload, useXHR, useCache) { clearTimeout(this._checkCurrentTimeChangesTimeout); clearTimeout(this._callbackFunctionOkTimeout); clearTimeout(this._recursiveCallTimeout); clearTimeout(this._checkPlayingFinishingTimeout); filePath = filePath || this.filePath; //If the status is LOADED and the file path give is the same as the current one, just exits: if (!forceReload &amp;&amp; this.status === CB_AudioFile.LOADED &amp;&amp; this.filePath === filePath) { if (typeof(callbackOk) === \"function\") { callbackOk.call(this); } return this; } this.status = CB_AudioFile.LOADING; //The file is loading. var that = this; if (typeof(useCache) === \"undefined\" || useCache === null) { useCache = this.DEFAULT_OPTIONS.useCache; } var filePathIndex = this._getCacheIndex(filePath); //If we do not use cache the maximum of objects loading is reached or we use cache but the file path is loading, calls the function again after some time and exits: //if (!useCache &amp;&amp; CB_AudioFile_API_WAAPI_beingLoading &gt;= CB_AudioFile_API_WAAPI_maximumLoading || useCache &amp;&amp; typeof(CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].loading) !== \"undefined\" &amp;&amp; CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].loading) if (autoPlay &amp;&amp; !useCache &amp;&amp; CB_AudioFile_API_WAAPI_beingLoading &gt;= CB_AudioFile_API_WAAPI_maximumLoading || useCache &amp;&amp; typeof(CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].loading) !== \"undefined\" &amp;&amp; CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].loading) { this._recursiveCallTimeout = setTimeout(function() { that.load(filePath, autoPlay, callbackOk, callbackError, forceReload, useXHR, useCache); }, 100); return this; } //If the buffer for this file path is still not in the cache, other files will have to wait until it loads: if (typeof(CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].buffer) === \"undefined\" || CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].buffer === null) { CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].loading = true; //The file path is loading. } if (typeof(useXHR) === \"undefined\" || useXHR === null) { useXHR = this.DEFAULT_OPTIONS.useXHR; } //Destroys previous object (if any): this.destructor(true, false, true); //Also stops the sound (if any) and prevents firing onStop. this.status = CB_AudioFile.LOADING; //The file is loading. if (!this._loadingCounterIncreased) { this._loadingCounterIncreased = true; CB_AudioFile_API_WAAPI_beingLoading++; //Increases the counter of the objects which are loading (destructor has decreased 1). } this.filePath = filePath; //Callback wrapper function when an error happens: var callbackFunctionError = function(error, failedChecking, avoidRegisteringError) { if (that.status === CB_AudioFile.ABORTED) { return; } //If it is has been aborted, we exit. if (filePath.substring(0, 5).toLowerCase() === \"data:\") { filePath = filePath.substring(0, 15) + \"[...]\" + filePath.substring(filePath.length - 2); } if (typeof(error) === \"undefined\" || error === null) { error = \"Unknown error for \" + filePath + \" file\"; } else if (typeof(error.status) !== \"undefined\") { error = \"XHR request for \" + filePath + \" file returned \" + error.status; } else { error = \"Error message for \" + filePath + \" file: \" + error; } //Stores as failed (-1) in the cache (for the next time if any CB_AudioFile_API[\"WAAPI\"] object wants to use cache for the same file path): if (!failedChecking) //We do not store in the cache as it has failed if it has failed checking (because maybe the file is fine but just failed checking). { if (!avoidRegisteringError) { CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].error = error; } CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].buffer = -1; } if (that._loadingCounterIncreased) { that._loadingCounterIncreased = false; CB_AudioFile_API_WAAPI_beingLoading--; //Decreases the counter of the objects which are loading. if (CB_AudioFile_API_WAAPI_beingLoading &lt; 0) { CB_AudioFile_API_WAAPI_beingLoading = 0; } } CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].loading = false; //The file path is not loading anymore. that.status = CB_AudioFile.FAILED; //File failed to load. autoPlay = false; //var fileName = filePath; if (typeof(callbackError) === \"function\") { callbackError.call(that, error); } //Calls the Error function back. }; //Callback wrapper function when all goes well: var callbackFunctionOk = function() { //Function to execute when all is OK: var allIsFine = function() { if (that.status === CB_AudioFile.ABORTED) { return; } //If it is has been aborted, we exit. //Stores the buffer in the cache (for the next time if any CB_AudioFile_API[\"WAAPI\"] object wants to use cache for the same file path): CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].buffer = that.buffer; if (that._loadingCounterIncreased) { that._loadingCounterIncreased = false; CB_AudioFile_API_WAAPI_beingLoading--; //Decreases the counter of the objects which are loading. if (CB_AudioFile_API_WAAPI_beingLoading &lt; 0) { CB_AudioFile_API_WAAPI_beingLoading = 0; } } CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].loading = false; //The file path is not loading anymore. if (typeof(callbackOk) === \"function\") { callbackOk.call(that); } //Calls the OK function back. //Plays automatically if we want to: if (autoPlay) { that.play(); } }; that.status = CB_AudioFile.UNCHECKED; //The file is still unchecked. //If we want to play automatically, checks if the currentTime changes (some web clients cannot play if the user did not fire an event to call the play function): if (autoPlay) { that.checkPlaying(function() { allIsFine(); }, function(error) { callbackFunctionError(error, true); }, false, false, useCache); } else { //Starts playing and stops immediately the sound (needed for some web clients, as Edge, to be able to play the sound later from the first attempt): try { that.source = CB_AudioFile_API[\"WAAPI\"].audioContext.createBufferSource(); var source = that.source; source.buffer = that.buffer; that.gainNode = CB_AudioFile_API[\"WAAPI\"].audioContext.createGain(); that.source.connect(that.gainNode); that.gainNode.connect(CB_AudioFile_API[\"WAAPI\"].audioContext.destination); var previousVolume = that.volume; if (CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING) { that.setVolume(0); } source.loop = false; source.start(0, 0); that.source.stop(0); that.setVolume(previousVolume); } catch(E) {} //Calls the final function: allIsFine(); } } try { //Function that decodes the binary data: var callbackFunctionDecode = function(binaryData) { that.progressDownloading = 100; //The file must have been downloaded since we want to decode it now. that.decodeAudioData(binaryData, callbackFunctionOk, callbackFunctionError); }; if (typeof(window.AudioContext) === \"undefined\" &amp;&amp; typeof(window.webkitAudioContext) === \"undefined\") { callbackFunctionError(\"Web Audio API not found\"); CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].loading = false; //The file path is not loading. return null; } //Just creates an audio context: if (typeof(CB_AudioFile_API[\"WAAPI\"].audioContext) === \"undefined\" || CB_AudioFile_API[\"WAAPI\"].audioContext === null) { CB_AudioFile_API[\"WAAPI\"].audioContext = new (window.AudioContext || window.webkitAudioContext)(); //Hack (source: https://stackoverflow.com/questions/56768576/safari-audiocontext-suspended-even-with-onclick-creation/56770254#56770254): try { CB_AudioFile_API[\"WAAPI\"].audioContext.createGain(); } catch (createGainError) { CB_console(\"Error creating a GainNode for the AudioContext: \" + createGainError); } try { CB_AudioFile_API[\"WAAPI\"].audioContext.resume(); } catch (audioContextResumeError) { CB_console(\"Error resuming AudioContext: \" + audioContextResumeError); } if (!CB_AudioFile_API[\"WAAPI\"].audioContext) { callbackFunctionError(\"AudioContext/webkitAudioContext object could not be created! Value returned: \" + CB_AudioFile_API[\"WAAPI\"].audioContext); CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].loading = false; //The file path is not loading. return null; } } if (CB_AudioFile_API[\"WAAPI\"].audioContext &amp;&amp; CB_AudioFile_API[\"WAAPI\"].audioContext.state === \"suspended\") { CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].loading = false; //The file path is not loading. try { var readStateHack = CB_AudioFile_API[\"WAAPI\"].audioContext.state; //Hack. Source: https://stackoverflow.com/questions/56768576/safari-audiocontext-suspended-even-with-onclick-creation/56770254#56770254 CB_AudioFile_API[\"WAAPI\"].audioContext.resume(); //CB_AudioFile_API[\"WAAPI\"].audioContext.onstatechange = function() CB_Events.on ( CB_AudioFile_API[\"WAAPI\"].audioContext, \"statechange\", function() { if (CB_AudioFile_API[\"WAAPI\"].audioContext.state === \"running\") { that.load(filePath, autoPlay, callbackOk, callbackError, forceReload, useXHR, useCache); } }, false, //useCapture. true, //keepOldEventFunction. true //erasable. ); } catch (resumeOrOnStateChangeError) { CB_console(\"Error resuming or managing 'onStateChange' event: \" + resumeOrOnStateChangeError); } return this; } //If we want to use the cache and the file has already been loaded before, gets the buffer from the cache: if (useCache &amp;&amp; typeof(CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].buffer) !== \"undefined\" &amp;&amp; CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].buffer !== null) { this.buffer = CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].buffer; this.progressDownloading = 100; this._callbackFunctionOkTimeout = setTimeout ( (this.buffer === -1) ? function() { callbackFunctionError(\"File path from the cache already failed before. Previous message: \" + CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].error, false, true); } : callbackFunctionOk, 10 ); } //If we have received a data URI (base64), we don't need to use AJAX (XHR): else if (filePath.substring(0, 5).toLowerCase() === \"data:\") { if (filePath.indexOf(\";base64\") !== -1) { //Note: Base64Binary needs Uint8Array and ArrayBuffer support. But the web client will support it if the Web Audio API is supported. var base64Data = filePath.substring(filePath.indexOf(\",\") + 1); //We just need the data. this.progressDownloading = 100; var byteArray = Base64Binary.decodeArrayBuffer(base64Data); callbackFunctionDecode(byteArray); } else { callbackFunctionError(\"Data URI does not contain the ';base64' string\"); } } //...otherwise, we use AJAX (XHR) to load the file given: else if (useXHR) { //When the file is loaded, calls the function to set it as ready and load the buffer too: var XHR = CB_Net.XHR.callBinary(filePath, null, null, \"arraybuffer\", null, function(XHR) { callbackFunctionDecode(XHR.response); }, callbackFunctionError, [200, 206]); //Allows partial content (206 XHR status). this.progressDownloading = 0; XHR.onprogress = function updateProgress (event) { if (event.lengthComputable) { that.progressDownloading = event.loaded / event.total * 100; } }; } //...otherwise, we use WAAPI from an Audio object: else { this.progressDownloading = 0; //Function that processes the Audio element: var processAudioElement = function() { if (typeof(audioFileObject) !== \"undefined\" &amp;&amp; typeof(audioFileObject.audioObject) !== \"undefined\" &amp;&amp; audioFileObject.audioObject !== null) { try { var source = CB_AudioFile_API[\"WAAPI\"].audioContext.createMediaElementSource(audioFileObject.audioObject); var gainNode = CB_AudioFile_API[\"WAAPI\"].audioContext.createGain(); /////source.connect(gainNode); /////gainNode.connect(CB_AudioFile_API[\"WAAPI\"].audioContext.destination); analyser = CB_AudioFile_API[\"WAAPI\"].audioContext.createAnalyser(); source.connect(analyser); analyser.connect(CB_AudioFile_API[\"WAAPI\"].audioContext.destination); //source.start(0, 0); callbackFunctionOk(); //Calls the OK function back. } catch (error) { callbackFunctionError(error); } } else { callbackFunctionError(\"Audio element is undefined or null\"); } }; //Creates an Audio object with AAPI: var audioFileObject = new CB_AudioFile_API[\"AAPI\"](filePath, \"CB_media_\" + this.id, { autoLoad: true, autoPlay: false, loop: false }, processAudioElement, callbackFunctionError); } } catch(E) { callbackFunctionError(E); CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].loading = false; //The file path is not loading. return null; } //Plays automatically if we want to: //if (autoPlay) { this.play(); } //if (autoPlay) { setTimeout(function() { that.play(); }, 5000); } return this; } /** * Decodes binary audio data given. Internal usage only recommended. * @function CB_AudioFile_API.WAAPI#decodeAudioData * @param {ArrayBuffer} binaryData - [ArrayBuffer]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer} with the audio data to be decoded. * @param {function} [callbackOk] - Function with no parameters to be called when the audio data has been decoded successfully, being \"this\" the {@link CB_AudioFile_API.WAAPI} object itself. * @param {function} [callbackError] - Function to be called if the audio data has not been decoded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.WAAPI} object itself. * @returns {undefined|Promise} Returns the returning value of calling the [BaseAudioContext.decodeAudioData]{@link https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/decodeAudioData} function, which returns void (undefined) or a [Promise]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise} (whose methods \"then\" and \"catch\" will have already been used internally by this function). */ CB_AudioFile_API[\"WAAPI\"].prototype.decodeAudioData = function(binaryData, callbackOk, callbackError) { var that = this; var callbackCalled = false; var callbackDecodedOk = function(buffer) { if (callbackCalled) { return; } callbackCalled = true; //In case of error: //if (typeof(buffer) === \"undefined\" || buffer === null || !buffer) if (!buffer) { if (typeof(callbackError) === \"function\") { callbackError.call(that, \"Buffer is not defined or null or empty\"); } } //...otherwise, the sound has been loaded correctly: else { that.buffer = buffer; //Stores the buffer in this object. if (typeof(callbackOk) === \"function\") { callbackOk.call(that); } //Calls the OK function back. } }; var callbackDecodedError = function(error) //In case of error: { if (callbackCalled) { return; } callbackCalled = true; if (typeof(callbackError) === \"function\") { callbackError.call(that, error); } }; var returningValue = CB_AudioFile_API[\"WAAPI\"].audioContext.decodeAudioData(binaryData, callbackDecodedOk, callbackDecodedError); if (typeof(returningValue) !== \"undefined\" &amp;&amp; returningValue !== null &amp;&amp; typeof(returningValue.then) === \"function\") { returningValue.then(callbackDecodedOk)[\"catch\"](callbackDecodedError); } return returningValue; } /** * Checks whether the audio can be played or not. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. Also recommended to use before calling the {@link CB_AudioFile_API.WAAPI#play} method the first time. The checking action will only be performed if the value of the {@link CB_AudioFile_API.WAAPI#status} property belongs to the {@link CB_AudioFile.UNCHECKED} or to the {@link CB_AudioFile.CHECKING} value. After checking, if the audio can be played, the {@link CB_AudioFile_API.WAAPI#status} of the object will get the value of {@link CB_AudioFile.LOADED}. Otherwise, if it cannot be played, the {@link CB_AudioFile_API.WAAPI#status} property will get the value of {CB_AudioFile.FAILED}. * @function CB_AudioFile_API.WAAPI#checkPlaying * @param {function} [callbackOk] - Function with no parameters to be called when the audio has been checked successfully, being \"this\" the {@link CB_AudioFile_API.WAAPI} object itself. * @param {function} [callbackError] - Function to be called if the audio has not been checked successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.WAAPI} object itself. * @param {boolean} [ignoreStatus=false] - If set to false and the {@link CB_AudioFile_API.WAAPI#status} property does not belong neither to the \"UNCHECKED\" status (defined in the {@link CB_AudioFile.UNCHECKED} constant) nor to the \"CHECKING\" status (defined in the {@link CB_AudioFile.CHECKING} constant), it will fail calling the \"callbackError\" function (if any). If set to true, it will try to perform the checking action regardless the status of the audio. * @param {boolean} [ignoreQueue=false] - If set to false and there is already the maximum number of audio files being checked (defined internally), the function will exit and it will call itself automatically again and again until the checking process can be performed (when its queue turn has been reached). This is done for performance purposes. * @param {boolean} [useCache=false] - If set to true (not recommended) and the same audio file was checked previously, it will not perform the checking process again and it will do the same as the previous call. * @returns {boolean} Returns false if the checking could not be performed and failed. If it returns true, it can mean either the checking has been processed successfully or it will fail in the future, so it is recommended to ignore the returning value and use the callback functions instead. */ CB_AudioFile_API[\"WAAPI\"].prototype.checkPlaying = function(callbackOk, callbackError, ignoreStatus, ignoreQueue, useCache) { /////clearTimeout(this._recursiveCallCheckingTimeout); if (!ignoreStatus &amp;&amp; this.status !== CB_AudioFile.UNCHECKED &amp;&amp; this.status !== CB_AudioFile.CHECKING) { if (typeof(callbackError) === \"function\") { callbackError.call(this, \"Cannot check if status is not unchecked or checking (status is \" + this.status + \")\"); } return false; } this.status = CB_AudioFile.CHECKING; var that = this; var filePathIndex = this._getCacheIndex(this.filePath); if (useCache &amp;&amp; typeof(CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].checkResult) !== \"undefined\" &amp;&amp; CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].checkResult !== null) { if (CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].checkResult) { this.status = CB_AudioFile.LOADED; if (typeof(callbackOk) === \"function\") { callbackOk.call(that); } return true; } else { this.status = CB_AudioFile.FAILED; if (typeof(callbackError) === \"function\") { callbackError.call(that, \"File path from the cache already failed checking before.\"); } return false; } } //If we do not use cache the maximum of objects checking is reached or we use cache but the file path is checking, calls the function again after some time and exits: if (!ignoreQueue &amp;&amp; CB_AudioFile_API_WAAPI_beingChecking &gt;= CB_AudioFile_API_WAAPI_maximumChecking) { this._recursiveCallCheckingTimeout = setTimeout(function() { that.checkPlaying(callbackOk, callbackError, ignoreStatus, useCache); }, 10); return true; } //////this.status = CB_AudioFile.CHECKING; if (!this._checkingCounterIncreased) { this._checkingCounterIncreased = true; CB_AudioFile_API_WAAPI_beingChecking++; //Increases the counter of the objects which are checking. } var previousVolume = this.volume; var finishedChecking = function(ok, error, keepStatus) { //Stops the file: that.source.stop(0); //Restores the volume: that._checkPlayingFinishingTimeout = //Timeout to prevent hearing the sound in some web clients. setTimeout ( function() { that.setVolume(previousVolume); //If the file is ok: if (ok) { if (!keepStatus) { that.status = CB_AudioFile.LOADED; } if (typeof(callbackOk) === \"function\") { callbackOk.call(that); } } //...otherwise, if the file has failed: else { if (!keepStatus) { that.status = CB_AudioFile.FAILED; } if (typeof(callbackError) === \"function\") { callbackError.call(that, error); } } }, 10 ); if (that._checkingCounterIncreased) { that._checkingCounterIncreased = false; CB_AudioFile_API_WAAPI_beingChecking--; //Decreases the counter of the objects which are checking. if (CB_AudioFile_API_WAAPI_beingChecking &lt; 0) { CB_AudioFile_API_WAAPI_beingChecking = 0; } } CB_AudioFile_API[\"WAAPI\"]._cache[filePathIndex].checkResult = ok; //Stores the result in the cache. }; try { //Tries to play it silently and checks whether current time has changed. If it has not changed, the file has not been loaded properly. //Note: In Opera with Android sometimes it doesn't throw any error and status is \"playing\" but currentTime is always zero and no sound can be heard. this.source = CB_AudioFile_API[\"WAAPI\"].audioContext.createBufferSource(); var source = this.source; source.buffer = this.buffer; this.gainNode = CB_AudioFile_API[\"WAAPI\"].audioContext.createGain(); this.source.connect(this.gainNode); this.gainNode.connect(CB_AudioFile_API[\"WAAPI\"].audioContext.destination); if (CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING) { this.setVolume(0); } source.loop = false; source.start(0, 0); var currentTime = CB_AudioFile_API[\"WAAPI\"].audioContext.currentTime; var timesChecked = 0; clearTimeout(this._checkCurrentTimeChangesTimeout); clearTimeout(this._checkPlayingFinishingTimeout); var checkCurrentTimeChanges = function(callbackOk, callbackError) { if (that.status === CB_AudioFile.ABORTED || that.status === CB_AudioFile.FAILED) { finishedChecking(false, \"Audio file object is \" + (that.status === CB_AudioFile.ABORTED ? \"ABORTED\" : \"FAILED\") + \".\", true); return; } try { that.status = CB_AudioFile.CHECKING; clearTimeout(that._checkCurrentTimeChangesTimeout); var currentTimeNow = CB_AudioFile_API[\"WAAPI\"].audioContext.currentTime; //We check whther the currentTime has changed or not, until a certain number of times: if (currentTime === currentTimeNow) { if (timesChecked &lt; 1000) { timesChecked++; that._checkCurrentTimeChangesTimeout = setTimeout(function() { checkCurrentTimeChanges(callbackOk, callbackError); }, 1); return; } else { finishedChecking(false, \"currentTime does not change (it is \" + currentTime + \").\"); } } else { /////that.status = CB_AudioFile.LOADED; //The file has been loaded. finishedChecking(true); } } catch(E) { finishedChecking(false, E); } }; checkCurrentTimeChanges(callbackOk, callbackError); return true; } catch(E) { finishedChecking(false, E); return false; } } /** * Tells the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. * @function CB_AudioFile_API.WAAPI#getDuration * @returns {number} Returns the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. */ CB_AudioFile_API[\"WAAPI\"].prototype.getDuration = function() { var duration; if (typeof(this.buffer) !== \"undefined\" &amp;&amp; this.buffer !== null) { duration = this.buffer.duration * 1000; } if (typeof(duration) === \"undefined\" || duration === null || isNaN(duration) || duration &lt; 0) { duration = 0; } return duration; } /** * Plays the audio. * @function CB_AudioFile_API.WAAPI#play * @param {number} [startAt=0 | {@link CB_AudioFile_API.WAAPI#lastStartAt} | stopAt] - Time in milliseconds where we want the audio to start at. If not provided or it is not a valid number, it will use zero (0) as default which belongs to the beginning of the audio. If the value provided is greater than the \"stopAt\" provided, it will use the value set in the {@link CB_AudioFile_API.WAAPI#lastStartAt} property (which belongs to the \"startAt\" value the last time that this method was called). If, even using the {@link CB_AudioFile_API.WAAPI#lastStartAt} value is still greather than the \"stopAt\" provided, it will use the same value as the \"stopAt\" which means it will not play and will stop immediately. * @param {number} [stopAt={@link CB_AudioFile_API.WAAPI#getDuration}()] - Time in milliseconds where we want the audio to stop at. If not provided or it is not a valid number, it will use the returning value of the {@link CB_AudioFile_API.WAAPI#getDuration} method (which should belong to the total duration of the audio, if it was calculated correctly). * @param {boolean} [loop={@link CB_AudioFile_API.WAAPI#loop}] - Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the {@link CB_AudioFile_API.WAAPI#onStop} method) will not be called. * @param {boolean} [avoidDelayedPlay=false] - If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the \"stop\" method will be called immediately. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the {@link CB_AudioFile_API.WAAPI#stop} method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). * @param {function} [onPlayStart] - Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the {@link CB_AudioFile_API.WAAPI} object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. * @param {function} [onLoadError] - Function to be called if the audio cannot be played successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.WAAPI} object. * @param {boolean} [isResume=false] - If set to true (not recommended) and it is a looping audio, the next loop will use the value of the {@link CB_AudioFile_API.WAAPI#lastStartAt} property as the \"startAt\" parameter when it calls this method again automatically (internally). Recommended for internal usage only. * @param {boolean} [isLooping=false] - Used to determine whether this method was called automatically again by itself because it is looping the audio. Recommended for internal usage only. * @param {integer} [startPlayingTime] - Contains the time when the audio should start playing. Recommended for internal usage only. * @returns {boolean|integer} It returns false if the duration is 0 (\"startAt\" and \"stopAt\" are the same number), returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. */ CB_AudioFile_API[\"WAAPI\"].prototype.play = function(startAt, stopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, isResume, isLooping, startPlayingTime) { var that = this; var duration = this.getDuration(); if (typeof(startPlayingTime) === \"undefined\" || startPlayingTime === null) { startPlayingTime = CB_Device.getTiming(); } //If the sound is not ready yet, calls the function again but later: /*if (this.status !== CB_AudioFile.LOADED || this.getDuration() === 0) //Duration must be greater than zero. { this.stopped = true; this.paused = false; //If it has not failed or aborted, calls the function again but later: if (this.status !== CB_AudioFile.FAILED &amp;&amp; this.status !== CB_AudioFile.ABORTED) { setTimeout(function() { that.play(startAt, stopAt, loop, allowOverlapping, avoidDelayedPlay, onLoadError, isResume, isLooping); }, 1); } //...otherwise, if it has failed, sets it as stopped: //else { this.stopped = true; } return -1; }*/ if (this.status !== CB_AudioFile.LOADED || duration === 0) //Duration must be greater than zero. { this.stopped = true; this.paused = false; //If it has not failed or aborted: if (this.status !== CB_AudioFile.FAILED &amp;&amp; this.status !== CB_AudioFile.ABORTED) //It must be UNLOADED, LOADING, LOADED, UNCHECKED or CHECKING. { //Function that calls the play method recursively (unless the maximum time allowed has expired): var playLaterFunctionCalled = false; var playLaterFunction = function() { if (playLaterFunctionCalled) { return; } playLaterFunctionCalled = true; //If the recursive delay is not null and is a valid number: if (typeof(allowedRecursiveDelay) === \"undefined\" || allowedRecursiveDelay === null || isNaN(allowedRecursiveDelay) || allowedRecursiveDelay &lt; 0) { allowedRecursiveDelay = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT; //We use default value. } var timeNow = CB_Device.getTiming(); //If the time expired is less or equal to the delay allowed: if (timeNow - startPlayingTime &lt;= allowedRecursiveDelay) { //Calls play method again: that.play(startAt, stopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, isResume, isLooping, startPlayingTime); } //...otherwise, just stops the sound: /////else { that.stop(false, false); } //Sets as stopped and fires onStop function (if any). else { that.stop(false, false, true); } //Sets as stopped and fires onStop function (if any). }; //Function to execute when the sound loads successfully (or finishes checking successfully): var onLoad = function() { //If we allow delayed play, plays the sound: if (!avoidDelayedPlay) { playLaterFunction(); } //...otherwise, just stops the sound (to fire onStop function): else { that.stop(false, false, true); } //Sets as stopped and fires onStop function (if any). }; //If it is UNLOADED or we had a duration before but not now and it is not LOADING, loads the file again: if (this.status === CB_AudioFile.UNLOADED || this.status !== CB_AudioFile.LOADING &amp;&amp; this._lastDuration !== null &amp;&amp; duration === 0) { this.load(this.filePath, false, onLoad, onLoadError, true); } //...otherwise, if it is UNCHECKED, we call the checking function: else if (this.status === CB_AudioFile.UNCHECKED) { this.checkPlaying(onLoad, onLoadError, false, true, false); } //...otherwise, if it is not CHECKING (it must be LOADING or LOADED with duration 0 from the beginning), we will not reload the sound: else if (this.status !== CB_AudioFile.CHECKING) { //If we allow delayed play, calls the play method again but after some time: if (!avoidDelayedPlay) { setTimeout(playLaterFunction, 1); } //...otherwise, just stops the sound (to fire onStop function): /////else { this.stop(false, false); } //Sets as stopped and fires onStop function (if any). else { this.stop(false, false, true); } //Sets as stopped and fires onStop function (if any). } } return -1; } this._lastDuration = duration; //Defines the default parameters: if (CB_trim(startAt) === \"\") { startAt = 0; } //Starts at the beginning as default. if (CB_trim(stopAt) === \"\") { stopAt = 0; } //If it is not a number, default is zero. if (typeof(loop) === \"undefined\" || loop === null) { loop = this.loop; } //If not set, uses the default (or last one used). else { this.loop = loop; } //...otherwise, stores the new setting given. //Sanitizes startAt and stopAt: startAt = parseFloat(startAt); stopAt = parseFloat(stopAt); if (startAt &lt; 0) { startAt = 0; } if (stopAt &lt;= 0 || stopAt &gt; duration) { stopAt = duration; } //If the stopAt is not correct, plays until the end of the file. if (startAt &gt; stopAt) { startAt = this.lastStartAt; } //In the case start time is greater than the stop time, starts as the previous time. if (startAt &gt; stopAt || isNaN(startAt)) { startAt = stopAt; } //If the duration is zero (startAt and stopAt are equal), exits: if (startAt === stopAt) { this.stop(); return false; } //Next loop (if any) it will start at the same time by default: var startAtNextLoop = startAt; //If it is a resume, next loop we should start from the previous startAt used: if (isResume) { startAtNextLoop = this.lastStartAt; } //...otherwise, if it is not a resume, stores the startAt used: else { this.lastStartAt = startAt; } this.lastStopAt = stopAt; //Stores stopAt used. //Adds the event to check when the file reaches the stop time: var whenStopFunction = function() { //Removes the event and timeout: clearTimeout(that._timeoutWhenStop); //Clears the previous timeout. //CB_Events.remove(source, \"ended\", whenStopFunction, false); //CB_Events.remove(source, \"webkitended\", whenStopFunction, false); //If the sound has been stopped or paused or the stop time has changed, exits: if (that.stopped || that.paused || that.lastStopAt !== stopAt) { return; } //...otherwise, if the stop time has not been reached yet, calls the function again after a while: ///////else if (that.getCurrentTime() &lt; stopAt) { setTimeout(whenStopFunction, 1); return; } //If we want to loop, loops again: if (that.loop) { //that.stop(true); //Stops the sound without setting its property as stopped. that.play(startAtNextLoop, stopAt, true, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, false, true); //Plays again the sound. } //...otherwise, if we don't want to loop, we stop: else { that.stop(); } }; //Clears the previous timeout (if any): clearTimeout(this._timeoutWhenStop); //If it is not a loop (it is the first call to the play method) or we do not want to loop: if (!isLooping || !loop) { CB_symmetricCallClear(\"WAAPI_AUDIO_FILE\" + this._id_internal); } //We clean the cache of setTimeoutSynchronized for the loop function. //If it is looping or does not allow overlapping and it is not paused, stops the possible previous sound: //if (isLooping || !allowOverlapping &amp;&amp; !this.paused) { this.stop(true); } //Stops the sound without setting its property as stopped. this.stop(true, true); //Stops the sound without setting its property as stopped. //Prepares the mystical stuff: this.source = CB_AudioFile_API[\"WAAPI\"].audioContext.createBufferSource(); var source = this.source; source.buffer = this.buffer; //Creates a gain node to be able to set the volume later: this.gainNode = CB_AudioFile_API[\"WAAPI\"].audioContext.createGain(); this.source.connect(this.gainNode); this.gainNode.connect(CB_AudioFile_API[\"WAAPI\"].audioContext.destination); //Applies the current volume: this.setVolume(this.volume); //Plays the sound: source.loop = false; //We will use our own way to loop, so we don't need the normal way. source.start(0, startAt / 1000, (stopAt - startAt) / 1000); //WAAPI needs seconds. //Stores the start time (useful for pause/resume): this._startTime = CB_AudioFile_API[\"WAAPI\"].audioContext.currentTime - (startAt / 1000); //WAAPI needs seconds. //Sets the event and timeout for when the sound finishes: //if (typeof(source.onended) !== \"undefined\") { CB_Events.add(source, \"ended\", whenStopFunction, false, true, true); } //else if (typeof(source.webkitended) !== \"undefined\") { CB_Events.add(source, \"webkitended\", whenStopFunction, false, true, true); } //else //{ var msToFinish = stopAt - startAt; this._timeoutWhenStop = CB_symmetricCall(whenStopFunction, msToFinish, \"WAAPI_AUDIO_FILE\" + this._id_internal); //} //The sound is neither paused nor stopped: this.paused = this.stopped = false; //If it is the first time (not a loop) and there is a function to call when the play starts, we call it: if (!isLooping &amp;&amp; typeof(onPlayStart) === \"function\") { onPlayStart.call(this, startAt, stopAt, startAtNextLoop, loop, avoidDelayedPlay, allowedRecursiveDelay, startPlayingTime); onPlayStart = null; } //Prevents execution again. return true; } /** * Resumes the audio (after being paused), starting from the same point it was paused previously. * @function CB_AudioFile_API.WAAPI#resume * @param {boolean} [loop={@link CB_AudioFile_API.WAAPI#loop}] - Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the {@link CB_AudioFile_API.WAAPI#onStop} method) will not be called. * @param {boolean} [avoidDelayedPlay=false] - If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the {@link CB_AudioFile_API.WAAPI#stop} method will be called immediately. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the {@link CB_AudioFile_API.WAAPI#stop} method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). * @param {function} [onPlayStart] - Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the {@link CB_AudioFile_API.WAAPI} object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. * @param {function} [onLoadError] - Function to be called if the audio cannot be played successfully. It will not be called if the audio is not paused or is stopped. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the {@link CB_AudioFile_API.WAAPI} object. * @returns {boolean|integer} Returns the returning value of the {@link CB_AudioFile_API.WAAPI#play} method which is called internally. It returns false if the audio is not paused or it is stopped, returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. */ CB_AudioFile_API[\"WAAPI\"].prototype.resume = function(loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError) { //If it not paused or it is stopped, exits the function: if (!this.paused || this.stopped) { return false; } //var startAt = this.pauseTime - (this._startTime * 1000); var startAt = this.pauseTime; //If it has been paused after the stop time (happens sometimes when the sound was nearly to finish): if (startAt &gt;= this.lastStopAt) { startAt = this.lastStopAt - 1; //We will begin just 1 millisecond before (otherwise the play method would begin again from lastStartAt). } return this.play(startAt, this.lastStopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onLoadError, true, false); } /** * Pauses the audio when it is being played. * @function CB_AudioFile_API.WAAPI#pause * @param {function} [onPause] - Function without parameters to be called when the audio is paused successfully, being \"this\" the {@link CB_AudioFile_API.WAAPI} object. * @param {boolean} [keepPausedUnaltered=false] - If set to true (not recommended), the {@link CB_AudioFile_API.WAAPI#paused} property will not be set to true and it will remain with its current value. * @returns {boolean} It returns false if the audio is already paused or it is stopped or if it cannot be paused. Returns true otherwise. */ CB_AudioFile_API[\"WAAPI\"].prototype.pause = function(onPause, keepPausedUnaltered) { //If it already paused or stopped, exits the function: if (this.paused || this.stopped) { return false; } if (typeof(CB_AudioFile_API[\"WAAPI\"].audioContext) !== \"undefined\" &amp;&amp; CB_AudioFile_API[\"WAAPI\"].audioContext !== null) { if (typeof(this.source) !== \"undefined\" &amp;&amp; this.source !== null) { clearTimeout(this._timeoutWhenStop); //Prevents that the file is set as stopped or to be executed again. if (!keepPausedUnaltered) { this.paused = true; } //Prevents error on Safari Mobile (\"InvalidStateError: DOM Exception 11: An attempt was made to use an object that is not, or is no longer, usable.\"): try { this.source.stop(0); } catch(E) {} //this.pauseTime = CB_AudioFile_API[\"WAAPI\"].audioContext.currentTime * 1000; this.pauseTime = (CB_AudioFile_API[\"WAAPI\"].audioContext.currentTime - this._startTime) * 1000; if (typeof(onPause) === \"function\") { onPause.call(this); } return true; } } return false; } /** * Stops the audio. * @function CB_AudioFile_API.WAAPI#stop * @param {boolean} [keepStoppedUnaltered=false] - If set to true (not recommended), the {@link CB_AudioFile_API.WAAPI#stopped} property will not be set to true and it will remain with its current value. * @param {boolean} [avoidOnStop=false] - If set to false and there is an \"onStop\" function defined (through the {@link CB_AudioFile_API.WAAPI#onStop} method), it will be called after stopping the audio (or after trying to do it, at least) but only if either the \"forceOnStop\" parameter is set to true or if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. If set to true, the \"onStop\" function (if any) will not be called at all. * @param {boolean} [forceOnStop=false] - If it is set to true and the \"avoidOnStop\" parameter is set to false and there is an \"onStop\" function defined (through the {@link CB_AudioFile_API.WAAPI#onStop} method), it will be called regardless the audio was stopped before or not. If set to false, the \"onStop\" function (if any) will only be called if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. This parameter will be ignored if the \"avoidOnStop\" parameter is set to true. * @returns {boolean} It returns false if the stopping action cannot be performed at all (this could happen when the audio has not been loaded properly, for example). Returns true otherwise (this only means that it has been tried to be stopped but it could not be successfully). */ CB_AudioFile_API[\"WAAPI\"].prototype.stop = function(keepStoppedUnaltered, avoidOnStop, forceOnStop) { if (typeof(this.source) !== \"undefined\" &amp;&amp; this.source !== null) { ///////clearTimeout(this._timeoutWhenStop); //Prevents that the file is set as stopped or to be executed again. var stoppedBefore = this.stopped; if (!keepStoppedUnaltered) { this.stopped = true; } this.paused = false; //If it is stopped, it is not paused. //Prevents error on Safari Mobile (\"InvalidStateError: DOM Exception 11: An attempt was made to use an object that is not, or is no longer, usable.\"): try { this.source.stop(0); } catch(E) {} //If we do not want to avoid onStop, it was not stopped before but it is now and onStop has a valid function assigned, we execute it: if (!avoidOnStop &amp;&amp; (!stoppedBefore &amp;&amp; this.stopped || forceOnStop) &amp;&amp; typeof(this.onStopFunction) === \"function\") { this.onStopFunction.call(this); } return true; } return false; } /** * Sets the desired volume for the audio file (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). * @function CB_AudioFile_API.WAAPI#setVolume * @param {number} [volume={@link CB_Speaker.getVolume()} | {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME}] - Desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). * @param {boolean} [forceSetVolumeProperty=false] - If set to true (not recommended), it will change the {@link CB_AudioFile_API.WAAPI#volume} property even when the volume failed to be changed. * @param {function} [onSetVolume] - Callback function which will be called if it has been possible to set the volume (or at least it was possible to try it). It will not receive any parameters, being \"this\" the {@link CB_AudioFile_API.WAAPI} object. * @param {boolean} [saveForUnmute=false] - If set to true (not recommended), it will save internally the current volume before setting it so it will restore the same volume again after calling the {@link CB_AudioFile_API.WAAPI#unmute} method. Internal usage only recommended. * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). */ CB_AudioFile_API[\"WAAPI\"].prototype.setVolume = function(volume, forceSetVolumeProperty, onSetVolume, saveForUnmute) { //Defines the default parameters: volume = parseInt(volume); if (isNaN(volume)) { this.DEFAULT_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration[CB_BASE_NAME].CB_Speaker_DEFAULT_VOLUME; volume = this.DEFAULT_VOLUME; } //Sets the volume within their limits if it is beyond them: var MAX_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM ? CB_Speaker.getVolume() : 100; if (volume &gt; MAX_VOLUME) { volume = MAX_VOLUME; } else if (volume &lt; 0) { volume = 0; } if (typeof(this.gainNode) !== \"undefined\" &amp;&amp; this.gainNode !== null) { if (typeof(this.gainNode.gain.setValueAtTime) !== \"undefined\") { this.gainNode.gain.setValueAtTime(volume / 100, CB_AudioFile_API[\"WAAPI\"].audioContext.currentTime); } else { this.gainNode.gain.value = volume / 100; } //fraction * fraction; if ((saveForUnmute || volume === 0) &amp;&amp; this.volume &gt; 0) { this.volumeBeforeMute = this.volume; } //Also saves the previous volume if the desired one is zero (muted). this.volume = volume; if (typeof(onSetVolume) === \"function\") { onSetVolume.call(this); } } if (forceSetVolumeProperty) { this.volume = volume; } return this.volume; } /** * Mutes the audio file. * @function CB_AudioFile_API.WAAPI#mute * @param {function} [onMute] - Callback function which will be called if it has been possible to mute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the {@link CB_AudioFile_API.WAAPI} object. * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). If all goes well, the returning value should be zero (0). Note that, even when it returns a zero (0) value, this does not always mean that the mute has been applied successfully. */ CB_AudioFile_API[\"WAAPI\"].prototype.mute = function(onMute) { //Only mutes the sound if it is not muted already: if (this.volume &gt; 0) { //Mutes the audio: this.setVolume(0, false, onMute, true); //It modifies this.volumeBeforeMute. } return this.volume; } /** * Restores audio after muting it (unmutes it). * @function CB_AudioFile_API.WAAPI#unmute * @param {function} [onUnmute] - Callback function which will be called if it has been possible to unmute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the {@link CB_AudioFile_API.WAAPI} object. * @returns {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). */ CB_AudioFile_API[\"WAAPI\"].prototype.unmute = function(onUnmute) { //Only unmutes if it is still muted: if (this.volume === 0) { //Restores the volume before muting: this.setVolume(this.volumeBeforeMute, false, onUnmute); } return this.volume; } /** * Gets the current time (in milliseconds) which belongs to the position where the audio is currently playing or where it has been paused. Note that some audio APIs and clients could give wrong values. * @function CB_AudioFile_API.WAAPI#getCurrentTime * @returns {number} Returns the current time (in milliseconds). Note that some audio APIs and clients could give wrong values. */ CB_AudioFile_API[\"WAAPI\"].prototype.getCurrentTime = function() { var currentTime; if (typeof(CB_AudioFile_API[\"WAAPI\"].audioContext) !== \"undefined\" &amp;&amp; CB_AudioFile_API[\"WAAPI\"].audioContext !== null) { if (this.stopped) { currentTime = 0; } else if (this.paused) { //currentTime = this.pauseTime - (this._startTime * 1000); currentTime = this.pauseTime; } else { currentTime = (CB_AudioFile_API[\"WAAPI\"].audioContext.currentTime - this._startTime) * 1000; } //Maybe it is a loop: var duration = this.getDuration(); if (duration &gt; 0) //Avoids division by zero. { currentTime %= duration; } } if (typeof(currentTime) === \"undefined\" || currentTime === null || isNaN(currentTime) || currentTime &lt; 0) { currentTime = 0; } return currentTime; } /** * Sets a function to execute when the audio file stops playing or removes it. * @function CB_AudioFile_API.WAAPI#onStop * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. No parameters will be received, being \"this\" the {@link CB_AudioFile_API.WAAPI} object. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @returns {boolean} Returns whether the event has been set or not (removed). */ CB_AudioFile_API[\"WAAPI\"].prototype.onStop = function(callbackFunction, keepOldFunction) { //If not set, it keeps old function by default: if (typeof(keepOldFunction) === \"undefined\" || keepOldFunction === null) { keepOldFunction = true; } if (typeof(callbackFunction) !== \"function\") { this.onStopFunction = null; return false; } //If we don't want to keep the old function: if (!keepOldFunction) { this.onStopFunction = callbackFunction; } //...otherwise if we want to keep the old function, we keep it: else { var that = this; //Stores old function: var oldFunction = this.onStopFunction; //Stores old function of eventFunctionHolder. this.onStopFunction = function() { if (typeof(oldFunction) === \"function\") { oldFunction.call(that); } callbackFunction.call(that); }; } return true; } /** * Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. * @function CB_AudioFile_API.WAAPI#getProgress * @returns {number} Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. */ CB_AudioFile_API[\"WAAPI\"].prototype.getProgress = function() { if (this.status === CB_AudioFile.LOADED || this.status === CB_AudioFile.UNCHECKED || this.status === CB_AudioFile.CHECKING) { return 100; } else if (this.status === CB_AudioFile.UNLOADED) { return 0; } var progress = 0; //Calculates the progress (only if it is LOADING, FAILED or ABORTED): //TODO: if decodeAudioData method gets a way to know its progress in the future, use that way here. //Progress downloading is considered as the 50% of the process (the other 50% would be te decodinng by decodeAudioData method): progress = this.progressDownloading / 2; return progress; } × Search results Close "},"CrossBase_audiovisual_audio_CB_AudioFileCache.js.html":{"id":"CrossBase_audiovisual_audio_CB_AudioFileCache.js.html","title":"Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js /** * @file Audio files cache management. Contains the {@link CB_AudioFileCache} class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Object whose property names are audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"') and their value is an array of strings with the URIs (audio file paths or audio data URIs) of the audio files in order of preference. The best audio format for the current client will be tried to be calculated and it will use the first working URI (audio file path or data URI). The more audio formats and URIs provided the better, as it will help to maximize the compatibility with as many clients as possible (as some audio APIs and client just support some formats, or use absolute paths instead of relative ones, etc.). Even with different formats, all provided URIs should belong to the same audio (this means same sound or same music, with same length, etc.). NOTE: Only some clients with some audio APIs will support data URIs. * @example * { * \"audio/mp4\" : [ \"first/path/sound.m4a\", \"alternative/path/sound.m4a\", \"alternative/path/2/sound.mp4\", ... ], * \"audio/ogg\" : [ \"first/path/sound.opus\", \"alternative/path/sound.ogg\", \"alternative/path/2/sound.ogg\", ... ], * \"audio/mpeg\" : [ \"first/path/sound.mp3\", \"alternative/path/sound.mp3\", \"alternative/path/2/sound.mp3\", ... ], * \"audio/wav\" : [ \"first/path/sound.wav\", \"alternative/path/sound.wav\", \"alternative/path/2/sound.wav\", ... ], * ... * } * @memberof CB_AudioFileCache * @typedef {Object} CB_AudioFileCache.URIS_OBJECT * @property {array} filePaths - Being the name of each property the audio format (it can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"'), the value will always be a numeric array of strings with the URIs (audio file paths or audio data URIs) of the audio files in order of preference. The best audio format for the current client will be tried to be calculated and it will use the first working URI (audio file path or data URI). The more audio formats and URIs provided the better, as it will help to maximize the compatibility with as many clients as possible (as some audio APIs and client just support some formats, or use absolute paths instead of relative ones, etc.). Even with different formats, all provided URIs should belong to the same audio (this means same sound or same music, with same length, etc.). NOTE: Only some clients with some audio APIs will support data URIs. */ /** * Object with the desired data and options for the audio files cache. * @memberof CB_AudioFileCache * @typedef {Object} CB_AudioFileCache.DATA_OBJECT * @property {CB_AudioFileCache.URIS_OBJECT} URIs - Object whose property names audio formats and their value is an array of strings with the URIs (audio file paths or audio data URIs) of the audio files in order of preference. The best audio format for the current client will be tried to be calculated and it will use the first working URI (audio file path or data URI). The more audio formats and URIs provided the better, as it will help to maximize the compatibility with as many clients as possible (as some audio APIs and client just support some formats, or use absolute paths instead of relative ones, etc.). Even with different formats, all provided URIs should belong to the same audio (this means same sound or same music, with same length, etc.). NOTE: Only some clients with some audio APIs will support data URIs. If a valid value is given, this will be added to the {@link CB_AudioFileCache#URIs} property. * @property {string} [id=\"\"] - Desired identifier for the audio files cache. Internal usage only recommended. If a valid value is given, this will be added to the {@link CB_AudioFileCache#id} property. * @property {array} [preferredAPIs={@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS}] - Array of strings with the preferred audio API or audio APIs, in order of preference. Possible audio APIs are \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). It will try to calculate and use the best one for the current client. If a valid value is given, this will be added to the {@link CB_AudioFileCache#preferredAPIs} property. * @property {array} [preferredFormats={@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_FORMATS}] - Array of strings with the preferred audio format or audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"'), in order of preference. It will try to calculate and use the best one for the current client. If a valid value is given, this will be added to the {@link CB_AudioFileCache#preferredFormats} property. * @property {integer} [minimumAudioFiles={@link CB_AudioFileCache.minimumAudioFiles_DEFAULT}] - Minimum {@link CB_AudioFile} objects to create internally. It must be an integer being 1 the minimum. If a valid value is given, this will be added to the {@link CB_AudioFileCache#minimumAudioFiles} property. * @property {integer|null} [maximumAudioFiles={@link CB_AudioFileCache.maximumAudioFiles_DEFAULT}] - Maximum {@link CB_AudioFile} objects that are allowed to be created internally. If it is set to null, there will not be a maximum (it will be unlimited). If an integer is provided, it must be the same number or greater than the value set in the {@link CB_AudioFileCache#minimumAudioFiles} property (also provided by the \"minimumAudioFiles\" of this object), allowing 1 minimum. If a valid value is given, this will be added to the {@link CB_AudioFileCache#maximumAudioFiles} property. * @property {integer} [minimumAudioFilesFree=parseInt({@link CB_AudioFileCache#minimumAudioFiles} * 0.25 + 0.5)] - New {@link CB_AudioFile} objects will be created internally when the number of free {@link CB_AudioFile} objects reaches this limit. If provided, it must be an integer being 0 (zero) the minimum. It will end using a 25% of the {@link CB_AudioFileCache#minimumAudioFiles} by default, rounded to ceil, allowing 0 (zero) minimum. If a valid value is given, this will be added to the {@link CB_AudioFileCache#minimumAudioFilesFree} property. * @property {integer} [newAudioFilesWhenNeeded=Math.min(parseInt({@link CB_AudioFileCache#minimumAudioFiles} * 0.1 + 0.5), 1)] - Number of new {@link CB_AudioFile} objects to create internally when the minimum limit of free {@link CB_AudioFile} objects ({@link CB_AudioFileCache#minimumAudioFilesFree}) is reached. If provided, it must be an integer being 0 (zero) the minimum. It will end using a 10% of the {@link CB_AudioFileCache#minimumAudioFiles} by default, rounded to ceil, allowing 1 minimum. If a valid value is given, this will be added to the {@link CB_AudioFileCache#newAudioFilesWhenNeeded} property. * @property {integer} [retries={@link CB_AudioFileCache.retries_DEFAULT}] - Number of retries to try to load a {@link CB_AudioFile} object internally before trying to load the next possible one (if any). It must be an integer being 0 the minimum. If a valid value is given, this will be added to the {@link CB_AudioFileCache#retries} property. * @property {boolean} [checkManually={@link CB_AudioFileCache.checkManually_DEFAULT}] - Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) by default. If a valid value is given, this will be added to the {@link CB_AudioFileCache#checkManually} property. * @property {boolean} [checkManuallyOnNeededCreated={@link CB_AudioFileCache.checkManuallyOnNeededCreated_DEFAULT}] - Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when creates a new {@link CB_AudioFile} object needed. If a valid value is given, this will be added to the {@link CB_AudioFileCache#checkManuallyOnNeededCreated} property. * @property {boolean} [checkManuallyOnPlayingFailed={@link CB_AudioFileCache.checkManuallyOnPlayingFailed_DEFAULT}] - Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when playing one has failed and tries to reload it. If a valid value is given, this will be added to the {@link CB_AudioFileCache#checkManuallyOnPlayingFailed} property. * @property {boolean} [checkManuallyOnCheckingFailed={@link CB_AudioFileCache.checkManuallyOnCheckingFailed_DEFAULT}] - Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when checking one has failed and tries to reload it. If a valid value is given, this will be added to the {@link CB_AudioFileCache#checkManuallyOnCheckingFailed} property. * @property {function} [onLoad] - Desired function to be called once the cache has been loaded. The first and unique parameter will be an integer with the {@link CB_AudioFile} objects that still need to be checked, if any, being \"this\" the current {@link CB_AudioFileCache} object. If a valid value is given, this will be added to the {@link CB_AudioFileCache#onLoad} property. * @property {function} [onError] - Desired function to be called when any kind of error happens. The first and unique parameter will be a string with the error description (if it could be determined), being \"this\" the current {@link CB_AudioFileCache} object. If a valid value is given, this will be added to the {@link CB_AudioFileCache#onError} property. * @property {boolean} [disableAutoLoad=false] - If set to true, it will not create automatically the {@link CB_AudioFile} objects by calling the {@link CB_AudioFileCache#createAudioFiles} method internally. Internal usage only recommended. */ /** * The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. * @class * @classdesc Class to manage a cache with multiple {@link CB_AudioFile} objects (they should be the same sound although they can be in different formats). This is not only useful for performance purposes but also for being able to play the same sound simultaneously and multiple times in different audio APIs and clients. * @param {CB_AudioFileCache.DATA_OBJECT} [dataObject] - Object with the desired data and options for the audio files cache. * @returns {CB_AudioFileCache} Returns a new {@link CB_AudioFileCache} object. * @todo Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). * @todo Method getCopy and static method filterProperties (similar to the ones from {@link CB_GraphicSprites} and {@link CB_GraphicSpritesScene}). */ var CB_AudioFileCache = function(dataObject) { //Creates an instance of this object and returns it in the case that it is being called from an unexpected context: if (this === window || !(this instanceof CB_AudioFileCache)) { return new CB_AudioFileCache(dataObject); } //Static properties and constants: /** * Keeps the default volume. If the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT} property is true, this will keep the result of calling the {@link CB_Speaker.getVolume} function. Otherwise, it will use the value of the {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME} variable. * @constant * @type {number} * @default CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME */ CB_AudioFileCache.prototype.DEFAULT_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration[CB_BASE_NAME].CB_Speaker_DEFAULT_VOLUME; //Properties and variables: /** * Tells whether the cache is unloaded ({@link CB_AudioFileCache.UNLOADED}), loading ({@link CB_AudioFileCache.LOADING}), unchecked ({@link CB_AudioFileCache.UNCHECKED}), checking ({@link CB_AudioFileCache.CHECKING}), loaded ({@link CB_AudioFileCache.LOADED}), failed ({@link CB_AudioFileCache.FAILED}) or aborted ({@link CB_AudioFileCache.ABORTED}). * @var CB_AudioFileCache#status * @readonly * @type {integer} * @default {@link CB_AudioFileCache.UNLOADED} */ this.status = CB_AudioFileCache.UNLOADED; /** * Stores the identifier for the audio files cache. * @var * @readonly * @type {string} * @default */ this.id = \"\"; /** * Stores an array of strings with the preferred audio API or audio APIs, in order of preference. Possible audio APIs are \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). Internal usage only recommended. * @var * @readonly * @type {array} * @default CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS */ this.preferredAPIs = CB_Configuration[CB_BASE_NAME].CB_AudioFileCache_PREFERRED_AUDIO_APIS; /** * Stores an array of strings with the preferred audio format or audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"'), in order of preference. Internal usage only recommended. * @var * @readonly * @type {array} * @default CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_FORMATS */ this.preferredFormats = CB_Configuration[CB_BASE_NAME].CB_AudioFileCache_PREFERRED_AUDIO_FORMATS; /** * Object whose property names audio formats and their value is an array of strings with the URIs (audio file paths or audio data URIs) of the audio files in order of preference. The more audio formats and URIs provided the better, as it will help to maximize the compatibility with as many clients as possible (as some audio APIs and client just support some formats, or use absolute paths instead of relative ones, etc.). Even with different formats, all provided URIs should belong to the same audio (this means same sound or same music, with same length, etc.). NOTE: Only some clients with some audio APIs will support data URIs. Internal usage only recommended. * @var * @readonly * @type {CB_AudioFileCache.URIS_OBJECT} */ this.URIs = {}; /** * Minimum {@link CB_AudioFile} objects to create internally. It must be an integer being 1 the minimum. Internal usage only recommended. * @var * @readonly * @type {integer} * @default CB_AudioFileCache.minimumAudioFiles_DEFAULT */ this.minimumAudioFiles = CB_AudioFileCache.minimumAudioFiles_DEFAULT; /** * Maximum {@link CB_AudioFile} objects that are to be created internally. If it is set to null, there will not be a maximum (it will be unlimited). If an integer is provided, it must be the same number or greater than the value set in the {@link CB_AudioFileCache#minimumAudioFiles} property, allowing 1 minimum. Internal usage only recommended. * @var * @readonly * @type {integer|null} * @default CB_AudioFileCache.maximumAudioFiles_DEFAULT */ this.maximumAudioFiles = CB_AudioFileCache.maximumAudioFiles_DEFAULT; /** * New {@link CB_AudioFile} objects will be created internally when the number of free {@link CB_AudioFile} objects reaches this limit. It must be an integer being 0 (zero) the minimum. Internal usage only recommended. * @var * @readonly * @type {integer} * @default parseInt({@link CB_AudioFileCache#minimumAudioFiles} * 0.25 + 0.5) */ this.minimumAudioFilesFree = CB_AudioFileCache._minimumAudioFilesFree_FIRST_VALUE; /** * Number of new {@link CB_AudioFile} objects to create internally when the minimum limit of free {@link CB_AudioFile} objects ({@link CB_AudioFileCache#minimumAudioFilesFree}) is reached. It must be an integer being 0 (zero) the minimum. Internal usage only recommended. * @var * @readonly * @type {integer} * @default Math.min(parseInt({@link CB_AudioFileCache#minimumAudioFiles} * 0.1 + 0.5), 1) */ this.newAudioFilesWhenNeeded = CB_AudioFileCache._newAudioFilesWhenNeeded_FIRST_VALUE; /** * Number of retries to try to load a {@link CB_AudioFile} object internally before trying to load the next possible one internally (if any). It must be an integer being 0 the minimum. Internal usage only recommended. * @var * @readonly * @type {integer} * @default CB_AudioFileCache.retries_DEFAULT */ this.retries = CB_AudioFileCache.retries_DEFAULT; /** * Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually). Internal usage only recommended. * @var * @readonly * @type {boolean} * @default CB_AudioFileCache.checkManually_DEFAULT */ this.checkManually = CB_AudioFileCache.checkManually_DEFAULT; /** * Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when creates a new {@link CB_AudioFile} object needed. Internal usage only recommended. * @var * @readonly * @type {boolean} * @default CB_AudioFileCache.checkManuallyOnNeededCreated_DEFAULT */ this.checkManuallyOnNeededCreated = CB_AudioFileCache.checkManuallyOnNeededCreated_DEFAULT; /** * Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when playing one has failed and tries to reload it. Internal usage only recommended. * @var * @readonly * @type {boolean} * @default CB_AudioFileCache.checkManuallyOnPlayingFailed_DEFAULT */ this.checkManuallyOnPlayingFailed = CB_AudioFileCache.checkManuallyOnPlayingFailed_DEFAULT; /** * Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when checking one has failed and tries to reload it. Internal usage only recommended. * @var * @readonly * @type {boolean} * @default CB_AudioFileCache.checkManuallyOnCheckingFailed_DEFAULT */ this.checkManuallyOnCheckingFailed = CB_AudioFileCache.checkManuallyOnCheckingFailed_DEFAULT; /** * Desired function to be called once the cache has been loaded. The first and unique parameter will be an integer with the {@link CB_AudioFile} objects that still need to be checked, if any, being \"this\" the current {@link CB_AudioFileCache} object. Internal usage only recommended. * @var * @readonly * @type {function} * @default */ this.onLoad = null; /** * Desired function to be called when any kind of error happens. The first and unique parameter will be a string with the error description (if it could be determined), being \"this\" the current {@link CB_AudioFileCache} object. Internal usage only recommended. * @var * @readonly * @type {function} * @default */ this.onError = null; /** * Numeric array containing all the {@link CB_AudioFile} objects created internally. Internal usage only recommended. * @var * @readonly * @type {array} * @default */ this.audioFiles = []; /** * Total number of {@link CB_AudioFile} objects created internally (optimization purposes, to avoid using {@link CB_AudioFileCache#audioFiles}.length). Internal usage only recommended. * @var * @readonly * @type {integer} * @default */ this.audioFilesCreated = 0; /** * Stack that stores the indexes (belonged to the {@link CB_AudioFileCache#audioFiles} array) of the free {@link CB_AudioFile} objects. Internal usage only recommended. * @var * @readonly * @type {array} * @default */ this.audioFilesFree = []; /** * Pointer for the {@link CB_AudioFileCache#audioFilesFree} stack (for optimization purposes). Internal usage only recommended. * @var * @readonly * @type {integer} * @default */ this.audioFilesFreePointer = -1; /** * Object with sound instance identifiers (integers created by the {@link CB_AudioFileCache#play} method) which are going to play (this way we can cancel the sound before it starts playing). Each property name is the identifier of the sound instance and the value will be an object with \"cancelled\" (boolean, to know whether the sound instance was cancelled or not) and \"object\" (containing the {@link CB_AudioFile} object used) properties. Internal usage only recommended. * @var * @readonly * @type {Object} * @default */ this.soundInstancesQueued = {}; /** * Stores the minimum duration found among all the {@link CB_AudioFile} objects. Internal usage only recommended. * @var * @readonly * @type {number} * @default 0 */ this.duration = 0; /** * Stores the maximum duration found among all the {@link CB_AudioFile} objects. Internal usage only recommended. * @var * @readonly * @type {number} * @default 0 */ this.durationMaximum = 0; //Internal properties: this._URIsListLast = undefined; this._lastSuccededIndexes = {}; //Stores last indexes that were used when an object is created successfully, ordered by URIs and APIs (for optimization purposes). this._checkCacheLoadedTimeout = null; this._checkCacheLoadedTimeoutMs = 500; this._onLoadCalled = false; //Tells whether the onLoad has been called already or not. this._existingObjectIds = []; this._clearAudioFilesTimeout = null; this._createNewAudioFilesIfNeededTimeout = null; ///////this._callRecursivelyIfNotTooLateCalled = false; this._checkingPlaying = false; this._settingAPI = false; //Calls the constructor of the object when creates an instance: return this._init(dataObject); } //Static properties and constants: /////CB_AudioFileCache.MAX_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM; CB_AudioFileCache._soundInstanceIdUnique = 0; /** * Status value for audio file cache which is unloaded. Can be used to compare the value returned by the {@link CB_AudioFileCache#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default 0 */ CB_AudioFileCache.UNLOADED = 0; /** * Status value for an audio file cache which is loading. Can be used to compare the value returned by the {@link CB_AudioFileCache#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFileCache.LOADING = 1; /** * Status value for an audio file cache which has not been checked yet. Can be used to compare the value returned by the {@link CB_AudioFileCache#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFileCache.UNCHECKED = 2; /** * Status value for an audio file cache which is being checked currently. Can be used to compare the value returned by the {@link CB_AudioFileCache#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFileCache.CHECKING = 3; /** * Status value for an audio file cache which has been loaded. Can be used to compare the value returned by the {@link CB_AudioFileCache#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFileCache.LOADED = 4; /** * Status value for an audio file cache which failed to be loaded or failed for any other reason. Can be used to compare the value returned by the {@link CB_AudioFileCache#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFileCache.FAILED = 5; /** * Status value for an audio file cache which has been aborted. This will happen when the audio file cache has been destroyed with the {@link CB_AudioFileCache#destructor} method. Can be used to compare the value returned by the {@link CB_AudioFileCache#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFileCache.ABORTED = 6; /** * Default value for the {@link CB_AudioFileCache#minimumAudioFiles} property. * @constant * @type {integer} * @default */ CB_AudioFileCache.minimumAudioFiles_DEFAULT = 2; /** * Default value for the {@link CB_AudioFileCache#maximumAudioFiles} property. * @constant * @type {integer|null} * @default null */ CB_AudioFileCache.maximumAudioFiles_DEFAULT = null; /** * Default value for the {@link CB_AudioFileCache#retries} property. * @constant * @type {integer} * @default */ CB_AudioFileCache.retries_DEFAULT = 1; /** * Default value for the {@link CB_AudioFileCache#checkManually} property. * @constant * @type {boolean} * @default false */ CB_AudioFileCache.checkManually_DEFAULT = false; /** * Default value for the {@link CB_AudioFileCache#checkManuallyOnNeededCreated} property. * @constant * @type {boolean} * @default false */ CB_AudioFileCache.checkManuallyOnNeededCreated_DEFAULT = false; /** * Default value for the {@link CB_AudioFileCache#checkManuallyOnPlayingFailed} property. * @constant * @type {boolean} * @default false */ CB_AudioFileCache.checkManuallyOnPlayingFailed_DEFAULT = false; /** * Default value for the {@link CB_AudioFileCache#checkManuallyOnCheckingFailed} property. * @constant * @type {boolean} * @default false */ CB_AudioFileCache.checkManuallyOnCheckingFailed_DEFAULT = false; CB_AudioFileCache._minimumAudioFilesFree_FIRST_VALUE = 1; //First value for the {@link CB_AudioFileCache#minimumAudioFilesFree} property, although it will end using a 25% of the {@link CB_AudioFileCache#minimumAudioFiles} by default, rounded to ceil, allowing 0 (zero) minimum. CB_AudioFileCache._newAudioFilesWhenNeeded_FIRST_VALUE = 1; //First value for the {@link CB_AudioFileCache#newAudioFilesWhenNeeded} property, although it will end using a 10% of the {@link CB_AudioFileCache#minimumAudioFiles} by default, rounded to ceil, allowing 1 minimum. //Constructor: CB_AudioFileCache.prototype._init = function(dataObject) { /* FORMAT: dataObject = { [id : String,] [preferredAPIs : Array&lt;String&gt;,] [preferredFormats : Array&lt;String&gt;,] URIs : Object, [minimumAudioFiles : Integer,] [maximumAudioFiles : Integer,] [minimumAudioFilesFree : Integer,] [newAudioFilesWhenNeeded : Integer,] [retries : Integer,] [checkManually : Boolean,] [checkManuallyOnNeededCreated : Boolean,] [checkManuallyOnPlayingFailed : Boolean,] [checkManuallyOnCheckingFailed : Boolean,] [disableAutoLoad : Boolean,] [onLoad : Function,] [onError : Function] }; */ //Tries to load the data (if any): this.load(dataObject); //Returns the object: return this; } /** * Destroys the audio file cache object, including all the internal {@link CB_AudioFile} objects, and frees memory. By default, unless the \"preventAbortedStatus\" is set to true, sets the current status of the audio file cache object as ABORTED ({@link CB_AudioFileCache.ABORTED} value). * @function * @param {boolean} [stopSounds=false] - Used as the \"stopSound\" parameter when calling internally the {@link CB_AudioFile#destructor} method for all the {@link CB_AudioFile} objects. * @param {boolean} [preventAbortedStatus=false] - If set to true (not recommended), it will not assign the status of \"ABORTED\" (it will not assign the value of {@link CB_AudioFileCache.ABORTED} to the {@link CB_AudioFileCache#status} property). */ CB_AudioFileCache.prototype.destructor = function(stopSounds, preventAbortedStatus) { clearTimeout(this._checkCacheLoadedTimeout); clearTimeout(this._clearAudioFilesTimeout); clearTimeout(this._createNewAudioFilesIfNeededTimeout); this.cancelSoundInstances(true, true); //Destroys all sounds: this.destroyAll(stopSounds); //Resets properties to their default value: this.preferredAPIs = CB_Configuration[CB_BASE_NAME].CB_AudioFileCache_PREFERRED_AUDIO_APIS; this.preferredFormats = CB_Configuration[CB_BASE_NAME].CB_AudioFileCache_PREFERRED_AUDIO_FORMATS; this.URIs = {}; this.minimumAudioFiles = CB_AudioFileCache.minimumAudioFiles_DEFAULT; this.maximumAudioFiles = CB_AudioFileCache.maximumAudioFiles_DEFAULT; this.minimumAudioFilesFree = CB_AudioFileCache._minimumAudioFilesFree_FIRST_VALUE; this.newAudioFilesWhenNeeded = CB_AudioFileCache._newAudioFilesWhenNeeded_FIRST_VALUE; this.retries = CB_AudioFileCache.retries_DEFAULT; this.checkManually = CB_AudioFileCache.checkManually_DEFAULT; this.checkManuallyOnNeededCreated = CB_AudioFileCache.checkManuallyOnNeededCreated_DEFAULT; this.checkManuallyOnPlayingFailed = CB_AudioFileCache.checkManuallyOnPlayingFailed_DEFAULT; this.checkManuallyOnCheckingFailed = CB_AudioFileCache.checkManuallyOnCheckingFailed_DEFAULT; this.onLoad = null; this.onError = null; this.audioFiles = []; this.audioFilesCreated = 0; this.soundInstancesQueued = {}; this.duration = 0; this.durationMaximum = 0; //Resets the audioFilesFree stack and its pointer: this.audioFilesFree = []; this.audioFilesFreePointer = -1; //Sets the status as ABORTED: if (!preventAbortedStatus) { this.status = CB_AudioFileCache.ABORTED; } } /** * Loads the audio file cache with the desired data given. This method is called by the constructor automatically. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. * @function * @param {CB_AudioFileCache.DATA_OBJECT} dataObject - Object with the desired data and options for the audio files cache. * @returns {CB_AudioFileCache|null} If a \"dataObject\" is given, it returns the current {@link CB_AudioFileCache} object. Otherwise, it returns null. */ CB_AudioFileCache.prototype.load = function(dataObject) { if (typeof(dataObject) === \"undefined\" || dataObject === null) { return null; } this.status = CB_AudioFileCache.LOADING; //The cache is loading. //Destroys all previous data (if any): this.destructor(true, true); //Also stops all sounds. //Sanitizes the given data: dataObject.id = CB_trim(dataObject.id); dataObject.minimumAudioFiles = parseInt(CB_trim(dataObject.minimumAudioFiles)); if (dataObject.maximumAudioFiles !== null) { dataObject.maximumAudioFiles = parseInt(CB_trim(dataObject.maximumAudioFiles)); } dataObject.minimumAudioFilesFree = parseInt(CB_trim(dataObject.minimumAudioFilesFree)) dataObject.newAudioFilesWhenNeeded = parseInt(CB_trim(dataObject.newAudioFilesWhenNeeded)) dataObject.retries = parseInt(CB_trim(dataObject.retries)); //Sets the new data: if (dataObject.id !== \"\") { this.id = dataObject.id; } if (CB_isArray(dataObject.preferredAPIs) &amp;&amp; dataObject.preferredAPIs.length &gt; 0 &amp;&amp; CB_trim(dataObject.preferredAPIs.join(\"\")) !== \"\") { this.preferredAPIs = dataObject.preferredAPIs; } if (CB_isArray(dataObject.preferredFormats) &amp;&amp; dataObject.preferredFormats.length &gt; 0 &amp;&amp; CB_trim(dataObject.preferredFormats.join(\"\")) !== \"\") { this.preferredFormats = dataObject.preferredFormats; } if (typeof(dataObject.URIs) !== \"undefined\") { this.URIs = dataObject.URIs; } if (dataObject.minimumAudioFiles !== \"\" &amp;&amp; !isNaN(dataObject.minimumAudioFiles) &amp;&amp; dataObject.minimumAudioFiles &gt;= 1) { this.minimumAudioFiles = dataObject.minimumAudioFiles; } if (dataObject.maximumAudioFiles === null || dataObject.maximumAudioFiles !== \"\" &amp;&amp; !isNaN(dataObject.maximumAudioFiles) &amp;&amp; dataObject.maximumAudioFiles &gt;= this.minimumAudioFiles) { this.maximumAudioFiles = dataObject.maximumAudioFiles; } else { this.maximumAudioFiles = CB_AudioFileCache.maximumAudioFiles_DEFAULT; } if (dataObject.minimumAudioFilesFree !== \"\" &amp;&amp; !isNaN(dataObject.minimumAudioFilesFree) &amp;&amp; dataObject.minimumAudioFilesFree &gt;= 0) { this.minimumAudioFilesFree = dataObject.minimumAudioFilesFree; } else { //Uses a limit of 25% of the minimum by default: this.minimumAudioFilesFree = parseInt(this.minimumAudioFiles * 0.25 + 0.5); //Ceil round. } if (dataObject.newAudioFilesWhenNeeded !== \"\" &amp;&amp; !isNaN(dataObject.newAudioFilesWhenNeeded) &amp;&amp; dataObject.newAudioFilesWhenNeeded &gt;= 0) { this.newAudioFilesWhenNeeded = dataObject.newAudioFilesWhenNeeded; } else { //Creates a 10% of the minimum by default: this.newAudioFilesWhenNeeded = parseInt(this.minimumAudioFiles * 0.1 + 0.5); //Ceil round. if (this.newAudioFilesWhenNeeded &lt; 1) { this.newAudioFilesWhenNeeded = 1; } } if (dataObject.retries !== \"\" &amp;&amp; !isNaN(dataObject.retries) &amp;&amp; dataObject.retries &gt;= 0) { this.retries = dataObject.retries; } if (typeof(dataObject.checkManually) !== \"undefined\" &amp;&amp; dataObject.checkManually !== null) { this.checkManually = dataObject.checkManually; } if (typeof(dataObject.checkManuallyOnNeededCreated) !== \"undefined\" &amp;&amp; dataObject.checkManuallyOnNeededCreated !== null) { this.checkManuallyOnNeededCreated = dataObject.checkManuallyOnNeededCreated; } if (typeof(dataObject.checkManuallyOnPlayingFailed) !== \"undefined\" &amp;&amp; dataObject.checkManuallyOnPlayingFailed !== null) { this.checkManuallyOnPlayingFailed = dataObject.checkManuallyOnPlayingFailed; } if (typeof(dataObject.checkManuallyOnCheckingFailed) !== \"undefined\" &amp;&amp; dataObject.checkManuallyOnCheckingFailed !== null) { this.checkManuallyOnCheckingFailed = dataObject.checkManuallyOnCheckingFailed; } if (typeof(dataObject.onLoad) === \"function\") { this.onLoad = dataObject.onLoad; } if (typeof(dataObject.onError) === \"function\") { this.onError = dataObject.onError; } //If we want, loads the needed objects (if any): var disableAutoLoad = false; if (typeof(dataObject.disableAutoLoad) !== \"undefined\" &amp;&amp; dataObject.disableAutoLoad !== null) { disableAutoLoad = dataObject.disableAutoLoad; } if (!disableAutoLoad) { this.createAudioFiles(this.minimumAudioFiles); } //Creates the minimum number of objects desired. return this; } /** * Creates the desired number of internal {@link CB_AudioFile} objects (inside the {@link CB_AudioFileCache#audioFiles} property). This method is already called by the {@link CB_AudioFileCache#load} method automatically (unless the \"disableAutoLoad\" property has been set to true in the \"dataObject\" given). Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. * @function * @param {integer} minimumAudioFiles - Minimum {@link CB_AudioFile} objects to create internally. It must be an integer being 1 the minimum. If a valid value is given, this will be added to the {@link CB_AudioFileCache#minimumAudioFiles} property. * @param {boolean} [setAsLoaded=false] - If the {@link CB_AudioFile} objects already created internally (before calling this method) does not reach the number given in the \"minimumAudioFiles\", this parameter will be ignored. Otherwise, if set to true, it will set the {@link CB_AudioFileCache.status} property as \"LOADED\" (the value of the {@link CB_AudioFileCache#LOADED} property) after reaching the desired number. If set to false, the {@link CB_AudioFileCache.status} property will be set as \"LOADED\" {@link CB_AudioFileCache#LOADED} property) if the {@link CB_AudioFileCache#checkManually} property is set to true or set as \"UNCHECKED\" if the {@link CB_AudioFileCache#checkManually} property is set to false. Internal usage only recommended. * @returns {integer} Returns the number of {@link CB_AudioFile} objects which are intended to be created (they could fail). */ CB_AudioFileCache.prototype.createAudioFiles = function(minimumAudioFiles, setAsLoaded) { this.status = CB_AudioFileCache.LOADING; //The cache is loading. if (typeof(minimumAudioFiles) === \"undefined\" || minimumAudioFiles === null || isNaN(minimumAudioFiles) || minimumAudioFiles &lt; 1) { minimumAudioFiles = this.minimumAudioFiles; } //If there is a maximum of files set: if (typeof(this.maximumAudioFiles) !== \"undefined\" &amp;&amp; this.maximumAudioFiles !== null &amp;&amp; !isNaN(this.maximumAudioFiles) &amp;&amp; this.maximumAudioFiles &gt;= 1) { //If the minimum of files we want is bigger than the maximum, throws an error and exits: if (minimumAudioFiles &gt; this.maximumAudioFiles) { this.errorFunction(\"Cannot create \" + minimumAudioFiles + \" audio files. Maximum is \" + this.maximumAudioFiles + \".\"); return 0; } } //Sets as the minimum objects to create the number given: this.minimumAudioFiles = minimumAudioFiles; //Clears the array of the AudioFiles: this.clearAudioFiles(); //Creates the objects if they do not exist already: this.audioFilesCreated = 0; var audioFilesCreated = 0; var audioFilesCreating = 0; var audioFile; var that = this; for (var x = 0; x &lt; minimumAudioFiles; x++) { //If an object is needed: if (typeof(this.audioFiles[x]) === \"undefined\" || this.audioFiles[x] === null) { //this.audioFiles[x] = this.createAudioFile(); //If loads correctly, it will increase the audioFilesCreated property. //Creates a new object: /////setTimeout //Uses a delay to prevent Firefox error (\"Media resource [URI] could not be decoded\") since AAPI and SM2 call play() method (and many calls to play() method would fail). /////( ////////// function() /////{ audioFile = that.createAudioFile(null, null, null, null, null, null, true); //If loads correctly, it will increase the audioFilesCreated property. audioFilesCreating++; //////}, /////////x * 10 + 1 //////); //If no object has been created, throws an error (cache status will be FAILED): //////////if (typeof(audioFile) === \"undefined\" || audioFile === null) { ////////////this.errorFunction(\"Tried to create the audio object #\" + x + \" but is undefined or null.\"); ////////////return; //Exits the function. } } else { audioFilesCreated++; } //If the cache has already failed or is aborted, just exits: if (this.status === CB_AudioFileCache.FAILED || this.status === CB_AudioFileCache.ABORTED) { return audioFilesCreating; } } //If the files are already created, the cache has finished loading: //if (audioFilesCreated &gt;= minimumAudioFiles) { this.status = CB_AudioFileCache.LOADED; } if (audioFilesCreated &gt;= minimumAudioFiles) { this.status = this.checkManually &amp;&amp; !setAsLoaded ? CB_AudioFileCache.UNCHECKED : CB_AudioFileCache.LOADED; } //Stores the number of files already created: this.audioFilesCreated += audioFilesCreated; //It is an addition because some objects could have been created asynchronously. return audioFilesCreating; } /** * Creates one internal {@link CB_AudioFile} object (inside the {@link CB_AudioFileCache#audioFiles} property). This method is already called by the {@link CB_AudioFileCache#createAudioFiles} method and other methods automatically. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Internal usage only recommended. * @function * @param {CB_AudioFileCache.URIS_OBJECT} [URIs={@link CB_AudioFileCache#URIs}] - Object whose property names audio formats and their value is an array of strings with the URIs (audio file paths or audio data URIs) of the audio files in order of preference. It will try to calculate and use the best audio format for the current client and use the first working URI (audio file path or data URI). The more audio formats and URIs provided the better, as it will help to maximize the compatibility with as many clients as possible (as some audio APIs and client just support some formats, or use absolute paths instead of relative ones, etc.). Even with different formats, all provided URIs should belong to the same audio (this means same sound or same music, with same length, etc.). NOTE: Only some clients with some audio APIs will support data URIs. * @param {array} [preferredAPIs={@link CB_AudioFileCache#preferredAPIs}] - Array of strings with the preferred audio API or audio APIs, in order of preference. Possible audio APIs are \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). It will try to calculate and use the best one for the current client. * @param {array} [preferredFormats={@link CB_AudioFileCache#preferredFormats}] - Array of strings with the preferred audio format or audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"'), in order of preference. It will try to calculate and use the best one for the current client. * @param {CB_AudioFile} [audioObject] - A {@link CB_AudioFile} object that we want to reuse instead of creating a new one (for performance purposes). * @param {function} [callbackOk] - Function with no parameters that will be called once the {@link CB_AudioFile} object is created and loaded successfully (or after it has been checked successfully, depending on the desired option), being \"this\" the {@link CB_AudioFileCache} object itself. * @param {function} [callbackError] - Function called when any error is produced during creation, loading or checking process, etc. The unique parameter will be a string describing the error (if it was possible to be determined), being \"this\" the {@link CB_AudioFileCache} object itself. * @param {boolean} [storeURIsList=false] - If set to true, it will store internally the valid supported \"URIs\" from the given ones (needed by the {@link CB_AudioFileCache#setAudioAPIAll} method, for example). Internal usage only recommended. * @param {boolean} [checkAutomatically=false] - If set to true (not recommended), it will call the {@link CB_AudioFile#checkPlaying} method automatically. Otherwise, it will perform according to the value set at the {@link CB_AudioFileCache#checkManually} property. Internal usage only recommended. * @returns {CB_AudioFile|null} If it fails, it returns null. Otherwise, returns the {@link CB_AudioFile} that has been created or reused. */ CB_AudioFileCache.prototype.createAudioFile = function(URIs, preferredAPIs, preferredFormats, audioObject, callbackOk, callbackError, storeURIsList, checkAutomatically) { //If the cache has already failed or is aborted, just exits: if (this.status === CB_AudioFileCache.FAILED || this.status === CB_AudioFileCache.ABORTED) { return null; } this.status = CB_AudioFileCache.LOADING; //The cache is loading. //If not given, uses default parameters: if (typeof(URIs) === \"undefined\" || URIs === null) { URIs = this.URIs; } if (!CB_isArray(preferredAPIs) || preferredAPIs.length === 0 || CB_trim(preferredAPIs.join(\"\")) === \"\") { preferredAPIs = this.preferredAPIs; } if (!CB_isArray(preferredFormats) || preferredFormats.length === 0 || CB_trim(preferredFormats.join(\"\")) === \"\") { preferredFormats = this.preferredFormats; } //Filters the audio APIs to just use the supported ones: preferredAPIs = CB_AudioDetector.getSupportedAPIs(preferredAPIs); //If preferredAPIs is empty, throws the error and exits: if (preferredAPIs.length === 0) { this.errorFunction(\"No API supported from the provided ones.\"); return null; } //Filters the audio formats to just use the supported ones (also orders them with the \"probably\" ones first): var preferredFormatsSupported = CB_AudioDetector.getSupportedAudioFormats(preferredFormats, [\"probably\", \"maybe\"]); if (preferredFormatsSupported.length &gt; 0) { preferredFormats = preferredFormatsSupported; } //Only uses the filtered ones if there is at least one. else { this.errorFunction(\"No format supported from the provided ones.\"); return null; } //Filters the URIs given to just use the ones whose format is supported: var URIsList = []; var preferredFormatsLength = preferredFormats.length; var y, URIsListCurrentLength, isDataURI; for (var x = 0; x &lt; preferredFormatsLength; x++) { //If the support format has URIs associated: if (typeof(URIs[preferredFormats[x]]) !== \"undefined\" &amp;&amp; CB_isArray(URIs[preferredFormats[x]])) { URIsListCurrentLength = URIs[preferredFormats[x]].length; for (y = 0; y &lt; URIsListCurrentLength; y++) { //Only stores it if this kind of URI (data URI or normal one) is supported by the format: if (!CB_isString(URIs[preferredFormats[x]][y])) { continue; } isDataURI = (URIs[preferredFormats[x]][y].substring(0, 5).toLowerCase() === \"data:\"); if (CB_AudioDetector.isAudioFormatSupported(preferredFormats[x], isDataURI) !== \"\") { //Stores the current URI: URIsList[URIsList.length] = URIs[preferredFormats[x]][y++]; } } } } //If there are not URIs supported, throws the error and exits: if (URIsList.length === 0) { this.errorFunction(\"No URI supported from the provided ones.\"); return null; } else if (storeURIsList) { this._URIsListLast = URIsList; } //Returns the object created: return this._createAudioFileObjectRecursively(URIsList, preferredAPIs, audioObject, callbackOk, callbackError, null, null, null, null, null, checkAutomatically); } //Function that creates an audio file object trying given URIs and given APIs (internal usage only): CB_AudioFileCache.prototype._createAudioFileObjectRecursively = function(URIsList, preferredAPIs, audioObject, callbackOk, callbackError, URIsListIndex, stopAtURIsListIndex, preferredAPIsIndex, stopAtPreferredAPIsIndex, retryNumber, checkAutomatically) { this.status = CB_AudioFileCache.LOADING; //The cache is loading. //If there are not URIs supported, throws the error and exits: if (!CB_isArray(URIsList) || URIsList.length === 0) { this.errorFunction(\"The URIs provided are not in an array or its length is 0.\"); return null; } //If not given, uses default parameters: if (typeof(URIsListIndex) === \"undefined\" || URIsListIndex === null || isNaN(URIsListIndex)) { URIsListIndex = 0; } if (typeof(preferredAPIsIndex) === \"undefined\" || preferredAPIsIndex === null || isNaN(preferredAPIsIndex)) { preferredAPIsIndex = 0; } if (typeof(retryNumber) === \"undefined\" || retryNumber === null || isNaN(retryNumber)) { retryNumber = 0; } //If it does not exist yet, creates the last succeeded indexes for the given URIs and the given preferred APIs: if (typeof(this._lastSuccededIndexes[URIsList]) === \"undefined\" || this._lastSuccededIndexes[URIsList] === null) { this._lastSuccededIndexes[URIsList] = {}; } if (typeof(this._lastSuccededIndexes[URIsList][preferredAPIs]) === \"undefined\" || this._lastSuccededIndexes[URIsList][preferredAPIs] === null) { this._lastSuccededIndexes[URIsList][preferredAPIs] = { \"URIsListIndex\" : 0, \"preferredAPIsIndex\" : 0 }; //The first time, starts at the beginning. } //If this is not a recursive call (stopAtURIsListIndex will still not be created): if (typeof(stopAtURIsListIndex) === \"undefined\" || stopAtURIsListIndex === null) { //We continue from the last succeeded API and last succeeded URI (optimization purposes): URIsListIndex = this._lastSuccededIndexes[URIsList][preferredAPIs][\"URIsListIndex\"]; preferredAPIsIndex = this._lastSuccededIndexes[URIsList][preferredAPIs][\"preferredAPIsIndex\"]; //Calculates when we should stop trying to create the object (the last API and last URI we should try): stopAtPreferredAPIsIndex = preferredAPIsIndex; stopAtURIsListIndex = URIsListIndex - 1; if (stopAtURIsListIndex &lt; 0) { stopAtURIsListIndex = URIsList.length - 1; stopAtPreferredAPIsIndex--; if (stopAtPreferredAPIsIndex &lt; 0) { stopAtPreferredAPIsIndex = preferredAPIs.length - 1; } } } var that = this; //Function to call when the object is created successfully: var callbackOkFunction = function() { //Stores the API index and the URI index to use the next time (for optimization purposes): that._lastSuccededIndexes[URIsList][preferredAPIs][\"URIsListIndex\"] = URIsListIndex; that._lastSuccededIndexes[URIsList][preferredAPIs][\"preferredAPIsIndex\"] = preferredAPIsIndex; if (typeof(callbackOk) === \"function\") { callbackOk.call(that); } }; //Function to call when the object has failed (has not been created): var callbackErrorFunction = function(error) { //If the cache has already failed or is aborted, just exits: if (that.status === CB_AudioFileCache.FAILED || that.status === CB_AudioFileCache.ABORTED) { return; } ///////if (allAttemptsFailed) { return; } //If we have already tried all, throws an error (the status of the cache will be set to FAILED): if (preferredAPIsIndex === stopAtPreferredAPIsIndex &amp;&amp; URIsListIndex === stopAtURIsListIndex &amp;&amp; retryNumber === that.retries) { ///////allAttemptsFailed = true; that.errorFunction(\"A new audio object could not be created. All attempts failed. Last message: \" + error); if (typeof(callbackError) === \"function\") { callbackError.call(that, \"A new audio object could not be created. All attempts failed. Last message: \" + error); } return; } //...otherwise, continues trying: else { retryNumber++; //Increases the retries counter. //If the current retries are more than the allowed ones, passes to try the next method: if (retryNumber &gt; that.retries) { //Sanitizes the indexes for the next recursive call: URIsListIndex++; URIsListIndex %= URIsList.length; if (URIsListIndex === 0) { preferredAPIsIndex++; preferredAPIsIndex %= preferredAPIs.length; } retryNumber = 0; } //Calls the function again: that._createAudioFileObjectRecursively(URIsList, preferredAPIs, audioObject, callbackOk, callbackError, URIsListIndex, stopAtURIsListIndex, preferredAPIsIndex, stopAtPreferredAPIsIndex, retryNumber, checkAutomatically); //that._createAudioFileObject(URIsList[URIsListIndex], null, preferredAPIs[preferredAPIsIndex], callbackOk, callbackError, audioObject); } }; this._onLoadCalled = false; //Forces to call onLoad function again. audioObject = this._createAudioFileObject(URIsList[URIsListIndex], null, preferredAPIs[preferredAPIsIndex], callbackOkFunction, callbackErrorFunction, audioObject, checkAutomatically); return audioObject; } //Checks and declares whether the cache is completely loaded or not: CB_AudioFileCache.prototype._checkCacheLoaded = function(objectsNeedChecking) { clearTimeout(this._checkCacheLoadedTimeout); //If the method checkPlayingAll is executing, exits: if (this._checkingPlaying || this._settingAPI) { return; } //If the cache has failed or has been aborted or it is already loaded, just exits: if (this.status === CB_AudioFileCache.FAILED || this.status === CB_AudioFileCache.ABORTED || this.status === CB_AudioFileCache.LOADED) { return; } //Clears the array of the AudioFiles: this.clearAudioFiles(true); if (typeof(objectsNeedChecking) === \"undefined\" || objectsNeedChecking === null || isNaN(objectsNeedChecking) || objectsNeedChecking &lt; 0) { objectsNeedChecking = 0; } //If we don't need more objects, the cache is LOADED: if (this.audioFilesCreated &gt;= this.minimumAudioFiles || this.checkManually &amp;&amp; this.audioFilesCreated + objectsNeedChecking &gt;= this.minimumAudioFiles) { //Sets the cache status as loaded: //this.status = CB_AudioFileCache.LOADED; this.status = (objectsNeedChecking &gt; 0) ? CB_AudioFileCache.UNCHECKED : CB_AudioFileCache.LOADED; //If we have not called the onLoad function, calls the onLoad function (if any): if (!this._onLoadCalled &amp;&amp; typeof(this.onLoad) === \"function\") { this._onLoadCalled = true; this.onLoad.call(this, objectsNeedChecking); } } } //Function that creates an audio file (internal usage only): CB_AudioFileCache.prototype._createAudioFileObject = function(filePath, audioId, audioAPI, callbackOk, callbackError, audioObject, checkAutomatically) { this.status = CB_AudioFileCache.LOADING; //The cache is loading. //If there is a limit and we have already reached the maximum of objects allowed, throws an error: if (typeof(this.maximumAudioFiles) !== \"undefined\" &amp;&amp; this.maximumAudioFiles !== null &amp;&amp; !isNaN(this.maximumAudioFiles) &amp;&amp; this.maximumAudioFiles &gt;= 1) { if (this.audioFilesCreated &gt;= this.maximumAudioFiles) { this.errorFunction(\"A new object cannot be created. Maximum (\" + this.maximumAudioFiles + \") reached.\"); return null; } } var that = this; //Defines the function to call when the audio object is created successfully: var callbackOkFunction = function() { //If the sound needs to be checked, checks it and calls the function again if all is fine: if ((!that.checkManually || checkAutomatically) &amp;&amp; audioObject.getStatus() === CB_AudioFile.UNCHECKED) { audioObject.checkPlaying(callbackOkFunction, callbackErrorFunction, false, false, true); return; } //Clears the array of the AudioFiles: that.clearAudioFiles(); var audioFilesIndex = that.audioFiles.length; //If the object already exists, gets its index in the array: if (CB_indexOf(that._existingObjectIds, audioObject.id) !== -1) { //Search the object in the array: var audioFilesLength = that.audioFiles.length; var indexFound = false; for (var x = 0; x &lt; audioFilesLength; x++) { //If the object is defined and not null: if (typeof(that.audioFiles[x]) !== \"undefined\" &amp;&amp; that.audioFiles[x] !== null) { //If the object ID is the same as the current one: if (typeof(that.audioFiles[x].id) !== \"undefined\" &amp;&amp; that.audioFiles[x].id === audioObject.id) { //Gets its index and exists the bucle: audioFilesIndex = x; indexFound = true; //Exists the bucle: break; } } } //The object already existed but could not be found (which means it has been deleted by the Error function), so exits: //if (!indexFound) { return; } //Avoids calling the Ok function if the Error function has already been called. } //Stores the object ID to the existing ones: that._existingObjectIds[that._existingObjectIds.length] = audioObject.id; //Inserts the object into the array: that.audioFiles[audioFilesIndex] = audioObject; //The new object is free so we insert its index in the stack for free elements: that.audioFilesFree[++that.audioFilesFreePointer] = audioFilesIndex; //Also increases the pointer. //Increases the counter of the objects created: that.audioFilesCreated++; //Clears the array of the AudioFiles: that.clearAudioFiles(); //If we don't need more objects, we will check again after some time (before declaring the cache as LOADED) because some objects can still fire onerror (specially with SM2): /* clearTimeout(that._checkCacheLoadedTimeout); //Stops the previous timeout to check whether the cache is loaded (if any). if (that.audioFilesCreated &gt;= that.minimumAudioFiles) { that._checkCacheLoadedTimeout = setTimeout(function() { that._checkCacheLoaded.call(that); }, that._checkCacheLoadedTimeoutMs); } */ //Stores the minimum and maximum duration found: var duration = audioObject.getDuration(); if (duration &gt; 0 &amp;&amp; (that.duration === 0 || duration &lt; that.duration)) { that.duration = duration; } if (duration &gt; that.durationMaximum) { that.durationMaximum = duration; } //Calls the given OK function (if any): if (typeof(callbackOk) === \"function\") { callbackOk.call(that); } }; //Defines the function to call when the audio object could not be created (failed): var callbackErrorFunction = function(error) { //Clears the array of the AudioFiles: that.clearAudioFiles(); //If the object was already stored in the array (already existed): if (CB_indexOf(that._existingObjectIds, audioObject.id) !== -1) { //Finds its index in the array: var audioFilesLength = that.audioFiles.length; for (var x = 0; x &lt; audioFilesLength; x++) { //If the object is defined and not null: if (typeof(that.audioFiles[x]) !== \"undefined\" &amp;&amp; that.audioFiles[x] !== null) { //If the object ID is the same as the current one: if (typeof(that.audioFiles[x].id) !== \"undefined\" &amp;&amp; that.audioFiles[x].id === audioObject.id) { //Deletes the object from the array: that.audioFiles[x] = null; //This object should not count as created anymore: that.audioFilesCreated--; //Clears the array of the AudioFiles: that.clearAudioFiles(); //Exists the bucle: break; } } } } //Stores the object ID to the existing ones: that._existingObjectIds[that._existingObjectIds.length] = audioObject.id; //Calls the given error function (if any): if (typeof(callbackError) === \"function\") { callbackError.call(that, error); } }; //If it does not exist yet, tries to create the object: if (typeof(audioObject) === \"undefined\" || audioObject === null) { this.DEFAULT_VOLUME = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration[CB_BASE_NAME].CB_Speaker_DEFAULT_VOLUME; audioObject = new CB_AudioFile ( filePath, //filePath. null, //audioId. { autoLoad: true, autoPlay: false, loop: false, volume: CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING ? 0 : this.DEFAULT_VOLUME }, //options (volume is zero to prevent hearing the sound in some web clients). audioAPI, //audioAPI. callbackOkFunction, //callbackOk. callbackErrorFunction //callbackError. ); } //...otherwise, if the object already exists, loads it again with the new desired options: else { //audioObject.setVolume(0); //Sets volume to zero to prevent hearing the sound in some web clients. if (CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING) { audioObject.mute(); } //Sets volume to zero to prevent hearing the sound in some web clients. audioObject.load ( filePath, //filePath. audioAPI, //audioAPI. false, //autoPlay. callbackOkFunction, //callbackOk. callbackErrorFunction, //callbackError. true //ignoreOldValues. ); } return audioObject; } /** * Cleans the array of the {@link CB_AudioFile} objects (taking off the undefined or null ones) which is in the {@link CB_AudioFileCache#audioFiles} property, just keeping the valid ones and clearing (destroying and removing) the others. For performance purposes. Internal usage only recommended. * @function * @param {boolean} [avoidCallingCheckCacheLoaded=false] - If set to false and neither the {@link CB_AudioFileCache#checkPlayingAll} nor the {@link CB_AudioFileCache#setAudioAPIAll} methods are being executed, it will call the {@link CB_AudioFileCache#_checkCacheLoaded} internal method which will call the \"onLoad\" function defined in the {@link CB_AudioFileCache#onLoad} property if the number of needed {@link CB_AudioFile} objects has been reached (after performing the cleaning process). Internal usage only recommended. * @returns {array} Returns the value of the {@link CB_AudioFileCache#audioFiles} property. */ CB_AudioFileCache.prototype.clearAudioFiles = function(avoidCallingCheckCacheLoaded) { clearTimeout(this._clearAudioFilesTimeout); var audioFilesClean = []; var audioFilesFree = []; var audioFilesFreePointer = -1; var existingIDs = []; var someChecking = false; var audioFilesLength = this.audioFiles.length; var y = 0; var objectsLoaded = 0; var objectsNeedChecking = 0; var duration = 0; var durationMaximum = 0; var durationCurrent = 0; for (var x = 0; x &lt; audioFilesLength; x++) { //If the object is defined and not null: if (typeof(this.audioFiles[x]) !== \"undefined\" &amp;&amp; this.audioFiles[x] !== null) { //If the object status exists (it means it is a real CB_AudioFile object): if (typeof(this.audioFiles[x].getStatus) !== \"undefined\") { //If the object is LOADED, LOADING or CHECKING or UNCHECKED, we keep it: if (this.audioFiles[x].getStatus() === CB_AudioFile.LOADED || this.audioFiles[x].getStatus() === CB_AudioFile.LOADING || this.audioFiles[x].getStatus() === CB_AudioFile.CHECKING || this.audioFiles[x].getStatus() === CB_AudioFile.UNCHECKED) { //Only adds if it has not been added before: if (CB_indexOf(existingIDs, this.audioFiles[x].id) === -1) { audioFilesClean[y] = this.audioFiles[x]; existingIDs[y++] = this.audioFiles[x].id; //If the object is still unchecked or checking, we will wait for it: if (this.audioFiles[x].getStatus() === CB_AudioFile.CHECKING || this.audioFiles[x].getStatus() === CB_AudioFile.UNCHECKED) { objectsNeedChecking++; someChecking = true; } //...otherwise, if it is LOADED, or its LOADING but its internal object is LOADED (it happens when changing API): else if (this.audioFiles[x].getStatus() === CB_AudioFile.LOADED || this.audioFiles[x].getStatus() === CB_AudioFile.LOADING &amp;&amp; this.audioFiles[x].getStatus(true) === CB_AudioFile.LOADED) //|| this.checkManually &amp;&amp; (this.audioFiles[x].getStatus() === CB_AudioFile.UNCHECKED || this.audioFiles[x].getStatus() === CB_AudioFile.CHECKING) //, or we want to check manually and it is UNCHECKED or CHECKING, increases the counter for loaded objects { objectsLoaded++; //If the sound is not playing, it is a free object: if (!this.audioFiles[x].isPlaying()) { audioFilesFree[++audioFilesFreePointer] = x; //Stores the position of the object in the array. } durationCurrent = this.audioFiles[x].getDuration(); if (durationCurrent &gt; 0 &amp;&amp; (duration === 0 || durationCurrent &lt; duration)) { duration = durationCurrent; } if (durationCurrent &gt; durationMaximum) { durationMaximum = durationCurrent; } } } } //...otherwise, just destroy it: else { this.audioFiles[x].destructor(true, false, true); //Also stops it and avoids firing its onStop. this.audioFiles[x] = null; } } } } //Sets the real audio files created: this.audioFilesCreated = objectsLoaded; this.audioFiles = audioFilesClean; //Stores the new clean array. this.audioFilesFree = audioFilesFree; //Stores the free objects encountered. this.audioFilesFreePointer = audioFilesFreePointer; //Stores the pointer for the array of the free objects. //Stores the minimum and maximum duration found: this.duration = duration; this.durationMaximum = durationMaximum; var that = this; if (!avoidCallingCheckCacheLoaded &amp;&amp; !this._checkingPlaying &amp;&amp; !this._settingAPI) //Avoids calling the function if checkPlayingAll or setAudioAPIAll are being executed. { clearTimeout(this._checkCacheLoadedTimeout); //Stops the previous timeout to check whether the cache is loaded (if any). //If minimum objects are loaded or we are using manual checkingn and minimum objects are loaded or unchecked/checking: if (this.audioFilesCreated &gt;= this.minimumAudioFiles || this.checkManually &amp;&amp; this.audioFilesCreated + objectsNeedChecking &gt;= this.minimumAudioFiles) { //Calls the function to check whether the cache is loaded or not: this._checkCacheLoadedTimeout = setTimeout(function() { that._checkCacheLoaded.call(that, objectsNeedChecking); }, this._checkCacheLoadedTimeoutMs); } } //If some were checking, calls the function again after some time: if (!this.checkManually &amp;&amp; someChecking) { this._clearAudioFilesTimeout = setTimeout ( function() { that.clearAudioFiles.call(that); }, 1 ); } return this.audioFiles; } /** * If found, takes a given {@link CB_AudioFile} object off the {@link CB_AudioFileCache#audioFiles} property (and reloads it if we want to). NOTE: It does neither destroy nor remove the {@link CB_AudioFile} object so it can be used for other purposes (and if a {@link CB_AudioFile} object is given, it will be tried to be reused by the {@link CB_AudioFileCache#createAudioFile} method internally if it is called). Internal usage only recommended. * @function * @param {CB_AudioFile|string} audioObjectOrId - The {@link CB_AudioFile} object or a string with its identifier (not case sensitive) that we want to remove from the {@link CB_AudioFileCache#audioFiles} property. If a {@link CB_AudioFile} object is given, its {@link CB_AudioFile#id} property (which should be unique always) must be set as it is used to identify the object. NOTE: It does neither destroy nor remove the {@link CB_AudioFile} object so it can be used for other purposes (and if a {@link CB_AudioFile} object is given, it will be tried to be reused by the {@link CB_AudioFileCache#createAudioFile} method internally if it is called). * @param {boolean} [reload=false] - If it is set to true, the {@link CB_AudioFileCache#createAudioFile} method will be called automatically at the end of the process. If a {@link CB_AudioFile} object has been given (through the \"audioObjectOrId\" parameter) or found by its identifier, it will be tried to be reused by the {@link CB_AudioFileCache#createAudioFile} method (as its \"audioObject\" parameter). * @param {boolean} [checkManually=false] - Only used when the \"reload\" parameter is set to true, to calculate the \"checkAutomatically\" parameter when calling the {@link CB_AudioFileCache#createAudioFile} method internally. * @returns {boolean|CB_AudioFile|null} Returns null if the given \"audioObjectOrId\" parameter is not a valid {@link CB_AudioFile} object or its {@link CB_AudioFile#id} property is not set or when the \"audioObjectOrId\" parameter is an empty string. Returns a {@link CB_AudioFile} object, the given one through the \"audioObjectOrId\" parameter of the first one removed (it should be the first and unique one removed as the ID must be unique), if the {@link CB_AudioFileCache#createAudioFile} method is called internally (it will reuse this {@link CB_AudioFile} object). Otherwise, returns true if the number of internal {@link CB_AudioFile} objects (inside the {@link CB_AudioFileCache#audioFiles} property) has decreased or false otherwise. * @todo Think about calling the {@link CB_AudioFileCache#createAudioFile} method internally (when the \"reload\" parameter is set to true) only when the {@link CB_AudioFile} object has been found and removed from the {@link CB_AudioFileCache#audioFiles} property. */ CB_AudioFileCache.prototype.removeAudioFile = function(audioObjectOrId, reload, checkManually) { if (typeof(audioObjectOrId) === \"undefined\" || audioObjectOrId === null) { return null; } if (!(audioObjectOrId instanceof CB_AudioFile)) { //If a string or number is given, it will be assumed that it is the \"id\" desired: if (CB_isString(audioObjectOrId) || !isNaN(audioObjectOrId)) { audioObjectOrId = { \"id\" : audioObjectOrId + \"\" }; } else { return null; } } var id = CB_trim(audioObjectOrId.id).toUpperCase(); if (id === \"\") { return null; } //Looks through the array of the objects: var audioFilesNew = []; var audioFilesFree = []; var audioFilesFreePointer = -1; var objectsLoaded = 0; var audioFilesLength = this.audioFiles.length; var duration = 0; var durationMaximum = 0; var durationCurrent = 0; for (var x = 0; x &lt; audioFilesLength; x++) { //If the object exists: if (typeof(this.audioFiles[x]) !== \"undefined\" &amp;&amp; this.audioFiles[x] !== null) { //If the object does not have the desired ID: if (typeof(this.audioFiles[x].id) !== \"undefined\") { //If it is not the desired id, stores it in the new array: //if (CB_trim(this.audioFiles[x].id).toUpperCase() !== id) if (this.audioFiles[x].id !== id) { audioFilesNew[audioFilesNew.length] = this.audioFiles[x]; //If it is LOADED or its LOADING but its internal object is LOADED (it happens when changing API): if (this.audioFiles[x].getStatus() === CB_AudioFile.LOADED || this.audioFiles[x].getStatus() === CB_AudioFile.LOADING &amp;&amp; this.audioFiles[x].getStatus(true) === CB_AudioFile.LOADED) { objectsLoaded++; //Increases the counter of files loaded (files successfully created). //If it is not playing, the sound is free: if (!this.audioFiles[x].isPlaying()) { audioFilesFree[++audioFilesFreePointer] = x; //Stores the position of the object in the array. } } } //...else, if the CB_AudioFile object has been found and the \"audioObjectOrId\" is not a CB_AudioFile object (as for example if the \"audioObjectOrId\" parameter was a string with the id instead of a CB_AudioFile object): else if (!(audioObjectOrId instanceof CB_AudioFile)) { audioObjectOrId = this.audioFiles[x]; } //Stores it to call the \"this.createAudioFile\" method later (if we want to). //Stores the minimum and maximum duration found: durationCurrent = this.audioFiles[x].getDuration(); if (durationCurrent &gt; 0 &amp;&amp; (duration === 0 || durationCurrent &lt; duration)) { duration = durationCurrent; } if (durationCurrent &gt; durationMaximum) { durationMaximum = durationCurrent; } } } } //Sets the real audio files created: this.audioFilesCreated = objectsLoaded; //Replaces the audio files array with the new one (which should lacks of the id we wanted to remove): this.audioFiles = audioFilesNew; //Replaces the array of the free audio files and its pointer: this.audioFilesFree = audioFilesFree; //Stores the free objects encountered. this.audioFilesFreePointer = audioFilesFreePointer; //Stores the pointer for the array of the free objects. //Stores the minimum and maximum duration found: this.duration = duration; this.durationMaximum = durationMaximum; //Returns whether the number of internal CB_AudioFile objects has decreased or not: var returningValue = (this.audioFiles.length &lt; audioFilesLength); //If we want to reload the sound, we reload it (and will be returned): if (reload) { returningValue = this.createAudioFile(null, null, null, audioObjectOrId instanceof CB_AudioFile ? audioObjectOrId : null, null, null, null, !checkManually); } //Uses the same audio object. return returningValue; } //Removes objects with a given status from the cache until reach a desired number (if able): CB_AudioFileCache.prototype._purgeObjectsStatus = function(desiredNumber, status, includePlaying, stopSounds) { if (typeof(desiredNumber) === \"undefined\" || desiredNumber === null || isNaN(desiredNumber) || desiredNumber &lt;= 0) { return 0; } this.clearAudioFiles(true); var audioFilesLength = this.audioFiles.length; var existingObjects = audioFilesLength; if (existingObjects &lt;= this.minimumAudioFiles || existingObjects &lt;= desiredNumber) { return 0; } //First, removes not playing ones: for (var x = 0; x &lt; audioFilesLength &amp;&amp; existingObjects !== desiredNumber; x++) { //If the object exists and has the desired status, removes it: if (typeof(this.audioFiles[x]) !== \"undefined\" &amp;&amp; this.audioFiles[x] !== null) { if (this.audioFiles[x].getStatus() === status) { if (!this.audioFiles[x].isPlaying()) { this.audioFiles[x].destructor(stopSounds, false, true); //Avoids firing onStop. this.audioFiles[x] = null; existingObjects--; } } } } //Secondly, removes playing ones (if we want to): if (includePlaying) { for (x = 0; x &lt; audioFilesLength &amp;&amp; existingObjects !== desiredNumber; x++) { //If the object exists and has the desired status, removes it: if (typeof(this.audioFiles[x]) !== \"undefined\" &amp;&amp; this.audioFiles[x] !== null) { if (this.audioFiles[x].getStatus() === status) { this.audioFiles[x].destructor(stopSounds, false, true); //Avoids firing onStop. this.audioFiles[x] = null; existingObjects--; } } } } this.clearAudioFiles(true); return audioFilesLength - existingObjects; } /** * Tries to purge the audio file cache until it reaches a desired number of {@link CB_AudioFile} objects internally (set in the {@link CB_AudioFileCache#audioFiles} property), by removing and destroying some of the current {@link CB_AudioFile} objects. For performance purposes. * @function * @param {integer} desiredNumber - The desired number of internal {@link CB_AudioFile} objects that we want to keep in the {@link CB_AudioFileCache#audioFiles} property. It mus be 1 or greater. * @param {boolean} [setAsMinimumAudioFiles=false] - If set to true, it will set the value of the \"desiredNumber\" parameter to the {@link CB_AudioFileCache#minimumAudioFiles} property (only when there is a maximum defined in {@link CB_AudioFileCache#maximumAudioFiles}). * @param {boolean} [includePlaying=false] - If it is set to true and removing non-playing {@link CB_AudioFile} objects was not enough to reach the desired number (defined in the \"desiredNumber\" parameter), it will also try to remove objects which are being playing currently. * @param {boolean} [stopSounds=false] - Used as the \"stopSound\" parameter when calling the {@link CB_AudioFile#destructor} method of each {@link CB_AudioFile} object removed. * @param {array} [statuses=Array({@link CB_AudioFile.LOADING}, {@link CB_AudioFile.UNCHECKED}, {@link CB_AudioFile.CHECKING}, {@link CB_AudioFile.LOADED})] - Numeric array containing the statuses of the {@link CB_AudioFile} objects that we want this method to authorize to remove. This means that if the returning value of the {@link CB_AudioFile#getStatus} method of a {@link CB_AudioFile} object is not in this list, it will not be tried to be removed (unless they end removed by the {@link CB_AudioFileCache#clearAudioFiles} method called internally). Have in mind that this method will call the {@link CB_AudioFileCache#clearAudioFiles} method internally, which destroys the {@link CB_AudioFile} objects whose {@link CB_AudioFile#getStatus} method returns {@link CB_AudioFile.ABORTED} and {@link CB_AudioFile.FAILED}, so these two statuses need not be indicated. It will respect the order given. Possible values for this array are: {@link CB_AudioFile.UNLOADED}, {@link CB_AudioFile.LOADING}, {@link CB_AudioFile.UNCHECKED}, {@link CB_AudioFile.CHECKING}, {@link CB_AudioFile.LOADED}, {@link CB_AudioFile.FAILED} and {@link CB_AudioFile.ABORTED}. * @returns {integer} Returns the number of {@link CB_AudioFile} objects removed. */ CB_AudioFileCache.prototype.purge = function(desiredNumber, setAsMinimumAudioFiles, includePlaying, stopSounds, statuses) { desiredNumber = parseInt(CB_trim(desiredNumber)); if (desiredNumber === \"\" || isNaN(desiredNumber)) { return 0; } desiredNumber = parseInt(desiredNumber); if (desiredNumber &lt;= 0) { return 0; } if (setAsMinimumAudioFiles &amp;&amp; (typeof(this.maximumAudioFiles) === \"undefined\" || this.maximumAudioFiles === null || isNaN(this.maximumAudioFiles) || this.maximumAudioFiles === 0 || desiredNumber &lt;= this.maximumAudioFiles)) { this.minimumAudioFiles = desiredNumber; } var objectsRemoved = 0; if (typeof(statuses) === \"undefined\" || statuses === null || !CB_isArray(statuses) || statuses.length &lt;= 0) { statuses = [ CB_AudioFile.LOADING, CB_AudioFile.UNCHECKED, CB_AudioFile.CHECKING, CB_AudioFile.LOADED ]; //this._purgeObjectStatus will call clearAudioFiles which destroys ABORTED and FAILED. } var statusesLength = statuses.length; for (var x = 0; x &lt; statusesLength; x++) { objectsRemoved += this._purgeObjectsStatus(desiredNumber, statuses[x], includePlaying, stopSounds); if (this.audioFiles.length &lt;= desiredNumber) { break; } } return objectsRemoved; } //Creates a new audio file if neeed: CB_AudioFileCache.prototype._createNewAudioFilesIfNeeded = function() { //If we don't want to create any new file, just exists: if (this.newAudioFilesWhenNeeded &lt;= 0) { return; } //If it is not LOADED, exits: if (this.status !== CB_AudioFileCache.LOADED) { return; } //If there is not a minimum limit set, just exits: if (typeof(this.minimumAudioFilesFree) === \"undefined\" || this.minimumAudioFilesFree === null || isNaN(this.minimumAudioFilesFree)) { return; } //If we have reached the minimum, creates new ones: //if (this.audioFilesFreePointer + 1 &lt;= this.minimumAudioFilesFree) //Pointer starts with 0. if (this.audioFilesFreePointer &lt; this.minimumAudioFilesFree) //Pointer starts with 0. { var filesCreated = 0; var filesAlreadyCreated = 0; //Counts LOADED, LOADING, UNCHECKED and CHECKING as already created ones (in order not to create more than needed): var audioFilesLength = this.audioFiles.length; for (var x = 0; x &lt; audioFilesLength; x++) { //If the object exists: if (typeof(this.audioFiles[x]) !== \"undefined\" &amp;&amp; this.audioFiles[x] !== null) { //if (this.audioFiles[x].getStatus() === CB_AudioFile.LOADING || this.audioFiles[x].getStatus() === CB_AudioFile.UNCHECKED || this.audioFiles[x].getStatus() === CB_AudioFile.CHECKING) //If it is still LOADED or LOADING but its internal object is LOADED (would happen when changing API), marks the object as free and increments the pointer: if (this.audioFiles[x].getStatus() === CB_AudioFile.LOADED || this.audioFiles[x].getStatus() === CB_AudioFile.LOADING &amp;&amp; this.audioFiles[x].getStatus(true) === CB_AudioFile.LOADED) { filesAlreadyCreated++; } else if (this.audioFiles[x].getStatus() === CB_AudioFile.LOADING || this.audioFiles[x].getStatus() === CB_AudioFile.UNCHECKED || this.audioFiles[x].getStatus() === CB_AudioFile.CHECKING) { filesCreated++; } } } /* if (this.status !== CB_AudioFileCache.LOADED) { if (typeof(this.maximumAudioFiles) === \"undefined\" || this.maximumAudioFiles === null || this.audioFilesCreated + filesCreated &lt; this.maximumAudioFiles) { if (filesCreated &lt; this.newAudioFilesWhenNeeded) { var that = this; setTimeout(function() { that._createNewAudioFilesIfNeeded.call(that); }, 1); } } return; } */ //Creates the needed files (if any): while (typeof(this.maximumAudioFiles) === \"undefined\" || this.maximumAudioFiles === null || isNaN(this.maximumAudioFiles === null) || this.maximumAudioFiles === 0 || filesAlreadyCreated + filesCreated &lt; this.maximumAudioFiles) { //Only creates a new file if there is no maximum or it it has not been reached yet: if (filesCreated &lt; this.newAudioFilesWhenNeeded) { this.createAudioFile(null, null, null, null, null, null, null, !this.checkManuallyOnNeededCreated); filesCreated++; } else { break; } } } } /** * Object returned by the {@link CB_AudioFileCache#getFreeAudioFile} method. * @memberof CB_AudioFileCache * @typedef {Object} CB_AudioFileCache.getFreeAudioFile_OBJECT * @property {CB_AudioFile|null} object - Contains the {@link CB_AudioFile} object if found or null otherwise. * @property {string|integer} index - Contains the position of the {@link CB_AudioFile} object inside the {@link CB_AudioFileCache#audioFiles} property if found or \"-1\" otherwise. */ /** * Returns a free {@link CB_AudioFile} object, if any (from the {@link CB_AudioFileCache#audioFilesFree} property). Note that this will call the internal {@link CB_AudioFileCache#_createNewAudioFilesIfNeeded} method that could end creating a new {@link CB_AudioFile} object if needed. * @function * @param {boolean} [popIt=false] - If set to true, the {@link CB_AudioFile} object will also be \"popped\" (removed) from the {@link CB_AudioFileCache#audioFilesFree} property. * @returns {CB_AudioFileCache.getFreeAudioFile_OBJECT} Returns a {@link CB_AudioFileCache.getFreeAudioFile_OBJECT} object. */ CB_AudioFileCache.prototype.getFreeAudioFile = function(popIt) { var that = this; //If there is a free object, just returns it: if (this.audioFilesFreePointer &gt; -1) { //Sets the onStop function (which will mark the sound as free) for the object: var audioFilesIndex = this.audioFilesFree[this.audioFilesFreePointer]; var audioObject = this.audioFiles[audioFilesIndex]; //If we want, pops the element from the array of the free objects: if (popIt) { //Note: Indeed, setting it to null is not needed because we should only care about the elements before the pointer. this.audioFilesFree[this.audioFilesFreePointer--] = null; //Also decreases the pointer. } //Calls the function which creates new objects if needed: ////////clearTimeout(this._createNewAudioFilesIfNeededTimeout); this._createNewAudioFilesIfNeededTimeout = setTimeout(function() { that._createNewAudioFilesIfNeeded.call(that); }, 1); //Returns the object: return { \"object\" : audioObject, \"index\" : audioFilesIndex }; } //Calls the function which creates new objects if needed: ////////clearTimeout(this._createNewAudioFilesIfNeededTimeout); this._createNewAudioFilesIfNeededTimeout = setTimeout(function() { that._createNewAudioFilesIfNeeded.call(that); }, 1); //If there is no free object, returns null: return { \"object\" : null, \"index\" : -1 }; } /** * Tells the position of a desired {@link CB_AudioFile} object (by its identifier) in the {@link CB_AudioFileCache#audioFiles} property or -1 otherwise. * @function * @param {string} id - The identifier of the {@link CB_AudioFile} object (belongs to its {@link CB_AudioFile#id} property) whose position we want to find. Note that the identifier is not case sensitive and it should be unique for each object. * @returns {integer} Returns the position of a desired {@link CB_AudioFile} object (by its identifier) in the {@link CB_AudioFileCache#audioFiles} property or -1 otherwise. */ CB_AudioFileCache.prototype.getAudioFilePosition = function(id) { id = CB_trim(id).toUpperCase(); //id = (\"\" + id).toUpperCase(); if (id === \"\") { return -1; } //Looks through the array of the objects: var audioFilesLength = this.audioFiles.length; for (var x = 0; x &lt; audioFilesLength; x++) { //If the object exists: if (typeof(this.audioFiles[x]) !== \"undefined\" &amp;&amp; this.audioFiles[x] !== null) { //If the object has the desired ID: //if (typeof(this.audioFiles[x].id) !== \"undefined\" &amp;&amp; CB_trim(this.audioFiles[x].id).toUpperCase() === id) if (typeof(this.audioFiles[x].id) !== \"undefined\" &amp;&amp; this.audioFiles[x].id === id) { return x; //The \"x\" is the position. There should be only one with that ID (ID should be unique), so we can exit now. } } } return -1; } /** * Tells whether a desired {@link CB_AudioFile} object is free (it is in the {@link CB_AudioFileCache#audioFilesFree} property) or not, by its identifier. A free {@link CB_AudioFile} object is an object which is not being used and it is available to be used. * @function * @param {string} id - The identifier of the {@link CB_AudioFile} object (belongs to its {@link CB_AudioFile#id} property) that we want to check. Note that the identifier is not case sensitive and it should be unique for each object. * @returns {boolean} Returns whether a desired {@link CB_AudioFile} object is free (it is in the {@link CB_AudioFileCache#audioFilesFree} property) or not, by its identifier. A free {@link CB_AudioFile} object is an object which is not being used and it is available to be used. */ CB_AudioFileCache.prototype.isAudioFileFree = function(id) { var position = this.getAudioFilePosition(id); if (position === -1) { return false; } return this.isAudioFileFreeByPosition(position); } /** * Tells whether a given numeric position of a {@link CB_AudioFile} object in the {@link CB_AudioFileCache#audioFiles} property is stored in the {@link CB_AudioFileCache#audioFilesFree} property or not (this means that the {@link CB_AudioFile} object in that position of the {@link CB_AudioFileCache#audioFiles} property is free). A free {@link CB_AudioFile} object is an object which is not being used and it is available to be used. * @function * @param {integer} position - Position of the {@link CB_AudioFile} object in the {@link CB_AudioFileCache#audioFiles} property that we want to check whether it is in the {@link CB_AudioFileCache#audioFilesFree} property or not. * @returns {boolean} Returns whether the given numeric position of a {@link CB_AudioFile} object in the {@link CB_AudioFileCache#audioFiles} property is stored in the {@link CB_AudioFileCache#audioFilesFree} property or not (this means that the {@link CB_AudioFile} object in that position of the {@link CB_AudioFileCache#audioFiles} property is free). A free {@link CB_AudioFile} object is an object which is not being used and it is available to be used. */ CB_AudioFileCache.prototype.isAudioFileFreeByPosition = function(position) { //Looks through the array of the free objects: for (var x = 0; x &lt;= this.audioFilesFreePointer; x++) { if (typeof(this.audioFilesFree[x]) !== \"undefined\" &amp;&amp; this.audioFilesFree[x] === position) { return true; } } return false; } //Calls play method play again (in the case it has failed) if the delay is not more than the allowed one: CB_AudioFileCache.prototype._callRecursivelyIfNotTooLate = function(startAt, stopAt, loop, volume, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, startPlayingTime, startAtOriginal, soundInstanceId, _callRecursivelyIfNotTooLateCalledObject) { ////////if (this._callRecursivelyIfNotTooLateCalled) { return null; } ///////this._callRecursivelyIfNotTooLateCalled = true; if (_callRecursivelyIfNotTooLateCalledObject.called) { return null; } _callRecursivelyIfNotTooLateCalledObject.called = true; //Finds out the duration of the track: var startAtReal = startAtOriginal; var stopAtReal = stopAt; if (CB_trim(startAtReal) === \"\") { startAtReal = 0; } if (CB_trim(stopAtReal) === \"\") { stopAtReal = 0; } startAtReal = parseFloat(startAtReal); stopAtReal = parseFloat(stopAtReal); if (startAtReal &lt; 0) { startAtReal = 0; } if (stopAtReal &lt;= 0 || stopAtReal &gt; this.duration) { stopAtReal = this.duration; } if (startAtReal &gt; stopAtReal || isNaN(startAtReal)) { startAtReal = stopAtReal; } var durationReal = stopAtReal - startAtReal; //If the recursive delay is not null and is a valid number: if (typeof(allowedRecursiveDelay) === \"undefined\" || allowedRecursiveDelay === null || isNaN(allowedRecursiveDelay) || allowedRecursiveDelay &lt; 0) { allowedRecursiveDelay = CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT; //We use default value. } if (typeof(allowedRecursiveDelaySkipping) === \"undefined\" || allowedRecursiveDelaySkipping === null || isNaN(allowedRecursiveDelaySkipping) || allowedRecursiveDelaySkipping &lt; 0) { //////allowedRecursiveDelaySkipping = this.duration - startAtOriginal; //We use duration as default value. allowedRecursiveDelaySkipping = durationReal; //We use duration as default value. //Apply margins (because some web clients have problems to play files near their end): //if (allowedRecursiveDelaySkipping &gt; 500) { allowedRecursiveDelaySkipping -= 500; } //else if (allowedRecursiveDelaySkipping &gt; 100) { allowedRecursiveDelaySkipping -= 100; } //else if (allowedRecursiveDelaySkipping &gt; 10) { allowedRecursiveDelaySkipping -= 10; } } var timeNow = CB_Device.getTiming(); var timeExpired = timeNow - startPlayingTime; //If it is a loop, it should be played always, so we allow any expired time: if (loop) { timeExpired %= durationReal; } var that = this; //If the time expired is less or equal to the delay allowed: if (timeExpired &lt;= allowedRecursiveDelay) { //Calls the function again: setTimeout ( function() { that.play.call(that, startAtOriginal, stopAt, loop, volume, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, startPlayingTime, startAtOriginal, soundInstanceId, _callRecursivelyIfNotTooLateCalledObject); }, 1 ); return true; } //...otherwise, if the time expired is less or equal to the allowed recursive delay to play skipping: else if (timeExpired &lt;= allowedRecursiveDelaySkipping) { startAtOriginal = parseFloat(startAtOriginal); //Calls the function again: setTimeout ( function() { that.play.call(that, startAtOriginal + timeExpired, stopAt, loop, volume, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, startPlayingTime, startAtOriginal, soundInstanceId, _callRecursivelyIfNotTooLateCalledObject); }, 1 ); return true; } return null; } /** * Clears the sound instances (created by the {@link CB_AudioFileCache#play} method) which have been cancelled. * @function * @param {boolean} [clearWithObjectAssociated=false] - If set to true, it will also clear the sound instances which have a {@link CB_AudioFile} object associated. * @returns {integer} Returns the number of cleared sound instances. */ CB_AudioFileCache.prototype.clearSoundInstances = function(clearWithObjectAssociated) { var totalBefore = 0; var kept = 0; var soundInstancesQueuedNew = {}; for (var soundInstanceId in this.soundInstancesQueued) { totalBefore++; if (typeof(this.soundInstancesQueued[soundInstanceId]) !== \"undefined\") { //If it has not been cancelled or we do not want to clear with associated object and it has an object associated, we keep it: if (typeof(this.soundInstancesQueued[soundInstanceId].cancelled) === \"undefined\" || !this.soundInstancesQueued[soundInstanceId].cancelled || !clearWithObjectAssociated &amp;&amp; typeof(this.soundInstancesQueued[soundInstanceId].object) !== \"undefined\" &amp;&amp; this.soundInstancesQueued[soundInstanceId].object !== null) { kept++; soundInstancesQueuedNew[soundInstanceId] = this.soundInstancesQueued[soundInstanceId]; } } } this.soundInstancesQueued = soundInstancesQueuedNew; return totalBefore - kept; } /** * Cancels (to prevent they start playing) or enables all sound instances (created by the {@link CB_AudioFileCache#play} method). * @function * @param {boolean} [cancel=false] - Defines whether we want to cancel them or enable them. * @param {boolean} [affectWithObjectAssociated=false] - If set to true, it will also affect the sound instances which have a {@link CB_AudioFile} object associated. * @returns {integer} Returns the number of sound instances modified. */ CB_AudioFileCache.prototype.cancelSoundInstances = function(cancel, affectWithObjectAssociated) { var performed = 0; for (var soundInstanceId in this.soundInstancesQueued) { if (this.cancelSoundInstance(soundInstanceId, cancel, affectWithObjectAssociated)) { performed++; } } return performed; } /** * Cancels (to prevent it starts playing) or enables a sound instance (created by the {@link CB_AudioFileCache#play} method), by its identifier. * @function * @param {integer} soundInstanceId - The identifier (integer) of the sound instance we want to affect. * @param {boolean} [cancel=false] - Defines whether we want to cancel it or enable it. * @param {boolean} [affectWithObjectAssociated=false] - If set to true, it will also affect the sound instance even it has a {@link CB_AudioFile} object associated. * @returns {boolean} Returns true if the sound instance has been modified or false otherwise. */ CB_AudioFileCache.prototype.cancelSoundInstance = function(soundInstanceId, cancel, affectWithObjectAssociated) { //If the sound instance exists and the setting given is not already being used, sets it and returns true: cancel = !!cancel; if (typeof(this.soundInstancesQueued[soundInstanceId]) !== \"undefined\" &amp;&amp; typeof(this.soundInstancesQueued[soundInstanceId].cancelled) !== \"undefined\" &amp;&amp; this.soundInstancesQueued[soundInstanceId].cancelled !== cancel) { if (affectWithObjectAssociated || typeof(this.soundInstancesQueued[soundInstanceId].object) === \"undefined\" || this.soundInstancesQueued[soundInstanceId].object === null) { this.soundInstancesQueued[soundInstanceId].cancelled = cancel; return true; } } return false; } /** * Gets the {@link CB_AudioFile} object associated to a given sound instance ID (created by the {@link CB_AudioFileCache#play} method), if any, or null otherwise. * @function * @param {integer} soundInstanceId - The identifier (integer) of the sound instance we want to get. * @param {boolean} [avoidCancelled=false] - If set to true, it will not return the {@link CB_AudioFile} object if its sound instance has been cancelled. * @returns {CB_AudioFile|null} Returns the {@link CB_AudioFile} object associated to a given sound instance ID, if any, or null otherwise. */ CB_AudioFileCache.prototype.getAudioFileBySoundInstanceId = function(soundInstanceId, avoidCancelled) { //If the sound instance ID has an object associated: if (typeof(this.soundInstancesQueued[soundInstanceId]) !== \"undefined\" &amp;&amp; typeof(this.soundInstancesQueued[soundInstanceId].object) !== \"undefined\") { if (!avoidCancelled || typeof(this.soundInstancesQueued[soundInstanceId].cancelled) === \"undefined\" || !this.soundInstancesQueued[soundInstanceId].cancelled) { return this.soundInstancesQueued[soundInstanceId].object; } } return null; } //Function to execute when a sound stops: CB_AudioFileCache.prototype._onStopDefaultFunction = function(indexObject, thisObject, statusBefore, soundInstanceId, functionWhenError) { var wasCancelled = false; if (typeof(soundInstanceId) !== \"undefined\" &amp;&amp; soundInstanceId !== null) { if (typeof(this.soundInstancesQueued[soundInstanceId]) === \"undefined\" || this.soundInstancesQueued[soundInstanceId] === null || this.soundInstancesQueued[soundInstanceId].cancelled) { wasCancelled = true; } else if (typeof(this.soundInstancesQueued[soundInstanceId]) !== \"undefined\") { this.soundInstancesQueued[soundInstanceId].object = null; this.soundInstancesQueued[soundInstanceId].cancelled = true; } } if (typeof(thisObject) === \"undefined\" || thisObject === null) { return; } //thisObject.setVolume(0); //Sets volume to zero (to prevent hearing the sound in some web clients when checkPlaying is called). if (CB_Configuration[CB_BASE_NAME].CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING) { thisObject.mute(); } //Sets volume to zero (to prevent hearing the sound in some web clients when checkPlaying is called). //If it is still LOADED or LOADING but its internal object is LOADED (would happen when changing API), marks the object as free and increments the pointer: if (thisObject.getStatus() === CB_AudioFile.LOADED || thisObject.getStatus() === CB_AudioFile.LOADING &amp;&amp; thisObject.getStatus(true) === CB_AudioFile.LOADED) { //Marks the object as free and increments the pointer: this.audioFilesFree[++this.audioFilesFreePointer] = indexObject; //Also increases the pointer (\"x\" is the position of the object in the array). //If the status before playing was UNCHECKED (now is LOADED), it has been checked successfully, so it increases the files created counter: if (statusBefore === CB_AudioFile.UNCHECKED) { this.audioFilesCreated++; //Stores the minimum and maximum duration found: var duration = thisObject.getDuration(); if (duration &gt; 0 &amp;&amp; (this.duration === 0 || duration &lt; this.duration)) { this.duration = duration; } if (duration &gt; this.durationMaximum) { this.durationMaximum = duration; } } } //...otherwise, if it is FAILED or ABORTED, removes the sound and reloads another one: else if (thisObject.getStatus() === CB_AudioFile.FAILED || thisObject.getStatus() === CB_AudioFile.ABORTED || thisObject.getStatus() === CB_AudioFile.UNCHECKED) { this.removeAudioFile(thisObject, true, this.checkManuallyOnPlayingFailed); //Sets the sound instance as not cancelled: if (!wasCancelled &amp;&amp; typeof(soundInstanceId) !== \"undefined\" &amp;&amp; soundInstanceId !== null) { this.soundInstancesQueued[soundInstanceId] = {}; this.soundInstancesQueued[soundInstanceId].cancelled = false; this.soundInstancesQueued[soundInstanceId].object = null; } if (typeof(functionWhenError) === \"function\") { functionWhenError(); } } } /** * Plays a sound of the cache (if there is any free). If a sound cannot be played, this method can call itself internally again and again (with most of the given parameters being the same, depending on the circumstances) to try to play the sound until a desired time limit is reached. If a {@link CB_AudioFile} object cannot be played and it is determined necessary, it will try to reload it internally (by calling the {@link CB_AudioFileCache#removeAudioFile} method). * @function * @param {number} [startAt=0 | {@link CB_AudioFile_API.WAAPI#lastStartAt} | {@link CB_AudioFile_API.SM2#lastStartAt} | {@link CB_AudioFile_API.ACMP#lastStartAt} | {@link CB_AudioFile_API.AAPI#lastStartAt} | stopAt] - Time in milliseconds where we want the audio to start at. If not provided or it is not a valid number, it will use zero (0) as default which belongs to the beginning of the audio. If the value provided is greater than the \"stopAt\" provided, it will use the value set in the \"lastStartAt\" property of the used audio API object (which belongs to the \"startAt\" value the last time that the \"play\" method was called). If, even using the \"lastStartAt\" value is still greater than the \"stopAt\" provided, it will use the same value as the \"stopAt\" which means it will not play and will stop immediately. Used internally as the \"startAt\" parameter to call the {@link CB_AudioFile#play} method of the free {@link CB_AudioFile} object (if any). * @param {number} [stopAt={@link CB_AudioFile_API.WAAPI#getDuration}() | {@link CB_AudioFile_API.SM2#getDuration}() | {@link CB_AudioFile_API.ACMP#getDuration}() | {@link CB_AudioFile_API.AAPI#getDuration}()] - Time in milliseconds where we want the audio to stop at. If not provided or it is not a valid number, it will use the returning value of the \"getDuration\" method of the used audio API object (which should belong to the total duration of the audio, if it was calculated correctly). Used internally as the \"stopAt\" parameter to call the {@link CB_AudioFile#play} method of the free {@link CB_AudioFile} object (if any). * @param {boolean} [loop={@link CB_AudioFile#loop}] - Sets whether we want to play the audio looping (starting again and again) or just play it once. Used internally as the \"loop\" parameter to call the {@link CB_AudioFile#play} method of the free {@link CB_AudioFile} object (if any). * @param {number} [volume=CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME] - Desired volume to play the audio. Used internally as the \"volume\" parameter to call the {@link CB_AudioFile#setVolume} method of the free {@link CB_AudioFile} object (if any), before playing it. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all. Used only when the audio is not able to play immediately. * @param {boolean} [allowedRecursiveDelaySkipping=stopAt-startAt] - If provided (uses milliseconds) and the time expired trying to start playing the sound without success is still inside this amount of time provided, it will try to play the sound but skipping the part of the audio which should have already been played already. In other words, it will try to start playing the sound as if the previous non-played part (which should have been playing during the time which already expired) was already being playing silently. Only used when the time set in the \"allowedRecursiveDelay\" parameter has been reached and the audio did not start playing yet. The default value is the duration of the sound that we want to play (having in mind the real value of the \"startAt\" and \"stopAt\" parameters which are calculated internally and can be different from the provided ones in the case that they had any error). * @param {function} [onPlayStart] - Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"soundInstanceId\" (the identifier of the sound instance used), \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the {@link CB_AudioFile} object used (if any). Used internally as the \"onPlayStart\" parameter (wrapped in another function) to call the {@link CB_AudioFile#play} method of the free {@link CB_AudioFile} object (if any). * @param {function} [onStop] - Function to call when the sound stops playing, with an unique parameter which belongs to the \"soundInstanceId\" (the identifier of the sound instance used), being \"this\" the {@link CB_AudioFile} object (if any). Used internally as the \"callbackFunction\" parameter (wrapped in a function) to call the {@link CB_AudioFile#onStop} method of the free {@link CB_AudioFile} object (if any), before playing it. * @param {number} [startPlayingTime=CB_Device.getTiming()] - Used internally to calculate the amount of time (in milliseconds) expired without playing the sound. Internal usage only recommended. * @param {number} [startAtOriginal=startAt] - Used internally to start playing the sound accurately and skipping the part which could not be played before, if the time expired without being played is still inside the amount of time provided in the \"allowedRecursiveDelaySkipping\" parameter. Internal usage only recommended. * @param {integer} [soundInstanceId=CB_AudioFileCache._soundInstanceIdUnique++] - The identifier of the sound instance that will be played. Used internally when the function is called recursively in the case that the sound could not be played immediately. Internal usage only recommended. * @param {Object} [_callRecursivelyIfNotTooLateCalledObject] - Object with just the \"called\" property (boolean). Used internally to know whether the current execution thread called already the {@link _callRecursivelyIfNotTooLate} internal method for the same sound instance or not. Internal usage only recommended. * @returns {integer|null} Returns the sound instance ID used if there was one free or null otherwise. To get a sound instance returned does not mean necessarily that the sound started playing so it is necessary to use a callback function as the \"onPlayStart\" parameter for checking this. The sound instance created (if any), will be cancelled automatically once the sound is stopped. */ CB_AudioFileCache.prototype.play = function(startAt, stopAt, loop, volume, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, startPlayingTime, startAtOriginal, soundInstanceId, _callRecursivelyIfNotTooLateCalledObject) { var that = this; //The first time, we choose a unique sound instance ID: if (typeof(soundInstanceId) === \"undefined\" || soundInstanceId === null) { soundInstanceId = CB_AudioFileCache._soundInstanceIdUnique++; this.soundInstancesQueued[soundInstanceId] = {}; this.soundInstancesQueued[soundInstanceId].cancelled = false; this.soundInstancesQueued[soundInstanceId].object = null; //Since it is the first time, it modifies the onPlayStart function to assign the audio object to the sound instance ID: var onPlayStartOld = onPlayStart; onPlayStart = function(startAt, stopAt, startAtNextLoop, loop, avoidDelayedPlay, allowedRecursiveDelay, startPlayingTime) { that.soundInstancesQueued[soundInstanceId].object = this; if (typeof(onPlayStartOld) === \"function\") { onPlayStartOld.call(this, soundInstanceId, startAt, stopAt, startAtNextLoop, loop, avoidDelayedPlay, allowedRecursiveDelay, startPlayingTime); } }; } //If the sound instance has been cancelled, we exit: if (typeof(this.soundInstancesQueued[soundInstanceId]) === \"undefined\" || this.soundInstancesQueued[soundInstanceId] === null || this.soundInstancesQueued[soundInstanceId].cancelled) { return null; } ///////this._callRecursivelyIfNotTooLateCalled[soundInstanceId] = false; if (typeof(_callRecursivelyIfNotTooLateCalledObject) === \"undefined\" || _callRecursivelyIfNotTooLateCalledObject === null) { _callRecursivelyIfNotTooLateCalledObject = {}; } _callRecursivelyIfNotTooLateCalledObject.called = false; //If there is a free audio object, proceeds: var freeAudioFile = this.getFreeAudioFile(true); if (typeof(freeAudioFile.object) !== \"undefined\" &amp;&amp; freeAudioFile.object !== null) { var audioObject = freeAudioFile.object; var statusBefore = audioObject.getStatus(); if (typeof(startPlayingTime) === \"undefined\" || startPlayingTime === null) { startPlayingTime = CB_Device.getTiming(); } if (typeof(startAtOriginal) === \"undefined\" || startAtOriginal === null) { startAtOriginal = startAt; } //Sets the onStop function that marks the sound as free: audioObject._fireOnStopByUser = true; audioObject.onStop ( function() { that._onStopDefaultFunction.call(that, freeAudioFile.index, audioObject, statusBefore, soundInstanceId, function() { that._callRecursivelyIfNotTooLate.call(that, startAt, stopAt, loop, volume, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, startPlayingTime, startAtOriginal, soundInstanceId, _callRecursivelyIfNotTooLateCalledObject); }); if (typeof(onStop) === \"function\" &amp;&amp; audioObject._fireOnStopByUser) { onStop.call(audioObject, soundInstanceId); } }, false //Does not keep any possibly existing onStop function. ); /////////////////////////audioObject.onStop(onStop, true); //Keeps the previous function (which marks object as free when it stops). //audioObject.setVolume((statusBefore === CB_AudioFile.UNCHECKED) ? 0 : volume); //If it is UNCHECKED, sets volume to zero (to prevent hearing the sound in some web clients when checkPlaying is called). audioObject.setVolume(volume); audioObject.audioFileObject.lastStartAt = startAtOriginal; //Next loop should start from the original startAt. var played = audioObject.play ( startAt, //startAt stopAt, //stopAt loop, //loop true, //avoidDelayedPlay 0, //allowedRecursiveDelay onPlayStart, //onPlayStart function() { that.soundInstancesQueued[soundInstanceId].object = null; that.removeAudioFile(audioObject, true, that.checkManuallyOnPlayingFailed); that._callRecursivelyIfNotTooLate.call(that, startAt, stopAt, loop, volume, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, startPlayingTime, startAtOriginal, soundInstanceId, _callRecursivelyIfNotTooLateCalledObject); }, //onLoadError true //isResume (simulates a resume to force next loop (if any) to start from the original startAt). ); //If the sound has not been played: if (played === -1) { this.soundInstancesQueued[soundInstanceId].object = null; //If the sound is FAILED or ABORTED, removes it: if (audioObject.getStatus() === CB_AudioFile.FAILED || audioObject.getStatus() === CB_AudioFile.ABORTED) { this.removeAudioFile(audioObject, true, this.checkManuallyOnPlayingFailed); } //If we do not allow delayed play, calls play method again (if the maximum allowed delay has still not expired): ////////if (avoidDelayedPlay) ////////{ this._callRecursivelyIfNotTooLate(startAt, stopAt, loop, volume, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, startPlayingTime, startAtOriginal, soundInstanceId, _callRecursivelyIfNotTooLateCalledObject); ////////} } //////return audioObject; } //...otherwise, if there is no object free: else { this.soundInstancesQueued[soundInstanceId].object = null; //Calls the same function recursively: if (typeof(startPlayingTime) === \"undefined\" || startPlayingTime === null) { startPlayingTime = CB_Device.getTiming(); } if (typeof(startAtOriginal) === \"undefined\" || startAtOriginal === null) { startAtOriginal = startAt; } this._callRecursivelyIfNotTooLate(startAt, stopAt, loop, volume, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, startPlayingTime, startAtOriginal, soundInstanceId, _callRecursivelyIfNotTooLateCalledObject); //return null; } return soundInstanceId; } /** * Object used by the {@link CB_AudioFileCache#executeFunctionAll} method when the \"returnSetTimeoutsArray\" parameter is set to true. * @memberof CB_AudioFileCache * @typedef {Object} CB_AudioFileCache.executeFunctionAll_OBJECT * @property {CB_AudioFile} item - The {@link CB_AudioFile} affected. * @property {integer} setTimeoutReturningValue - The returning value of calling the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} internally or null if it was not called, depending on the \"delayBetweenEach\" parameter. * @property {number} setTimeoutDelay - The value used as the second parameter when calling the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} internally or zero if it was not called, depending on the \"delayBetweenEach\" parameter. */ /** * Alias for {@link CB_AudioFileCache#executeFunctionAll}. * @function CB_AudioFileCache#executeAll * @see {@link CB_AudioFileCache#executeFunctionAll} */ /** * Alias for {@link CB_AudioFileCache#executeFunctionAll}. * @function CB_AudioFileCache#forEach * @see {@link CB_AudioFileCache#executeFunctionAll} */ /** * Performs a desired action, using the provided function, on all the existing {@link CB_AudioFile} objects or on the desired ones (if provided). Calls the {@link CB_Arrays.executeFunctionAll} function internally and returns its returning value. * @function * @param {CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} functionEach - Function that will be called for each {@link CB_AudioFile} object. As the first parameter it receives the {@link CB_AudioFile} object of the \"audioFiles\" being looped, as the second parameter the position of this {@link CB_AudioFile} object in the \"audioFiles\" array provided (or, if not provided, in the array of the {@link CB_AudioFileCache#audioFiles} property), the third parameter is the array being looped and the fourth parameter will be the \"delayBetweenEach\" being used, being \"this\" the {@link CB_AudioFile} object itself. * @param {number|CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} [delayBetweenEach=0] - If a value greater than zero is used, it will be used as the delay desired between each call to the \"functionEach\" function (calling them using the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function internally). If not provided or the value is 0 (zero) or lower, each call to the \"functionEach\" function will be performed immediately one after the other. If a function is provided, it will be called with the same parameters as the \"functionEach\" function and its returning value will be used as the delay (executed every loop for each {@link CB_AudioFile} object). * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - A numeric array containing the {@link CB_AudioFile} objects that we want to loop. It should contain only {@link CB_AudioFile} objects which are already in the current audio file cache. If not provided, it will use all the {@link CB_AudioFile} objects contained in the cache. * @param {boolean} [returnSetTimeoutsArray=false] - Defines whether we want the method to return an integer or a numeric array with information of each [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} call. Returning an array with information of each [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} call is only useful when the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function is called internally, which happens when the \"delayBetweenEach\" parameter is greater than 0 (zero). * @param {boolean} [delayBetweenEachAffectsFirst=false] - If set to true, the desired delay (if any) will also affect the first call to the \"functionEach\" function. * @param {CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK} [functionFinish] - Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. * @returns {integer|array} If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the {@link CB_AudioFile} objects given in the \"audioFiles\" parameter). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a {@link CB_AudioFileCache.executeFunctionAll_OBJECT} object for each {@link CB_AudioFile} given. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function. * @todo Think about only allowing {@link CB_AudioFile} objects (in the \"audioFiles\" parameter) which are already in the cache (identify them by their ID), to avoid problems. */ CB_AudioFileCache.prototype.executeFunctionAll = CB_AudioFileCache.prototype.executeAll = CB_AudioFileCache.prototype.forEach = function(functionEach, delayBetweenEach, audioFiles, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, functionFinish) { return CB_Arrays.executeFunctionAll(CB_isArray(audioFiles) ? audioFiles : this.audioFiles, functionEach, delayBetweenEach, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, functionFinish); /* if (typeof(functionEach) !== \"function\") { return returnSetTimeoutsArray ? [] : 0; } if (typeof(delayBetweenEach) === \"undefined\" || delayBetweenEach === null || isNaN(delayBetweenEach) || delayBetweenEach &lt; 0) { delayBetweenEach = 0; } if (typeof(audioFiles) === \"undefined\" || audioFiles === null || !CB_isArray(audioFiles)) { audioFiles = this.audioFiles; } var setTimeoutsInformation = []; var audioFilesLength = audioFiles.length; var y = 0; var setTimeoutReturningValue = null; var setTimeoutDelay = 0; for (var x = 0; x &lt; audioFilesLength; x++) { //If the object exists: if (typeof(audioFiles[x]) !== \"undefined\" &amp;&amp; audioFiles[x] !== null) { //Executes the given function (\"this\" parameters will point to the current object): if (delayBetweenEach === 0) { functionEach.call(audioFiles[x], x); //\"x\" is the position of the object in the array. } else { new function(x) //Closure to get unique value of \"x\" variable for each loop. { setTimeoutDelay = delayBetweenEachAffectsFirst ? delayBetweenEach * (y + 1) : delayBetweenEach * y; setTimeoutReturningValue = setTimeout ( function() { functionEach.call(audioFiles[x], x); //\"x\" is the position of the object in the array. }, setTimeoutDelay ); }(x); } setTimeoutsInformation[setTimeoutsInformation.length] = { \"item\" : audioFiles[x], \"setTimeoutReturningValue\" : setTimeoutReturningValue, \"setTimeoutDelay\" : setTimeoutDelay }; y++; } } if (returnSetTimeoutsArray) { return setTimeoutsInformation; } else { return y; } */ } /** * Destroys all the {@link CB_AudioFile} objects and frees memory, by calling {@link CB_AudioFile#destructor}(stopSounds, false, true). * @function * @param {boolean} [stopSounds=false] - Used internally as the \"stopSound\" parameter when calling the {@link CB_AudioFile#destructor} method of each {@link CB_AudioFile} object. * @returns {integer} Returns the number of {@link CB_AudioFile} objects whose {@link CB_AudioFile#destructor} has been called. * @todo Think about implementing an \"audioFiles\" parameter. */ CB_AudioFileCache.prototype.destroyAll = function(stopSounds) { //Destroys each object: var destroyed = this.executeFunctionAll(function() { this.destructor(stopSounds, false, true); }); //Avoids firing onStop. //No one is free now: this.audioFilesFree = []; this.audioFilesFreePointer = -1; return destroyed; } /** * Callback function used by the {@link CB_AudioFileCache#checkPlayingAll} method that will be called when all the process was performed successfully. * @memberof CB_AudioFileCache * @callback CB_AudioFileCache.checkPlayingAll_CALLBACK_OK * @param {integer} performedActions - The number of {@link CB_AudioFile} objects that can be played. * @param {integer} uncheckedObjects - The number of {@link CB_AudioFile} objects that needed to be checked before calling this method. */ /** * Callback function used by the {@link CB_AudioFileCache#checkPlayingAll} method that will be called when not all was performed successfully. * @memberof CB_AudioFileCache * @callback CB_AudioFileCache.checkPlayingAll_CALLBACK_ERROR * @param {string} errorMessage - A string describing the error, if it could be determined. * @param {integer} performedActions - The number of {@link CB_AudioFile} objects that can be played. * @param {integer|undefined} uncheckedObjects - The number of {@link CB_AudioFile} objects that needed to be checked before calling this method (it will be undefined if it could not be determined). */ /** * Checks whether each {@link CB_AudioFile} object whose {@link CB_AudioFile#getStatus} method returns the \"unchecked\" value (which belongs to the value of the {@link CB_AudioFile#UNCHECKED} property) can be played or not. After checking, if the audio can be played, the status of the {@link CB_AudioFile} object will get the value of {@link CB_AudioFile.LOADED}. Otherwise, if it cannot be played, the status of the {@link CB_AudioFile} object will get the value of {@link CB_AudioFile.FAILED}. If a {@link CB_AudioFile} object cannot be played and it is determined necessary, it will try to reload it internally (by calling the {@link CB_AudioFileCache#removeAudioFile} method). It will call the {@link CB_AudioFileCache#clearAudioFiles} method internally after finishing. Recommended to be called through a user-driven event (as onClick, onTouch, etc.). * @function * @param {CB_AudioFileCache.checkPlayingAll_CALLBACK_OK} [callbackOk] - A function which will be called if all the {@link CB_AudioFile} objects whose {@link CB_AudioFile#getStatus} method returned the \"unchecked\" value (which belongs to the value of the {@link CB_AudioFile#UNCHECKED} property) could finally be checked successfully and all can be played, being \"this\" the {@link CB_AudioFileCache} object itself. * @param {CB_AudioFileCache.checkPlayingAll_CALLBACK_ERROR} [callbackError] - A function which will be called if not all the {@link CB_AudioFile} objects whose {@link CB_AudioFile#getStatus} method returned the \"unchecked\" value (which belongs to the value of the {@link CB_AudioFile#UNCHECKED} property) could finally be checked successfully and any cannot be played, being \"this\" the {@link CB_AudioFileCache} object itself. This function will be called immediately if the method was previously called and it is still running currently. * @param {boolean} [ignoreQueue=false] - Used internally as the \"ignoreQueue\" parameter when calling the {@link CB_AudioFile#checkPlaying} method of each {@link CB_AudioFile} object. * @returns {integer} Returns the number of {@link CB_AudioFile} objects whose status belonged to the \"unchecked\" value (the value of the {@link CB_AudioFile#UNCHECKED} property) before the execution of this method. It will return 0 (zero) if the method is tried to be executed while there is another previous call of it still running. It will also return 0 (zero) if the status of the audio file cache is not loaded (the {@link CB_AudioFileCache#status} property does not belong to the value set in the {@link CB_AudioFileCache.LOADED} property) nor unchecked (the {@link CB_AudioFileCache#status} property does not belong to the value set in the {@link CB_AudioFileCache.UNCHECKED} property). * @todo Think about implementing an \"audioFiles\" parameter. */ CB_AudioFileCache.prototype.checkPlayingAll = function(callbackOk, callbackError, ignoreQueue) { if (this._checkingPlaying) { if (typeof(callbackError) === \"function\") { callbackError.call(this, \"Method checkPlayingAll cannot be executed again until it finishes.\", 0, undefined); } return 0; } //If the cache status is not LOADED, exits: if (this.status !== CB_AudioFileCache.LOADED &amp;&amp; this.status !== CB_AudioFileCache.UNCHECKED) { if (typeof(callbackError) === \"function\") { callbackError.call(this, \"Cache status is not neither loaded nor unchecked.\", 0, undefined); } return 0; } this._checkingPlaying = true; var that = this; //Counts UNCHECKED objects: var uncheckedObjects = 0; this.executeFunctionAll ( function() { if (this.getStatus() === CB_AudioFile.UNCHECKED) { uncheckedObjects++; } } ); if (uncheckedObjects === 0) { if (typeof(callbackOk) === \"function\") { callbackOk.call(this, 0, 0); } this._checkingPlaying = false; return 0; } var performedActions = 0; var errorsHappenend = 0; var lastError = \"\"; //Function to execute when an object fails to be checked: var callbackErrorFunction = function(thisObject, error) { that.removeAudioFile(thisObject, true, that.checkManuallyOnCheckingFailed); errorsHappenend++; lastError = error; if (performedActions + errorsHappenend &gt;= uncheckedObjects) { that.clearAudioFiles(); if (typeof(callbackError) === \"function\") { callbackError.call(that, \"Not all objects could be checked. Message: \" + error, performedActions, uncheckedObjects); callbackError = null; //Prevents executing again. } that._checkingPlaying = false; } }; //Function to execute when an object checks successfully: var callbackOkFunction = function(indexObject, thisObject) { //If it is LOADED or LOADING but its internal object is LOADED (would happen when changing API), marks the object as free and increments the pointer: if (thisObject.getStatus() === CB_AudioFile.LOADED || thisObject.getStatus() === CB_AudioFile.LOADING &amp;&amp; thisObject.getStatus(true) === CB_AudioFile.LOADED) { //Marks the object as free and increments the pointer: that.audioFilesFree[++that.audioFilesFreePointer] = indexObject; //Also increases the pointer (\"x\" is the position of the object in the array). //Increases the files created counter: that.audioFilesCreated++; performedActions++; //Stores the minimum and maximum duration found: var duration = thisObject.getDuration(); if (duration &gt; 0 &amp;&amp; (that.duration === 0 || duration &lt; that.duration)) { that.duration = duration; } if (duration &gt; that.durationMaximum) { that.durationMaximum = duration; } if (performedActions &gt;= uncheckedObjects) { that.clearAudioFiles(); if (that.status === CB_AudioFileCache.UNCHECKED) { that.status = CB_AudioFileCache.LOADED; } if (typeof(callbackOk) === \"function\") { callbackOk.call(that, performedActions, uncheckedObjects); callbackOk = null; //Prevents executing again (although is very unlikely). } that._checkingPlaying = false; } else if (performedActions + errorsHappenend &gt;= uncheckedObjects) { that.clearAudioFiles(); if (typeof(callbackError) === \"function\") { callbackError.call(that, \"Not all objects could be checked. Message: \" + lastError, performedActions, uncheckedObjects); callbackError = null; //Prevents executing again. } that._checkingPlaying = false; } } //...otherwise, if it is FAILED or ABORTED, calls the error functionn: else if (audioObject.getStatus() === CB_AudioFile.FAILED || audioObject.getStatus() === CB_AudioFile.ABORTED) { callbackErrorFunction(\"The object status is not LOADED or is not LOADING and internal object LOADED (status: \" + audioObject.getStatus() + \", status internal object: \" + audioObject.getStatus(true) + \") after checking successfully.\"); } }; //Executes checkPlaying for all UNCHECKED objects: this.executeFunctionAll ( function(object, indexObject) { if (this.getStatus() === CB_AudioFile.UNCHECKED) { var thisObject = this; //Tries to play the sound: this.checkPlaying ( function() { callbackOkFunction(indexObject, thisObject); }, function(error) { callbackErrorFunction(thisObject, error); }, false, ignoreQueue, false ); } } ); return uncheckedObjects; } /** * Tries to play all the {@link CB_AudioFile} objects by calling their {@link CB_AudioFile#play} method internally. If a {@link CB_AudioFile} object cannot be played and it is determined necessary, it will try to reload it internally (by calling the {@link CB_AudioFileCache#removeAudioFile} method). It does not create sound instances. * @function * @param {number} [startAt=0 | {@link CB_AudioFile_API.WAAPI#lastStartAt} | {@link CB_AudioFile_API.SM2#lastStartAt} | {@link CB_AudioFile_API.ACMP#lastStartAt} | {@link CB_AudioFile_API.AAPI#lastStartAt} | stopAt] - Time in milliseconds where we want the audio to start at. If not provided or it is not a valid number, it will use zero (0) as default which belongs to the beginning of the audio. If the value provided is greater than the \"stopAt\" provided, it will use the value set in the \"lastStartAt\" property of the used audio API object (which belongs to the \"startAt\" value the last time that the \"play\" method was called). If, even using the \"lastStartAt\" value is still greater than the \"stopAt\" provided, it will use the same value as the \"stopAt\" which means it will not play and will stop immediately. Used internally as the \"startAt\" parameter to call the {@link CB_AudioFile#play} method of the {@link CB_AudioFile} object. * @param {number} [stopAt={@link CB_AudioFile_API.WAAPI#getDuration}() | {@link CB_AudioFile_API.SM2#getDuration}() | {@link CB_AudioFile_API.ACMP#getDuration}() | {@link CB_AudioFile_API.AAPI#getDuration}()] - Time in milliseconds where we want the audio to stop at. If not provided or it is not a valid number, it will use the returning value of the \"getDuration\" method of the used audio API object (which should belong to the total duration of the audio, if it was calculated correctly). Used internally as the \"stopAt\" parameter to call the {@link CB_AudioFile#play} method of the {@link CB_AudioFile} object. * @param {boolean} [loop={@link CB_AudioFile#loop}] - Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined will not be called. Used internally as the \"loop\" parameter to call the {@link CB_AudioFile#play} method of the {@link CB_AudioFile} object. * @param {number} [volume=CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME] - Desired volume to play the audio. Used internally as the \"volume\" parameter to call the {@link CB_AudioFile#setVolume} method of the {@link CB_AudioFile} object, before playing it. * @param {boolean} [avoidDelayedPlay=false] - If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the \"stop\" method of the audio file object will be called immediately. Used internally as the \"avoidDelayedPlay\" parameter to call the {@link CB_AudioFile#play} method of the {@link CB_AudioFile} object. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the \"stop\" method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). Used internally as the \"allowedRecursiveDelay\" parameter to call the {@link CB_AudioFile#play} method of the {@link CB_AudioFile} object. * @param {function} [onPlayStart] - Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the {@link CB_AudioFile} object. Used internally as the \"onPlayStart\" parameter to call the {@link CB_AudioFile#play} method of the {@link CB_AudioFile} object. * @param {function} [onStop] - Function that will be called each time that a {@link CB_AudioFile} object stops playing. Used internally as the \"callbackFunction\" parameter to call the {@link CB_AudioFile#onStop} method of the {@link CB_AudioFile} object, before playing it. * @param {boolean} [includingPlaying=false] - If set to true, it will call the {@link CB_AudioFile#play} method even for those {@link CB_AudioFile} objects which are currently playing. * @returns {integer} Returns the number of {@link CB_AudioFile} objects whose {@link CB_AudioFile#play} method did not return the value of \"-1\" (this does not mean necessarily that they could be played successfully). * @todo Think about implementing an \"audioFiles\" parameter. */ CB_AudioFileCache.prototype.playAll = function(startAt, stopAt, loop, volume, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onStop, includingPlaying) { //Takes all objects out of the array of the free ones: this.audioFilesFree = []; this.audioFilesFreePointer = -1; var that = this; //Executes play for all: var performed = 0; this.executeFunctionAll ( function(object, indexObject) { if (includingPlaying || !this.isPlaying()) { var thisObject = this; var statusBefore = thisObject.getStatus(); //Function that removes the sound (executed when play method fails to reload it or when sound is FAILED or ABORTED): this.onStop ( function() { that._onStopDefaultFunction.call(that, indexObject, thisObject, statusBefore); if (typeof(onStop) === \"function\") { onStop.call(thisObject); } }, false //Does not keep any possibly existing onStop function. ); ////////////this.onStop(onStop, true); //Keeps the previous function (which marks object as free when it stops). this.setVolume(volume, true); //Forces to set volume property because unchecked objects which use WAAPI still does not have gainNode created. //Tries to play the sound: var played = this.play(startAt, stopAt, loop, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, function() { that.removeAudioFile(thisObject, true, that.checkManuallyOnPlayingFailed); }); //If the sound has not been played: if (played === -1) { //If the sound is FAILED or ABORTED, removes it: if (this.getStatus() === CB_AudioFile.FAILED || this.getStatus() === CB_AudioFile.ABORTED) { that.removeAudioFile(this, true, that.checkManuallyOnPlayingFailed); } } else { performed++; } } } ); return performed; } /** * Tries to stops all the existing {@link CB_AudioFile} objects or the desired ones (if provided), which are being played, by calling their {@link CB_AudioFile#stop} method internally. * @function * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - A numeric array containing the {@link CB_AudioFile} objects that we want to affect. It should contain only {@link CB_AudioFile} objects which are already in the current audio file cache. If not provided, it will use all the {@link CB_AudioFile} objects contained in the cache. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#stop} method that were performed (which should be the same number as the {@link CB_AudioFile} objects in the \"audioFiles\" parameter). */ CB_AudioFileCache.prototype.stopAll = function(audioFiles) { return this.executeFunctionAll(function() { this.stop(); }, 0, audioFiles); } /** * Plays silently and stops all {@link CB_AudioFile} objects after a desired time. It can be useful for some clients which need the {@link CB_AudioFile#play} method to be called through a user-driven event (as onClick, onTouch, etc.). Internally, it calls {@link CB_AudioFileCache#playAll}(0, null, false, 0, true, null, null, null, includingPlaying) and, after a desired delay, calls the {@link CB_AudioFileCache#stopAll} method. * @function * @param {boolean} [includingPlaying=false] - If set to true, it will call the {@link CB_AudioFile#play} method even for those {@link CB_AudioFile} objects which are currently playing. * @param {number} [delayBeforeStop=100] - Delay (in milliseconds) before stopping the audio, that will be used as the second parameter of the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function when calling the {@link CB_AudioFileCache#stopAll} method. * @returns {integer} Returns the number of {@link CB_AudioFile} objects whose {@link CB_AudioFile#play} method did not return the value of \"-1\" (this does not mean necessarily that they could be played successfully). * @todo Think about implementing an \"audioFiles\" parameter. */ CB_AudioFileCache.prototype.playAndStopAll = function(includingPlaying, delayBeforeStop) { if (typeof(delayBeforeStop) === \"undefined\" || delayBeforeStop === null || isNaN(delayBeforeStop) || delayBeforeStop &lt; 0) { delayBeforeStop = 100; } var played = this.playAll(0, null, false, 0, true, null, null, null, includingPlaying); //Plays silently. var that = this; setTimeout(function() { that.stopAll.call(that); }, delayBeforeStop); //Stops the sound after the delay desired. return played; } /** * Tries to pause all the existing {@link CB_AudioFile} objects or the desired ones (if provided), which are being played, by calling their {@link CB_AudioFile#pause} method internally. * @function * @param {function} [onPause] - Function without parameters to be called when the audio is paused successfully, being \"this\" the {@link CB_AudioFile} object. Used internally as the \"onPause\" parameter to call the {@link CB_AudioFile#pause} method of the {@link CB_AudioFile} object. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - A numeric array containing the {@link CB_AudioFile} objects that we want to affect. It should contain only {@link CB_AudioFile} objects which are already in the current audio file cache. If not provided, it will use all the {@link CB_AudioFile} objects contained in the cache. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#pause} method that were performed (which should be the same number as the {@link CB_AudioFile} objects in the \"audioFiles\" parameter). */ CB_AudioFileCache.prototype.pauseAll = function(onPause, audioFiles) { return this.executeFunctionAll(function() { this.pause(onPause); }, 0, audioFiles); } /** * Resumes all the existing {@link CB_AudioFile} objects or the desired ones (if provided), which are paused (and not stopped). It uses the {@link CB_AudioFileCache#play} method internally. * @function * @param {boolean} [loop={@link CB_AudioFile#loop}] - Used internally as the \"loop\" parameter to call the {@link CB_AudioFileCache#play} method. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - Used internally as the \"allowedRecursiveDelay\" parameter to call the {@link CB_AudioFileCache#play} method. * @param {boolean} [allowedRecursiveDelaySkipping=CB_AudioFile#lastStopAt-CB_AudioFile#lastStartAt] - Used internally as the \"allowedRecursiveDelaySkipping\" parameter to call the {@link CB_AudioFileCache#play} method. * @param {function} [onPlayStart] - Used internally as the \"onPlayStart\" parameter to call the {@link CB_AudioFileCache#play} method. * @param {function} [onStop] - Used internally as the \"onStop\" parameter to call the {@link CB_AudioFileCache#play} method. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - A numeric array containing the {@link CB_AudioFile} objects that we want to affect. It should contain only {@link CB_AudioFile} objects which are already in the current audio file cache. If not provided, it will use all the {@link CB_AudioFile} objects contained in the cache. * @returns {array} Returns a numeric array containing all the return values of each internal call to the {@link CB_AudioFileCache#play} method. */ CB_AudioFileCache.prototype.resumeAll = function(loop, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, audioFiles) { var that = this; var startAt; var startAtOriginal; var soundInstances = []; //var soundInstance; this.executeFunctionAll ( function() { if (this.isPaused() &amp;&amp; !this.isStopped()) { //Gets the data needed for the resume: startAt = this.audioFileObject.pauseTime; startAtOriginal = this.audioFileObject.lastStartAt; if (startAt &gt;= this.audioFileObject.lastStopAt) { startAt = this.audioFileObject.lastStopAt - 1; //We will begin just 1 millisecond before (otherwise the play method would begin again from lastStartAt). } //Maybe the object which will be played (resumed) will not be this one, so we stop it and declare it as not paused (no one paused should remain): this._fireOnStopByUser = false; this.stop(false, false, true); //This way we also make it free (firing onStop). this._fireOnStopByUser = true; //var loopSet = loop; //if (typeof(loopSet) === \"undefined\" || loopSet === null) { loopSet = this.loop; } //By default, uses the previous loop used. if (typeof(loop) === \"undefined\" || loop === null) { loop = this.loop; } //By default, uses the previous loop used. //Plays a sound (maybe not the same object) which will simulate a resume with the data we have: soundInstances[soundInstances.length] = that.play(startAt, this.audioFileObject.lastStopAt, loop /*loopSet*/, this.audioFileObject.volumeBeforeMute, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, null, startAtOriginal); //this.resume(loop, null, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, function() { that.removeAudioFile(thisObject, true); }); //soundInstances[soundInstances.length] = soundInstance; } }, 0, audioFiles ); return soundInstances; } /** * Mutes all the existing {@link CB_AudioFile} objects or the desired ones (if provided). It uses the {@link CB_AudioFile#mute} method internally. * @function * @param {function} [onMute] - Callback function which will be called for each audio file if it has been possible to mute it (or at least it was possible to try it), being \"this\" the {@link CB_AudioFile} object. Used internally as the \"onMute\" parameter to call the {@link CB_AudioFile#mute} method. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - A numeric array containing the {@link CB_AudioFile} objects that we want to affect. It should contain only {@link CB_AudioFile} objects which are already in the current audio file cache. If not provided, it will use all the {@link CB_AudioFile} objects contained in the cache. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#mute} method that were performed (which should be the same number as the {@link CB_AudioFile} objects in the \"audioFiles\" parameter). */ CB_AudioFileCache.prototype.muteAll = function(onMute, audioFiles) { return this.executeFunctionAll(function() { this.mute(onMute); }, 0, audioFiles); } /** * Unmutes all the existing {@link CB_AudioFile} objects or the desired ones (if provided). It uses the {@link CB_AudioFile#unmute} method internally. * @function * @param {function} [onUnmute] - Callback function which will be called for each audio file if it has been possible to unmute it (or at least it was possible to try it), being \"this\" the {@link CB_AudioFile} object. Used internally as the \"onUnmute\" parameter to call the {@link CB_AudioFile#unmute} method. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - A numeric array containing the {@link CB_AudioFile} objects that we want to affect. It should contain only {@link CB_AudioFile} objects which are already in the current audio file cache. If not provided, it will use all the {@link CB_AudioFile} objects contained in the cache. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#unmute} method that were performed (which should be the same number as the {@link CB_AudioFile} objects in the \"audioFiles\" parameter). */ CB_AudioFileCache.prototype.unmuteAll = function(onUnmute, audioFiles) { return this.executeFunctionAll(function() { this.unmute(onUnmute); }, 0, audioFiles); } /** * Sets the same volume for all the existing {@link CB_AudioFile} objects or the desired ones (if provided). It uses the {@link CB_AudioFile#setVolume} method internally. * @function * @param {number} [volume={@link CB_Speaker.getVolume()} | {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME}] - Desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the {@link CB_Speaker.getVolume} function if the {@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM} property is set to true or it will be 100 otherwise). Used internally as the \"volume\" parameter to call the {@link CB_AudioFile#setVolume} method. * @param {boolean} [forceSetVolumeProperty=false] - If set to true (not recommended), it will change the \"volume\" property of the used audio API object even when the volume was failed to be changed. Used internally as the \"forceSetVolumeProperty\" parameter to call the {@link CB_AudioFile#setVolume} method. * @param {function} [onSetVolume] - Callback function which will be called if it has been possible to set the volume (or at least it was possible to try it), being \"this\" the {@link CB_AudioFile} object. Used internally as the \"onSetVolume\" parameter to call the {@link CB_AudioFile#setVolume} method. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - A numeric array containing the {@link CB_AudioFile} objects that we want to affect. It should contain only {@link CB_AudioFile} objects which are already in the current audio file cache. If not provided, it will use all the {@link CB_AudioFile} objects contained in the cache. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#setVolume} method that were performed (which should be the same number as the {@link CB_AudioFile} objects in the \"audioFiles\" parameter). */ CB_AudioFileCache.prototype.setVolumeAll = function(volume, forceSetVolumeProperty, onSetVolume, audioFiles) { return this.executeFunctionAll(function() { this.setVolume(volume, forceSetVolumeProperty, onSetVolume); }, 0, audioFiles); } /** * Callback function used by the {@link CB_AudioFileCache#setAudioAPIAll} method that will be called when all the process was performed successfully. * @memberof CB_AudioFileCache * @callback CB_AudioFileCache.setAudioAPIAll_CALLBACK_OK * @param {integer} objectsChangedAPI - The number of {@link CB_AudioFile} objects that actually changed its audio API. * @param {integer} performedActions - The number of {@link CB_AudioFile} objects that ended with a desired audio API, including those ones which were already using it. * @param {integer} actionsNeeded - The total number of {@link CB_AudioFile} objects that were considered to perform the action (it will be undefined if it could not be determined). */ /** * Callback function used by the {@link CB_AudioFileCache#setAudioAPIAll} method that will be called when any error happened. * @memberof CB_AudioFileCache * @callback CB_AudioFileCache.setAudioAPIAll_CALLBACK_ERROR * @param {string} error - A string describing the error, if it was possible to be determined. * @param {integer} errorsHappened - The number of errors that happened, which could be greater than 1 if more than one internal call to the {@link CB_AudioFile#setAudioAPI} method failed. * @param {integer} objectsChangedAPI - The number of {@link CB_AudioFile} objects that actually changed its audio API. * @param {integer} performedActions - The number of {@link CB_AudioFile} objects that ended with a desired audio API, including those ones which were already using it. * @param {integer} actionsNeeded - The total number of {@link CB_AudioFile} objects that were considered to perform the action (it will be undefined if it could not be determined). */ /** * Tries to change the audio API for all the existing {@link CB_AudioFile} objects or the desired ones (if provided). Uses the {@link CB_AudioFile#setAudioAPI} method internally. This method is not allowed to be called if a previous call to it did not finish yet. The function defined in the \"callbackError\" parameter, if any, will be called immediately if the method was previously called and it is still running currently. * @function * @param {array|string} preferredAPIs - Array of strings with the preferred audio API or audio APIs, in order of preference. It also accepts a string with only one audio API. If more than one audio API is provided and setting an audio API fails for a {@link CB_AudioFile} object, it will try setting the next one and so on (this means that some of the {@link CB_AudioFile} objects could end with a different audio API). Possible audio APIs are \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). * @param {CB_AudioFileCache.setAudioAPIAll_CALLBACK_OK} [callbackOk] - Function that will be called when all the process was performed successfully, being \"this\" the {@link CB_AudioFileCache} object. * @param {CB_AudioFileCache.setAudioAPIAll_CALLBACK_ERROR} [callbackError] - Function that will be called when any error happened, being \"this\" the {@link CB_AudioFileCache} object. This function will be called immediately if the method was previously called and it is still running currently. * @param {boolean} [mandatory=false] - If set to true and any {@link CB_AudioFile} object could not perform successfully any call to its {@link CB_AudioFile#setAudioAPI} method for all desired audio APIs provided in the \"preferredAPIs\" parameter (this means that, internally, all the {@link CB_AudioFile#setAudioAPI} calls, one per desired audio API, have fired an error by calling the function defined in its \"callbackError\" parameter), the audio file cache will be set as \"FAILED\" (the {@link CB_AudioFileCache#status} property will be set to the value of {@link CB_AudioFileCache.FAILED}). * @param {string} [forceReload=false] - Used internally as the \"forceReload\" parameter when calling the {@link CB_AudioFile#setAudioAPI} method internally. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - A numeric array containing the {@link CB_AudioFile} objects that we want to affect. It should contain only {@link CB_AudioFile} objects which are already in the current audio file cache. If not provided, it will use all the {@link CB_AudioFile} objects contained in the cache. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#setAudioAPI} method that were performed (which should be the same number as the {@link CB_AudioFile} objects in the \"audioFiles\" parameter). */ CB_AudioFileCache.prototype.setAudioAPIAll = function(preferredAPIs, callbackOk, callbackError, mandatory, forceReload, audioFiles) { //No sound object should be free now (because all are changing their API): ///////this.audioFilesFree = []; ///////this.audioFilesFreePointer = -1; if (this._settingAPI) { if (typeof(callbackError) === \"function\") { callbackError.call(this, \"Method setAudioAPIAll cannot be executed again until it finishes.\", 1, 0, 0, undefined); } return 0; } this._settingAPI = true; var that = this; //Function to execute when all APIs fail to apply to a single object: var objectsChangedAPI = 0; var errorsHappened = 0; var errorFunction = function(error, avoidFailing, callErrorFunction) { errorsHappened++; //If all actions have performed (fine or with an error), sets the cache as LOADED and clears the array: if (performedActions + errorsHappened &gt;= actionsNeeded) { that.status = CB_AudioFileCache.LOADED; that.clearAudioFiles(); callErrorFunction = true; } //If it was mandatory and we do not want to avoid failing, sets the cache as FAILED: if (mandatory &amp;&amp; !avoidFailing) { that.status = CB_AudioFileCache.FAILED; } //Calls the error function (if any): if (callErrorFunction) { if (typeof(callbackError) === \"function\") { callbackError.call(that, error, errorsHappened, objectsChangedAPI, performedActions, actionsNeeded); callbackError = null; //Prevents calling the function again. } that._settingAPI = false; } }; var performedActions = 0; var actionsNeeded = undefined; //If no preferred APIs are sent, throws an error and exits: if (typeof(preferredAPIs) === \"undefined\" || preferredAPIs === null) { errorFunction(\"No APIs given.\", true, true); return 0; } //Avoid setting status to FAILED. //...otherwise, if the API sent is not an array, turns it into an array: else if (!CB_isArray(preferredAPIs)) { preferredAPIs = [CB_trim(preferredAPIs)]; } //Filters the audio APIs to just use the supported ones: preferredAPIs = CB_AudioDetector.getSupportedAPIs(preferredAPIs); //If preferredAPIs is empty, calls the OK function and exits: //if (preferredAPIs.length === 0) { callbackOkFunction(null, true); return 0; } //If preferredAPIs is empty, calls the error function and exits: if (preferredAPIs.length === 0) { errorFunction(\"No APIs supported from the provided ones.\", true, true); return 0; } //If the URI list has no elements, exits: if (typeof(this._URIsListLast) === \"undefined\" || !CB_isArray(this._URIsListLast) || this._URIsListLast.length === 0) { errorFunction(\"URIs list is undefined or empty.\", true, true); return 0; } //If the cache status is not LOADED, exits: if (this.status !== CB_AudioFileCache.LOADED) { errorFunction(\"Cache is not loaded.\", true, true); return 0; } //Defines how many actions will have to be performed: if (typeof(audioFiles) === \"undefined\" || audioFiles === null || !CB_isArray(audioFiles)) { audioFiles = this.audioFiles; } else if (audioFiles.length === 0) { if (typeof(callbackOk) === \"function\") { callbackOk.call(this, 0, 0, undefined); } this._settingAPI = false; return 0; } this.status = CB_AudioFileCache.LOADING; //The cache is loading. actionsNeeded = 0; var audioFilesLength = audioFiles.length; for (var x = 0; x &lt; audioFilesLength; x++) { //If the object exists: if (typeof(audioFiles[x]) !== \"undefined\" &amp;&amp; audioFiles[x] !== null) { actionsNeeded++; } } //Function to execute when the audio object has changed the API successfully: var callbackOkFunction = function(indexObject, sameAPI) { if (!sameAPI) { objectsChangedAPI++; } //The audio object is free now: ///////that.audioFilesFree[++that.audioFilesFreePointer] = indexObject; //Increments the counter of objects that have performed the action well: performedActions++; //Stores the minimum and maximum duration found: var duration = this.getDuration(); if (duration &gt; 0 &amp;&amp; (that.duration === 0 || duration &lt; that.duration)) { that.duration = duration; } if (duration &gt; that.durationMaximum) { that.durationMaximum = duration; } //If all objects have performed their action well: if (performedActions &gt;= actionsNeeded) { that.clearAudioFiles(); //The cache finished loading: that.status = CB_AudioFileCache.LOADED; //We call the OK function (if any): if (typeof(callbackOk) === \"function\") { callbackOk.call(that, objectsChangedAPI, performedActions, actionsNeeded); callbackOk = null; //Prevents calling the function again. } that._settingAPI = false; } //...otherwise, if all actions have performed (fine or with an error), sets the cache as LOADED and clears the array: else if (performedActions + errorsHappened &gt;= actionsNeeded) { that.status = CB_AudioFileCache.LOADED; that.clearAudioFiles(); //If it was mandatory, sets the cache as FAILED: if (mandatory) { that.status = CB_AudioFileCache.FAILED; } //Calls the error function (if any): if (typeof(callbackError) === \"function\") { callbackError.call(that, error, errorsHappened, objectsChangedAPI, performedActions, actionsNeeded); callbackError = null; //Prevents calling the function again. } that._settingAPI = false; } }; //Function to execute when the audio object has failed to change the API: var callbackErrorFunction = function(error, indexObject, preferredAPIs, URIsList, URIsIndex, currentRetry, APIsTried) { /////that.clearAudioFiles(); var thisObject = this; //If it is the last URI and last API we can try, fails: if (URIsIndex + 1 &gt;= URIsList.length &amp;&amp; preferredAPIs.length &lt;= 1) { thisObject.settingAPI = false; //Calls the error function: errorFunction(error); return; } //...otherwise, continues trying the next desired API: else { //If the desired number of retries have been executed, passes to the next URI: if (++currentRetry &gt; that.retries) { currentRetry = 0; //If all URIs have been tried, passes to the next API: if (++URIsIndex &gt;= URIsList.length) { URIsIndex = 0; preferredAPIs = preferredAPIs.slice(1); //Takes out the first API (the one we have already tried). } } //Calls the function again to try again: setTimeout ( function() { setAPIEach.call(thisObject, thisObject, indexObject, undefined, undefined, preferredAPIs, URIsList, URIsIndex, currentRetry, APIsTried); }, (currentRetry === 0) ? 100 : 1000 //Delay is bigger if we are still trying the same API (to avoid problems with Firefox and AAPI or SM2). ); } }; /////this.clearAudioFiles(); //Function to execute to change API for a single object: var setAPIEach = function(object, indexObject, array, delay, preferredAPIsLocal, URIsList, URIsIndex, currentRetry, APIsTried) { if (typeof(preferredAPIsLocal) === \"undefined\" || preferredAPIsLocal === null) { preferredAPIsLocal = preferredAPIs; } if (typeof(URIsList) === \"undefined\" || URIsList === null) { URIsList = that._URIsListLast; } if (typeof(URIsIndex) === \"undefined\" || URIsIndex === null) { URIsIndex = 0; } if (typeof(currentRetry) === \"undefined\" || currentRetry === null) { currentRetry = 0; } if (typeof(APIsTried) === \"undefined\" || APIsTried === null) { APIsTried = []; } //If the API used is already being used, just calls the OK function and exits: if (this.audioAPI === preferredAPIsLocal[0]) { callbackOkFunction.call(this, indexObject, true); return; } //If it is the first time we try the API: if (CB_indexOf(APIsTried, preferredAPIsLocal[0]) === -1) { //Stores the new API that we are going to try: APIsTried[APIsTried.length] = preferredAPIsLocal[0]; //If the current object has already loaded the current API before, gets its URI: if (typeof(this.audioFileObjects) !== \"undefined\" &amp;&amp; typeof(this.audioFileObjects[preferredAPIsLocal[0]]) !== \"undefined\") { if (typeof(this.audioFileObjects[preferredAPIsLocal[0]].status) !== \"undefined\" &amp;&amp; this.audioFileObjects[preferredAPIsLocal[0]].status === CB_AudioFile.LOADED) { if (typeof(this.audioFileObjects[preferredAPIsLocal[0]].filePath) !== \"undefined\" &amp;&amp; this.audioFileObjects[preferredAPIsLocal[0]].filePath !== null) { var firstURI = this.audioFileObjects[preferredAPIsLocal[0]].filePath; //If the currently used URI is in the URIs list: if (CB_indexOf(URIsList, firstURI) !== -1) { //Places the URI used at the beginning: var URIsListNew = []; URIsListNew[0] = firstURI; //Refills the array with the rest of the URIs: var URIsListLength = URIsList.length; for (var x = 0; x &lt; URIsListLength; x++) { if (URIsList[x] !== firstURI) { URIsListNew[URIsListNew.length] = URIsList[x]; } } //Saves the new order: URIsList = URIsListNew; } } } } } var thisObject = this; thisObject.settingAPI = true; //Tries to change the API: this.setAudioAPI ( preferredAPIsLocal[0], //audioAPI. true, //audoLoad. false, //autoPlay. function() { thisObject.settingAPI = false; callbackOkFunction.call(thisObject, indexObject); }, //callbackOk. function(error) { callbackErrorFunction.call(thisObject, error, indexObject, preferredAPIsLocal, URIsList, URIsIndex, currentRetry, APIsTried); }, //callbackError, false, //ignoreOldValues. URIsList[URIsIndex], //filePath. forceReload //forceReload ); /////that.clearAudioFiles(); }; //Tries to change the API for all objects: ///////this.executeFunctionAll(setAPIEach, 10); //return this.executeFunctionAll(setAPIEach); return this.executeFunctionAll(setAPIEach, 0, audioFiles); } /** * Tells whether any of the {@link CB_AudioFile} objects is playing or not. It uses the {@link CB_AudioFile#isPlaying} method internally. * @function * @returns {boolean} Returns whether any of the {@link CB_AudioFile} objects is playing or not. */ CB_AudioFileCache.prototype.isPlaying = function() { var audioFilesLength = this.audioFiles.length; for (var x = 0; x &lt; audioFilesLength; x++) { if (typeof(this.audioFiles[x]) !== \"undefined\" &amp;&amp; typeof(this.audioFiles[x].isPlaying) !== \"undefined\" &amp;&amp; this.audioFiles[x].isPlaying()) { return true; } } return false; } /** * Tells the current number of free {@link CB_AudioFile} objects (the number of objects which are available and ready to use). * @function * @returns {integer} Returns the current number of free {@link CB_AudioFile} objects (the number of objects which are available and ready to use). */ CB_AudioFileCache.prototype.getAudioFilesFreeNumber = function() { return this.audioFilesFreePointer + 1; } /** * Gets an array with all the {@link CB_AudioFile} objects. * @function * @param {boolean} [copy=false] - If set to true, instead of returning the {@link CB_AudioFileCache#audioFiles} property directly, it will return a new copy of it. * @returns {array} Returns an array with all the {@link CB_AudioFile} objects. */ CB_AudioFileCache.prototype.getAudioFiles = function(copy) { if (copy) { var audioFiles = []; var audioFilesLength = this.audioFiles.length; var y = 0; for (var x = 0; x &lt; audioFilesLength; x++) { if (typeof(this.audioFiles[x]) !== \"undefined\" &amp;&amp; this.audioFiles[x] !== null) { audioFiles[y++] = this.audioFiles[x]; } } return audioFiles; } else { return this.audioFiles; } } /** * Gets an array with the free {@link CB_AudioFile} objects (the objects which are available and ready to use). * @function * @returns {array} Returns an array with the free {@link CB_AudioFile} objects (the objects which are available and ready to use). */ CB_AudioFileCache.prototype.getAudioFilesFree = function() { var audioFiles = []; var audioFilesLength = this.audioFiles.length; var y = 0; for (var x = 0; x &lt; audioFilesLength; x++) { if (typeof(this.audioFiles[x]) !== \"undefined\" &amp;&amp; this.audioFiles[x] !== null &amp;&amp; this.isAudioFileFreeByPosition(x)) //\"x\" is the position. { audioFiles[y++] = this.audioFiles[x]; } } return audioFiles; } /** * Gets an array with the busy {@link CB_AudioFile} objects (the objects which are not available and ready to use). * @function * @returns {array} Returns an array with the busy {@link CB_AudioFile} objects (the objects which are not available and ready to use). */ CB_AudioFileCache.prototype.getAudioFilesBusy = function() { var audioFiles = []; var audioFilesLength = this.audioFiles.length; var y = 0; for (var x = 0; x &lt; audioFilesLength; x++) { if (typeof(this.audioFiles[x]) !== \"undefined\" &amp;&amp; this.audioFiles[x] !== null &amp;&amp; !this.isAudioFileFreeByPosition(x)) //\"x\" is the position. { audioFiles[y++] = this.audioFiles[x]; } } return audioFiles; } /** * Tells the number of {@link CB_AudioFile} objects created. * @function * @param {boolean} [real=false] - If set to true, instead of returning the value of the {@link CB_AudioFileCache#audioFilesCreated} property, it will return the value of the \"length\" property of the {@link CB_AudioFileCache#audioFiles} array which are the real number of {@link CB_AudioFile} objects used. If all went well, the returning value should be always the same regardless of this parameter. * @returns {integer} Returns the number of {@link CB_AudioFile} objects created. */ CB_AudioFileCache.prototype.getAudioFilesNumber = function(real) { if (real) { return this.audioFiles.length; } else { return this.audioFilesCreated; } } /** * Tells the duration (minimum or maximum) of the sound stored (in milliseconds). Although the audio file cache should always be used to cache the same sound only, the duration might not always be the same due the usage of different formats, file paths, etc. So this method returns either the minimum or the maximum duration found among all the {@link CB_AudioFile} objects. * @function * @param {boolean} [maximum=false] - If set to true, instead of returning the value of the {@link CB_AudioFileCache#duration} property (which belongs to the minimum duration found among all the {@link CB_AudioFile} objects), it will return the value of {@link CB_AudioFileCache#durationMaximum} property (which belongs to the maximum duration found among all the {@link CB_AudioFile} objects). * @returns {number} Returns the duration (minimum or maximum) of the sound stored (in milliseconds). Although the audio file cache should always be used to cache the same sound only, the duration might not always be the same due the usage of different formats, file paths, etc. So this method returns either the minimum or the maximum duration found among all the {@link CB_AudioFile} objects. */ CB_AudioFileCache.prototype.getDuration = function(maximum) { if (maximum) { return this.durationMaximum; } else { return this.duration; } } /** * Returns a number representing the percentage of the loading progress for the audio file cache (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. * @function * @param {boolean} [countLoadedObjects=false] - If set to true, it will count the {@link CB_AudioFile} objects whose {@link CB_AudioFile#getStatus} method returns \"LOADED\" (the value of the {@link CB_AudioFile#LOADED} property), instead of just using the array's \"length\" of the {@link CB_AudioFileCache#audioFiles} property. * @param {boolean} [alsoUncheckedAndCheckingObjects=false] - If set to true and the \"countLoadedObjects\" parameter is also true, it will also count the {@link CB_AudioFile} objects whose {@link CB_AudioFile#getStatus} method returns \"UNCHECKED\" (the value of the {@link CB_AudioFile#UNCHECKED} property) or \"CHECKING\" (the value of the {@link CB_AudioFile#CHECKING} property). If the \"countLoadedObjects\" parameter is false, this parameter will be ignored. * @returns {number} Returns a number representing the percentage of the loading progress for the audio file cache (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. * @todo Although it would be more accurate, it does not use the {@link CB_AudioFile#getProgress} method internally because the {@link CB_AudioFile} objects are not added to the {@link CB_AudioFileCache#audioFiles} property until they are loaded. It would be nice to code a way to be able to use it (perhaps a property where the {@link CB_AudioFile} objects loading are kept temporarily). */ CB_AudioFileCache.prototype.getProgress = function(countLoadedObjects, alsoUncheckedAndCheckingObjects) { //var objectsLoaded = (this.audioFiles.length &lt; this.audioFilesCreated) ? this.audioFiles.length : this.audioFilesCreated; //Takes the smallest number. var objectsLoaded = this.audioFiles.length; if (countLoadedObjects) { var audioFilesLength = this.audioFiles.length; var objectsReallyLoaded = 0; for (var x = 0; x &lt; audioFilesLength; x++) { if (typeof(this.audioFiles[x]) !== \"undefined\" &amp;&amp; typeof(this.audioFiles[x].getStatus) !== \"undefined\") //if (typeof(this.audioFiles[x]) !== \"undefined\" &amp;&amp; typeof(this.audioFiles[x].getStatus) !== \"undefined\") { if (typeof(this.audioFiles[x].settingAPI) === \"undefined\" || !this.audioFiles[x].settingAPI) { if (this.audioFiles[x].getStatus() === CB_AudioFile.LOADED) { objectsReallyLoaded++; } else if (alsoUncheckedAndCheckingObjects &amp;&amp; (this.audioFiles[x].getStatus() === CB_AudioFile.UNCHECKED || this.audioFiles[x].getStatus() === CB_AudioFile.CHECKING)) { objectsReallyLoaded++; } } /* //LOADED counts as one: if (this.audioFiles[x].getStatus() === CB_AudioFile.LOADED) { objectsReallyLoaded++; } //UNCHECKED and CHECKING counts as 50%: else if (this.audioFiles[x].getStatus() === CB_AudioFile.UNCHECKED || this.audioFiles[x].getStatus() === CB_AudioFile.CHECKING) { objectsReallyLoaded += 0.5; } //LOADING counts as 50% when the progress is 100%: else if (this.audioFiles[x].getStatus() === CB_AudioFile.LOADING) { objectsReallyLoaded += this.audioFiles[x].getProgress() / 200; //It will be 0.5 when the object is loaded completely (getProgress returns 100). } */ } } //objectsLoaded = (objectsLoaded &lt; objectsReallyLoaded) ? objectsLoaded : objectsReallyLoaded; //Takes the smallest number. objectsLoaded = objectsReallyLoaded; } var objectsNeeded = this.minimumAudioFiles; var progress = (objectsLoaded / objectsNeeded) * 100; if (progress &gt; 100) { progress = 100; } else if (progress &lt; 0) { progress = 0; } //if (progress === 100 &amp;&amp; this.status === CB_AudioFileCache.LOADING) { progress = 99.99; } return progress; } /** * Gets the current status of the audio file cache. * @function * @returns {number} Returns the current status of the audio file cache. It is a number, which should match the value of the {@link CB_AudioFileCache.UNLOADED} (still unloaded), {@link CB_AudioFileCache.LOADING} (loading), {@link CB_AudioFileCache.UNCHECKED} (not checked by calling the {@link CB_AudioFileCache#checkPlayingAll} method yet), {@link CB_AudioFileCache.CHECKING} (being checked by the {@link CB_AudioFileCache#checkPlayingAll} method), {@link CB_AudioFileCache.LOADED} (loaded), {@link CB_AudioFileCache.FAILED} (failed loading or failed to play or by any other reason) or {@link CB_AudioFileCache.ABORTED} (aborted because it was destroyed with the \"destructor\" method) property. */ CB_AudioFileCache.prototype.getStatus = function() { return this.status; } /** * Gets the current status of the audio file cache, as a string. * @function * @returns {string} Returns the current status of the audio file cache, as a string. Possible return values are \"UNLOADED\", \"LOADING\", \"UNCHECKED\", \"CHECKING\", \"LOADED\", \"FAILED\", \"ABORTED\" or \"UNKNOWN (UNKNOWN_STATUS)\" (where \"UNKNOWN_STATUS\" will be a value from the {@link CB_AudioFileCache#status} property not recognized as any possible status). */ CB_AudioFileCache.prototype.getStatusString = function() { var status = this.getStatus(); var statuses = [ \"UNLOADED\", \"LOADING\", \"UNCHECKED\", \"CHECKING\", \"LOADED\", \"FAILED\", \"ABORTED\" ]; if (typeof(statuses[status]) !== \"undefined\") { return statuses[status]; } else { return \"UNKNOWN (\" + status + \")\"; } } /** * Calls the error function which should be set in the {@link CB_AudioFileCache#onError} property (if any), being \"this\" the {@link CB_AudioFileCache} object itself. Internal usage only recommended. * @function * @param {string} [message] - The message describing the error that will be sent to the set {@link CB_AudioFileCache#onError} function (if any) as the first and unique parameter. * @param {boolean} [avoidFailing=false] - If set to true, it will not set the {@link CB_AudioFileCache#status} property to \"FAILED\" (the value of the {@link CB_AudioFile#FAILED} property). * @returns {boolean} Returns true if the {@link CB_AudioFileCache#onError} function could be called or false otherwise. */ CB_AudioFileCache.prototype.errorFunction = function(message, avoidFailing) { if (!avoidFailing) { this.status = CB_AudioFileCache.FAILED; } if (typeof(this.onError) === \"function\") { this.onError.call(this, message); return true; } return false; } × Search results Close "},"CrossBase_audiovisual_audio_CB_AudioFileSprites.js.html":{"id":"CrossBase_audiovisual_audio_CB_AudioFileSprites.js.html","title":"Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js /** * @file Audio sprites management. Contains the {@link CB_AudioFileSprites} class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * An object representing an audio sprite which can contain, optionally, the \"startAt\" and \"stopAt\" properties with a numeric value (representing when the audio sprite starts and when it stops, respectively). If not set, the default \"startAt\" value will be 0 (zero) and the default \"stopAt\" value will be null (which means it will not stop until the end of the audio is reached unless it is paused or stopped before). The \"fake\" property should never be used as it is used internally to distinguish real sprites from fake ones (generated and returned by the {@link CB_AudioFileSprites#getSprite} method when a requested sprite is not found). * @example { startAt: 10, stopAt: 20 } * @memberof CB_AudioFileSprites * @typedef {Object} CB_AudioFileSprites.SPRITE_OBJECT * @property {number} [startAt=0] - The time (in milliseconds) of the audio file where the audio sprite starts. If not provided, it will use the value of 0 (zero) which means that it will start from the beginning. * @property {number} [stopAt={@link CB_AudioFile_API.WAAPI#getDuration}() | {@link CB_AudioFile_API.SM2#getDuration}() | {@link CB_AudioFile_API.ACMP#getDuration}() | {@link CB_AudioFile_API.AAPI#getDuration}()] - The time (in milliseconds) of the audio file where the audio sprite stops. If not provided (not recommended), it will use the whole duration of the file (which means until it reaches its end). NOTE: Due to some possible problems between clients with different audio APIs calculating the duration of an audio file, it is recommended to always set the \"stopAt\" property even when we want it to stop at the end of the audio. */ /** * Object whose property names the identifiers of each sprite (a case-sensitive string) and their value is a {@link CB_AudioFileSprites.SPRITE_OBJECT} object. * @example * { * \"whole_audio\" : {}, * \"first_sprite\" : { stopAt: 10 }, * \"second_sprite\" : { startAt: 10, stopAt: 20 }, * \"third_sprite\" : { startAt: 20 }, * ... * } * @memberof CB_AudioFileSprites * @typedef {Object} CB_AudioFileSprites.SPRITES_OBJECT * @property {CB_AudioFileSprites.SPRITE_OBJECT} spriteInformation - Being the name of each property the identifier of a sprite (a string which cannot be \"_WITHOUT_SPRITE_ASSOCIATED\" as it is a reserved name), the value will always be a {@link CB_AudioFileSprites.SPRITE_OBJECT} object. */ /** * Object with the desired data and options for the audio sprites. It is almost identical to the {@link CB_AudioFileCache.DATA_OBJECT} but adding a \"sprites\" property. * @memberof CB_AudioFileSprites * @typedef {Object} CB_AudioFileSprites.DATA_OBJECT * @property {CB_AudioFileCache.URIS_OBJECT} URIs - Object whose property names audio formats and their value is an array of strings with the URIs (audio file paths or audio data URIs) of the audio files in order of preference. The best audio format for the current client will be tried to be calculated and it will use the first working URI (audio file path or data URI). The more audio formats and URIs provided the better, as it will help to maximize the compatibility with as many clients as possible (as some audio APIs and client just support some formats, or use absolute paths instead of relative ones, etc.). Even with different formats, all provided URIs should belong to the same audio (this means same sound or same music, with same length, etc.). NOTE: Only some clients with some audio APIs will support data URIs. If a valid value is given, this will be added to the {@link CB_AudioFileCache#URIs} property. * @property {CB_AudioFileSprites.SPRITES_OBJECT} [sprites] Object with the desired sprites. It will be used as the first parameter to call the {@link CB_AudioFileSprites#insertSprites} method internally. It will be added (after being processed) to the {@link CB_AudioFileCache#sprites} property. * @property {string} [id=\"\"] - Desired identifier for the audio file sprites object. Internal usage only recommended. If a valid value is given, this will be added to the {@link CB_AudioFileSprites#id} property as well as to the {@link CB_AudioFileCache#id} property of the internally-created {@link CB_AudioFileCache} object. * @property {array} [preferredAPIs={@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS}] - Array of strings with the preferred audio API or audio APIs, in order of preference. Possible audio APIs are \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). It will try to calculate and use the best one for the current client. If a valid value is given, this will be added to the {@link CB_AudioFileCache#preferredAPIs} property. * @property {array} [preferredFormats={@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_FORMATS}] - Array of strings with the preferred audio format or audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"'), in order of preference. It will try to calculate and use the best one for the current client. If a valid value is given, this will be added to the {@link CB_AudioFileCache#preferredFormats} property. * @property {integer} [minimumAudioFiles={@link CB_AudioFileCache.minimumAudioFiles_DEFAULT}] - Minimum {@link CB_AudioFile} objects to create internally. It must be an integer being 1 the minimum. If a valid value is given, this will be added to the {@link CB_AudioFileCache#minimumAudioFiles} property. * @property {integer} [maximumAudioFiles={@link CB_AudioFileCache.maximumAudioFiles_DEFAULT}] - Maximum {@link CB_AudioFile} objects that are to be created internally. If it is set to null, there will not be a maximum (it will be unlimited). If an integer is provided, it must be the same number or greater than the value set in the {@link CB_AudioFileCache#minimumAudioFiles} property (also provided by the \"minimumAudioFiles\" of this object), allowing 1 minimum. If a valid value is given, this will be added to the {@link CB_AudioFileCache#maximumAudioFiles} property. * @property {integer} [minimumAudioFilesFree=parseInt({@link CB_AudioFileCache#minimumAudioFiles} * 0.25 + 0.5)] - New {@link CB_AudioFile} objects will be created internally when the number of free {@link CB_AudioFile} objects reaches this limit. If provided, it must be an integer being 0 (zero) the minimum. It will end using a 25% of the {@link CB_AudioFileCache#minimumAudioFiles} by default, rounded to ceil, allowing 0 (zero) minimum. If a valid value is given, this will be added to the {@link CB_AudioFileCache#minimumAudioFilesFree} property. * @property {integer} [newAudioFilesWhenNeeded=Math.min(parseInt({@link CB_AudioFileCache#minimumAudioFiles} * 0.1 + 0.5), 1)] - Number of new {@link CB_AudioFile} objects to create internally when the minimum limit of free {@link CB_AudioFile} objects ({@link CB_AudioFileCache#minimumAudioFilesFree}) is reached. If provided, it must be an integer being 0 (zero) the minimum. It will end using a 10% of the {@link CB_AudioFileCache#minimumAudioFiles} by default, rounded to ceil, allowing 1 minimum. If a valid value is given, this will be added to the {@link CB_AudioFileCache#newAudioFilesWhenNeeded} property. * @property {integer} [retries={@link CB_AudioFileCache.retries_DEFAULT}] - Number of retries to try to load a {@link CB_AudioFile} object internally before trying to load the next possible one internally (if any). It must be an integer being 0 the minimum. If a valid value is given, this will be added to the {@link CB_AudioFileCache#retries} property. * @property {boolean} [checkManually={@link CB_AudioFileCache.checkManually_DEFAULT}] - Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) by default. If a valid value is given, this will be added to the {@link CB_AudioFileCache#checkManually} property. * @property {boolean} [checkManuallyOnNeededCreated={@link CB_AudioFileCache.checkManuallyOnNeededCreated_DEFAULT}] - Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when creates a new {@link CB_AudioFile} object needed. If a valid value is given, this will be added to the {@link CB_AudioFileCache#checkManuallyOnNeededCreated} property. * @property {boolean} [checkManuallyOnPlayingFailed={@link CB_AudioFileCache.checkManuallyOnPlayingFailed_DEFAULT}] - Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when playing one has failed and tries to reload it. If a valid value is given, this will be added to the {@link CB_AudioFileCache#checkManuallyOnPlayingFailed} property. * @property {boolean} [checkManuallyOnCheckingFailed={@link CB_AudioFileCache.checkManuallyOnCheckingFailed_DEFAULT}] - Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when checking one has failed and tries to reload it. If a valid value is given, this will be added to the {@link CB_AudioFileCache#checkManuallyOnCheckingFailed} property. * @property {function} [onLoad] - Desired function to be called once the cache has been loaded. The first and unique parameter will be an integer with the {@link CB_AudioFile} objects that still need to be checked, if any, being \"this\" the current {@link CB_AudioFileCache} object. If a valid value is given, this will be added to the {@link CB_AudioFileCache#onLoad} property. * @property {function} [onError] - Desired function to be called when any kind of error happens. The first and unique parameter will be a string with the error description (if it could be determined), being \"this\" the current {@link CB_AudioFileCache} object. If a valid value is given, this will be added to the {@link CB_AudioFileCache#onError} property. * @property {boolean} [disableAutoLoad=false] - If set to true, it will not create automatically the {@link CB_AudioFile} objects by calling the {@link CB_AudioFileCache#createAudioFiles} method internally. Internal usage only recommended. */ /** * The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. * @class * @classdesc Class to manage audio sprites of a {@link CB_AudioFileCache} object (used internally). * @param {CB_AudioFileSprites.DATA_OBJECT} [dataObject] - Object with the desired data and options for the audio sprites. Although it can contain a \"sprites\" property, it will also be used as the first and unique parameter when calling the constructor of the {@link CB_AudioFileCache} object internally. * @returns {CB_AudioFileSprites} Returns a new {@link CB_AudioFileSprites} object. * @todo Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). * @todo Think about using wrapper to replace \"this\" in callbacks (callbackOk, callbackError) to point to the {@link CB_AudioFileSprites} object itself. * @todo Method getCopy and static method filterProperties (similar to the ones from {@link CB_GraphicSprites} and {@link CB_GraphicSpritesScene}). */ var CB_AudioFileSprites = function(dataObject) { //Creates an instance of this object and returns it in the case that it is being called from an unexpected context: if (this === window || !(this instanceof CB_AudioFileSprites)) { return new CB_AudioFileSprites(dataObject); } //Properties and variables: /** * Stores the identifier for the audio file sprites object. * @var * @readonly * @type {string} * @default */ this.id = \"\"; /** * Object with information about the sprites. * @var * @readonly * @type {CB_AudioFileSprites.SPRITES_OBJECT} * @default */ this.sprites = {}; /** * Object whose property names are the sprite identifiers (strings), including one called \"_WITHOUT_SPRITE_ASSOCIATED\" for sound instances without a sprite associated, and their values are an array containing the sound instance identifiers (created by the {@link CB_AudioFileSprites#play} method). Internal usage only recommended. * @var * @readonly * @type {Object} * @default { \"_WITHOUT_SPRITE_ASSOCIATED\" : [] } */ this.spriteSoundInstances = { \"_WITHOUT_SPRITE_ASSOCIATED\" : [] }; //Object with the sound instances associated to each sprite ID. //If not defined, defines a fake prototype object: CB_AudioFileSprites._audioFileCachePrototype = CB_AudioFileSprites._audioFileCachePrototype || { DEFAULT_ERROR_MESSAGE : \"CB_AudioFileCache object not loaded (using prototype).\", usingPrototype : true, status : CB_AudioFileCache.UNLOADED, audioFiles : [], audioFilesCreated : 0, audioFilesFreePointer : 0, soundInstancesQueued : {}, duration : 0, destructor : function() {}, createAudioFiles : function() { return 0; }, createAudioFile : function(URIs, preferredAPIs, preferredFormats, audioObject, callbackOk, callbackError) { if (typeof(callbackError) === \"function\") { callbackError.call(CB_AudioFileSprites._audioFileCachePrototype, DEFAULT_ERROR_MESSAGE); } return null; }, clearAudioFiles : function() { return []; }, removeAudioFile : function() { return null; }, purge : function() { return 0; }, getFreeAudioFile : function() { return { \"object\" : null, \"index\" : -1 }; }, isAudioFileFree : function() { return false; }, clearSoundInstances : function() { return 0; }, cancelSoundInstances : function() { return false; }, cancelSoundInstance : function() { return false; }, getAudioFileBySoundInstanceId : function() { return null; }, play : function(startAt, stopAt, loop, volume, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop) { if (typeof(onStop) === \"function\") { onStop(); } return null; }, executeFunctionAll : function() { return 0; }, destroyAll : function() { return 0; }, checkPlayingAll : function(callbackOk, callbackError) { if (typeof(callbackError) === \"function\") { callbackError.call(CB_AudioFileSprites._audioFileCachePrototype, DEFAULT_ERROR_MESSAGE); } return 0; }, playAll : function(startAt, stopAt, loop, volume, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onStop) { if (typeof(onStop) === \"function\") { onStop(); } return 0; }, stopAll : function() { return 0; }, playAndStopAll : function() { return 0; }, pauseAll : function() { return 0; }, resumeAll : function(loop, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop) { if (typeof(onStop) === \"function\") { onStop(); } return 0; }, muteAll : function() { return 0; }, unmuteAll : function() { return 0; }, setVolumeAll : function() { return 0; }, setAudioAPIAll : function(preferredAPIs, callbackOk, callbackError) { if (typeof(callbackError) === \"function\") { callbackError.call(CB_AudioFileSprites._audioFileCachePrototype, DEFAULT_ERROR_MESSAGE); } return 0; }, getStatus : function() { return CB_AudioFileCache.UNLOADED; }, getStatusString : function() { return \"UNLOADED\"; }, getAudioFilesFreeNumber : function() { return 0; }, getAudioFiles : function() { return []; }, getAudioFilesFree : function() { return []; }, getAudioFilesBusy : function() { return []; }, getAudioFilesNumber : function() { return 0; }, getDuration : function() { return 0; }, getProgress : function() { return 0; }, isPlaying : function() { return false; } }; /** * Contains the {@link CB_AudioFileCache} object. Internal usage only recommended. * @var * @readonly * @type {CB_AudioFileCache} * @default */ this.audioFileCache = CB_AudioFileSprites._audioFileCachePrototype; //Keeps the CB_AudioFileCache object. //Calls the constructor of the object when creates an instance: return this._init(dataObject); } //Constructor: CB_AudioFileSprites.prototype._init = function(dataObject) { /* FORMAT: dataObject = { [id : String,] [preferredAPIs : Array&lt;String&gt;,] [preferredFormats : Array&lt;String&gt;,] URIs : Object, [minimumAudioFiles : Integer,] [maximumAudioFiles : Integer,] [minimumAudioFilesFree : Integer,] [newAudioFilesWhenNeeded : Integer,] [retries : Integer,] [checkManually : Boolean,] [checkManuallyOnNeededCreated : Boolean,] [checkManuallyOnPlayingFailed : Boolean,] [checkManuallyOnCheckingFailed : Boolean,] [disableAutoLoad : Boolean,] [onLoad : Function,] [onError : Function,] sprites : { \"sprite_id\" : { [startAt : Integer,] [stopAt : Integer,] } [, ...] } }; */ //Tries to load the data (if any): this.load(dataObject); //Returns the object: return this; } /** * Destroys the audio file sprites object (removing all sprites, etc.), including the internal audio file cache object, and frees memory. By default, unless the \"preventAbortedStatus\" is set to true, sets the current status of the {@link CB_AudioFileCache} object as ABORTED ({@link CB_AudioFileCache.ABORTED} value). * @function * @param {boolean} [stopSounds=false] - Used as the \"stopSounds\" parameter when calling internally the {@link CB_AudioFileCache#destructor} method of the {@link CB_AudioFileCache} object. * @param {boolean} [preventAbortedStatus=false] - If set to true (not recommended), it will not assign the status of \"ABORTED\" (it will not assign the value of {@link CB_AudioFileCache.ABORTED} to the {@link CB_AudioFileCache#status} property). */ CB_AudioFileSprites.prototype.destructor = function(stopSounds, preventAbortedStatus) { //Resets properties to their default value: this.sprites = {}; this.spriteSoundInstances = { \"_WITHOUT_SPRITE_ASSOCIATED\" : [] }; //Destroys the CB_AudioFileCache object: this.audioFileCache.destructor(stopSounds, preventAbortedStatus); this.audioFileCache = CB_AudioFileSprites._audioFileCachePrototype; } /** * Loads the audio file sprites with the desired data given. This method is called by the constructor automatically. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. * @function * @param {CB_AudioFileSprites.DATA_OBJECT} dataObject - Object with the desired data and options for the audio file sprites. * @returns {CB_AudioFileSprites|null} If a \"dataObject\" is given, it returns the current {@link CB_AudioFileSprites} object. Otherwise, it returns null. */ CB_AudioFileSprites.prototype.load = function(dataObject) { if (typeof(dataObject) === \"undefined\" || dataObject === null) { return null; } //Destroys all previous data (if any): this.destructor(true, true); //Also stops all sounds. //Sanitizes the given data: dataObject.id = CB_trim(dataObject.id); //Sets the new data: if (dataObject.id !== \"\") { this.id = dataObject.id; } //Inserts the sprites: if (typeof(dataObject.sprites) !== \"undefined\" &amp;&amp; dataObject.sprites !== null) { this.removeSprites(); this.insertSprites(dataObject.sprites); } //Creates the audio file cache object: this.audioFileCache = new CB_AudioFileCache(dataObject); return this; } /** * Alias for {@link CB_AudioFileSprites#removeSprites}. * @function CB_AudioFileSprites#removeSpritesAll * @see {@link CB_AudioFileSprites#removeSprites} */ /** * Removes all the sprites by clearing the {@link CB_AudioFileSprites#sprites} property. * @function */ CB_AudioFileSprites.prototype.removeSprites = CB_AudioFileSprites.prototype.removeSpritesAll = function() { this.sprites = {}; } /** * Inserts the given sprites. It will keep the existing ones. If a sprite identifier already existed and it is given again (not recommended), it will be replaced by the new one (but keeping its current sound instances, if any). * @function * @param {CB_AudioFileSprites.SPRITES_OBJECT} sprites - Object with the desired sprites. * @returns {integer} Returns the number of sprites inserted. */ CB_AudioFileSprites.prototype.insertSprites = function(sprites) { var inserted = 0; if (typeof(sprites) !== \"undefined\" &amp;&amp; sprites !== null) { for (var spriteId in sprites) { //Inserts the sprite: if (this.insertSprite(sprites[spriteId], spriteId)) { inserted++; } } } return inserted; } /** * Inserts the given sprite. It will keep the existing ones. If a sprite identifier already existed and it is given again (not recommended), it will be replaced by the new one (but keeping its current sound instances, if any). * @function * @param {CB_AudioFileSprites.SPRITE_OBJECT} sprite - Object with the desired sprite. * @param {string} spriteId - The identifier for the sprite. * @returns {boolean} Returns true if the sprite has been inserted or false otherwise. */ CB_AudioFileSprites.prototype.insertSprite = function(sprite, spriteId) { if (typeof(spriteId) === \"undefined\" || spriteId === null) { return false; } this.sprites[spriteId] = {}; this.setStartAtSprite(spriteId, (typeof(sprite.startAt) === \"undefined\") ? undefined : sprite.startAt); this.setStopAtSprite(spriteId, (typeof(sprite.stopAt) === \"undefined\") ? undefined : sprite.stopAt); if (typeof(this.spriteSoundInstances[spriteId]) === \"undefined\" || this.spriteSoundInstances[spriteId] === null) { this.spriteSoundInstances[spriteId] = []; } return true; } /** * Sets when a sprite begins (stored in its \"startAt\" property), by sprite identifier. * @function * @param {string} spriteId - The identifier for the sprite. * @param {number} startAt - The time (in milliseconds) of the audio file where the audio sprite starts. * @returns {boolean} Returns true if the sprite has been modified or false otherwise. */ CB_AudioFileSprites.prototype.setStartAtSprite = function(spriteId, startAt) { if (typeof(this.sprites[spriteId]) === \"undefined\" || this.sprites[spriteId] === null) { return false; } this.sprites[spriteId].startAt = 0; if (typeof(startAt) !== \"undefined\" &amp;&amp; startAt !== null &amp;&amp; !isNaN(startAt) &amp;&amp; startAt &gt;= 0 &amp;&amp; this.sprites[spriteId].startAt !== startAt) { this.sprites[spriteId].startAt = startAt; return true; } return false; } /** * Sets when a sprite ends (stored in its \"stopAt\" property), by sprite identifier. * @function * @param {string} spriteId - The identifier for the sprite. * @param {number} stopAt - The time (in milliseconds) of the audio file where the audio sprite ends. * @returns {boolean} Returns true if the sprite has been modified or false otherwise. */ CB_AudioFileSprites.prototype.setStopAtSprite = function(spriteId, stopAt) { if (typeof(this.sprites[spriteId]) === \"undefined\" || this.sprites[spriteId] === null) { return false; } this.sprites[spriteId].stopAt = null; if (typeof(stopAt) !== \"undefined\" &amp;&amp; stopAt !== null &amp;&amp; !isNaN(stopAt) &amp;&amp; stopAt &gt; this.sprites[spriteId].startAt &amp;&amp; this.sprites[spriteId].stopAt !== stopAt) { this.sprites[spriteId].stopAt = stopAt; return true; } return false; } /** * Removes a sprite by its ID. * @function * @param {string} spriteId - The identifier for the sprite. * @returns {boolean} Returns true if the sprite has been deleted or false otherwise. */ CB_AudioFileSprites.prototype.removeSprite = function(spriteId) { if (typeof(this.sprites[spriteId]) !== \"undefined\" &amp;&amp; this.sprites[spriteId] !== null) { this.sprites[spriteId] = null; var sprites = {}; var deleted = false; for (spriteId in this.sprites) { if (typeof(this.sprites[spriteId]) !== \"undefined\" &amp;&amp; this.sprites[spriteId] !== null) { sprites[spriteId] = this.sprites[spriteId]; deleted = true; } } this.sprites = sprites; return deleted; } return false; } /** * Returns a sprite by its ID. * @function * @param {string} spriteId - The identifier for the sprite. * @returns {CB_AudioFileSprites.SPRITE_OBJECT} Returns the desired sprite or a fake object if it was not found. The fake object will be this one: { \"startAt\" : 0, \"stopAt\" : null, \"fake\" : true }. */ CB_AudioFileSprites.prototype.getSprite = function(spriteId) { if (typeof(this.sprites[spriteId]) !== \"undefined\") { return this.sprites[spriteId]; } return { \"startAt\" : 0, \"stopAt\" : null, \"fake\" : true }; } /** * Returns an object with the sprites (and includes \"_WITHOUT_SPRITE_ASSOCIATED\" if we want to). * @function * @param {boolean} [includeWithoutSpriteAssociated=false] - If set to true, the returning object will also contain a property called \"_WITHOUT_SPRITE_ASSOCIATED\" whose value will be an empty object (unless the property existed before in the object stored in the {@link CB_AudioFileSprites#sprites} property and had a value which is not an empty object). If set to false, the returning object will not contain the \"_WITHOUT_SPRITE_ASSOCIATED\" property unless the property existed before in the object stored in the {@link CB_AudioFileSprites#sprites} property. * @returns {CB_AudioFileSprites.SPRITES_OBJECT} Returns an object with the sprites (and includes \"_WITHOUT_SPRITE_ASSOCIATED\" if we want to). */ CB_AudioFileSprites.prototype.getSprites = function(includeWithoutSpriteAssociated) { if (!includeWithoutSpriteAssociated) { return this.sprites; } else { var sprites = {}; sprites[\"_WITHOUT_SPRITE_ASSOCIATED\"] = {}; for (var spriteId in this.sprites) { sprites[spriteId] = this.sprites[spriteId]; } return sprites; } } /** * Returns an array of the sound instance identifiers (created by the {@link CB_AudioFileSprites#play} method) used by the given sprite identifier. * @function * @param {string} spriteId - The identifier for the sprite. * @returns {array} Returns a numeric array of the sound instances (created by the {@link CB_AudioFileSprites#play} method) used by the given sprite identifier. */ CB_AudioFileSprites.prototype.getSoundInstancesIdBySpriteId = function(spriteId) { if (typeof(this.spriteSoundInstances[spriteId]) !== \"undefined\") { return this.spriteSoundInstances[spriteId]; } return []; } /** * Returns the sound instances (their ID) used (stored in the {@link CB_AudioFileSprites#spriteSoundInstances} property). * @function * @param {boolean} [oneDimension=false] - If set to true, it will return the {@link CB_AudioFileSprites#spriteSoundInstances} property directly (which includes the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated). Otherwise, if it is set to true, it will return a numeric array whose values are the sound instance IDs. * @param {boolean} [includeWithoutSpriteAssociated=false] - If set to true, it will also return the sound instance identifiers which are not associated to any sprite. Used as the \"includeWithoutSpriteAssociated\" parameter when calling the {@link CB_AudioFileSprites#getSprites} method internally. Only used when the \"oneDimension\" parameter is set to true. * @returns {Object|array} Returns the sound instances (their ID) used (stored in the {@link CB_AudioFileSprites#spriteSoundInstances} property). If the \"oneDimension\" parameter is set to false, the property names of the returning object are the sprite identifiers (strings), including one called \"_WITHOUT_SPRITE_ASSOCIATED\" for sound instances without a sprite associated, and their values are an array containing the sound instance IDs. If the \"oneDimension\" parameter is set to true, it will return a numeric array whose values are the sound instance identifiers (if the \"includeWithoutSpriteAssociated\" parameter it set to true, it will also include the sound instances which are not associated to any sprite). */ CB_AudioFileSprites.prototype.getSoundInstancesId = function(oneDimension, includeWithoutSpriteAssociated) { if (!oneDimension) { return this.spriteSoundInstances; } else { var soundInstances = []; var soundInstancesSprite; var soundInstancesSpriteLength; var y = 0; var x = 0; var sprites = this.getSprites(includeWithoutSpriteAssociated); for (var spriteId in sprites) { soundInstancesSprite = this.getSoundInstancesIdBySpriteId(spriteId); soundInstancesSpriteLength = soundInstancesSprite.length; for (x = 0; x &lt; soundInstancesSpriteLength; x++) { soundInstances[y++] = soundInstancesSprite[x]; } } return soundInstances; } } /** * Returns an array of the {@link CB_AudioFile} objects used by the sound instances that belong to a given sprite identifier. * @function * @param {string} spriteId - The identifier for the sprite. * @param {boolean} [avoidCancelled=false] - If set to true, it will not return the {@link CB_AudioFile} objects whose sound instance has been cancelled. Used as the \"avoidCancelled\" parameter when calling the {@link CB_AudioFileSprites#getAudioFileBySoundInstanceId} method internally. * @returns {array} Returns an array of the {@link CB_AudioFile} objects used by the sound instances that belong to the given sprite identifier. */ CB_AudioFileSprites.prototype.getAudioFilesUsedBySpriteId = function(spriteId, avoidCancelled) { var soundInstances = this.getSoundInstancesIdBySpriteId(spriteId); var audioFiles = []; var y = 0; var soundInstancesLength = soundInstances.length; var currentObject = null; for (var x = 0; x &lt; soundInstancesLength; x++) { currentObject = this.getAudioFileBySoundInstanceId(soundInstances[x], avoidCancelled); if (currentObject !== null) { audioFiles[y++] = currentObject; } } return audioFiles; } /** * Object returned by the {@link CB_AudioFileSprites#getAudioFilesUsed} method. Each property names will be the sprites identifiers except the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated (if we wanted to include them). * @memberof CB_AudioFileSprites * @typedef {Object} CB_AudioFileSprites.getAudioFilesUsed_OBJECT * @property {CB_AudioFile} spriteId - Each property name will be a sprite identifier (it can be \"_WITHOUT_SPRITE_ASSOCIATED\" for sound instances without a sprite associated, if we wanted to include them). The value will be a numeric array with the {@link CB_AudioFile} objects used. */ /** * Returns the {@link CB_AudioFile} objects used by all the sounds instances currently created. * @function * @param {boolean} [oneDimension=false] - If set to false, it will return an object whose property names are the sprite identifiers (including the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated, if the \"includeWithoutSpriteAssociated\" is set to true) and their value will be a numeric array with the {@link CB_AudioFile} objects used. Otherwise, if set to true, it will return a numeric array with the {@link CB_AudioFile} objects used (if the \"includeWithoutSpriteAssociated\" parameter is set to true, it will also contain the {@link CB_AudioFile} objects whose sound instance ID is not associated to any sprite). * @param {boolean} [includeWithoutSpriteAssociated=false] - If set to true, it will also return the {@link CB_AudioFile} objects whose sound instance ID is not associated to any sprite. Used as the \"includeWithoutSpriteAssociated\" parameter when calling the {@link CB_AudioFileSprites#getSprites} method internally. * @param {boolean} [avoidCancelled=false] - If set to true, it will not return the {@link CB_AudioFile} objects whose sound instance has been cancelled. Used as the \"avoidCancelled\" parameter when calling the {@link CB_AudioFileSprites#getAudioFilesUsedBySpriteId} method internally. * @returns {CB_AudioFileSprites.getAudioFilesUsed_OBJECT|array} Returns the {@link CB_AudioFile} objects used by all the sounds instances currently created. If the \"oneDimension\" parameter is set to false, it will return a {@link CB_AudioFileSprites.getAudioFilesUsed_OBJECT} object whose property names are the sprite identifiers (including the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated, if the \"includeWithoutSpriteAssociated\" is set to true) and their value will be a numeric array with the {@link CB_AudioFile} objects used. Otherwise, if the \"oneDimension\" parameter set to true, it will return a numeric array with the {@link CB_AudioFile} objects used (if the \"includeWithoutSpriteAssociated\" parameter is set to true, it will also contain the {@link CB_AudioFile} objects whose sound instance ID is not associated to any sprite). */ CB_AudioFileSprites.prototype.getAudioFilesUsed = function(oneDimension, includeWithoutSpriteAssociated, avoidCancelled) { var audioFiles; var sprites = this.getSprites(includeWithoutSpriteAssociated); if (!oneDimension) { audioFiles = {}; for (var spriteId in sprites) { audioFiles[spriteId] = this.getAudioFilesUsedBySpriteId(spriteId, avoidCancelled); } } else { audioFiles = []; var audioFilesSprite; var audioFilesSpriteLength; var y = 0; var x = 0; for (var spriteId in sprites) { audioFilesSprite = this.getAudioFilesUsedBySpriteId(spriteId, avoidCancelled); audioFilesSpriteLength = audioFilesSprite.length; for (x = 0; x &lt; audioFilesSpriteLength; x++) { audioFiles[y++] = audioFilesSprite[x]; } } } return audioFiles; } /** * Alias for {@link CB_AudioFileSprites#executeFunctionAllSprite}. * @function CB_AudioFileSprites#executeAllSprite * @see {@link CB_AudioFileSprites#executeFunctionAllSprite} */ /** * Alias for {@link CB_AudioFileSprites#executeFunctionAllSprite}. * @function CB_AudioFileSprites#forEachSpriteById * @see {@link CB_AudioFileSprites#executeFunctionAllSprite} */ /** * Executes a desired function for all the {@link CB_AudioFile} objects used by the sound instances currently created that belong to a given sprite (by its ID). It calls the {@link CB_AudioFileSprites#executeFunctionAll} method internally and returns its returning value. * @function * @param {string} spriteId - The identifier for the sprite. * @param {CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} functionEach - Used as the \"functionEach\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAll} method internally. * @param {number|CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} [delayBetweenEach=0] - Used as the \"delayBetweenEach\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAll} method internally. * @param {boolean} [avoidCancelled=false] - If set to true, it will not affect the {@link CB_AudioFile} objects whose sound instance has been cancelled. Used as the \"avoidCancelled\" parameter when calling the {@link CB_AudioFileSprites#getAudioFilesUsedBySpriteId} method internally. * @param {boolean} [returnSetTimeoutsArray=false] - Used as the \"returnSetTimeoutsArray\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAll} method internally. * @param {boolean} [delayBetweenEachAffectsFirst=false] - Used as the \"delayBetweenEachAffectsFirst\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAll} method internally. * @param {CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK} [functionFinish] - Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. * @returns {integer|array} If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the {@link CB_AudioFile} objects used by the sound instances that belong to the given sprite identifier). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a {@link CB_AudioFileCache.executeFunctionAll_OBJECT} object for each {@link CB_AudioFile} given. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function. */ CB_AudioFileSprites.prototype.executeFunctionAllSprite = CB_AudioFileSprites.prototype.executeAllSprite = CB_AudioFileSprites.prototype.forEachSpriteById = function(spriteId, functionEach, delayBetweenEach, avoidCancelled, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, finishFunction) { return this.executeFunctionAll(functionEach, delayBetweenEach, this.getAudioFilesUsedBySpriteId(spriteId, avoidCancelled), returnSetTimeoutsArray, delayBetweenEachAffectsFirst, finishFunction); } /** * Alias for {@link CB_AudioFileSprites#executeFunctionAllSprites}. * @function CB_AudioFileSprites#executeAllSprites * @see {@link CB_AudioFileSprites#executeFunctionAllSprites} */ /** * Alias for {@link CB_AudioFileSprites#executeFunctionAllSprites}. * @function CB_AudioFileSprites#forEachSprite * @see {@link CB_AudioFileSprites#executeFunctionAllSprites} */ /** * Executes a desired function for all the {@link CB_AudioFile} objects used by all the sound instances currently created. It calls the {@link CB_AudioFileSprites#executeFunctionAll} method internally and returns its returning value. * @function * @param {CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} functionEach - Used as the \"functionEach\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAll} method internally. * @param {number|CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} [delayBetweenEach=0] - Used as the \"delayBetweenEach\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAll} method internally. * @param {boolean} [includeWithoutSpriteAssociated=false] - If set to true, it will also affect the {@link CB_AudioFile} objects whose sound instance ID is not associated to any sprite. Used as the \"includeWithoutSpriteAssociated\" parameter when calling the {@link CB_AudioFileSprites#getAudioFilesUsed} method internally. * @param {boolean} [avoidCancelled=false] - If set to true, it will not affect the {@link CB_AudioFile} objects whose sound instance has been cancelled. Used as the \"avoidCancelled\" parameter when calling the {@link CB_AudioFileSprites#getAudioFilesUsed} method internally. * @param {boolean} [returnSetTimeoutsArray=false] - Used as the \"returnSetTimeoutsArray\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAll} method internally. * @param {boolean} [delayBetweenEachAffectsFirst=false] - Used as the \"delayBetweenEachAffectsFirst\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAll} method internally. * @param {CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK} [functionFinish] - Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. * @returns {integer|array} If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the {@link CB_AudioFile} objects used by the sound instances that belong to the sprites). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a {@link CB_AudioFileCache.executeFunctionAll_OBJECT} object for each {@link CB_AudioFile} given. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function. */ CB_AudioFileSprites.prototype.executeFunctionAllSprites = CB_AudioFileSprites.prototype.executeAllSprites = CB_AudioFileSprites.prototype.forEachSprite = function(functionEach, delayBetweenEach, includeWithoutSpriteAssociated, avoidCancelled, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, finishFunction) { return this.executeFunctionAll(functionEach, delayBetweenEach, this.getAudioFilesUsed(true, includeWithoutSpriteAssociated, avoidCancelled), returnSetTimeoutsArray, delayBetweenEachAffectsFirst, finishFunction); } /** * Tells whether a given sprite (by its ID) is playing or not. Note that there could be more than one sound instance (with a {@CB_AudioFile} object) by each sprite with different status (paused, stopped, etc.) and this method will return true if any of them is playing. * @function * @param {string} spriteId - The identifier for the sprite. * @returns {boolean} Returns whether a given sprite (by its ID) is playing or not. */ CB_AudioFileSprites.prototype.isPlayingSprite = function(spriteId) { var audioFiles = this.getAudioFilesUsedBySpriteId(spriteId); var audioFilesLength = audioFiles.length; for (var x = 0; x &lt; audioFilesLength; x++) { if (audioFiles[x].isPlaying()) { return true; } } return false; } /** * Tells whether a given sprite (by its ID) is paused or not. Note that there could be more than one sound instance (with a {@CB_AudioFile} object) by each sprite with different status (paused, stopped, etc.) and this method will return true if any of them is paused. * @function * @param {string} spriteId - The identifier for the sprite. * @returns {boolean} Returns whether a given sprite (by its ID) is paused or not. */ CB_AudioFileSprites.prototype.isPausedSprite = function(spriteId) { var audioFiles = this.getAudioFilesUsedBySpriteId(spriteId); var audioFilesLength = audioFiles.length; for (var x = 0; x &lt; audioFilesLength; x++) { if (audioFiles[x].isPaused()) { return true; } } return false; } /** * Tells whether a given sprite (by its ID) is stopped or not. Note that there could be more than one sound instance (with a {@CB_AudioFile} object) by each sprite with different status (paused, stopped, etc.) and this method will only return true if all of them are stopped. * @function * @param {string} spriteId - The identifier for the sprite. * @param {boolean} [checkAudioFileObjects=false] - If set to true, it will check all the {@CB_AudioFile} objects associated to the sprite. Doing so, as internally all stopped {@CB_AudioFile} objects are disassociated from their sound instances, this method should return false normally (unless something went wrong). * @returns {boolean} Returns whether a given sprite (by its ID) is stopped or not. As internally all stopped {@CB_AudioFile} objects are disassociated from their sound instances, this method should return false normally (unless something went wrong). */ CB_AudioFileSprites.prototype.isStoppedSprite = function(spriteId, checkAudioFileObjects) { var audioFiles = this.getAudioFilesUsedBySpriteId(spriteId); var audioFilesLength = audioFiles.length; if (!checkAudioFileObjects) { return audioFilesLength === 0; //If no audio file is found, it should mean that the sound instances have been stopped. } else { for (var x = 0; x &lt; audioFilesLength; x++) { if (audioFiles[x].isStopped()) { return true; } } return false; } } /** * Plays a sprite by its ID. If the sprite is found, uses the {@link CB_AudioFileSprites#play} method internally and returns its returning value. * @function * @param {string} spriteId - The identifier for the sprite. Used as the \"spriteId\" parameter when calling the {@link CB_AudioFileSprites#play} method internally. * @param {boolean} [loop={@link CB_AudioFile#loop}] - Used as the \"loop\" parameter when calling the {@link CB_AudioFileSprites#play} method internally. * @param {number} [volume=CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME] - Used as the \"volume\" parameter when calling the {@link CB_AudioFileSprites#play} method internally. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - Used as the \"allowedRecursiveDelay\" parameter when calling the {@link CB_AudioFileSprites#play} method internally. * @param {boolean} [allowedRecursiveDelaySkipping=stopAt-startAt] - Used as the \"allowedRecursiveDelaySkipping\" parameter when calling the {@link CB_AudioFileSprites#play} method internally. * @param {function} [onPlayStart] - Used as the \"onPlayStart\" parameter when calling the {@link CB_AudioFileSprites#play} method internally. * @param {function} [onStop] - Used as the \"onStop\" parameter when calling the {@link CB_AudioFileSprites#play} method internally. * @returns {integer|null} Returns null if the sprite was not found. Otherwise, returns the sound instance ID used if there was one free or null otherwise. To get a sound instance returned does not mean necessarily that the sound started playing so it is necessary to use a callback function as the \"onPlayStart\" parameter for checking this. The sound instance created (if any), will be cancelled automatically once the sound is stopped. */ CB_AudioFileSprites.prototype.playSprite = function(spriteId, loop, volume, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop) { var sprite = this.getSprite(spriteId); var soundInstance = this.play(sprite.startAt, sprite.stopAt, loop, volume, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, spriteId); return soundInstance; } /** * Stops all the {@link CB_AudioFile} objects that belong to the sound instances (created by the {@link CB_AudioFileSprites#play} or the {@link CB_AudioFileSprites#playSprite} methods) which are playing used by a given sprite identifier. Uses the {@link CB_AudioFileSprites#stopAll} method internally and returns its returning value. * @function * @param {string} spriteId - The identifier for the sprite. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#stop} method that were performed internally. */ CB_AudioFileSprites.prototype.stopSprite = function(spriteId) { return this.stopAll(this.getAudioFilesUsedBySpriteId(spriteId)); } /** * Pauses all the {@link CB_AudioFile} objects that belong to the sound instances (created by the {@link CB_AudioFileSprites#play} or the {@link CB_AudioFileSprites#playSprite} methods) which are playing used by a given sprite identifier. Uses the {@link CB_AudioFileSprites#pauseAll} method internally and returns its returning value. * @function * @param {string} spriteId - The identifier for the sprite. * @param {function} [onPause] - Function without parameters to be called when the audio is paused successfully, being \"this\" the {@link CB_AudioFile} object. Used internally as the \"onPause\" parameter to call the {@link CB_AudioFileSprites#pauseAll} method. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#pause} method that were performed internally. */ CB_AudioFileSprites.prototype.pauseSprite = function(spriteId, onPause) { return this.pauseAll(onPause, this.getAudioFilesUsedBySpriteId(spriteId)); } /** * Resumes all the {@link CB_AudioFile} objects that belong to the sound instances (created by the {@link CB_AudioFileSprites#play} or the {@link CB_AudioFileSprites#playSprite} methods) used by a given sprite identifier. Uses the {@link CB_AudioFileSprites#resumeAll} method internally and returns its returning value. * @function * @param {string} spriteId - Used as the \"spriteId\" parameter when calling the {@link CB_AudioFileSprites#resumeAll} method internally. * @param {boolean} [loop={@link CB_AudioFile#loop}] - Used as the \"loop\" parameter when calling the {@link CB_AudioFileSprites#resumeAll} method internally. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - Used as the \"allowedRecursiveDelay\" parameter when calling the {@link CB_AudioFileSprites#resumeAll} method internally. * @param {boolean} [allowedRecursiveDelaySkipping=stopAt-startAt] - Used as the \"allowedRecursiveDelaySkipping\" parameter when calling the {@link CB_AudioFileSprites#resumeAll} method internally. * @param {function} [onPlayStart] - Used as the \"onPlayStart\" parameter when calling the {@link CB_AudioFileSprites#resumeAll} method internally. * @param {function} [onStop] - Used as the \"onStop\" parameter when calling the {@link CB_AudioFileSprites#resumeAll} method internally. * @returns {array} Returns null if the sprite identifier given could not be found. Otherwise, returns a numeric array containing all the return values of each internal call to the {@link CB_AudioFileCache#play} method (called through {@link CB_AudioFileSprites#resumeAll}). */ CB_AudioFileSprites.prototype.resumeSprite = function(spriteId, loop, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop) { return this.resumeAll(loop, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, this.getAudioFilesUsedBySpriteId(spriteId), spriteId); } /** * Mutes all the {@link CB_AudioFile} objects that belong to the sound instances (created by the {@link CB_AudioFileSprites#play} or the {@link CB_AudioFileSprites#playSprite} methods) used by a given sprite identifier. Uses the {@link CB_AudioFileSprites#muteAll} method internally and returns its returning value. * @function * @param {string} spriteId - The identifier for the sprite. * @param {function} [onMute] - Callback function which will be called for each audio file if it has been possible to mute it (or at least it was possible to try it), being \"this\" the {@link CB_AudioFile} object. Used internally as the \"onMute\" parameter to call the {@link CB_AudioFileSprites#muteAll} method. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#mute} method that were performed internally. */ CB_AudioFileSprites.prototype.muteSprite = function(spriteId, onMute) { return this.muteAll(onMute, this.getAudioFilesUsedBySpriteId(spriteId)); } /** * Unmutes all the {@link CB_AudioFile} objects that belong to the sound instances (created by the {@link CB_AudioFileSprites#play} or the {@link CB_AudioFileSprites#playSprite} methods) used by a given sprite identifier. Uses the {@link CB_AudioFileSprites#unmuteAll} method internally and returns its returning value. * @function * @param {string} spriteId - The identifier for the sprite. * @param {function} [onUnmute] - Used internally as the \"onUnmute\" parameter to call the {@link CB_AudioFileSprites#unmuteAll} method. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#unmute} method that were performed internally. */ CB_AudioFileSprites.prototype.unmuteSprite = function(spriteId, onUnmute) { return this.unmuteAll(onUnmute, this.getAudioFilesUsedBySpriteId(spriteId)); } /** * Sets the same desired volume to all the {@link CB_AudioFile} objects that belong to the sound instances (created by the {@link CB_AudioFileSprites#play} or the {@link CB_AudioFileSprites#playSprite} methods) used by a given sprite identifier. Uses the {@link CB_AudioFileSprites#setVolumeAll} method internally and returns its returning value. * @function * @param {string} spriteId - The identifier for the sprite. * @param {number} [volume={@link CB_Speaker.getVolume()} | {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME}] - Used as the \"volume\" parameter when calling the {@link CB_AudioFileSprites#setVolumeAll} method internally. * @param {boolean} [forceSetVolumeProperty=false] - Used as the \"forceSetVolumeProperty\" parameter when calling the {@link CB_AudioFileSprites#setVolumeAll} method internally. * @param {function} [onSetVolume] - Used as the \"onSetVolume\" parameter when calling the {@link CB_AudioFileSprites#setVolumeAll} method internally. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#setVolume} method that were performed internally. */ CB_AudioFileSprites.prototype.setVolumeSprite = function(spriteId, volume, forceSetVolumeProperty, onSetVolume) { return this.setVolumeAll(volume, forceSetVolumeProperty, onSetVolume, this.getAudioFilesUsedBySpriteId(spriteId)); } /** * Tries to change the desired audio API of the {@link CB_AudioFile} objects that belong to the sound instances (created by the {@link CB_AudioFileSprites#play} or the {@link CB_AudioFileSprites#playSprite} methods) used by a given sprite identifier. Uses the {@link CB_AudioFileSprites#setAudioAPIAll} method internally and returns its returning value. * @function * @param {string} spriteId - The identifier for the sprite. * @param {array} preferredAPIs - Used as the \"preferredAPIs\" parameter when calling the {@link CB_AudioFileSprites#setAudioAPIAll} method internally. * @param {CB_AudioFileCache.setAudioAPIAll_CALLBACK_OK} [callbackOk] - Used as the \"callbackOk\" parameter when calling the {@link CB_AudioFileSprites#setAudioAPIAll} method internally. * @param {CB_AudioFileCache.setAudioAPIAll_CALLBACK_ERROR} [callbackError] - Used as the \"callbackError\" parameter when calling the {@link CB_AudioFileSprites#setAudioAPIAll} method internally. * @param {boolean} [mandatory=false] - Used as the \"mandatory\" parameter when calling the {@link CB_AudioFileSprites#setAudioAPIAll} method internally. * @param {string} [forceReload=false] - Used as the \"forceReload\" parameter when calling the {@link CB_AudioFileSprites#setAudioAPIAll} method internally. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#setAudioAPI} method that were performed internally. */ CB_AudioFileSprites.prototype.setAudioAPISprite = function(spriteId, preferredAPIs, callbackOk, callbackError, mandatory, forceReload) { return this.setAudioAPIAll(preferredAPIs, callbackOk, callbackError, mandatory, forceReload, this.getAudioFilesUsedBySpriteId(spriteId)); } /** * Creates the desired number of internal {@link CB_AudioFile} objects (inside the {@link CB_AudioFileCache#audioFiles} property). Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Uses the {@link CB_AudioFileCache#createAudioFiles} method internally and returns its returning value. * @function * @param {integer} minimumAudioFiles - Used as the \"minimumAudioFiles\" parameter when calling the {@link CB_AudioFileCache#createAudioFiles} method internally. * @returns {integer} Returns the number of {@link CB_AudioFile} objects which are intended to be created (they could fail). */ CB_AudioFileSprites.prototype.createAudioFiles = function(minimumAudioFiles) { return this.audioFileCache.createAudioFiles(minimumAudioFiles); } /** * Creates one internal {@link CB_AudioFile} object (inside the {@link CB_AudioFileCache#audioFiles} property). Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Uses the {@link CB_AudioFileCache#createAudioFile} method internally and returns its returning value. Internal usage only recommended. * @function * @param {CB_AudioFileCache.URIS_OBJECT} [URIs={@link CB_AudioFileCache#URIs}] - Used as the \"URIs\" parameter when calling the {@link CB_AudioFileCache#createAudioFile} method internally. * @param {array} [preferredAPIs={@link CB_AudioFileCache#preferredAPIs}] - Used as the \"preferredAPIs\" parameter when calling the {@link CB_AudioFileCache#createAudioFile} method internally. * @param {array} [preferredFormats={@link CB_AudioFileCache#preferredFormats}] - Used as the \"preferredFormats\" parameter when calling the {@link CB_AudioFileCache#createAudioFile} method internally. * @param {CB_AudioFile} [audioObject] - Used as the \"audioObject\" parameter when calling the {@link CB_AudioFileCache#createAudioFile} method internally. * @param {function} [callbackOk] - Used as the \"callbackOk\" parameter when calling the {@link CB_AudioFileCache#createAudioFile} method internally. * @param {function} [callbackError] - Used as the \"callbackError\" parameter when calling the {@link CB_AudioFileCache#createAudioFile} method internally. * @param {boolean} [storeURIsList=false] - Used as the \"storeURIsList\" parameter when calling the {@link CB_AudioFileCache#createAudioFile} method internally. * @param {boolean} [checkAutomatically=false] - Used as the \"checkAutomatically\" parameter when calling the {@link CB_AudioFileCache#createAudioFile} method internally. * @returns {CB_AudioFile|null} If it fails, it returns null. Otherwise, returns the {@link CB_AudioFile} that has been created or reused. */ CB_AudioFileSprites.prototype.createAudioFile = function(URIs, preferredAPIs, preferredFormats, audioObject, callbackOk, callbackError, storeURIsList, checkAutomatically) { return this.audioFileCache.createAudioFile(URIs, preferredAPIs, preferredFormats, audioObject, callbackOk, callbackError, storeURIsList, checkAutomatically); } /** * Cleans the array of the {@link CB_AudioFile} objects (taking off the undefined or null ones) which is in the {@link CB_AudioFileCache#audioFiles} property, just keeping the valid ones and clearing (destroying and removing) the others. For performance purposes. Uses the {@link CB_AudioFileCache#clearAudioFiles} method internally and returns its returning value. Internal usage only recommended. * @function * @param {boolean} [avoidCallingCheckCacheLoaded=false] - Used as the \"avoidCallingCheckCacheLoaded\" parameter when calling the {@link CB_AudioFileCache#clearAudioFiles} method internally. * @returns {array} Returns the value of the {@link CB_AudioFileCache#audioFiles} property. */ CB_AudioFileSprites.prototype.clearAudioFiles = function(avoidCallingCheckCacheLoaded) { return this.audioFileCache.clearAudioFiles(avoidCallingCheckCacheLoaded); } /** * If found, takes a given {@link CB_AudioFile} object off the {@link CB_AudioFileCache#audioFiles} property (and reloads it if we want to). NOTE: It does neither destroy nor remove the {@link CB_AudioFile} object so it can be used for other purposes (and if a {@link CB_AudioFile} object is given, it will be tried to be reused by the {@link CB_AudioFileCache#createAudioFile} method internally if it is called). Uses the {@link CB_AudioFileCache#removeAudioFile} method internally and returns its returning value. Internal usage only recommended. * @function * @param {CB_AudioFile|string} audioObjectOrId - Used as the \"audioObjectOrId\" parameter when calling the {@link CB_AudioFileCache#removeAudioFile} method internally. * @param {boolean} [reload=false] - Used as the \"reload\" parameter when calling the {@link CB_AudioFileCache#removeAudioFile} method internally. * @param {boolean} [checkManually=false] - Used as the \"checkManually\" parameter when calling the {@link CB_AudioFileCache#removeAudioFile} method internally. * @returns {boolean|CB_AudioFile|null} Returns null if the given \"audioObjectOrId\" parameter is not a valid {@link CB_AudioFile} object or its {@link CB_AudioFile#id} property is not set or when the \"audioObjectOrId\" parameter is an empty string. Returns a {@link CB_AudioFile} object, the given one through the \"audioObjectOrId\" parameter of the first one removed (it should be the first and unique one removed as the ID must be unique), if the {@link CB_AudioFileCache#createAudioFile} method is called internally (it will reuse this {@link CB_AudioFile} object). Otherwise, returns true if all goes well. */ CB_AudioFileSprites.prototype.removeAudioFile = function(audioObjectOrId, reload, checkManually) { return this.audioFileCache.removeAudioFile(audioObjectOrId, reload, checkManually); } /** * Tries to purge the audio file cache until it reaches a desired number of {@link CB_AudioFile} objects internally (set in the {@link CB_AudioFileCache#audioFiles} property), by removing and destroying some of the current {@link CB_AudioFile} objects. For performance purposes. Uses the {@link CB_AudioFileCache#purge} method internally and returns its returning value. * @function * @param {integer} desiredNumber - Used as the \"desiredNumber\" parameter when calling the {@link CB_AudioFileCache#purge} method internally. * @param {boolean} [setAsMinimumAudioFiles=false] - Used as the \"setAsMinimumAudioFiles\" parameter when calling the {@link CB_AudioFileCache#purge} method internally. * @param {boolean} [includePlaying=false] - Used as the \"includePlaying\" parameter when calling the {@link CB_AudioFileCache#purge} method internally. * @param {boolean} [stopSounds=false] - Used as the \"stopSounds\" parameter when calling the {@link CB_AudioFileCache#purge} method internally. * @param {array} [statuses=Array({@link CB_AudioFile.LOADING}, {@link CB_AudioFile.UNCHECKED}, {@link CB_AudioFile.CHECKING}, {@link CB_AudioFile.LOADED})] - Used as the \"statuses\" parameter when calling the {@link CB_AudioFileCache#purge} method internally. * @returns {integer} Returns the number of {@link CB_AudioFile} objects removed. */ CB_AudioFileSprites.prototype.purge = function(desiredNumber, setAsMinimumAudioFiles, includePlaying, stopSounds, statuses) { return this.audioFileCache.purge(desiredNumber, setAsMinimumAudioFiles, includePlaying, stopSounds, statuses); } /** * Returns a free {@link CB_AudioFile} object, if any (from the {@link CB_AudioFileCache#audioFilesFree} property). Note that this will call the internal {@link CB_AudioFileCache#_createNewAudioFilesIfNeeded} method that could end creating a new {@link CB_AudioFile} object if needed. Uses the {@link CB_AudioFileCache#getFreeAudioFile} method internally and returns its returning value. * @function * @param {boolean} [popIt=false] - Used as the \"popIt\" parameter when calling the {@link CB_AudioFileCache#getFreeAudioFile} method internally. * @returns {CB_AudioFileCache.getFreeAudioFile_OBJECT} Returns a {@link CB_AudioFileCache.getFreeAudioFile_OBJECT} object. */ CB_AudioFileSprites.prototype.getFreeAudioFile = function(popIt) { return this.audioFileCache.getFreeAudioFile(popIt); } /** * Tells whether a desired {@link CB_AudioFile} object is free (it is in the {@link CB_AudioFileCache#audioFilesFree} property) or not, by its identifier. A free {@link CB_AudioFile} object is an object which is not being used and it is available to be used. Uses the {@link CB_AudioFileCache#isAudioFileFree} method internally and returns its returning value. * @function * @param {string} id - Used as the \"id\" parameter when calling the {@link CB_AudioFileCache#isAudioFileFree} method internally. * @returns {boolean} Returns whether a desired {@link CB_AudioFile} object is free (it is in the {@link CB_AudioFileCache#audioFilesFree} property) or not, by its identifier. A free {@link CB_AudioFile} object is an object which is not being used and it is available to be used. */ CB_AudioFileSprites.prototype.isAudioFileFree = function(id) { return this.audioFileCache.isAudioFileFree(id); } /** * Clears the sound instances (created by the {@link CB_AudioFileCache#play} method) which have been cancelled. Uses the {@link CB_AudioFileCache#clearSoundInstances} method internally and returns its returning value. * @function * @param {boolean} [clearWithObjectAssociated=false] - Used as the \"clearWithObjectAssociated\" parameter when calling the {@link CB_AudioFileCache#clearSoundInstances} method internally. * @returns {integer} Returns the number of cleared sound instances. */ CB_AudioFileSprites.prototype.clearSoundInstances = function(clearWithObjectAssociated) { //Clears the sound instances in the cache object: var cleared = this.audioFileCache.clearSoundInstances(clearWithObjectAssociated); var soundInstances; var soundInstancesLength; var spriteSoundInstances = {}; var sprites = this.getSprites(true); var y = 0; for (var spriteId in sprites) { spriteSoundInstances[spriteId] = []; y = 0; soundInstances = this.getSoundInstancesIdBySpriteId(spriteId); soundInstancesLength = soundInstances.length; for (var x = 0; x &lt; soundInstancesLength; x++) { if (typeof(this.audioFileCache.soundInstancesQueued[soundInstances[x]]) !== \"undefined\") { spriteSoundInstances[spriteId][y++] = soundInstances[x]; } } } this.spriteSoundInstances = spriteSoundInstances; return cleared; } /** * Cancels (to prevent they start playing) or enables all sound instances (created by the {@link CB_AudioFileCache#play} method). Uses the {@link CB_AudioFileCache#cancelSoundInstances} method internally and returns its returning value. * @function * @param {boolean} [cancel=false] - Used as the \"cancel\" parameter when calling the {@link CB_AudioFileCache#cancelSoundInstances} method internally. * @param {boolean} [affectWithObjectAssociated=false] - Used as the \"affectWithObjectAssociated\" parameter when calling the {@link CB_AudioFileCache#cancelSoundInstances} method internally. * @returns {integer} Returns the number of sound instances modified. */ CB_AudioFileSprites.prototype.cancelSoundInstances = function(cancel, affectWithObjectAssociated) { return this.audioFileCache.cancelSoundInstances(cancel, affectWithObjectAssociated); } /** * Cancels (to prevent it starts playing) or enables a sound instance (created by the {@link CB_AudioFileCache#play} method), by its identifier. Uses the {@link CB_AudioFileCache#cancelSoundInstance} method internally and returns its returning value. * @function * @param {integer} soundInstanceId - Used as the \"soundInstanceId\" parameter when calling the {@link CB_AudioFileCache#cancelSoundInstance} method internally. * @param {boolean} [cancel=false] - Used as the \"cancel\" parameter when calling the {@link CB_AudioFileCache#cancelSoundInstance} method internally. * @param {boolean} [affectWithObjectAssociated=false] - Used as the \"affectWithObjectAssociated\" parameter when calling the {@link CB_AudioFileCache#cancelSoundInstance} method internally. * @returns {boolean} Returns true if the sound instance has been modified or false otherwise. */ CB_AudioFileSprites.prototype.cancelSoundInstance = function(soundInstanceId, cancel, affectWithObjectAssociated) { return this.audioFileCache.cancelSoundInstance(soundInstanceId, cancel, affectWithObjectAssociated); } /** * Gets the {@link CB_AudioFile} object associated to a given sound instance ID (created by the {@link CB_AudioFileCache#play} method), if any, or null otherwise. Uses the {@link CB_AudioFileCache#getAudioFileBySoundInstanceId} method internally and returns its returning value. * @function * @param {integer} soundInstanceId - Used as the \"soundInstanceId\" parameter when calling the {@link CB_AudioFileCache#getAudioFileBySoundInstanceId} method internally. * @param {boolean} [avoidCancelled=false] - Used as the \"avoidCancelled\" parameter when calling the {@link CB_AudioFileCache#getAudioFileBySoundInstanceId} method internally. * @returns {CB_AudioFile|null} Returns the {@link CB_AudioFile} object associated to a given sound instance ID, if any, or null otherwise. */ CB_AudioFileSprites.prototype.getAudioFileBySoundInstanceId = function(soundInstanceId, avoidCancelled) { return this.audioFileCache.getAudioFileBySoundInstanceId(soundInstanceId, avoidCancelled); } /** * Plays a sound of the cache (if there is any free), using a sprite if desired. If a sound cannot be played, this method can call itself internally again and again (with most of the given parameters being the same, depending on the circumstances) to try to play the sound until a desired time limit is reached. If a {@link CB_AudioFile} object cannot be played and it is determined necessary, it will try to reload it internally (by calling the {@link CB_AudioFileCache#removeAudioFile} method). Uses the {@link CB_AudioFileCache#play} method internally and returns its returning value. Internal usage only recommended. To play a sprite, better use the {@link CB_AudioFileSprites#playSprite} method instead. * @function * @param {number} [startAt=0 | {@link CB_AudioFile_API.WAAPI#lastStartAt} | {@link CB_AudioFile_API.SM2#lastStartAt} | {@link CB_AudioFile_API.ACMP#lastStartAt} | {@link CB_AudioFile_API.AAPI#lastStartAt} | stopAt] - Used as the \"startAt\" parameter when calling the {@link CB_AudioFileCache#play} method internally. * @param {number} [stopAt={@link CB_AudioFile_API.WAAPI#getDuration}() | {@link CB_AudioFile_API.SM2#getDuration}() | {@link CB_AudioFile_API.ACMP#getDuration}() | {@link CB_AudioFile_API.AAPI#getDuration}()] - Used as the \"stopAt\" parameter when calling the {@link CB_AudioFileCache#play} method internally. * @param {boolean} [loop={@link CB_AudioFile#loop}] - Used as the \"loop\" parameter when calling the {@link CB_AudioFileCache#play} method internally. * @param {number} [volume=CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME] - Used as the \"volume\" parameter when calling the {@link CB_AudioFileCache#play} method internally. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - Used as the \"allowedRecursiveDelay\" parameter when calling the {@link CB_AudioFileCache#play} method internally. * @param {boolean} [allowedRecursiveDelaySkipping=stopAt-startAt] - Used as the \"allowedRecursiveDelaySkipping\" parameter when calling the {@link CB_AudioFileCache#play} method internally. * @param {function} [onPlayStart] - Used as the \"onPlayStart\" parameter when calling the {@link CB_AudioFileCache#play} method internally. * @param {function} [onStop] - Used as the \"onStop\" parameter when calling the {@link CB_AudioFileCache#play} method internally. * @param {string} [spriteId='_WITHOUT_SPRITE_ASSOCIATED'] - The identifier for the sprite. Internal usage only recommended. * @returns {integer|null} Returns null if a sprite identifier was given but it could not be found. Otherwise, returns the sound instance ID used if there was one free or null otherwise. To get a sound instance returned does not mean necessarily that the sound started playing so it is necessary to use a callback function as the \"onPlayStart\" parameter for checking this. The sound instance created (if any), will be cancelled automatically once the sound is stopped. */ CB_AudioFileSprites.prototype.play = function(startAt, stopAt, loop, volume, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, spriteId) { if (typeof(spriteId) === \"undefined\" || spriteId === null) { spriteId = \"_WITHOUT_SPRITE_ASSOCIATED\"; } else if (typeof(this.sprites[spriteId]) === \"undefined\" || this.sprites[spriteId] === null) { return null; } //if (typeof(this.sprites[spriteId]) === \"undefined\" || this.sprites[spriteId] === null) { return null; } var soundInstance = this.audioFileCache.play(startAt, stopAt, loop, volume, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop); if (typeof(this.spriteSoundInstances[spriteId]) !== \"undefined\") { this.spriteSoundInstances[spriteId][this.spriteSoundInstances[spriteId].length] = soundInstance; } return soundInstance; } /** * Alias for {@link CB_AudioFileSprites#executeFunctionAll}. * @function CB_AudioFileSprites#executeAll * @see {@link CB_AudioFileSprites#executeFunctionAll} */ /** * Alias for {@link CB_AudioFileSprites#executeFunctionAll}. * @function CB_AudioFileSprites#forEach * @see {@link CB_AudioFileSprites#executeFunctionAll} */ /** * Performs a desired action, using the provided function, on all the existing {@link CB_AudioFile} objects or on the desired ones (if provided). Uses the {@link CB_AudioFileCache#executeFunctionAll} method internally and returns its returning value. * @function * @param {CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} functionEach - Used as the \"functionEach\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAll} method internally. * @param {number|CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} [delayBetweenEach=0] - Used as the \"delayBetweenEach\" parameter when calling the {@link CB_AudioFileCache#executeFunctionAll} method internally. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileCache#executeFunctionAll} method internally. * @param {boolean} [returnSetTimeoutsArray=false] - Used as the \"returnSetTimeoutsArray\" parameter when calling the {@link CB_AudioFileCache#executeFunctionAll} method internally. * @param {boolean} [delayBetweenEachAffectsFirst=false] - Used as the \"delayBetweenEachAffectsFirst\" parameter when calling the {@link CB_AudioFileCache#executeFunctionAll} method internally. * @param {CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK} [functionFinish] - Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. * @returns {integer|array} If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the {@link CB_AudioFile} objects given in the \"audioFiles\" parameter). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a {@link CB_AudioFileCache.executeFunctionAll_OBJECT} object for each {@link CB_AudioFile} given. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function. */ CB_AudioFileSprites.prototype.executeFunctionAll = CB_AudioFileSprites.prototype.executeAll = CB_AudioFileSprites.prototype.forEach = function(functionEach, delayBetweenEach, audioFiles, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, finishFunction) { return this.audioFileCache.executeFunctionAll(functionEach, delayBetweenEach, audioFiles, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, finishFunction); } /** * Destroys all the {@link CB_AudioFile} objects and frees memory, by calling {@link CB_AudioFile#destructor}(stopSounds, false, true). Uses the {@link CB_AudioFileCache#destroyAll} method internally and returns its returning value. * @function * @param {boolean} [stopSounds=false] - Used as the \"stopSounds\" parameter when calling the {@link CB_AudioFileCache#destroyAll} method internally. * @returns {integer} Returns the number of {@link CB_AudioFile} objects whose {@link CB_AudioFile#destructor} has been called. */ CB_AudioFileSprites.prototype.destroyAll = function(stopSounds) { return this.audioFileCache.destroyAll(stopSounds); } /** * Checks whether each {@link CB_AudioFile} object whose {@link CB_AudioFile#getStatus} method returns the \"unchecked\" value (which belongs to the value of the {@link CB_AudioFile#UNCHECKED} property) can be played or not. After checking, if the audio can be played, the status of the {@link CB_AudioFile} object will get the value of {@link CB_AudioFile.LOADED}. Otherwise, if it cannot be played, the status of the {@link CB_AudioFile} object will get the value of {@link CB_AudioFile.FAILED}. If a {@link CB_AudioFile} object cannot be played and it is determined necessary, it will try to reload it internally (by calling the {@link CB_AudioFileCache#removeAudioFile} method). It will call the {@link CB_AudioFileCache#clearAudioFiles} method internally after finishing. Uses the {@link CB_AudioFileCache#checkPlayingAll} method internally and returns its returning value. Recommended to be called through a user-driven event (as onClick, onTouch, etc.). * @function * @param {CB_AudioFileCache.checkPlayingAll_CALLBACK_OK} [callbackOk] - Used as the \"callbackOk\" parameter when calling the {@link CB_AudioFileCache#checkPlayingAll} method internally. * @param {CB_AudioFileCache.checkPlayingAll_CALLBACK_ERROR} [callbackError] - Used as the \"callbackError\" parameter when calling the {@link CB_AudioFileCache#checkPlayingAll} method internally. * @param {boolean} [ignoreQueue=false] - Used as the \"ignoreQueue\" parameter when calling the {@link CB_AudioFileCache#checkPlayingAll} method internally. * @returns {integer} Returns the number of {@link CB_AudioFile} objects whose status belonged to the \"unchecked\" value (the value of the {@link CB_AudioFile#UNCHECKED} property) before the execution of this method. It will return 0 (zero) if the method is tried to be executed while there is another previous call of it still running. It will also return 0 (zero) if the status of the audio file cache is not loaded (the {@link CB_AudioFileCache#status} property does not belong to the value set in the {@link CB_AudioFileCache.LOADED} property). */ CB_AudioFileSprites.prototype.checkPlayingAll = function(callbackOk, callbackError, ignoreQueue) { return this.audioFileCache.checkPlayingAll(callbackOk, callbackError, ignoreQueue); } /** * Tries to play all the {@link CB_AudioFile} objects by calling their {@link CB_AudioFile#play} method internally. If a {@link CB_AudioFile} object cannot be played and it is determined necessary, it will try to reload it internally (by calling the {@link CB_AudioFileCache#removeAudioFile} method). Uses the {@link CB_AudioFileCache#playAll} method internally and returns its returning value. * @function * @param {number} [startAt=0 | {@link CB_AudioFile_API.WAAPI#lastStartAt} | {@link CB_AudioFile_API.SM2#lastStartAt} | {@link CB_AudioFile_API.ACMP#lastStartAt} | {@link CB_AudioFile_API.AAPI#lastStartAt} | stopAt] - Used as the \"startAt\" parameter when calling the {@link CB_AudioFileCache#playAll} method internally. * @param {number} [stopAt={@link CB_AudioFile_API.WAAPI#getDuration}() | {@link CB_AudioFile_API.SM2#getDuration}() | {@link CB_AudioFile_API.ACMP#getDuration}() | {@link CB_AudioFile_API.AAPI#getDuration}()] - Used as the \"stopAt\" parameter when calling the {@link CB_AudioFileCache#playAll} method internally. * @param {boolean} [loop={@link CB_AudioFile#loop}] - Used as the \"loop\" parameter when calling the {@link CB_AudioFileCache#playAll} method internally. * @param {number} [volume=CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME] - Used as the \"volume\" parameter when calling the {@link CB_AudioFileCache#playAll} method internally. * @param {boolean} [avoidDelayedPlay=false] - Used as the \"avoidDelayedPlay\" parameter when calling the {@link CB_AudioFileCache#playAll} method internally. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - Used as the \"allowedRecursiveDelay\" parameter when calling the {@link CB_AudioFileCache#playAll} method internally. * @param {function} [onPlayStart] - Used as the \"onPlayStart\" parameter when calling the {@link CB_AudioFileCache#playAll} method internally. * @param {function} [onStop] - Used as the \"onStop\" parameter when calling the {@link CB_AudioFileCache#playAll} method internally. * @param {boolean} [includingPlaying=false] - Used as the \"includingPlaying\" parameter when calling the {@link CB_AudioFileCache#playAll} method internally. * @returns {integer} Returns the number of {@link CB_AudioFile} objects whose {@link CB_AudioFile#play} method did not return the value of \"-1\" (this does not mean necessarily that they could be played successfully). */ CB_AudioFileSprites.prototype.playAll = function(startAt, stopAt, loop, volume, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onStop, includingPlaying) { return this.audioFileCache.playAll(startAt, stopAt, loop, volume, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onStop, includingPlaying); } /** * Tries to stops all the existing {@link CB_AudioFile} objects or the desired ones (if provided), which are being played, by calling their {@link CB_AudioFile#stop} method internally. Uses the {@link CB_AudioFileCache#stopAll} method internally and returns its returning value. * @function * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileCache#stopAll} method internally. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#stop} method that were performed (which should be the same number as the {@link CB_AudioFile} objects in the \"audioFiles\" parameter). */ CB_AudioFileSprites.prototype.stopAll = function(audioFiles) { return this.audioFileCache.stopAll(audioFiles); } /** * Plays silently and stops all {@link CB_AudioFile} objects after a desired time. It can be useful for some clients which need the {@link CB_AudioFile#play} method to be called through a user-driven event (as onClick, onTouch, etc.). Internally, it calls {@link CB_AudioFileCache#playAll}(0, null, false, 0, true, null, null, null, includingPlaying) and, after a desired delay, calls the {@link CB_AudioFileCache#stopAll} method. Uses the {@link CB_AudioFileCache#playAndStopAll} method internally and returns its returning value. * @function * @param {boolean} [includingPlaying=false] - Used as the \"includingPlaying\" parameter when calling the {@link CB_AudioFileCache#playAndStopAll} method internally. * @param {number} [delayBeforeStop=100] - Used as the \"delayBeforeStop\" parameter when calling the {@link CB_AudioFileCache#playAndStopAll} method internally. * @returns {integer} Returns the number of {@link CB_AudioFile} objects whose {@link CB_AudioFile#play} method did not return the value of \"-1\" (this does not mean necessarily that they could be played successfully). */ CB_AudioFileSprites.prototype.playAndStopAll = function(includingPlaying, delayBeforeStop) { return this.audioFileCache.playAndStopAll(includingPlaying, delayBeforeStop); } /** * Tries to pause all the existing {@link CB_AudioFile} objects or the desired ones (if provided), which are being played, by calling their {@link CB_AudioFile#pause} method internally. Uses the {@link CB_AudioFileCache#pauseAll} method internally and returns its returning value. * @function * @param {function} [onPause] - Used as the \"onPause\" parameter when calling the {@link CB_AudioFileCache#pauseAll} method internally. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileCache#pauseAll} method internally. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#pause} method that were performed (which should be the same number as the {@link CB_AudioFile} objects in the \"audioFiles\" parameter). */ CB_AudioFileSprites.prototype.pauseAll = function(onPause, audioFiles) { return this.audioFileCache.pauseAll(onPause, audioFiles); } /** * Resumes all the existing {@link CB_AudioFile} objects or the desired ones (if provided), which are paused (and not stopped). Can be focused on just one sprite identifier if desired. Uses the {@link CB_AudioFileCache#resumeAll} method internally and returns its returning value. Internal usage only recommended. To resume a sprite, better use the {@link CB_AudioFileSprites#resumeSprite} method instead. * @function * @param {boolean} [loop={@link CB_AudioFile#loop}] - Used as the \"loop\" parameter when calling the {@link CB_AudioFileCache#resumeAll} method internally. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - Used as the \"allowedRecursiveDelay\" parameter when calling the {@link CB_AudioFileCache#resumeAll} method internally. * @param {boolean} [allowedRecursiveDelaySkipping=CB_AudioFile#lastStopAt-CB_AudioFile#lastStartAt] - Used as the \"allowedRecursiveDelaySkipping\" parameter when calling the {@link CB_AudioFileCache#resumeAll} method internally. * @param {function} [onPlayStart] - Used as the \"onPlayStart\" parameter when calling the {@link CB_AudioFileCache#resumeAll} method internally. * @param {function} [onStop] - Used as the \"onStop\" parameter when calling the {@link CB_AudioFileCache#resumeAll} method internally. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileCache#resumeAll} method internally. * @param {string} [spriteId='_WITHOUT_SPRITE_ASSOCIATED'] - The identifier for the sprite. Internal usage only recommended. * @returns {array} Returns null if a sprite identifier was given but it could not be found. Otherwise, returns a numeric array containing all the return values of each internal call to the {@link CB_AudioFileCache#play} method. */ CB_AudioFileSprites.prototype.resumeAll = function(loop, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, audioFiles, spriteId) { if (typeof(spriteId) === \"undefined\" || spriteId === null) { spriteId = \"_WITHOUT_SPRITE_ASSOCIATED\"; } else if (typeof(this.sprites[spriteId]) === \"undefined\" || this.sprites[spriteId] === null) { return null; } //if (typeof(this.sprites[spriteId]) === \"undefined\" || this.sprites[spriteId] === null) { return null; } var soundInstances = this.audioFileCache.resumeAll(loop, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, audioFiles); if (typeof(this.spriteSoundInstances[spriteId]) !== \"undefined\") { //Stores the sound instances used by the resume (if any): var soundInstancesLength = soundInstances.length; for (var x = 0; x &lt; soundInstancesLength; x++) { this.spriteSoundInstances[spriteId][this.spriteSoundInstances[spriteId].length] = soundInstances[x]; } } return soundInstances; } /** * Mutes all the existing {@link CB_AudioFile} objects or the desired ones (if provided). Uses the {@link CB_AudioFileCache#muteAll} method internally and returns its returning value. * @function * @param {function} [onMute] - Used as the \"onMute\" parameter when calling the {@link CB_AudioFileCache#muteAll} method internally. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileCache#muteAll} method internally. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#mute} method that were performed (which should be the same number as the {@link CB_AudioFile} objects in the \"audioFiles\" parameter). */ CB_AudioFileSprites.prototype.muteAll = function(onMute, audioFiles) { return this.audioFileCache.muteAll(onMute, audioFiles); } /** * Unmutes all the existing {@link CB_AudioFile} objects or the desired ones (if provided). Uses the {@link CB_AudioFileCache#unmuteAll} method internally and returns its returning value. * @function * @param {function} [onUnmute] - Used as the \"onUnmute\" parameter when calling the {@link CB_AudioFileCache#unmuteAll} method internally. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileCache#unmuteAll} method internally. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#unmute} method that were performed (which should be the same number as the {@link CB_AudioFile} objects in the \"audioFiles\" parameter). */ CB_AudioFileSprites.prototype.unmuteAll = function(onUnmute, audioFiles) { return this.audioFileCache.unmuteAll(onUnmute, audioFiles); } /** * Sets the same volume for all the existing {@link CB_AudioFile} objects or the desired ones (if provided). Uses the {@link CB_AudioFileCache#setVolumeAll} method internally and returns its returning value. * @function * @param {number} [volume={@link CB_Speaker.getVolume()} | {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME}] - Used as the \"volume\" parameter when calling the {@link CB_AudioFileCache#setVolumeAll} method internally. * @param {boolean} [forceSetVolumeProperty=false] - Used as the \"forceSetVolumeProperty\" parameter when calling the {@link CB_AudioFileCache#setVolumeAll} method internally. * @param {function} [onSetVolume] - Used as the \"onSetVolume\" parameter when calling the {@link CB_AudioFileCache#setVolumeAll} method internally. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileCache#setVolumeAll} method internally. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#setVolume} method that were performed (which should be the same number as the {@link CB_AudioFile} objects in the \"audioFiles\" parameter). */ CB_AudioFileSprites.prototype.setVolumeAll = function(volume, forceSetVolumeProperty, onSetVolume, audioFiles) { return this.audioFileCache.setVolumeAll(volume, forceSetVolumeProperty, onSetVolume, audioFiles); } /** * Tries to change the audio API for all the existing {@link CB_AudioFile} objects or the desired ones (if provided). This method is not allowed to be called if a previous call to it did not finish yet. The function defined in the \"callbackError\" parameter, if any, will be called immediately if the method was previously called and it is still running currently. Uses the {@link CB_AudioFileCache#setAudioAPIAll} method internally and returns its returning value. * @function * @param {array|string} preferredAPIs - Used as the \"preferredAPIs\" parameter when calling the {@link CB_AudioFileCache#setAudioAPIAll} method internally. * @param {CB_AudioFileCache.setAudioAPIAll_CALLBACK_OK} [callbackOk] - Used as the \"callbackOk\" parameter when calling the {@link CB_AudioFileCache#setAudioAPIAll} method internally. * @param {CB_AudioFileCache.setAudioAPIAll_CALLBACK_ERROR} [callbackError] - Used as the \"callbackError\" parameter when calling the {@link CB_AudioFileCache#setAudioAPIAll} method internally. * @param {boolean} [mandatory=false] - Used as the \"mandatory\" parameter when calling the {@link CB_AudioFileCache#setAudioAPIAll} method internally. * @param {string} [forceReload=false] - Used as the \"forceReload\" parameter when calling the {@link CB_AudioFileCache#setAudioAPIAll} method internally. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileCache#setAudioAPIAll} method internally. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#setAudioAPI} method that were performed (which should be the same number as the {@link CB_AudioFile} objects in the \"audioFiles\" parameter). */ CB_AudioFileSprites.prototype.setAudioAPIAll = function(preferredAPIs, callbackOk, callbackError, mandatory, forceReload, audioFiles) { return this.audioFileCache.setAudioAPIAll(preferredAPIs, callbackOk, callbackError, mandatory, forceReload, audioFiles); } /** * Tells whether any of the {@link CB_AudioFile} objects is playing or not. Uses the {@link CB_AudioFileCache#isPlaying} method internally and returns its returning value. * @function * @returns {boolean} Returns whether any of the {@link CB_AudioFile} objects is playing or not. */ CB_AudioFileSprites.prototype.isPlaying = function() { return this.audioFileCache.isPlaying(); } /** * Tells the current number of free {@link CB_AudioFile} objects (the number of objects which are available and ready to use). Uses the {@link CB_AudioFileCache#getAudioFilesFreeNumber} method internally and returns its returning value. * @function * @returns {integer} Returns the current number of free {@link CB_AudioFile} objects (the number of objects which are available and ready to use). */ CB_AudioFileSprites.prototype.getAudioFilesFreeNumber = function() { return this.audioFileCache.getAudioFilesFreeNumber(); } /** * Gets an array with all the {@link CB_AudioFile} objects. Uses the {@link CB_AudioFileCache#getAudioFiles} method internally and returns its returning value. * @function * @param {boolean} [copy=false] - Used as the \"copy\" parameter when calling the {@link CB_AudioFileCache#getAudioFiles} method internally. * @returns {array} Returns an array with all the {@link CB_AudioFile} objects. */ CB_AudioFileSprites.prototype.getAudioFiles = function(copy) { return this.audioFileCache.getAudioFiles(copy); } /** * Gets an array with the free {@link CB_AudioFile} objects (the objects which are available and ready to use). Uses the {@link CB_AudioFileCache#getAudioFilesFree} method internally and returns its returning value. * @function * @returns {array} Returns an array with the free {@link CB_AudioFile} objects (the objects which are available and ready to use). */ CB_AudioFileSprites.prototype.getAudioFilesFree = function() { return this.audioFileCache.getAudioFilesFree(); } /** * Gets an array with the busy {@link CB_AudioFile} objects (the objects which are not available and ready to use). Uses the {@link CB_AudioFileCache#getAudioFilesBusy} method internally and returns its returning value. * @function * @returns {array} Returns an array with the busy {@link CB_AudioFile} objects (the objects which are not available and ready to use). */ CB_AudioFileSprites.prototype.getAudioFilesBusy = function() { return this.audioFileCache.getAudioFilesBusy(); } /** * Tells the number of {@link CB_AudioFile} objects created. Uses the {@link CB_AudioFileCache#getAudioFilesNumber} method internally and returns its returning value. * @function * @param {boolean} [real=false] - Used as the \"real\" parameter when calling the {@link CB_AudioFileCache#getAudioFilesNumber} method internally. * @returns {integer} Returns the number of {@link CB_AudioFile} objects created. */ CB_AudioFileSprites.prototype.getAudioFilesNumber = function(real) { return this.audioFileCache.getAudioFilesNumber(real); } /** * Tells the duration (minimum or maximum) of the sound stored (in milliseconds). Although the audio file cache should always be used to cache the same sound only, the duration might not always be the same due the usage of different formats, file paths, etc. So this method returns either the minimum or the maximum duration found among all the {@link CB_AudioFile} objects. Uses the {@link CB_AudioFileCache#getDuration} method internally and returns its returning value. * @function * @param {boolean} [maximum=false] - Used as the \"maximum\" parameter when calling the {@link CB_AudioFileCache#getDuration} method internally. * @returns {number} Returns the duration (minimum or maximum) of the sound stored (in milliseconds). Although the audio file cache should always be used to cache the same sound only, the duration might not always be the same due the usage of different formats, file paths, etc. So this method returns either the minimum or the maximum duration found among all the {@link CB_AudioFile} objects. */ CB_AudioFileSprites.prototype.getDuration = function(maximum) { return this.audioFileCache.getDuration(maximum); } /** * Returns a number representing the percentage of the loading progress for the audio file sprites object (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Uses the {@link CB_AudioFileCache#getProgress} method internally and returns its returning value. * @function * @param {boolean} [countLoadedObjects=false] - Used as the \"countLoadedObjects\" parameter when calling the {@link CB_AudioFileCache#getProgress} method internally. * @param {boolean} [alsoUncheckedAndCheckingObjects=false] - Used as the \"alsoUncheckedAndCheckingObjects\" parameter when calling the {@link CB_AudioFileCache#getProgress} method internally. * @returns {number} Returns a number representing the percentage of the loading progress for the audio file sprites object (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. */ CB_AudioFileSprites.prototype.getProgress = function(countLoadedObjects, alsoUncheckedAndCheckingObjects) { return this.audioFileCache.getProgress(countLoadedObjects, alsoUncheckedAndCheckingObjects); } /** * Gets the current status of the audio file sprites object. Uses the {@link CB_AudioFileCache#getStatus} method internally and returns its returning value. * @function * @returns {number} Returns the current status of the audio file sprites object. It is a number, which should match the value of the {@link CB_AudioFileCache.UNLOADED} (still unloaded), {@link CB_AudioFileCache.LOADING} (loading), {@link CB_AudioFileCache.UNCHECKED} (not checked by calling the {@link CB_AudioFileCache#checkPlayingAll} method yet), {@link CB_AudioFileCache.CHECKING} (being checked by the {@link CB_AudioFileCache#checkPlayingAll} method), {@link CB_AudioFileCache.LOADED} (loaded), {@link CB_AudioFileCache.FAILED} (failed loading or failed to play or by any other reason) or {@link CB_AudioFileCache.ABORTED} (aborted because it was destroyed with the \"destructor\" method) property. */ CB_AudioFileSprites.prototype.getStatus = function() { return this.audioFileCache.getStatus(); } /** * Gets the current status of the audio file sprites, as a string. Uses the {@link CB_AudioFileCache#getStatusString} method internally and returns its returning value. * @function * @returns {string} Returns the current status of the audio file sprites, as a string. Possible return values are \"UNLOADED\", \"LOADING\", \"UNCHECKED\", \"CHECKING\", \"LOADED\", \"FAILED\", \"ABORTED\" or \"UNKNOWN (UNKNOWN_STATUS)\" (where \"UNKNOWN_STATUS\" will be a value from the {@link CB_AudioFileCache#status} property not recognized as any possible status). */ CB_AudioFileSprites.prototype.getStatusString = function() { return this.audioFileCache.getStatusString(); } × Search results Close "},"CrossBase_audiovisual_audio_CB_AudioFileSpritesPool.js.html":{"id":"CrossBase_audiovisual_audio_CB_AudioFileSpritesPool.js.html","title":"Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js /** * @file Audio sprites pool management. Contains the {@link CB_AudioFileSpritesPool} class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Object whose property names the identifiers of each sprite (a case-sensitive string) and their value is a {@link CB_AudioFileSprites.DATA_OBJECT} object. * @example * { * \"sprites_group_id_1\" : CB_AudioFileSprites.DATA_OBJECT, * \"sprites_group_id_2\" : CB_AudioFileSprites.DATA_OBJECT, * \"sprites_group_id_3\" : CB_AudioFileSprites.DATA_OBJECT, * ... * } * @memberof CB_AudioFileSpritesPool * @typedef {Object} CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT * @property {CB_AudioFileSprites.DATA_OBJECT} spritesGroupId - Being the name of each property the unique identifier of a sprites group which will use a future internally-created {@link CB_AudioFileSprites} object, the value will always be the {@link CB_AudioFileSprites.DATA_OBJECT} that the {@link CB_AudioFileSprites} object will use to be created (received by its constructor). Some of the missing properties (\"preferredAPIs\", \"preferredFormats\", \"minimumAudioFiles\", \"maximumAudioFiles\", \"minimumAudioFilesFree\", \"newAudioFilesWhenNeeded\", \"retries\", \"checkManually\", \"checkManuallyOnNeededCreated\", \"checkManuallyOnPlayingFailed\", \"checkManuallyOnCheckingFailed\" and \"disableAutoLoad\") will use the value set on the properties of the main {@link CB_AudioFileSpritesPool.DATA_OBJECT} object (if any) used by the {@link CB_AudioFileSpritesPool} object. If a function in the \"onError\" parameter is given, it will always be wrapped so the main error function set on the {@link CB_AudioFileSpritesPool#onError} parameter will always be called (if any) through the {@link CB_AudioFileSpritesPool#errorFunction} method. */ /** * Object with the desired data and options for the audio sprites. It is almost identical to the {@link CB_AudioFileSprites.DATA_OBJECT} but adding a \"spritesGroups\" property. * @memberof CB_AudioFileSpritesPool * @typedef {Object} CB_AudioFileSpritesPool.DATA_OBJECT * @property {CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} [spritesGroups] - Object with the desired sprites groups, containing the {@link CB_AudioFileSprites.DATA_OBJECT} objects which will be used to create the {@link CB_AudioFileSprites} objects internally. Each group will have a {@link CB_AudioFileSprites} object. It will be used as the first parameter to call the {@link CB_AudioFileSpritesPool#insertSpritesGroups} method internally. Some of the missing properties (\"preferredAPIs\", \"preferredFormats\", \"minimumAudioFiles\", \"maximumAudioFiles\", \"minimumAudioFilesFree\", \"newAudioFilesWhenNeeded\", \"retries\", \"checkManually\", \"checkManuallyOnNeededCreated\", \"checkManuallyOnPlayingFailed\", \"checkManuallyOnCheckingFailed\" and \"disableAutoLoad\") of the {@link CB_AudioFileSprites.DATA_OBJECT} objects given will use the value set on the other properties of this object (if any). * @property {string} [id=\"\"] - Desired identifier for the object. If a valid value is given, this will be added to the {@link CB_AudioFileSpritesPool#id} property. * @property {array} [preferredAPIs={@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS}] - Array of strings with the preferred audio API or audio APIs, in order of preference. Possible audio APIs are \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). It will try to calculate and use the best one for the current client. If a valid value is given, this will be added to the {@link CB_AudioFileSpritesPool#preferredAPIs} property. If the {@link CB_AudioFileSprites.DATA_OBJECT} object (defined in the {@link CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} object set in the \"spritesGroups\") of a certain sprites group does not contain the \"preferredAPIs\" property, it will use the value of this property instead when creating its {@link CB_AudioFileSprites} object internally. * @property {array} [preferredFormats={@link CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_FORMATS}] - Array of strings with the preferred audio format or audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"'), in order of preference. It will try to calculate and use the best one for the current client. If a valid value is given, this will be added to the {@link CB_AudioFileSpritesPool#preferredFormats} property. If the {@link CB_AudioFileSprites.DATA_OBJECT} object (defined in the {@link CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} object set in the \"spritesGroups\") of a certain sprites group does not contain the \"preferredFormats\" property, it will use the value of this property instead when creating its {@link CB_AudioFileSprites} object internally. * @property {integer} [minimumAudioFiles={@link CB_AudioFileCache.minimumAudioFiles_DEFAULT}] - Minimum {@link CB_AudioFile} objects to create internally. It must be an integer being 1 the minimum. If a valid value is given, this will be added to the {@link CB_AudioFileSpritesPool#minimumAudioFiles} property. If the {@link CB_AudioFileSprites.DATA_OBJECT} object (defined in the {@link CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} object set in the \"spritesGroups\") of a certain sprites group does not contain the \"minimumAudioFiles\" property, it will use the value of this property instead when creating its {@link CB_AudioFileSprites} object internally. * @property {integer} [maximumAudioFiles={@link CB_AudioFileCache.maximumAudioFiles_DEFAULT}] - Maximum {@link CB_AudioFile} objects that are to be created internally. If it is set to null, there will not be a maximum (it will be unlimited). If an integer is provided, it must be the same number or greater than the value set in the {@link CB_AudioFileCache#minimumAudioFiles} property (also provided by the \"minimumAudioFiles\" of this object), allowing 1 minimum. If a valid value is given, this will be added to the {@link CB_AudioFileSpritesPool#maximumAudioFiles} property. If the {@link CB_AudioFileSprites.DATA_OBJECT} object (defined in the {@link CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} object set in the \"spritesGroups\") of a certain sprites group does not contain the \"maximumAudioFiles\" property, it will use the value of this property instead when creating its {@link CB_AudioFileSprites} object internally. * @property {integer} [minimumAudioFilesFree=parseInt({@link CB_AudioFileCache#minimumAudioFiles} * 0.25 + 0.5)] - New {@link CB_AudioFile} objects will be created internally when the number of free {@link CB_AudioFile} objects reaches this limit. If provided, it must be an integer being 0 (zero) the minimum. It will end using a 25% of the {@link CB_AudioFileSpritesPool#minimumAudioFiles} by default, rounded to ceil, allowing 0 (zero) minimum. If a valid value is given, this will be added to the {@link CB_AudioFileSpritesPool#minimumAudioFilesFree} property. If the {@link CB_AudioFileSprites.DATA_OBJECT} object (defined in the {@link CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} object set in the \"spritesGroups\") of a certain sprites group does not contain the \"minimumAudioFilesFree\" property, it will use the value of this property instead when creating its {@link CB_AudioFileSprites} object internally. * @property {integer} [newAudioFilesWhenNeeded=Math.min(parseInt({@link CB_AudioFileCache#minimumAudioFiles} * 0.1 + 0.5), 1)] - Number of new {@link CB_AudioFile} objects to create internally when the minimum limit of free {@link CB_AudioFile} objects ({@link CB_AudioFileSpritesPool#minimumAudioFilesFree}) is reached. If provided, it must be an integer being 0 (zero) the minimum. It will end using a 10% of the {@link CB_AudioFileSpritesPool#minimumAudioFiles} by default, rounded to ceil, allowing 1 minimum. If a valid value is given, this will be added to the {@link CB_AudioFileSpritesPool#newAudioFilesWhenNeeded} property. If the {@link CB_AudioFileSprites.DATA_OBJECT} object (defined in the {@link CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} object set in the \"spritesGroups\") of a certain sprites group does not contain the \"newAudioFilesWhenNeeded\" property, it will use the value of this property instead when creating its {@link CB_AudioFileSprites} object internally. * @property {integer} [retries={@link CB_AudioFileCache.retries_DEFAULT}] - Number of retries to try to load a {@link CB_AudioFile} object internally before trying to load the next possible one internally (if any). It must be an integer being 0 the minimum. If a valid value is given, this will be added to the {@link CB_AudioFileSpritesPool#retries} property. If the {@link CB_AudioFileSprites.DATA_OBJECT} object (defined in the {@link CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} object set in the \"spritesGroups\") of a certain sprites group does not contain the \"retries\" property, it will use the value of this property instead when creating its {@link CB_AudioFileSprites} object internally. * @property {boolean} [checkManually={@link CB_AudioFileCache.checkManually_DEFAULT}] - Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) by default. If a valid value is given, this will be added to the {@link CB_AudioFileSpritesPool#checkManually} property. If the {@link CB_AudioFileSprites.DATA_OBJECT} object (defined in the {@link CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} object set in the \"spritesGroups\") of a certain sprites group does not contain the \"checkManually\" property, it will use the value of this property instead when creating its {@link CB_AudioFileSprites} object internally. * @property {boolean} [checkManuallyOnNeededCreated={@link CB_AudioFileCache.checkManuallyOnNeededCreated_DEFAULT}] - Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when creates a new {@link CB_AudioFile} object needed. If a valid value is given, this will be added to the {@link CB_AudioFileSpritesPool#checkManuallyOnNeededCreated} property. If the {@link CB_AudioFileSprites.DATA_OBJECT} object (defined in the {@link CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} object set in the \"spritesGroups\") of a certain sprites group does not contain the \"checkManuallyOnNeededCreated\" property, it will use the value of this property instead when creating its {@link CB_AudioFileSprites} object internally. * @property {boolean} [checkManuallyOnPlayingFailed={@link CB_AudioFileCache.checkManuallyOnPlayingFailed_DEFAULT}] - Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when playing one has failed and tries to reload it. If a valid value is given, this will be added to the {@link CB_AudioFileSpritesPool#checkManuallyOnPlayingFailed} property. If the {@link CB_AudioFileSprites.DATA_OBJECT} object (defined in the {@link CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} object set in the \"spritesGroups\") of a certain sprites group does not contain the \"checkManuallyOnPlayingFailed\" property, it will use the value of this property instead when creating its {@link CB_AudioFileSprites} object internally. * @property {boolean} [checkManuallyOnCheckingFailed={@link CB_AudioFileCache.checkManuallyOnCheckingFailed_DEFAULT}] - Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when checking one has failed and tries to reload it. If a valid value is given, this will be added to the {@link CB_AudioFileSpritesPool#checkManuallyOnCheckingFailed} property. If the {@link CB_AudioFileSprites.DATA_OBJECT} object (defined in the {@link CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} object set in the \"spritesGroups\") of a certain sprites group does not contain the \"checkManuallyOnCheckingFailed\" property, it will use the value of this property instead when creating its {@link CB_AudioFileSprites} object internally. * @property {function} [onLoad] - Desired function to be called once the pool has been loaded. The first and unique parameter will be an integer with the {@link CB_AudioFile} objects that still need to be checked, if any, being \"this\" the current {@link CB_AudioFileSpritesPool} object. If a valid value is given, this will be added to the {@link CB_AudioFileSpritesPool#onLoad} property. * @property {function} [onError] - Desired function to be called when any kind of error happens. The first and unique parameter will be a string with the error description (if it could be determined), being \"this\" the current {@link CB_AudioFileSpritesPool} object. If a valid value is given, this will be added to the {@link CB_AudioFileSpritesPool#onError} property. If a function is set, it will always be called through the {@link CB_AudioFileSpritesPool#errorFunction} method whenever the \"onError\" event of an internally-created {@link CB_AudioFileSprites} object is fired. * @property {boolean} [disableAutoLoad=false] - If set to true, it will not create automatically the {@link CB_AudioFile} objects by calling the {@link CB_AudioFileCache#createAudioFiles} method internally. Internal usage only recommended. If the {@link CB_AudioFileSprites.DATA_OBJECT} object (defined in the {@link CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} object set in the \"spritesGroups\") of a certain sprites group does not contain the \"disableAutoLoad\" property, it will use the value of this property instead when creating its {@link CB_AudioFileSprites} object internally. */ /** * The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. * @class * @classdesc Class to manage many audio sprites stored in different groups, each with one {@link CB_AudioFileSprites} object (used internally). * @param {CB_AudioFileSpritesPool.DATA_OBJECT} [dataObject] - Object with the desired data and options for the groups of audio sprites. Each group will have a {@link CB_AudioFileSprites} object. Some of its properties (\"preferredAPIs\", \"preferredFormats\", \"minimumAudioFiles\", \"maximumAudioFiles\", \"minimumAudioFilesFree\", \"newAudioFilesWhenNeeded\", \"retries\", \"checkManually\", \"checkManuallyOnNeededCreated\", \"checkManuallyOnPlayingFailed\", \"checkManuallyOnCheckingFailed\" and \"disableAutoLoad\") will be used as the default value to create internally the {@link CB_AudioFileSprites} objects when the value is not given in the {@link CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} object (set as the value of the {@link CB_AudioFileSpritesPool.DATA_OBJECT#spritesGroups} property). * @returns {CB_AudioFileSpritesPool} Returns a new {@link CB_AudioFileSpritesPool} object. * @todo Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). * @todo Method getCopy and static method filterProperties (similar to the ones from {@link CB_GraphicSprites} and {@link CB_GraphicSpritesScene}). */ var CB_AudioFileSpritesPool = function(dataObject) { //Creates an instance of this object and returns it in the case that it is being called from an unexpected context: if (this === window || !(this instanceof CB_AudioFileSpritesPool)) { return new CB_AudioFileSpritesPool(dataObject); } //Properties and variables: /** * Stores the identifier for the audio file sprites pool object. * @var * @readonly * @type {string} * @default */ this.id = \"\"; /** * Stores an array of strings with the preferred audio API or audio APIs, in order of preference. Possible audio APIs are \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). Internal usage only recommended. * @var * @readonly * @type {array} * @default CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS */ this.preferredAPIs = undefined; /** * Stores an array of strings with the preferred audio format or audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"'), in order of preference. Internal usage only recommended. * @var * @readonly * @type {array} * @default CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_FORMATS */ this.preferredFormats = undefined; /** * Minimum {@link CB_AudioFile} objects to create internally for each {@link CB_AudioFileSprites} object. It must be an integer being 1 the minimum. Internal usage only recommended. * @var * @readonly * @type {integer} * @default CB_AudioFileCache.minimumAudioFiles_DEFAULT */ this.minimumAudioFiles = undefined; /** * Maximum {@link CB_AudioFile} objects that are to be created internally for each {@link CB_AudioFileSprites} object. If it is set to null, there will not be a maximum (it will be unlimited). If an integer is provided, it must be the same number or greater than the value set in the {@link CB_AudioFileCache#minimumAudioFiles} property, allowing 1 minimum. Internal usage only recommended. * @var * @readonly * @type {integer|null} * @default CB_AudioFileCache.maximumAudioFiles_DEFAULT */ this.maximumAudioFiles = undefined; /** * New {@link CB_AudioFile} objects will be created internally for each {@link CB_AudioFileSprites} object when the number of free {@link CB_AudioFile} objects reaches this limit. It must be an integer being 0 (zero) the minimum. Internal usage only recommended. * @var * @readonly * @type {integer} * @default parseInt({@link CB_AudioFileCache#minimumAudioFiles} * 0.25 + 0.5) */ this.minimumAudioFilesFree = undefined; /** * Number of new {@link CB_AudioFile} objects to create internally for each {@link CB_AudioFileSprites} object when the minimum limit of free {@link CB_AudioFile} objects ({@link CB_AudioFileCache#minimumAudioFilesFree}) is reached. It must be an integer being 0 (zero) the minimum. Internal usage only recommended. * @var * @readonly * @type {integer} * @default Math.min(parseInt({@link CB_AudioFileCache#minimumAudioFiles} * 0.1 + 0.5), 1) */ this.newAudioFilesWhenNeeded = undefined; /** * Number of retries to try to load a {@link CB_AudioFile} object internally before trying to load the next possible one internally (if any). It must be an integer being 0 the minimum. Internal usage only recommended. * @var * @readonly * @type {integer} * @default CB_AudioFileCache.retries_DEFAULT */ this.retries = undefined; /** * Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually). Internal usage only recommended. * @var * @readonly * @type {boolean} * @default CB_AudioFileCache.checkManually_DEFAULT */ this.checkManually = undefined; /** * Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when creates a new {@link CB_AudioFile} object needed. Internal usage only recommended. * @var * @readonly * @type {boolean} * @default CB_AudioFileCache.checkManuallyOnNeededCreated_DEFAULT */ this.checkManuallyOnNeededCreated = undefined; /** * Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when playing one has failed and tries to reload it. Internal usage only recommended. * @var * @readonly * @type {boolean} * @default CB_AudioFileCache.checkManuallyOnPlayingFailed_DEFAULT */ this.checkManuallyOnPlayingFailed = undefined; /** * Tells whether the {@link CB_AudioFile} objects must be checked automatically or not (manually) when checking one has failed and tries to reload it. Internal usage only recommended. * @var * @readonly * @type {boolean} * @default CB_AudioFileCache.checkManuallyOnCheckingFailed_DEFAULT */ this.checkManuallyOnCheckingFailed = undefined; /** * If set to true, it will not create automatically the {@link CB_AudioFile} objects by calling the {@link CB_AudioFileCache#createAudioFiles} method internally. Internal usage only recommended. * @var * @readonly * @type {boolean} * @default false */ this.disableAutoLoad = undefined; /** * Desired function to be called once the pool has been loaded. The first and unique parameter will be an integer with the {@link CB_AudioFile} objects that still need to be checked, if any, being \"this\" the current {@link CB_AudioFileSpritesPool} object. * @var * @readonly * @type {function} * @default */ this.onLoad = undefined; /** * Desired function to be called when any kind of error happens. The first and unique parameter will be a string with the error description (if it could be determined), being \"this\" the current {@link CB_AudioFileSpritesPool} object. If a function is set, it will always be called through the {@link CB_AudioFileSpritesPool#errorFunction} method whenever the \"onError\" event of an internally-created {@link CB_AudioFileSprites} object is fired. * @var * @readonly * @type {function} * @default */ this.onError = undefined; //Function to call if not all AudioFiles can be loaded. /** * Stores the internally-created {@link CB_AudioFileSprites} objects, using the name of each property as their group ID and the value being the {@link CB_AudioFileSprites} object itself. Internal usage only recommended. * @var * @readonly * @type {Object} * @default */ this.audioFileSprites = {}; //Object with the CB_AudioFileSprites objects. //Internal properties: this._aborted = false; this._checkSpritesGroupsLoadedTimeout = null; this._checkPlayingAllInterval; this._checkPlayingAllPerforming = false; this._setAudioAPIAllInterval; this._setAudioAPIAllPerforming = false; this._errorFunctionExecuted = false; //Calls the constructor of the object when creates an instance: return this._init(dataObject); } //Static properties and constants: /** * Status value for audio file sprites pool which is unloaded. Can be used to compare the value returned by the {@link CB_AudioFileSpritesPool#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default 0 */ CB_AudioFileSpritesPool.UNLOADED = 0; //Status value for unloaded cache. /** * Status value for an audio file sprites pool which is loading. Can be used to compare the value returned by the {@link CB_AudioFileSpritesPool#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFileSpritesPool.LOADING = 1; //Status value for loading cache. /** * Status value for an audio file sprites pool which has not been checked yet. Can be used to compare the value returned by the {@link CB_AudioFileSpritesPool#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFileSpritesPool.UNCHECKED = 2; //STatus value for an unchecked cache. /** * Status value for an audio file sprites pool which is being checked currently. Can be used to compare the value returned by the {@link CB_AudioFileSpritesPool#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFileSpritesPool.CHECKING = 3; //Status value for checking a cache. /** * Status value for an audio file sprites pool which has been loaded. Can be used to compare the value returned by the {@link CB_AudioFileSpritesPool#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFileSpritesPool.LOADED = 4; //Status value for loaded cache. /** * Status value for an audio file sprites pool which failed to be loaded or failed for any other reason. Can be used to compare the value returned by the {@link CB_AudioFileSpritesPool#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFileSpritesPool.FAILED = 5; //Status value for failed to load cache. /** * Status value for an audio file sprites pool which has been aborted. This will happen when the audio file sprites pool has been destroyed with the {@link CB_AudioFileSpritesPool#destructor} method. Can be used to compare the value returned by the {@link CB_AudioFileSpritesPool#getStatus} method. Recommended for internal usage only. * @constant * @type {integer} * @default */ CB_AudioFileSpritesPool.ABORTED = 6; //Status value for aborted cache. //Constructor: CB_AudioFileSpritesPool.prototype._init = function(dataObject) { /* FORMAT: dataObject = { [id : String,] [onLoad : Function,] [onError : Function,] [preferredAPIs : Array&lt;String&gt;,] [preferredFormats : Array&lt;String&gt;,] [minimumAudioFiles : Integer,] [maximumAudioFiles : Integer,] [minimumAudioFilesFree : Integer,] [newAudioFilesWhenNeeded : Integer,] [retries : Integer,] [checkManually : Boolean,] [checkManuallyOnNeededCreated : Boolean,] [checkManuallyOnPlayingFailed : Boolean,] [checkManuallyOnCheckingFailed : Boolean,] [disableAutoLoad : Boolean,] spritesGroups : { \"sprites_group_id\" : CB_AudioFileSprites.DATA_OBJECT [, ...] } }; */ //Tries to load the data (if any): this.load(dataObject); //Returns the object: return this; } /** * Destroys the audio file sprites pool object (removing all sprites, etc.), including the internal audio file sprites objects, and frees memory. By default, unless the \"preventAbortedStatus\" is set to true, sets the current status of all the {@link CB_AudioFileCache} objects as ABORTED ({@link CB_AudioFileCache.ABORTED} value). Internally, calls the {@link CB_AudioFileSprites#destructor} method of all the internally-created {@link CB_AudioFileSprites} objects. * @function * @param {boolean} [stopSounds=false] - Used as the \"stopSounds\" parameter when calling internally the {@link CB_AudioFileSprites#destructor} method of all the internally-created {@link CB_AudioFileSprites} objects. * @param {boolean} [preventAbortedStatus=false] - If set to true (not recommended), it will not assign the status of \"ABORTED\" (it will not set the {@link CB_AudioFileSpritesPool#_aborted} property to true}. Used as the \"preventAbortedStatus\" parameter when calling internally the {@link CB_AudioFileSprites#destructor} method of all the internally-created {@link CB_AudioFileSprites} objects. */ CB_AudioFileSpritesPool.prototype.destructor = function(stopSounds, preventAbortedStatus) { clearInterval(this._checkPlayingAllInterval); clearInterval(this._setAudioAPIAllInterval); clearTimeout(this._checkSpritesGroupsLoadedTimeout); //Destroys the CB_AudioFileSprites objects: for (var audioFileSpritesObject in this.audioFileSprites) { this.audioFileSprites[audioFileSpritesObject].destructor(stopSounds, preventAbortedStatus); } //Resets properties to their default value: this.preferredAPIs = undefined; this.preferredFormats = undefined; this.minimumAudioFiles = undefined; this.maximumAudioFiles = undefined; this.minimumAudioFilesFree = undefined; this.newAudioFilesWhenNeeded = undefined; this.retries = undefined; this.checkManually = undefined; this.checkManuallyOnNeededCreated = undefined; this.checkManuallyOnPlayingFailed = undefined; this.checkManuallyOnCheckingFailed = undefined; this.disableAutoLoad = undefined; this.onLoad = undefined; this.onError = undefined; this.audioFileSprites = {}; if (!preventAbortedStatus) { this._aborted = true; } } /** * Loads the audio file sprites pool with the desired data given. This method is called by the constructor automatically. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. * @function * @param {CB_AudioFileSpritesPool.DATA_OBJECT} dataObject - Object with the desired data and options for the audio file sprites. * @returns {CB_AudioFileSpritesPool|null} If a \"dataObject\" is given, it returns the current {@link CB_AudioFileSpritesPool} object. Otherwise, it returns null. */ CB_AudioFileSpritesPool.prototype.load = function(dataObject) { if (typeof(dataObject) === \"undefined\" || dataObject === null) { return null; } //Destroys all previous data (if any): this.destructor(true, true); //Also stops all sounds. this._aborted = false; //Sanitizes the given data: dataObject.id = CB_trim(dataObject.id); //Sets the new data: if (dataObject.id !== \"\") { this.id = dataObject.id; } if (typeof(dataObject.preferredAPIs) !== \"undefined\") { this.preferredAPIs = dataObject.preferredAPIs; } if (typeof(dataObject.preferredFormats) !== \"undefined\") { this.preferredFormats = dataObject.preferredFormats; } if (typeof(dataObject.minimumAudioFiles) !== \"undefined\") { this.minimumAudioFiles = dataObject.minimumAudioFiles; } if (typeof(dataObject.maximumAudioFiles) !== \"undefined\") { this.maximumAudioFiles = dataObject.maximumAudioFiles; } if (typeof(dataObject.minimumAudioFilesFree) !== \"undefined\") { this.minimumAudioFilesFree = dataObject.minimumAudioFilesFree; } if (typeof(dataObject.newAudioFilesWhenNeeded) !== \"undefined\") { this.newAudioFilesWhenNeeded = dataObject.newAudioFilesWhenNeeded; } if (typeof(dataObject.retries) !== \"undefined\") { this.retries = dataObject.retries; } if (typeof(dataObject.checkManually) !== \"undefined\") { this.checkManually = dataObject.checkManually; } if (typeof(dataObject.checkManuallyOnNeededCreated) !== \"undefined\") { this.checkManuallyOnNeededCreated = dataObject.checkManuallyOnNeededCreated; } if (typeof(dataObject.checkManuallyOnPlayingFailed) !== \"undefined\") { this.checkManuallyOnPlayingFailed = dataObject.checkManuallyOnPlayingFailed; } if (typeof(dataObject.checkManuallyOnCheckingFailed) !== \"undefined\") { this.checkManuallyOnCheckingFailed = dataObject.checkManuallyOnCheckingFailed; } if (typeof(dataObject.disableAutoLoad) !== \"undefined\") { this.disableAutoLoad = dataObject.disableAutoLoad; } if (typeof(dataObject.onLoad) !== \"undefined\") { this.onLoad = dataObject.onLoad; } if (typeof(dataObject.onError) !== \"undefined\") { this.onError = dataObject.onError; } //Inserts the CB_AudioFileSprites objects: if (typeof(dataObject.spritesGroups) !== \"undefined\" &amp;&amp; dataObject.spritesGroups !== null) { this.removeSpritesGroups(); this.insertSpritesGroups(dataObject.spritesGroups); } return this; } //Checks whether all CB_AudioFileSprites objects are loaded or not: CB_AudioFileSpritesPool.prototype._checkSpritesGroupsLoaded = function() { clearTimeout(this._checkSpritesGroupsLoadedTimeout); var allLoaded = true; var x; for (var audioFileSpritesObject in this.audioFileSprites) { x++; if (!this.audioFileSprites[audioFileSpritesObject].audioFileCache.checkManually &amp;&amp; this.audioFileSprites[audioFileSpritesObject].getStatus() !== CB_AudioFileCache.LOADED) { allLoaded = false; break; } else if (this.audioFileSprites[audioFileSpritesObject].audioFileCache.checkManually &amp;&amp; this.audioFileSprites[audioFileSpritesObject].getStatus() !== CB_AudioFileCache.UNCHECKED &amp;&amp; this.audioFileSprites[audioFileSpritesObject].getStatus() !== CB_AudioFileCache.LOADED) { allLoaded = false; break; } } if (x === 0) { allLoaded = false; } var that = this; if (this.getStatus() === CB_AudioFileSpritesPool.LOADING || this.getStatus() === CB_AudioFileSpritesPool.UNCHECKED) { if (!allLoaded) { this._checkSpritesGroupsLoadedTimeout = setTimeout(function() { that._checkSpritesGroupsLoaded.call(that); }, 100); } else { if (typeof(this.onLoad) === \"function\") { var objectsNeedChecking = 0; var audioFiles; var audioFilesLength; var x; for (var audioFileSpritesObject in this.audioFileSprites) { audioFiles = this.audioFileSprites[audioFileSpritesObject].getAudioFiles(false); audioFilesLength = audioFiles.length; for (x = 0; x &lt; audioFilesLength; x++) { if (audioFiles[x].getStatus() === CB_AudioFile.UNCHECKED) { objectsNeedChecking++; } } } this.onLoad.call(this, objectsNeedChecking); } } } } /** * Removes all the sprites groups ({@link CB_AudioFileSprites} objects) by clearing the {@link CB_AudioFileSpritesPool#audioFileSprites} property. * @function */ CB_AudioFileSpritesPool.prototype.removeSpritesGroups = function() { this.audioFileSprites = {}; } /** * Inserts the given sprites groups. * @function * @param {CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT} sprites - Object with the desired sprites groups. * @returns {integer} Returns the number of sprites groups inserted. */ CB_AudioFileSpritesPool.prototype.insertSpritesGroups = function(spritesGroups) { var inserted = 0; var that = this; if (typeof(spritesGroups) !== \"undefined\" &amp;&amp; spritesGroups !== null) { clearTimeout(this._checkSpritesGroupsLoadedTimeout); for (var spritesGroupId in spritesGroups) { //Inserts the sprite: if (this.insertSpritesGroup(spritesGroupId, spritesGroups[spritesGroupId], true)) { inserted++; } } this._checkSpritesGroupsLoadedTimeout = setTimeout(function() { that._checkSpritesGroupsLoaded.call(that); }, 100); } return inserted; } /** * Inserts the given sprites group to the audio file sprites pool object. * @function * @param {string} spritesGroupId - The identifier for the sprites group. * @param {CB_AudioFileSprites.DATA_OBJECT} [dataObject] - Object with the data of the sprites group. Optional but recommended. * @param {boolean} [avoidCheckingLoaded=false] - If set to true, it will not check whether all sprites groups has been loaded after inserting the desired one. This is done internally by the {@link CB_AudioFileSpritesPool#_checkSpritesGroupsLoaded} method which will fire the {@link CB_AudioFileSpritesPool#onLoad} function (if any). * @returns {boolean} Returns true if the sprites group has been inserted or false otherwise. */ CB_AudioFileSpritesPool.prototype.insertSpritesGroup = function(spritesGroupId, dataObject, avoidCheckingLoaded) { if (typeof(spritesGroupId) === \"undefined\" || spritesGroupId === null) { return false; } if (typeof(dataObject) === \"undefined\" || dataObject === null) { dataObject = {}; } if (avoidCheckingLoaded) { clearTimeout(this._checkSpritesGroupsLoadedTimeout); } var dataObjectCopy = {}; dataObjectCopy.id = spritesGroupId; dataObjectCopy.preferredAPIs = dataObject.preferredAPIs; dataObjectCopy.preferredFormats = dataObject.preferredFormats; dataObjectCopy.URIs = dataObject.URIs; dataObjectCopy.minimumAudioFiles = dataObject.minimumAudioFiles; dataObjectCopy.maximumAudioFiles = dataObject.maximumAudioFiles; dataObjectCopy.minimumAudioFilesFree = dataObject.minimumAudioFilesFree; dataObjectCopy.newAudioFilesWhenNeeded = dataObject.newAudioFilesWhenNeeded; dataObjectCopy.retries = dataObject.retries; dataObjectCopy.checkManually = dataObject.checkManually; dataObjectCopy.checkManuallyOnNeededCreated = dataObject.checkManuallyOnNeededCreated; dataObjectCopy.checkManuallyOnPlayingFailed = dataObject.checkManuallyOnPlayingFailed; dataObjectCopy.checkManuallyOnCheckingFailed = dataObject.checkManuallyOnCheckingFailed; dataObjectCopy.disableAutoLoad = dataObject.disableAutoLoad; dataObjectCopy.onLoad = dataObject.onLoad; dataObjectCopy.onError = dataObject.onError; dataObjectCopy.sprites = dataObject.sprites; if (typeof(dataObjectCopy.preferredAPIs) === \"undefined\" &amp;&amp; typeof(this.preferredAPIs) !== \"undefined\") { dataObjectCopy.preferredAPIs = this.preferredAPIs; } if (typeof(dataObjectCopy.preferredFormats) === \"undefined\" &amp;&amp; typeof(this.preferredFormats) !== \"undefined\") { dataObjectCopy.preferredFormats = this.preferredFormats; } if (typeof(dataObjectCopy.minimumAudioFiles) === \"undefined\" &amp;&amp; typeof(this.minimumAudioFiles) !== \"undefined\") { dataObjectCopy.minimumAudioFiles = this.minimumAudioFiles; } if (typeof(dataObjectCopy.maximumAudioFiles) === \"undefined\" &amp;&amp; typeof(this.maximumAudioFiles) !== \"undefined\") { dataObjectCopy.maximumAudioFiles = this.maximumAudioFiles; } if (typeof(dataObjectCopy.minimumAudioFilesFree) === \"undefined\" &amp;&amp; typeof(this.minimumAudioFilesFree) !== \"undefined\") { dataObjectCopy.minimumAudioFilesFree = this.minimumAudioFilesFree; } if (typeof(dataObjectCopy.newAudioFilesWhenNeeded) === \"undefined\" &amp;&amp; typeof(this.newAudioFilesWhenNeeded) !== \"undefined\") { dataObjectCopy.newAudioFilesWhenNeeded = this.newAudioFilesWhenNeeded; } if (typeof(dataObjectCopy.retries) === \"undefined\" &amp;&amp; typeof(this.retries) !== \"undefined\") { dataObjectCopy.retries = this.retries; } if (typeof(dataObjectCopy.checkManually) === \"undefined\" &amp;&amp; typeof(this.checkManually) !== \"undefined\") { dataObjectCopy.checkManually = this.checkManually; } if (typeof(dataObjectCopy.checkManuallyOnNeededCreated) === \"undefined\" &amp;&amp; typeof(this.checkManuallyOnNeededCreated) !== \"undefined\") { dataObjectCopy.checkManuallyOnNeededCreated = this.checkManuallyOnNeededCreated; } if (typeof(dataObjectCopy.checkManuallyOnPlayingFailed) === \"undefined\" &amp;&amp; typeof(this.checkManuallyOnPlayingFailed) !== \"undefined\") { dataObjectCopy.checkManuallyOnPlayingFailed = this.checkManuallyOnPlayingFailed; } if (typeof(dataObjectCopy.checkManuallyOnCheckingFailed) === \"undefined\" &amp;&amp; typeof(this.checkManuallyOnCheckingFailed) !== \"undefined\") { dataObjectCopy.checkManuallyOnCheckingFailed = this.checkManuallyOnCheckingFailed; } if (typeof(dataObjectCopy.disableAutoLoad) === \"undefined\" &amp;&amp; typeof(this.disableAutoLoad) !== \"undefined\") { dataObjectCopy.disableAutoLoad = this.disableAutoLoad; } //Wraps the error function: var that = this; var onErrorOld = dataObjectCopy.onError; dataObjectCopy.onError = function(error) { if (typeof(onErrorOld) === \"function\") { onErrorOld.call(this, error); } setTimeout(function() { that.errorFunction.call(that, error); }, 100); }; this._errorFunctionExecuted = false; //Allows the execution of the error function again. this.audioFileSprites[spritesGroupId] = new CB_AudioFileSprites(dataObjectCopy); if (!avoidCheckingLoaded) { this._checkSpritesGroupsLoadedTimeout = setTimeout(function() { that._checkSpritesGroupsLoaded.call(that); }, 100); } return true; } /** * Removes a sprites group by its ID. * @function * @param {string} spritesGroupId - The identifier for the sprites group. * @param {boolean} [destroy=false] - If set to true, it will call the {@link CB_AudioFileSprites#destructor} method of the {@link CB_AudioFileSprites} object which belongs to the desired sprites group. * @param {boolean} [stopSounds=false] - If the \"destroy\" parameter is set to false, this parameter will be ignored. Used as the \"stopSound\" parameter when calling internally the {@link CB_AudioFileSprites#destructor} method of the {@link CB_AudioFileSprites} object which belongs to the desired sprites group. * @param {boolean} [preventAbortedStatus=false] - If the \"destroy\" parameter is set to false, this parameter will be ignored. Used as the \"preventAbortedStatus\" parameter when calling internally the {@link CB_AudioFileSprites#destructor} method of the {@link CB_AudioFileSprites} object which belongs to the desired sprites group. * @returns {boolean} Returns true if the sprites group has been deleted or false otherwise. */ CB_AudioFileSpritesPool.prototype.removeSpritesGroup = function(spritesGroupId, destroy, stopSounds, preventAbortedStatus) { if (typeof(this.audioFileSprites[spritesGroupId]) !== \"undefined\" &amp;&amp; this.audioFileSprites[spritesGroupId] !== null) { if (destroy) { this.audioFileSprites[spritesGroupId].destructor(stopSounds, preventAbortedStatus); } this.audioFileSprites[spritesGroupId] = null; var audioFileSprites = {}; for (spritesGroupId in this.audioFileSprites) { if (typeof(this.audioFileSprites[spritesGroupId]) !== \"undefined\" &amp;&amp; this.audioFileSprites[spritesGroupId] !== null) { audioFileSprites[spritesGroupId] = this.audioFileSprites[spritesGroupId]; } } this.audioFileSprites = audioFileSprites; return true; } return false; } /** * Returns a sprites group (the {@link CB_AudioFileSprites} object) by its ID. * @function * @param {string} spritesGroupId - The identifier for the sprites group. * @param {boolean} [withoutChecking=false] - If set to true and the sprites group cannot be found, the method will return undefined (or whatever is stored by the given ID) instead of null. * @returns {CB_AudioFileSprites|undefined|*|null} Returns null if the \"withoutChecking\" parameter is set to true and the sprites group cannot be found. Otherwise, it will return what is stored internally by the given ID which can be a {@link CB_AudioFileSprites} object if found or undefined (or whatever is stored by the given ID) if not found. */ CB_AudioFileSpritesPool.prototype.getSpritesGroup = function(spritesGroupId, withoutChecking) { //return this.audioFileSprites[spritesGroupId]; if (typeof(this.audioFileSprites[spritesGroupId]) !== \"undefined\" || withoutChecking) { return this.audioFileSprites[spritesGroupId]; } return null; } /** * Returns an object with the sprites groups (all the internally-created {@link CB_AudioFileSprites} objects), being the name of each property their group ID and the value being the {@link CB_AudioFileSprites} object itself. Internally, it just returns the {@link CB_AudioFileSpritesPool#audioFileSprites} property. * @function * @returns {Object} Returns an object with the sprites groups (all the internally-created {@link CB_AudioFileSprites} objects), being the name of each property their group ID and the value being the {@link CB_AudioFileSprites} object itself. Internally, it just returns the {@link CB_AudioFileSpritesPool#audioFileSprites} property. */ CB_AudioFileSpritesPool.prototype.getSpritesGroups = function() { return this.audioFileSprites; } /** * Returns an object with the sprites (and includes \"_WITHOUT_SPRITE_ASSOCIATED\" if we want to). Internally, uses the {@link CB_AudioFileSprites#getSprites} method. * @function * @param {boolean} [includeWithoutSpriteAssociated=false] - If set to true, the returning object will also contain a property called \"_WITHOUT_SPRITE_ASSOCIATED\" whose value will be an empty object (unless the \"orderBySpritesGroup\" parameter is set to true and the property existed before in the object stored in the {@link CB_AudioFileSprites#sprites} property and had a value which is not an empty object). If set to false and the \"orderBySpritesGroup\" parameter is also set to false, the returning object will not contain the \"_WITHOUT_SPRITE_ASSOCIATED\" property. If set to false and the \"orderBySpritesGroup\" parameter is set to true, the returning object will not contain the \"_WITHOUT_SPRITE_ASSOCIATED\" property unless the property existed before in the object stored in the {@link CB_AudioFileSprites#sprites} property. * @param {boolean} [orderBySpritesGroup=false] - If set to false, it will return a {@link CB_AudioFileSprites.SPRITES_OBJECT} object whose properties will be the ID of each sprite (each sprite ID should be unique) and their value will be a {@link CB_AudioFileSprites.SPRITE_OBJECT} object. If set to true, it will return an object whose properties will be the ID of each sprites group and the value will be a {@link CB_AudioFileSprites.SPRITES_OBJECT} object which will include its sprites. * @returns {CB_AudioFileSprites.SPRITES_OBJECT|Object} If the \"orderBySpritesGroup\" is set to false, it will return a {@link CB_AudioFileSprites.SPRITES_OBJECT} object whose properties will be the ID of each sprite (each sprite ID should be unique) and their value will be a {@link CB_AudioFileSprites.SPRITE_OBJECT} object. If the \"orderBySpritesGroup\" is set to true, it will return an object whose properties will be the ID of each sprites group and the value will be a {@link CB_AudioFileSprites.SPRITES_OBJECT} object which will include its sprites. */ CB_AudioFileSpritesPool.prototype.getSprites = function(includeWithoutSpriteAssociated, orderBySpritesGroup) { var sprites = {}; if (!orderBySpritesGroup) { if (includeWithoutSpriteAssociated) { sprites[\"_WITHOUT_SPRITE_ASSOCIATED\"] = {}; } var spritesLoop; var spriteId; for (var spritesGroupId in this.audioFileSprites) { spritesLoop = this.audioFileSprites[spritesGroupId].getSprites(false); for (spriteId in spritesLoop) { sprites[spriteId] = spritesLoop[spriteId]; } } } else { for (var spritesGroupId in this.audioFileSprites) { sprites[spritesGroupId] = this.audioFileSprites[spritesGroupId].getSprites(includeWithoutSpriteAssociated); } } return sprites; } /** * Returns the sound instances (their ID) used (stored in the {@link CB_AudioFileSprites#spriteSoundInstances} property of each {@link CB_AudioFileSprites} object). * @function * @param {boolean} [oneDimension=false] - If set to false, it will return an object whose property names will be the ID of each sprites group and their value will be the {@link CB_AudioFileSprites#spriteSoundInstances} property of each {@link CB_AudioFileSprites} object (which includes the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated) which belongs to that sprites group. Otherwise, if it is set to true, it will return a numeric array whose values are the sound instance IDs. * @param {boolean} [includeWithoutSpriteAssociated=false] - If set to true, it will also return the sound instance identifiers which are not associated to any sprite. Used as the \"includeWithoutSpriteAssociated\" parameter when calling the {@link CB_AudioFileSprites#getSoundInstancesId} method internally. Only used when the \"oneDimension\" parameter is set to true. * @returns {Object|array} Returns the sound instances (their ID) used (stored in the {@link CB_AudioFileSprites#spriteSoundInstances} property). If the \"oneDimension\" parameter is set to false, it will return an object whose property names will be the ID of each sprites group and their value will be the {@link CB_AudioFileSprites#spriteSoundInstances} property of each {@link CB_AudioFileSprites} object (which includes the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated) which belongs to that sprites group. If the \"oneDimension\" parameter is set to true, it will return a numeric array whose values are the sound instance identifiers (if the \"includeWithoutSpriteAssociated\" parameter it set to true, it will also include the sound instances which are not associated to any sprite). */ CB_AudioFileSpritesPool.prototype.getSoundInstancesId = function(oneDimension, includeWithoutSpriteAssociated) { var soundInstances; if (!oneDimension) { soundInstances = {}; for (var spritesGroupId in this.audioFileSprites) { soundInstances[spritesGroupId] = this.audioFileSprites[spritesGroupId].getSoundInstancesId(false, includeWithoutSpriteAssociated); } } else { soundInstances = []; var soundInstancesSpritesGroup; var soundInstancesSpritesGroupLength; var y = 0; var x = 0; for (var spritesGroupId in this.audioFileSprites) { soundInstancesSpritesGroup = this.audioFileSprites[spritesGroupId].getSoundInstancesId(true, includeWithoutSpriteAssociated); soundInstancesSpritesGroupLength = soundInstancesSpritesGroup.length; for (x = 0; x &lt; soundInstancesSpritesGroupLength; x++) { soundInstances[y++] = soundInstancesSpritesGroup[x]; } } } return soundInstances; } /** * Object returned by the {@link CB_AudioFileSpritesPool#getAudioFilesUsed} method. Each property names will be the the ID of each sprites group and their value will be a {@link CB_AudioFileSprites.getAudioFilesUsed_OBJECT} object. * @memberof CB_AudioFileSpritesPool * @typedef {Object} CB_AudioFileSpritesPool.getAudioFilesUsed_OBJECT * @property {CB_AudioFileSpritesPool.getAudioFilesUsed_OBJECT} spriteId - Each property names will be the the ID of each sprites group and their value will be a {@link CB_AudioFileSprites.getAudioFilesUsed_OBJECT} object. */ /** * Returns the {@link CB_AudioFile} objects used by all the sounds instances of all the sprites groups. * @function * @param {boolean} [oneDimension=false] - If set to false, it will return an object whose property names will be the ID of each sprites group and their value will be the an object whose property names are the sprite identifiers (including the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated, if the \"includeWithoutSpriteAssociated\" is set to true) and their value will be a numeric array with the {@link CB_AudioFile} objects used. Otherwise, if set to true, it will return a numeric array with the {@link CB_AudioFile} objects used (if the \"includeWithoutSpriteAssociated\" parameter is set to true, it will also contain the {@link CB_AudioFile} objects whose sound instance ID is not associated to any sprite). * @param {boolean} [includeWithoutSpriteAssociated=false] - If set to true, it will also return the {@link CB_AudioFile} objects whose sound instance ID is not associated to any sprite. Used as the \"includeWithoutSpriteAssociated\" parameter when calling the {@link CB_AudioFileSprites#getAudioFilesUsed} method internally. * @param {boolean} [avoidCancelled=false] - If set to true, it will not return the {@link CB_AudioFile} objects whose sound instance has been cancelled. Used as the \"avoidCancelled\" parameter when calling the {@link CB_AudioFileSprites#getAudioFilesUsed} method internally. * @returns {CB_AudioFileSprites.getAudioFilesUsed_OBJECT|array} Returns the {@link CB_AudioFile} objects used by all the sounds instances of all the sprites groups. If the \"oneDimension\" parameter is set to false, it will return a {@link CB_AudioFileSpritesPool.getAudioFilesUsed_OBJECT} object whose property names will be the ID of each sprites group and their value will be a {@link CB_AudioFileSprites.getAudioFilesUsed_OBJECT} object whose property names are the sprite identifiers (including the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated, if the \"includeWithoutSpriteAssociated\" is set to true) and their value will be a numeric array with the {@link CB_AudioFile} objects used. Otherwise, if the \"oneDimension\" parameter set to true, it will return a numeric array with the {@link CB_AudioFile} objects used (if the \"includeWithoutSpriteAssociated\" parameter is set to true, it will also contain the {@link CB_AudioFile} objects whose sound instance ID is not associated to any sprite). */ CB_AudioFileSpritesPool.prototype.getAudioFilesUsed = function(oneDimension, includeWithoutSpriteAssociated, avoidCancelled) { var audioFiles; if (!oneDimension) { audioFiles = {}; for (var spritesGroupId in this.audioFileSprites) { audioFiles[spritesGroupId] = this.audioFileSprites[spritesGroupId].getAudioFilesUsed(false, includeWithoutSpriteAssociated, avoidCancelled); } } else { audioFiles = []; var audioFilesSpritesGroup; var audioFilesSpritesGroupLength; var y = 0; var x = 0; for (var spritesGroupId in this.audioFileSprites) { audioFilesSpritesGroup = this.audioFileSprites[spritesGroupId].getAudioFilesUsed(true, includeWithoutSpriteAssociated, avoidCancelled); audioFilesSpritesGroupLength = audioFilesSpritesGroup.length; for (x = 0; x &lt; audioFilesSpritesGroupLength; x++) { audioFiles[y++] = audioFilesSpritesGroup[x]; } } } return audioFiles; } /** * Callback that is used when finishes all iterations after looping through the items. Being \"this\" an array with all the items. * @memberof CB_AudioFileSpritesPool * @callback CB_AudioFileSpritesPool.executeFunctionAll_ON_FINISH_CALLBACK * @param {array} array - An array with all the items which were being looped. * @param {integer} itemsAffected - The number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null). * @param {integer} delayMaximum - The maximum \"delay\" used. */ /** * Alias for {@link CB_AudioFileSpritesPool#executeFunctionAllSprites}. * @function CB_AudioFileSpritesPool#executeAllSprites * @see {@link CB_AudioFileSpritesPool#executeFunctionAllSprites} */ /** * Alias for {@link CB_AudioFileSpritesPool#executeFunctionAllSprites}. * @function CB_AudioFileSpritesPool#forEachSprite * @see {@link CB_AudioFileSpritesPool#executeFunctionAllSprites} */ /** * Executes a desired function for all the {@link CB_AudioFile} objects used by all the sound instances currently created of each sprite group. It calls the {@link CB_AudioFileSprites#executeFunctionAllSprites} method internally. * @function * @param {CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} functionEach - Used as the \"functionEach\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAllSprites} method internally. * @param {number|CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} [delayBetweenEach=0] - Used as the \"delayBetweenEach\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAllSprites} method internally. Note that each call to the {@link CB_AudioFileSprites#executeFunctionAllSprites} method will be performed sequentially one after the other, without adding a delay. * @param {boolean} [includeWithoutSpriteAssociated=false] - Used as the \"includeWithoutSpriteAssociated\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAllSprites} method internally. * @param {boolean} [avoidCancelled=false] - Used as the \"avoidCancelled\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAllSprites} method internally. * @param {boolean} [delayBetweenEachAffectsFirst=false] - Used as the \"delayBetweenEachAffectsFirst\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAllSprites} method internally. Internal usage only recommended. Note that each call to the {@link CB_AudioFileSprites#executeFunctionAllSprites} method will be performed sequentially one after the other, without adding a delay. * @param {CB_AudioFileSpritesPool.executeFunctionAll_ON_FINISH_CALLBACK} [functionFinish] - Function that will be called for when it has finished looping all the items. The first parameter will be the array containing all the items which were looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. * @returns {integer} It will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the {@link CB_AudioFile} objects used by the sound instances that belong to the sprites of each sprites group). Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function. * @todo Think about implementing a \"returnSetTimeoutsArray\" or similar (as in {@link CB_AudioFileSprites#executeFunctionAllSprites}). * @todo Think about consider executing only one by one (now it will loop {@link CB_AudioFile} objects from different sprites groups simultaneously). */ CB_AudioFileSpritesPool.prototype.executeFunctionAllSprites = CB_AudioFileSpritesPool.prototype.executeAllSprites = CB_AudioFileSpritesPool.prototype.forEachSprite = function(functionEach, delayBetweenEach, includeWithoutSpriteAssociated, avoidCancelled, delayBetweenEachAffectsFirst, functionFinish) { var spritesGroups = 0; for (var spritesGroupId in this.audioFileSprites) { spritesGroups++; } //Counts the number of sprites groups. var functionFinishLoopTimes = 0; var functionFinishLoop = function(array, itemsAffected, delay) { functionFinishLoopTimes++; for (var x = 0; x &lt; itemsAffected.length; x++) { arrayAllItems[arrayAllItems.length] = itemsAffected[x]; } //If it is the last time, calls the finish function: if (spritesGroups === functionFinishLoopTimes &amp;&amp; typeof(functionFinish) === \"function\") { functionFinish.call(arrayAllItems, arrayAllItems, performed, delay); } }; var arrayAllItems = []; var performed = 0; for (var spritesGroupId in this.audioFileSprites) { performed += this.audioFileSprites[spritesGroupId].executeFunctionAllSprites(functionEach, delayBetweenEach, includeWithoutSpriteAssociated, avoidCancelled, false, delayBetweenEachAffectsFirst, functionFinishLoop); //The desired delay (if any) will only start affecting after the first call. } return performed; } /** * Cleans the arrays of the {@link CB_AudioFile} objects (taking off the undefined or null ones) which is in the {@link CB_AudioFileCache#audioFiles} property used by each {@link CB_AudioFileSprites} object, just keeping the valid ones and clearing (destroying and removing) the others. For performance purposes. Uses the {@link CB_AudioFileSprites#clearAudioFiles} method internally. Internal usage only recommended. * @function * @param {boolean} [avoidCallingCheckCacheLoaded=false] - Used as the \"avoidCallingCheckCacheLoaded\" parameter when calling the {@link CB_AudioFileSprites#clearAudioFiles} method internally. * @returns {array} Returns an object whose each property name is the sprites group ID and each value is the returning value of calling internally the {@link CB_AudioFileSprites#clearAudioFiles} method. */ CB_AudioFileSpritesPool.prototype.clearAudioFiles = function(avoidCallingCheckCacheLoaded) { var audioFiles = {}; for (var spritesGroupId in this.audioFileSprites) { audioFiles[spritesGroupId] = this.audioFileSprites[spritesGroupId].clearAudioFiles(avoidCallingCheckCacheLoaded); } return audioFiles; } /** * Tries to purge the audio file cache of each {@link CB_AudioFileSprites} object until it reaches a desired number of {@link CB_AudioFile} objects internally (set in the {@link CB_AudioFileCache#audioFiles} property), by removing and destroying some of the current {@link CB_AudioFile} objects. Note that the desired number is for each {@link CB_AudioFileSprites} object and not a global number. For performance purposes. Uses the {@link CB_AudioFileSprites#purge} method internally. * @function * @param {integer} desiredNumber - Used as the \"desiredNumber\" parameter when calling the {@link CB_AudioFileSprites#purge} method internally. Note that the desired number is for each {@link CB_AudioFileSprites} object and not a global number. * @param {boolean} [setAsMinimumAudioFiles=false] - Used as the \"setAsMinimumAudioFiles\" parameter when calling the {@link CB_AudioFileSprites#purge} method internally. * @param {boolean} [includePlaying=false] - Used as the \"includePlaying\" parameter when calling the {@link CB_AudioFileSprites#purge} method internally. * @param {boolean} [stopSounds=false] - Used as the \"stopSounds\" parameter when calling the {@link CB_AudioFileSprites#purge} method internally. * @param {array} [statuses=Array({@link CB_AudioFile.LOADING}, {@link CB_AudioFile.UNCHECKED}, {@link CB_AudioFile.CHECKING}, {@link CB_AudioFile.LOADED})] - Used as the \"statuses\" parameter when calling the {@link CB_AudioFileSprites#purge} method internally. * @returns {integer} Returns the number of {@link CB_AudioFile} objects removed. */ CB_AudioFileSpritesPool.prototype.purge = function(desiredNumber, setAsMinimumAudioFiles, includePlaying, stopSounds, statuses) { var objectsRemoved = 0; for (var spritesGroupId in this.audioFileSprites) { objectsRemoved += this.audioFileSprites[spritesGroupId].purge(desiredNumber, setAsMinimumAudioFiles, includePlaying, stopSounds, statuses); } return objectsRemoved; } /** * Tells whether a desired {@link CB_AudioFile} object is free (it is in the {@link CB_AudioFileCache#audioFilesFree} property of any {@link CB_AudioFileSprites} object) or not, by its identifier. A free {@link CB_AudioFile} object is an object which is not being used and it is available to be used. Uses the {@link CB_AudioFileSprites#isAudioFileFree} method internally. * @function * @param {string} id - Used as the \"id\" parameter when calling the {@link CB_AudioFileSprites#isAudioFileFree} method internally. * @returns {boolean} Returns whether a desired {@link CB_AudioFile} object is free (it is in the {@link CB_AudioFileCache#audioFilesFree} property of any {@link CB_AudioFileSprites} object) or not, by its identifier. A free {@link CB_AudioFile} object is an object which is not being used and it is available to be used. */ CB_AudioFileSpritesPool.prototype.isAudioFileFree = function(id) { for (var spritesGroupId in this.audioFileSprites) { if (this.audioFileSprites[spritesGroupId].isAudioFileFree(id)) { return true; } } return false; } /** * Clears the sound instances (created by the {@link CB_AudioFileCache#play} method) which have been cancelled. Uses the {@link CB_AudioFileSprites#clearSoundInstances} method internally. * @function * @param {boolean} [clearWithObjectAssociated=false] - Used as the \"clearWithObjectAssociated\" parameter when calling the {@link CB_AudioFileSprites#clearSoundInstances} method internally. * @returns {integer} Returns the number of cleared sound instances. */ CB_AudioFileSpritesPool.prototype.clearSoundInstances = function(clearWithObjectAssociated) { var cleared = 0; for (var spritesGroupId in this.audioFileSprites) { cleared += this.audioFileSprites[spritesGroupId].clearSoundInstances(clearWithObjectAssociated); } return cleared; } /** * Cancels (to prevent they start playing) or enables all sound instances (created by the {@link CB_AudioFileCache#play} method). Uses the {@link CB_AudioFileSprites#cancelSoundInstances} method internally. * @function * @param {boolean} [cancel=false] - Used as the \"cancel\" parameter when calling the {@link CB_AudioFileSprites#cancelSoundInstances} method internally. * @param {boolean} [affectWithObjectAssociated=false] - Used as the \"affectWithObjectAssociated\" parameter when calling the {@link CB_AudioFileSprites#cancelSoundInstances} method internally. * @returns {integer} Returns the number of sound instances modified. */ CB_AudioFileSpritesPool.prototype.cancelSoundInstances = function(cancel, affectWithObjectAssociated) { var performed = 0; for (var spritesGroupId in this.audioFileSprites) { performed += this.audioFileSprites[spritesGroupId].cancelSoundInstances(cancel, affectWithObjectAssociated); } return performed; } /** * Cancels (to prevent it starts playing) or enables a sound instance (created by the {@link CB_AudioFileCache#play} method), by its identifier. Uses the {@link CB_AudioFileSprites#cancelSoundInstance} method internally. * @function * @param {integer} soundInstanceId - Used as the \"soundInstanceId\" parameter when calling the {@link CB_AudioFileSprites#cancelSoundInstance} method internally. * @param {boolean} [cancel=false] - Used as the \"cancel\" parameter when calling the {@link CB_AudioFileSprites#cancelSoundInstance} method internally. * @param {boolean} [affectWithObjectAssociated=false] - Used as the \"affectWithObjectAssociated\" parameter when calling the {@link CB_AudioFileSprites#cancelSoundInstance} method internally. * @returns {boolean} Returns true if the sound instance has been modified or false otherwise. */ CB_AudioFileSpritesPool.prototype.cancelSoundInstance = function(soundInstanceId, cancel, affectWithObjectAssociated) { for (var spritesGroupId in this.audioFileSprites) { if (this.audioFileSprites[spritesGroupId].cancelSoundInstance(soundInstanceId, cancel, affectWithObjectAssociated)) { return true; } } return false; } /** * Gets the {@link CB_AudioFile} object associated to a given sound instance ID (created by the {@link CB_AudioFileCache#play} method), if any, or null otherwise. Uses the {@link CB_AudioFileSprites#getAudioFileBySoundInstanceId} method internally. * @function * @param {integer} soundInstanceId - Used as the \"soundInstanceId\" parameter when calling the {@link CB_AudioFileSprites#getAudioFileBySoundInstanceId} method internally. * @param {boolean} [avoidCancelled=false] - Used as the \"avoidCancelled\" parameter when calling the {@link CB_AudioFileSprites#getAudioFileBySoundInstanceId} method internally. * @returns {CB_AudioFile|null} Returns the {@link CB_AudioFile} object associated to a given sound instance ID, if any, or null otherwise. */ CB_AudioFileSpritesPool.prototype.getAudioFileBySoundInstanceId = function(soundInstanceId, avoidCancelled) { var audioFile; for (var spritesGroupId in this.audioFileSprites) { audioFile = this.audioFileSprites[spritesGroupId].getAudioFileBySoundInstanceId(soundInstanceId, avoidCancelled); if (typeof(audioFile) !== \"undefined\" &amp;&amp; audioFile !== null) { return audioFile; } } return null; } /** * Alias for {@link CB_AudioFileSpritesPool#executeFunctionAll}. * @function CB_AudioFileSpritesPool#executeAll * @see {@link CB_AudioFileSpritesPool#executeFunctionAll} */ /** * Alias for {@link CB_AudioFileSpritesPool#executeFunctionAll}. * @function CB_AudioFileSpritesPool#forEach * @see {@link CB_AudioFileSpritesPool#executeFunctionAll} */ /** * Performs a desired action, using the provided function, on all the existing {@link CB_AudioFile} objects or on the desired ones (if provided). Uses the {@link CB_AudioFileSprites#executeFunctionAll} method internally. * @function * @param {CB_Arrays.CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} functionEach - Used as the \"functionEach\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAll} method internally. * @param {number|CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} [delayBetweenEach=0] - Used as the \"delayBetweenEach\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAll} method internally. Note that each call to the {@link CB_AudioFileSprites#executeFunctionAll} method will be performed sequentially one after the other, without adding a delay. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAll} method internally. * @param {boolean} [returnArrayOfSetTimeoutsArray=false] - If it is set to false, it will return the number of calls to the \"functionEach\" function that were performed. Otherwise, if it is set to true, it will return a numeric array and each value (which will belong to each sprites group) will be another numeric array with a {@link CB_AudioFileCache.executeFunctionAll_OBJECT} object for each {@link CB_AudioFile} of that sprites group. * @param {boolean} [delayBetweenEachAffectsFirst=false] - Used as the \"delayBetweenEachAffectsFirst\" parameter when calling the {@link CB_AudioFileSprites#executeFunctionAll} method internally. Note that each call to the {@link CB_AudioFileSprites#executeFunctionAll} method will be performed sequentially one after the other, without adding a delay. * @param {CB_AudioFileSpritesPool.executeFunctionAll_ON_FINISH_CALLBACK} [functionFinish] - Function that will be called for when it has finished looping all the items. The first parameter will be the array containing all the items which were looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. * @returns {integer|array} If the \"returnArrayOfSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed. Otherwise, if the \"returnArrayOfSetTimeoutsArray\" is set to true, it will return a numeric array and each value will be another numeric array with a {@link CB_AudioFileCache.executeFunctionAll_OBJECT} object for each {@link CB_AudioFile} given. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function. * @todo Think about consider executing only one by one (now it will loop {@link CB_AudioFile} objects from different sprites groups simultaneously). */ CB_AudioFileSpritesPool.prototype.executeFunctionAll = CB_AudioFileSpritesPool.prototype.executeAll = CB_AudioFileSpritesPool.prototype.forEach = function(functionEach, delayBetweenEach, audioFiles, returnArrayOfSetTimeoutsArray, delayBetweenEachAffectsFirst, functionFinish) { var spritesGroups = 0; for (var spritesGroupId in this.audioFileSprites) { spritesGroups++; } //Counts the number of sprites groups. var functionFinishLoopTimes = 0; var functionFinishLoop = function(array, itemsAffected, delay) { functionFinishLoopTimes++; for (var x = 0; x &lt; itemsAffected.length; x++) { arrayAllItems[arrayAllItems.length] = itemsAffected[x]; } //If it is the last time, calls the finish function: if (spritesGroups === functionFinishLoopTimes &amp;&amp; typeof(functionFinish) === \"function\") { functionFinish.call(arrayAllItems, arrayAllItems, performed, delay); } }; var arrayAllItems = []; if (returnArrayOfSetTimeoutsArray) { var arrayOfSetTimeoutsObjects = []; for (var spritesGroupId in this.audioFileSprites) { arrayOfSetTimeoutsObjects[arrayOfSetTimeoutsObjects.length] = this.audioFileSprites[spritesGroupId].executeFunctionAll(functionEach, delayBetweenEach, audioFiles, true, delayBetweenEachAffectsFirst, functionFinishLoop); //The desired delay (if any) will only start affecting after the first call. } return arrayOfSetTimeoutsObjects; } else { var performed = 0; for (var spritesGroupId in this.audioFileSprites) { performed += this.audioFileSprites[spritesGroupId].executeFunctionAll(functionEach, delayBetweenEach, audioFiles, false, delayBetweenEachAffectsFirst, functionFinishLoop); //The desired delay (if any) will only start affecting after the first call. } return performed; } } /** * Destroys all the {@link CB_AudioFile} objects and frees memory, by calling {@link CB_AudioFile#destructor}(stopSounds, false, true). Uses the {@link CB_AudioFileSprites#destroyAll} method internally. * @function * @param {boolean} [stopSounds=false] - Used as the \"stopSounds\" parameter when calling the {@link CB_AudioFileSprites#destroyAll} method internally. * @returns {integer} Returns the number of {@link CB_AudioFile} objects whose {@link CB_AudioFile#destructor} has been called. */ CB_AudioFileSpritesPool.prototype.destroyAll = function(stopSounds) { var destroyed = 0; for (var spritesGroupId in this.audioFileSprites) { destroyed += this.audioFileSprites[spritesGroupId].destroyAll(stopSounds); } return destroyed; } /** * Callback function used by the {@link CB_AudioFileSpritesPool#checkPlayingAll} method that will be called when all the process was performed successfully. * @memberof CB_AudioFileSpritesPool * @callback CB_AudioFileSpritesPool.checkPlayingAll_CALLBACK_OK * @param {integer} performedActions - The number of {@link CB_AudioFile} objects that can be played. * @param {integer} uncheckedObjects - The number of {@link CB_AudioFile} objects that needed to be checked before calling this method. */ /** * Callback function used by the {@link CB_AudioFileSpritesPool#checkPlayingAll} method that will be called when not all was performed successfully. * @memberof CB_AudioFileSpritesPool * @callback CB_AudioFileSpritesPool.checkPlayingAll_CALLBACK_ERROR * @param {Object} errorsObject - Object whose property names are the ID of each sprites group or \"GENERAL_ERROR\" if the error is not related to any sprites group and their value will be a {@link CB_AudioFileSpritesPool.checkPlayingAll_CALLBACK_ERROR_OBJECT} object. * @param {integer} performedActions - The number of {@link CB_AudioFile} objects that can be played). * @param {integer|undefined} uncheckedObjects - The number of {@link CB_AudioFile} objects that needed to be checked before calling this method (it will be undefined if it could not be determined). */ /** * An object with errors, used by the {@link CB_AudioFileSpritesPool.checkPlayingAll_CALLBACK_ERROR} callback (used by the {@link CB_AudioFileSpritesPool#checkPlayingAll} method). * @memberof CB_AudioFileSpritesPool * @typedef {Object} CB_AudioFileSpritesPool.checkPlayingAll_CALLBACK_ERROR_OBJECT * @property {string} error - A string describing the error (if it was possible to be determined). * @property {integer} checked - The number of {@link CB_AudioFile} objects that can be played. * @property {integer|undefined} needed - The number of {@link CB_AudioFile} objects that needed to be checked before calling this method (it will be undefined if it could not be determined). */ /** * Checks whether each {@link CB_AudioFile} object whose {@link CB_AudioFile#getStatus} method returns the \"unchecked\" value (which belongs to the value of the {@link CB_AudioFile#UNCHECKED} property) can be played or not. After checking, if the audio can be played, the status of the {@link CB_AudioFile} object will get the value of {@link CB_AudioFile.LOADED}. Otherwise, if it cannot be played, the status of the {@link CB_AudioFile} object will get the value of {@link CB_AudioFile.FAILED}. If a {@link CB_AudioFile} object cannot be played and it is determined necessary, it will try to reload it internally (by calling the {@link CB_AudioFileCache#removeAudioFile} method). It will call the {@link CB_AudioFileCache#clearAudioFiles} method internally after finishing each call to the {@link CB_AudioFileSprites#checkPlayingAll} method. Uses the {@link CB_AudioFileSprites#checkPlayingAll} method internally. Recommended to be called through a user-driven event (as onClick, onTouch, etc.). * @function * @param {CB_AudioFileSpritesPool.checkPlayingAll_CALLBACK_OK} [callbackOk] - A function which will be called if all the {@link CB_AudioFile} objects whose {@link CB_AudioFile#getStatus} method returned the \"unchecked\" value (which belongs to the value of the {@link CB_AudioFile#UNCHECKED} property) could finally be checked successfully and all can be played, being \"this\" the {@link CB_AudioFileSpritesPool} object itself. * @param {CB_AudioFileSpritesPool.checkPlayingAll_CALLBACK_ERROR} [callbackError] - A function which will be called if not all the {@link CB_AudioFile} objects whose {@link CB_AudioFile#getStatus} method returned the \"unchecked\" value (which belongs to the value of the {@link CB_AudioFile#UNCHECKED} property) could finally be checked successfully and any cannot be played, being \"this\" the {@link CB_AudioFileSpritesPool} object itself. This function will be called immediately if the method was previously called and it is still running currently. * @param {boolean} [ignoreQueue=false] - Used as the \"ignoreQueue\" parameter when calling the {@link CB_AudioFileSprites#checkPlayingAll} method internally. * @param {boolean} [ignoreStatus=false] - If it is set to false and the sprites pool object is loaded (the {@link CB_AudioFileSpritesPool#getStatus} method returns the value set in the {@link CB_AudioFileSpritesPool.LOADED} property), it will exit returning an error. Otherwise, if it is set to true, it will ignore the current sprites pool object status. * @returns {integer} Returns the number of {@link CB_AudioFile} objects whose status belonged to the \"unchecked\" value (the value of the {@link CB_AudioFile#UNCHECKED} property) before the execution of this method. It will return 0 (zero) if the method is tried to be executed while there is another previous call of it still running. It will also return 0 (zero) if the status of audio sprites pool is neither loaded (the {@link CB_AudioFileSpritesPool#getStatus} method does not returns the value set in the {@link CB_AudioFileSpritesPool.LOADED} property) nor unchecked (the {@link CB_AudioFileSpritesPool#status} method does not return the value set in the {@link CB_AudioFileSpritesPool.UNCHECKED} property). */ CB_AudioFileSpritesPool.prototype.checkPlayingAll = function(callbackOk, callbackError, ignoreQueue, ignoreStatus) { var errorMessage = \"\"; if (this._checkPlayingAllPerforming) { errorMessage = \"Method checkPlayingAll is being processed. Cannot be called again until it finishes.\"; } else if (!ignoreStatus &amp;&amp; this.getStatus() !== CB_AudioFileSpritesPool.LOADED &amp;&amp; this.getStatus() !== CB_AudioFileSpritesPool.UNCHECKED) { errorMessage = \"Sprites pool is not loaded.\"; } if (errorMessage !== \"\") { if (typeof(callbackError) === \"function\") { callbackError.call ( this, { \"GENERAL_ERROR\" : { \"error\" : errorMessage, \"checked\" : 0 } }, 0, undefined ); } return 0; } this._checkPlayingAllPerforming = true; clearInterval(this._checkPlayingAllInterval); var uncheckedObjects = 0; var failed = 0; var succeeded = 0; var needed = 0; var objectsChecked = 0; var errorsChecking = {}; for (var spritesGroupId in this.audioFileSprites) { uncheckedObjects += this.audioFileSprites[spritesGroupId].checkPlayingAll ( function(performedActions) //callbackOk: { objectsChecked += performedActions; succeeded++; }, function(error, performedActions, needed) //callbackError: { objectsChecked += performedActions; failed++; errorsChecking[spritesGroupId] = {}; errorsChecking[spritesGroupId].error = error; errorsChecking[spritesGroupId].checked = performedActions; errorsChecking[spritesGroupId].needed = needed; }, ignoreQueue //ignoreQueue. ); needed++; } var that = this; this._checkPlayingAllInterval = setInterval ( function() { if (succeeded &gt;= needed) { if (typeof(callbackOk) === \"function\") { callbackOk.call(that, objectsChecked, uncheckedObjects); } clearInterval(that._checkPlayingAllInterval); that._checkPlayingAllPerforming = false; } else if (succeeded + failed &gt;= needed) { if (typeof(callbackError) === \"function\") { callbackError.call(that, errorsChecking, objectsChecked, uncheckedObjects); } clearInterval(that._checkPlayingAllInterval); that._checkPlayingAllPerforming = false; } } , 100); return uncheckedObjects; } /** * Tries to play all the {@link CB_AudioFile} objects by calling their {@link CB_AudioFile#play} method internally. If a {@link CB_AudioFile} object cannot be played and it is determined necessary, it will try to reload it internally (by calling the {@link CB_AudioFileCache#removeAudioFile} method). Uses the {@link CB_AudioFileSprites#playAll} method internally. * @function * @param {number} [startAt=0 | {@link CB_AudioFile_API.WAAPI#lastStartAt} | {@link CB_AudioFile_API.SM2#lastStartAt} | {@link CB_AudioFile_API.ACMP#lastStartAt} | {@link CB_AudioFile_API.AAPI#lastStartAt} | stopAt] - Used as the \"startAt\" parameter when calling the {@link CB_AudioFileSprites#playAll} method internally. * @param {number} [stopAt={@link CB_AudioFile_API.WAAPI#getDuration}() | {@link CB_AudioFile_API.SM2#getDuration}() | {@link CB_AudioFile_API.ACMP#getDuration}() | {@link CB_AudioFile_API.AAPI#getDuration}()] - Used as the \"stopAt\" parameter when calling the {@link CB_AudioFileSprites#playAll} method internally. * @param {boolean} [loop={@link CB_AudioFile#loop}] - Used as the \"loop\" parameter when calling the {@link CB_AudioFileSprites#playAll} method internally. * @param {number} [volume=CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME] - Used as the \"volume\" parameter when calling the {@link CB_AudioFileSprites#playAll} method internally. * @param {boolean} [avoidDelayedPlay=false] - Used as the \"avoidDelayedPlay\" parameter when calling the {@link CB_AudioFileSprites#playAll} method internally. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - Used as the \"allowedRecursiveDelay\" parameter when calling the {@link CB_AudioFileSprites#playAll} method internally. * @param {function} [onPlayStart] - Used as the \"onPlayStart\" parameter when calling the {@link CB_AudioFileSprites#playAll} method internally. * @param {function} [onStop] - Used as the \"onStop\" parameter when calling the {@link CB_AudioFileSprites#playAll} method internally. * @param {boolean} [includingPlaying=false] - Used as the \"includingPlaying\" parameter when calling the {@link CB_AudioFileSprites#playAll} method internally. * @returns {integer} Returns the number of {@link CB_AudioFile} objects whose {@link CB_AudioFile#play} method did not return the value of \"-1\" (this does not mean necessarily that they could be played successfully). */ CB_AudioFileSpritesPool.prototype.playAll = function(startAt, stopAt, loop, volume, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onStop, includingPlaying) { var played = 0; for (var spritesGroupId in this.audioFileSprites) { played += this.audioFileSprites[spritesGroupId].playAll(startAt, stopAt, loop, volume, avoidDelayedPlay, allowedRecursiveDelay, onPlayStart, onStop, includingPlaying); } return played; } /** * Tries to stops all the existing {@link CB_AudioFile} objects or the desired ones (if provided), which are being played, by calling their {@link CB_AudioFile#stop} method internally. Uses the {@link CB_AudioFileSprites#stopAll} method internally. * @function * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileSprites#stopAll} method internally. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#stop} method that were performed. */ CB_AudioFileSpritesPool.prototype.stopAll = function(audioFiles) { var performed = 0; for (var spritesGroupId in this.audioFileSprites) { performed += this.audioFileSprites[spritesGroupId].stopAll(audioFiles); } return performed; } /** * Plays silently and stops all {@link CB_AudioFile} objects after a desired time. It can be useful for some clients which need the {@link CB_AudioFile#play} method to be called through a user-driven event (as onClick, onTouch, etc.). Internally, it calls {@link CB_AudioFileCache#playAll}(0, null, false, 0, true, null, null, null, includingPlaying) and, after a desired delay, calls the {@link CB_AudioFileCache#stopAll} method. Uses the {@link CB_AudioFileSprites#playAndStopAll} method internally. * @function * @param {boolean} [includingPlaying=false] - Used as the \"includingPlaying\" parameter when calling the {@link CB_AudioFileSprites#playAndStopAll} method internally. * @param {number} [delayBeforeStop=100] - Used as the \"delayBeforeStop\" parameter when calling the {@link CB_AudioFileSprites#playAndStopAll} method internally. * @returns {integer} Returns the number of {@link CB_AudioFile} objects whose {@link CB_AudioFile#play} method did not return the value of \"-1\" (this does not mean necessarily that they could be played successfully). */ CB_AudioFileSpritesPool.prototype.playAndStopAll = function(includingPlaying, delayBeforeStop) { var played = 0; for (var spritesGroupId in this.audioFileSprites) { played += this.audioFileSprites[spritesGroupId].playAndStopAll(includingPlaying, delayBeforeStop); } return played; } /** * Tries to pause all the existing {@link CB_AudioFile} objects or the desired ones (if provided), which are being played, by calling their {@link CB_AudioFile#pause} method internally. Uses the {@link CB_AudioFileSprites#pauseAll} method internally. * @function * @param {function} [onPause] - Used as the \"onPause\" parameter when calling the {@link CB_AudioFileSprites#pauseAll} method internally. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileSprites#pauseAll} method internally. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#pause} method that were performed. */ CB_AudioFileSpritesPool.prototype.pauseAll = function(onPause, audioFiles) { var performed = 0; for (var spritesGroupId in this.audioFileSprites) { performed += this.audioFileSprites[spritesGroupId].pauseAll(onPause, audioFiles); } return performed; } /** * Resumes all the existing {@link CB_AudioFile} objects or the desired ones (if provided), which are paused (and not stopped). Can be focused on just one sprite ID if desired. Uses the {@link CB_AudioFileSprites#resumeAll} method internally. Internal usage only recommended. To resume a sprite, better use the {@link CB_AudioFileSprites#resumeSprite} method instead. * @function * @param {boolean} [loop={@link CB_AudioFile#loop}] - Used as the \"loop\" parameter when calling the {@link CB_AudioFileSprites#resumeAll} method internally. * @param {boolean} [allowedRecursiveDelay={@link CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT}] - Used as the \"allowedRecursiveDelay\" parameter when calling the {@link CB_AudioFileSprites#resumeAll} method internally. * @param {boolean} [allowedRecursiveDelaySkipping=stopAt-startAt] - Used as the \"allowedRecursiveDelaySkipping\" parameter when calling the {@link CB_AudioFileSprites#resumeAll} method internally. * @param {function} [onPlayStart] - Used as the \"onPlayStart\" parameter when calling the {@link CB_AudioFileSprites#resumeAll} method internally. * @param {function} [onStop] - Used as the \"onStop\" parameter when calling the {@link CB_AudioFileSprites#resumeAll} method internally. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileSprites#resumeAll} method internally. * @param {string} [spriteId='_WITHOUT_SPRITE_ASSOCIATED'] - Used as the \"spriteId\" when calling the {@link CB_AudioFileSprites#resumeAll} method internally. Internal usage only recommended. * @returns {Object} Returns an object whose property names will be the ID of each sprites group and their value will be the returning value of the internal call to the {@link CB_AudioFileSprites#resumeAll} method. */ CB_AudioFileSpritesPool.prototype.resumeAll = function(loop, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, audioFiles, spriteId) { var soundInstances = {}; for (var spritesGroupId in this.audioFileSprites) { soundInstances[spritesGroupId] = this.audioFileSprites[spritesGroupId].resumeAll(loop, allowedRecursiveDelay, allowedRecursiveDelaySkipping, onPlayStart, onStop, audioFiles, spriteId); } return soundInstances; } /** * Mutes all the existing {@link CB_AudioFile} objects or the desired ones (if provided). Uses the {@link CB_AudioFileSprites#muteAll} method internally. * @function * @param {function} [onMute] - Used as the \"onMute\" parameter when calling the {@link CB_AudioFileSprites#muteAll} method internally. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileSprites#muteAll} method internally. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#mute} method that were performed. */ CB_AudioFileSpritesPool.prototype.muteAll = function(onMute, audioFiles) { var performed = 0; for (var spritesGroupId in this.audioFileSprites) { performed += this.audioFileSprites[spritesGroupId].muteAll(onMute, audioFiles); } return performed; } /** * Unmutes all the existing {@link CB_AudioFile} objects or the desired ones (if provided). Uses the {@link CB_AudioFileSprites#unmuteAll} method internally. * @function * @param {function} [onUnmute] - Used as the \"onUnmute\" parameter when calling the {@link CB_AudioFileSprites#unmuteAll} method internally. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileSprites#unmuteAll} method internally. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#unmute} method that were performed. */ CB_AudioFileSpritesPool.prototype.unmuteAll = function(onUnmute, audioFiles) { var performed = 0; for (var spritesGroupId in this.audioFileSprites) { performed += this.audioFileSprites[spritesGroupId].unmuteAll(onUnmute, audioFiles); } return performed; } /** * Sets the same volume for all the existing {@link CB_AudioFile} objects or the desired ones (if provided). Uses the {@link CB_AudioFileSprites#setVolumeAll} method internally. * @function * @param {number} [volume={@link CB_Speaker.getVolume()} | {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME}] - Used as the \"volume\" parameter when calling the {@link CB_AudioFileSprites#setVolumeAll} method internally. * @param {boolean} [forceSetVolumeProperty=false] - Used as the \"forceSetVolumeProperty\" parameter when calling the {@link CB_AudioFileSprites#setVolumeAll} method internally. * @param {function} [onSetVolume] - Used as the \"onSetVolume\" parameter when calling the {@link CB_AudioFileSprites#setVolumeAll} method internally. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileSprites#setVolumeAll} method internally. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#setVolume} method that were performed internally. */ CB_AudioFileSpritesPool.prototype.setVolumeAll = function(volume, forceSetVolumeProperty, onSetVolume, audioFiles) { var performed = 0; for (var spritesGroupId in this.audioFileSprites) { performed += this.audioFileSprites[spritesGroupId].setVolumeAll(volume, forceSetVolumeProperty, onSetVolume, audioFiles); } return performed; } /** * Callback function used by the {@link CB_AudioFileSpritesPool#setAudioAPIAll} method that will be called when all the process was performed successfully. * @memberof CB_AudioFileSpritesPool * @callback CB_AudioFileSpritesPool.setAudioAPIAll_CALLBACK_OK * @param {integer} objectsChangedAPI - The number of {@link CB_AudioFile} objects that actually changed its audio API. * @param {integer} performedActions - The number of {@link CB_AudioFile} objects that ended with a desired audio API, including those ones which were already using it. * @param {integer} actionsNeeded - The total number of {@link CB_AudioFile} objects that were considered to perform the action (it will be undefined if it could not be determined). */ /** * Callback function used by the {@link CB_AudioFileCache#setAudioAPIAll} method that will be called when any error happened. * @memberof CB_AudioFileSpritesPool * @callback CB_AudioFileSpritesPool.setAudioAPIAll_CALLBACK_ERROR * @param {Object} errorsObject - Object whose property names are the ID of each sprites group or \"GENERAL_ERROR\" if the error is not related to any sprites group and their value will be a {@link CB_AudioFileSpritesPool.setAudioAPIAll_CALLBACK_ERROR_OBJECT} object each. * @param {integer} errorsHappened - The number of errors that happened, which could be greater than 1 if more than one internal call to the {@link CB_AudioFile#setAudioAPI} method failed. * @param {integer} objectsChangedAPI - The number of {@link CB_AudioFile} objects that actually changed its audio API. * @param {integer} performedActions - The number of {@link CB_AudioFile} objects that ended with a desired audio API, including those ones which were already using it. * @param {integer|undefined} actionsNeeded - The total number of {@link CB_AudioFile} objects that were considered to perform the action (it will be undefined if it could not be determined). */ /** * Object used by the {@link CB_AudioFileSpritesPool.setAudioAPIAll_CALLBACK_ERROR} callback. Unless it belongs to a general error, its information will only be regarding a certain sprites group. * @memberof CB_AudioFileSpritesPool * @typedef {Object} CB_AudioFileSpritesPool.setAudioAPIAll_CALLBACK_ERROR_OBJECT * @property {string} error - A string describing the error, if it was possible to be determined. * @property {integer} errors - The number of errors that happened, which could be greater than 1 if more than one internal call to the {@link CB_AudioFile#setAudioAPI} method failed. * @property {integer} changed - The number of objects that actually changed its audio API. * @property {integer} performed - The number of {@link CB_AudioFile} objects that ended with a desired audio API, including those ones which were already using it. * @property {integer|undefined} needed - The total number of {@link CB_AudioFile} objects that were considered to perform the action (it will be undefined if it could not be determined). */ /** * Tries to change the audio API for all the existing {@link CB_AudioFile} objects or the desired ones (if provided). This method is not allowed to be called if a previous call to it did not finish yet. The function defined in the \"callbackError\" parameter, if any, will be called immediately if the method was previously called and it is still running currently. Uses the {@link CB_AudioFileSprites#setAudioAPIAll} method internally. * @function * @param {array|string} preferredAPIs - Used as the \"preferredAPIs\" parameter when calling the {@link CB_AudioFileSprites#setAudioAPIAll} method internally. * @param {CB_AudioFileSpritesPool.setAudioAPIAll_CALLBACK_OK} [callbackOk] - Function that will be called when all the process was performed successfully, being \"this\" the {@link CB_AudioFileSpritesPool} object. * @param {CB_AudioFileSpritesPool.setAudioAPIAll_CALLBACK_ERROR} [callbackError] - Function that will be called when any error happened, being \"this\" the {@link CB_AudioFileSpritesPool} object. This function will be called immediately if the method was previously called and it is still running currently. * @param {boolean} [mandatory=false] - Used as the \"mandatory\" parameter when calling the {@link CB_AudioFileSprites#setAudioAPIAll} method internally. * @param {string} [forceReload=false] - Used as the \"forceReload\" parameter when calling the {@link CB_AudioFileSprites#setAudioAPIAll} method internally. * @param {array} [audioFiles={@link CB_AudioFileCache#audioFiles}] - Used as the \"audioFiles\" parameter when calling the {@link CB_AudioFileSprites#setAudioAPIAll} method internally. * @returns {integer} Returns the number of calls to the {@link CB_AudioFile#setAudioAPI} method that were performed. */ CB_AudioFileSpritesPool.prototype.setAudioAPIAll = function(preferredAPIs, callbackOk, callbackError, mandatory, forceReload, audioFiles, ignoreStatus) { var errorMessage = \"\"; if (this._setAudioAPIAllPerforming) { errorMessage = \"Method setAudioAPIAll is being processed. Cannot be called again until it finishes.\"; } else if (!ignoreStatus &amp;&amp; this.getStatus() !== CB_AudioFileSpritesPool.LOADED) { errorMessage = \"Sprites pool is not loaded.\"; } if (errorMessage !== \"\") { if (typeof(callbackError) === \"function\") { callbackError.call ( this, { \"GENERAL_ERROR\" : { \"error\" : errorMessage, \"errors\" : 1, \"changed\" : 0, \"performed\" : 0, \"needed\" : undefined } }, 1, 0, 0, undefined ); } return 0; } this._setAudioAPIAllPerforming = true; clearInterval(this._setAudioAPIAllInterval); var performedReturn = 0; var failed = 0; var succeeded = 0; var needed = 0; var objectsChanged = 0; var errorsChecking = {}; var errors = 0; var performed = 0; var neededTotal = 0; for (var spritesGroupId in this.audioFileSprites) { performedReturn += this.audioFileSprites[spritesGroupId].setAudioAPIAll ( preferredAPIs, //preferredAPIs. function(objectsChangedAPI, performedActions, actionsNeeded) //callbackOk: { objectsChanged += objectsChangedAPI; performed += performedActions; actionsNeeded = parseInt(actionsNeeded); //It could be undefined. neededTotal += actionsNeeded; succeeded++; }, function(error, errorsHappened, objectsChangedAPI, performedActions, actionsNeeded) //callbackError: { failed++; actionsNeeded = parseInt(actionsNeeded); //It could be undefined. errors += errorsHappened; objectsChanged += objectsChangedAPI; performed += performedActions; neededTotal += actionsNeeded; errorsChecking[spritesGroupId] = {}; errorsChecking[spritesGroupId].error = error; errorsChecking[spritesGroupId].errors = errorsHappened; errorsChecking[spritesGroupId].changed = objectsChangedAPI; errorsChecking[spritesGroupId].performed = performedActions; errorsChecking[spritesGroupId].needed = actionsNeeded; }, mandatory, //mandatory. forceReload, //forceReload. audioFiles //audioFiles ); needed++; } var that = this; this._setAudioAPIAllInterval = setInterval ( function() { if (succeeded &gt;= needed) { if (typeof(callbackOk) === \"function\") { callbackOk.call(that, objectsChanged, performed, neededTotal); } clearInterval(that._setAudioAPIAllInterval); that._setAudioAPIAllPerforming = false; } else if (succeeded + failed &gt;= needed) { if (typeof(callbackError) === \"function\") { callbackError.call(that, errorsChecking, errors, objectsChanged, performed, neededTotal); } clearInterval(that._setAudioAPIAllInterval); that._setAudioAPIAllPerforming = false; } } , 100); return performedReturn; } /** * Tells whether any of the {@link CB_AudioFile} objects is playing or not. Uses the {@link CB_AudioFileSprites#isPlaying} method internally. * @function * @returns {boolean} Returns whether any of the {@link CB_AudioFile} objects is playing or not. */ CB_AudioFileSpritesPool.prototype.isPlaying = function() { for (var spritesGroupId in this.audioFileSprites) { if (this.audioFileSprites[spritesGroupId].isPlaying()) { return true; } } return false; } /** * Tells the current number of free {@link CB_AudioFile} objects (the number of objects which are available and ready to use). Uses the {@link CB_AudioFileSprites#getAudioFilesFreeNumber} method internally. * @function * @returns {integer} Returns the current number of free {@link CB_AudioFile} objects (the number of objects which are available and ready to use). */ CB_AudioFileSpritesPool.prototype.getAudioFilesFreeNumber = function() { var number = 0; for (var spritesGroupId in this.audioFileSprites) { number += this.audioFileSprites[spritesGroupId].getAudioFilesFreeNumber(); } return number; } /** * Gets an object with arrays or a one-dimension array with all the {@link CB_AudioFile} objects. Uses the {@link CB_AudioFileSprites#getAudioFiles} method internally. * @function * @param {boolean} [copy=false] - Used as the \"copy\" parameter when calling the {@link CB_AudioFileSprites#getAudioFiles} method internally. * @param {boolean} [oneDimension=false] - If it is set to true, the method will return an array with all the {@link CB_AudioFile} objects. Otherwise, if it is set to false, the method will return an object whose property names will be the ID of each sprites group and their value will be an array with all the {@link CB_AudioFile} objects that belong to that sprites group. * @returns {Object|array} If the \"oneDimension\" parameter is set to true, returns an array with all the {@link CB_AudioFile} objects. Otherwise, if the \"oneDimension\" parameter is set to false, it will return an object whose property names will be the ID of each sprites group and their value will be an array with all the {@link CB_AudioFile} objects that belong to that sprites group. */ CB_AudioFileSpritesPool.prototype.getAudioFiles = function(copy, oneDimension) { var audioFiles; if (!oneDimension) { audioFiles = {}; for (var spritesGroupId in this.audioFileSprites) { audioFiles[spritesGroupId] = this.audioFileSprites[spritesGroupId].getAudioFiles(copy); } } else { audioFiles = []; var audioFilesSpritesGroup; var audioFilesSpritesGroupLength; var y = 0; var x = 0; for (var spritesGroupId in this.audioFileSprites) { audioFilesSpritesGroup = this.audioFileSprites[spritesGroupId].getAudioFiles(copy); audioFilesSpritesGroupLength = audioFilesSpritesGroup.length; for (x = 0; x &lt; audioFilesSpritesGroupLength; x++) { audioFiles[y++] = audioFilesSpritesGroup[x]; } } } return audioFiles; } /** * Gets an object with arrays or a one-dimension array with the free {@link CB_AudioFile} objects (the objects which are available and ready to use). Uses the {@link CB_AudioFileSprites#getAudioFilesFree} method internally. * @function * @param {boolean} [oneDimension=false] - If it is set to true, the method will return an array with the free {@link CB_AudioFile} objects. Otherwise, if it is set to false, the method will return an object whose property names will be the ID of each sprites group and their value will be an array with the free {@link CB_AudioFile} objects that belong to that sprites group. * @returns {Object|array} If the \"oneDimension\" parameter is set to true, returns an array with the free {@link CB_AudioFile} objects. Otherwise, if the \"oneDimension\" parameter is set to false, it will return an object whose property names will be the ID of each sprites group and their value will be an array with the free {@link CB_AudioFile} objects that belong to that sprites group. */ CB_AudioFileSpritesPool.prototype.getAudioFilesFree = function(oneDimension) { var audioFiles; if (!oneDimension) { audioFiles = {}; for (var spritesGroupId in this.audioFileSprites) { audioFiles[spritesGroupId] = this.audioFileSprites[spritesGroupId].getAudioFilesFree(); } } else { audioFiles = []; var audioFilesSpritesGroup; var audioFilesSpritesGroupLength; var y = 0; var x = 0; for (var spritesGroupId in this.audioFileSprites) { audioFilesSpritesGroup = this.audioFileSprites[spritesGroupId].getAudioFilesFree(); audioFilesSpritesGroupLength = audioFilesSpritesGroup.length; for (x = 0; x &lt; audioFilesSpritesGroupLength; x++) { audioFiles[y++] = audioFilesSpritesGroup[x]; } } } return audioFiles; } /** * Gets an object with arrays or a one-dimension array with the busy {@link CB_AudioFile} objects (the objects which are not available and ready to use). Uses the {@link CB_AudioFileSprites#getAudioFilesBusy} method internally. * @function * @param {boolean} [oneDimension=false] - If it is set to true, the method will return an array with the busy {@link CB_AudioFile} objects. Otherwise, if it is set to false, the method will return an object whose property names will be the ID of each sprites group and their value will be an array with the busy {@link CB_AudioFile} objects that belong to that sprites group. * @returns {Object|array} If the \"oneDimension\" parameter is set to true, returns an array with the busy {@link CB_AudioFile} objects. Otherwise, if the \"oneDimension\" parameter is set to false, it will return an object whose property names will be the ID of each sprites group and their value will be an array with the busy {@link CB_AudioFile} objects that belong to that sprites group. */ CB_AudioFileSpritesPool.prototype.getAudioFilesBusy = function(oneDimension) { var audioFiles; if (!oneDimension) { audioFiles = {}; for (var spritesGroupId in this.audioFileSprites) { audioFiles[spritesGroupId] = this.audioFileSprites[spritesGroupId].getAudioFilesBusy(); } } else { audioFiles = []; var audioFilesSpritesGroup; var audioFilesSpritesGroupLength; var y = 0; var x = 0; for (var spritesGroupId in this.audioFileSprites) { audioFilesSpritesGroup = this.audioFileSprites[spritesGroupId].getAudioFilesBusy(); audioFilesSpritesGroupLength = audioFilesSpritesGroup.length; for (x = 0; x &lt; audioFilesSpritesGroupLength; x++) { audioFiles[y++] = audioFilesSpritesGroup[x]; } } } return audioFiles; } /** * Tells the number of {@link CB_AudioFile} objects created. Uses the {@link CB_AudioFileSprites#getAudioFilesNumber} method internally. * @function * @param {boolean} [real=false] - Used as the \"real\" parameter when calling the {@link CB_AudioFileSprites#getAudioFilesNumber} method internally. * @returns {integer} Returns the number of {@link CB_AudioFile} objects created. */ CB_AudioFileSpritesPool.prototype.getAudioFilesNumber = function(real) { var number = 0; for (var spritesGroupId in this.audioFileSprites) { number += this.audioFileSprites[spritesGroupId].getAudioFilesNumber(real); } return number; } /** * Returns a number representing the percentage of the loading progress for the audio sprites pool object (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Uses the {@link CB_AudioFileSprites#getProgress} method internally. * @function * @param {boolean} [countLoadedObjects=false] - Used as the \"countLoadedObjects\" parameter when calling the {@link CB_AudioFileSprites#getProgress} method internally. * @param {boolean} [alsoUncheckedAndCheckingObjects=false] - Used as the \"alsoUncheckedAndCheckingObjects\" parameter when calling the {@link CB_AudioFileSprites#getProgress} method internally. * @returns {number} Returns a number representing the percentage of the loading progress for the audio sprites pool object (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. */ CB_AudioFileSpritesPool.prototype.getProgress = function(countLoadedObjects, alsoUncheckedAndCheckingObjects) { var progress = 0; var spritesGroups = 0; for (var spritesGroupId in this.audioFileSprites) { progress += this.audioFileSprites[spritesGroupId].getProgress(countLoadedObjects, alsoUncheckedAndCheckingObjects); spritesGroups++; } if (spritesGroups !== 0) { progress /= spritesGroups; } return progress; } /** * Gets the current status of the audio file sprites pool object. Uses the {@link CB_AudioFileSprites#getStatus} method internally. * @function * @returns {number} Returns the current status of the audio file sprites pool object. It is a number, affected by the returning value of the {@link CB_AudioFileSprites#getStatus} method of each {@link CB_AudioFileSprites} object used internally, which should match the value of the {@link CB_AudioFileCache.UNLOADED} (still unloaded), {@link CB_AudioFileCache.LOADING} (loading), {@link CB_AudioFileCache.UNCHECKED} (not checked by calling the {@link CB_AudioFileCache#checkPlayingAll} method yet), {@link CB_AudioFileCache.CHECKING} (being checked by the {@link CB_AudioFileCache#checkPlayingAll} method), {@link CB_AudioFileCache.LOADED} (loaded), {@link CB_AudioFileCache.FAILED} (failed loading or failed to play or by any other reason) or {@link CB_AudioFileCache.ABORTED} (aborted because it was destroyed with the \"destructor\" method) property. */ CB_AudioFileSpritesPool.prototype.getStatus = function() { var status = null; var allLoaded = false; var loaded = 0; var anyUnloaded = false; var anyLoading = false; var anyUnchecked = false; var anyChecking = false; var anyFailed = false; var anyAborted = false; for (var audioFileSpritesObject in this.audioFileSprites) { if (this.audioFileSprites[audioFileSpritesObject].getStatus() === CB_AudioFileCache.UNLOADED) { anyUnloaded = true; } else if (this.audioFileSprites[audioFileSpritesObject].getStatus() === CB_AudioFileCache.LOADING) { anyLoading = true; } else if (this.audioFileSprites[audioFileSpritesObject].getStatus() === CB_AudioFileCache.UNCHECKED) { anyUnchecked = true; } else if (this.audioFileSprites[audioFileSpritesObject].getStatus() === CB_AudioFileCache.CHECKING) { anyChecking = true; } else if (this.audioFileSprites[audioFileSpritesObject].getStatus() === CB_AudioFileCache.FAILED) { anyFailed = true; } else if (this.audioFileSprites[audioFileSpritesObject].getStatus() === CB_AudioFileCache.ABORTED) { anyAborted = true; } else { loaded++; } } if (anyUnloaded) { status = CB_AudioFileSpritesPool.UNLOADED; } else if (anyLoading) { status = CB_AudioFileSpritesPool.LOADING; } else if (anyUnchecked) { status = CB_AudioFileSpritesPool.UNCHECKED; } else if (anyChecking) { status = CB_AudioFileSpritesPool.CHECKING; } else if (anyFailed) { status = CB_AudioFileSpritesPool.FAILED; } else if (anyAborted) { status = CB_AudioFileSpritesPool.ABORTED; } if (status === null) { if (loaded &gt; 0) { status = CB_AudioFileSpritesPool.LOADED; } else if (this._aborted) { status = CB_AudioFileSpritesPool.ABORTED; } else { status = CB_AudioFileSpritesPool.UNLOADED; } } return status; } /** * Gets the current status of the audio file sprites pool object, as a string. * @function * @returns {string} Returns the current status of the audio file sprites pool object, as a string. Possible return values are \"UNLOADED\", \"LOADING\", \"UNCHECKED\", \"CHECKING\", \"LOADED\", \"FAILED\", \"ABORTED\" or \"UNKNOWN (UNKNOWN_STATUS)\" (where \"UNKNOWN_STATUS\" will be a returning value from the {@link CB_AudioFileSpritesPool#getStatus} method not recognized as any possible status). */ CB_AudioFileSpritesPool.prototype.getStatusString = function() { var status = this.getStatus(); var statuses = [ \"UNLOADED\", \"LOADING\", \"UNCHECKED\", \"CHECKING\", \"LOADED\", \"FAILED\", \"ABORTED\" ]; if (typeof(statuses[status]) !== \"undefined\") { return statuses[status]; } else { return \"UNKNOWN (\" + status + \")\"; } } /** * Calls the error function which should be set in the {@link CB_AudioFileSprites#onError} property (if any), being \"this\" the {@link CB_AudioFileSpritesPool} object itself. Internal usage only recommended. * @function * @param {string} [message] - The message describing the error that will be sent to the set {@link CB_AudioFileSprites#onError} function (if any) as the first and unique parameter. * @param {boolean} [ignorePreviousExecution=false] - If it is set to false, the function set in the {@link CB_AudioFileSprites#onError} property (if any) will only be called if it was not executed previously. * @returns {boolean} Returns true if the {@link CB_AudioFileSprites#onError} function could be called or false otherwise. */ CB_AudioFileSpritesPool.prototype.errorFunction = function(message, ignorePreviousExecution) { if (ignorePreviousExecution || !this._errorFunctionExecuted) { if (typeof(this.onError) === \"function\") { this._errorFunctionExecuted = true; this.onError.call(this, message); return true; } } return false; } × Search results Close "},"CrossBase_audiovisual_image_CB_GraphicSprites.js.html":{"id":"CrossBase_audiovisual_image_CB_GraphicSprites.js.html","title":"Source: CrossBase/audiovisual/image/CB_GraphicSprites.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/audiovisual/image/CB_GraphicSprites.js /** * @file Group of graphic sprites management (2D or 3D). Contains the {@link CB_GraphicSprites} class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * An object with the information that belongs to a sub-sprite (data which belongs to a certain source) used by a graphic sprite. * @example { id: \"my_subsprite_1\", src: \"path/to/image.gif\", srcType: CB_GraphicSprites.SRC_TYPES.IMAGE, srcLeft: 10, srcTop: 20, srcWidth: 64, srcHeight: 32, left: 10, top: 20, width: 64, height: 32, zIndex: 1, disabled: false, data: { datum_1: \"value_1\", datum_2: 2, datum_3: [ \"a\", \"b\", \"c\" ] } } * @memberof CB_GraphicSprites * @typedef {Object} CB_GraphicSprites.SUBSPRITE_OBJECT * @property {string|*} [id='CB_GraphicSprites.subSprite_' + CB_GraphicSprites._idSubSpriteUnique++] - Identifier of the sub-sprite. It should be unique. It must be a value which evaluates to true. By default, it is generated automatically (with an internal counter). * @property {*} [src=this.parent.src|\"\"] - Source of origin. Can be a path or identifier of an image, text, bitmap, 3D object, etc. They can be used for any kind of source you may think of, including (but not limited to) one sprites sheet or more, one atlas or more, etc. or even a mix of all of them. If not provided, as default it will use the value from the sprite that it belongs to. * @property {string} [srcType=this.parent.srcType|{@link CB_GraphicSprites.SRC_TYPES_DEFAULT}] - Type of the source of origin. If not provided, as default it will use the value from the sprite that it belongs to. It should point to a property of the {@link CB_GraphicSprites.SRC_TYPES} object. You can use other values of the {@link CB_GraphicSprites.SRC_TYPES} object or create new ones. * @property {number} [srcLeft=this.parent.srcLeft|{@link CB_GraphicSprites.LEFT_SOURCE_DEFAULT}] - Left (horizontal) position in the original source (having in mind its real width and height). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprite that it belongs to. * @property {number} [srcTop=this.parent.srcTop|{@link CB_GraphicSprites.TOP_SOURCE_DEFAULT}] - Top (vertical) position in the original source (having in mind its real width and height). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprite that it belongs to. * @property {number} [srcWidth=this.parent.srcWidth|{@link CB_GraphicSprites.WIDTH_SOURCE_DEFAULT}] - Width of the original source. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprite that it belongs to. * @property {number} [srcHeight=this.parent.srcHeight|{@link CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT}] - Height of the original source. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprite that it belongs to. * @property {number} [left={@link CB_GraphicSprites.LEFT_DEFAULT}] - Left (horizontal) position in the destiny (inside the sprite). Unit agnostic (only numeric values are allowed). * @property {number} [top={@link CB_GraphicSprites.TOP_DEFAULT}] - Top (vertical) position in the destiny (inside the sprite). Unit agnostic (only numeric values are allowed). * @property {number} [width=this.parent.width|{@link CB_GraphicSprites.WIDTH_DEFAULT}] - Width of the destiny (inside the sprite). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprite that it belongs to. * @property {number} [height=this.parent.height|{@link CB_GraphicSprites.HEIGHT_DEFAULT}] - Height of the destiny (inside the sprite). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprite that it belongs to. * @property {number} [zIndex=this.parent.zIndex|{@link CB_GraphicSprites.ZINDEX_DEFAULT}] - The z-index for the destiny (inside the sprite). Only numeric values which are not zero (0) are allowed. If not provided, as default it will use the value from the sprite that it belongs to. To change the value of this property, use the \"setZIndex\" method of the sub-sprite or the {@link CB_GraphicSprites#setZIndexSubSprite} method (which will call the {@link CB_GraphicSpritesScene#updateSubSpritesByZIndex} method internally). * @property {boolean} [disabled=this.parent.disabled|false] - Tells whether this sub-sprite is disabled or not. Regardless its value, it will be considered disabled if its sprite parent is also disabled. If not provided, as default it will use the value from the sprite that it belongs to. * @property {object} [data=CB_combineJSON(this.parent.data, this.data)||this.parent.data||{ 'that' : CB_GraphicSprites.SPRITES_OBJECT, 'getThis' = function() { return this.that; } }] - Object with any additional data desired which can be any kind. If not provided, missing properties as default will use the value from the sprite that it belongs to. It will always have a \"that\" property pointing to the {@link CB_GraphicSprites.SUBSPRITE_OBJECT} object where it belongs to and a function in its \"getThis\" property returning the same value (added automatically). These properties (\"that\" and \"getThis\") cannot be overridden. * @property {boolean} [byReference=false] - If set to true, when inserting the sub-sprite, the same sub-sprite itself ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} object) will be inserted internally directly without making a copy of itself. * @property {CB_GraphicSprites.SPRITE_OBJECT} parent - Read-only property pointing to its parent ({@link CB_GraphicSprites.SPRITE_OBJECT} object). * @property {CB_GraphicSprites} container - Read-only property pointing to the {@link CB_GraphicSprites} object which contains it. * @property {boolean} isSubSprite - Read-only property which is always set to true to help identify this type of object. * @property {'subSprite'} type - Read-only property indicating the type of object (always \"subSprite\"). * @property {integer} position - Read-only property indicating the position of this sub-sprite in the array which is set the \"subSprites\" property of the sprite parent ({@link CB_GraphicSprites.SPRITE_OBJECT} object). * @property {integer} positionByZIndex - Read-only property indicating the position of this sub-sprite in the array which is set the \"subSpritesByZIndex\" property of the sprite parent ({@link CB_GraphicSprites.SPRITE_OBJECT} object). * @property {integer} time - Property which stores the time in milliseconds when its parent sprite was started being pointed for the last time (time elapsed since the [time origin]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin} which was obtained calling the {@link CB_Device.getTiming} function internally). Note that the parent could being not pointed anymore. If it has never being pointed before, it will be set to 0. It normally has the same value as the \"time\" property of its parent object but they can be modified independently. * @property {function} setTime - Read-only property which is a method that updates the \"time\" property of the sub-sprite (calls {@link CB_GraphicSprites#setTime} internally and returns its returning value). With only one parameter which belongs to the \"time\" parameter of the {@link CB_GraphicSprites#setTime} method. * @property {function} getTime - Read-only property which is a method that returns the \"time\" property of the sub-sprite (calls {@link CB_GraphicSprites#getTime} internally and returns its returning value). With only one parameter which belongs to the \"returnValueOnFail\" parameter of the {@link CB_GraphicSprites#getTime} method. If the \"time\" property of the sub-sprite is not found, it will use the \"time\" property from its sprite parent. * @property {function} getTimeElapsed - Read-only property which is a method that returns how many milliseconds elapsed since the sprite was or will be pointed (checking its \"time\" property), comparing with the time given in milliseconds (time elapsed since the [time origin]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin} which can be obtained calling the {@link CB_Device.getTiming} function) or with the current one if none is given (calls {@link CB_GraphicSprites#getTimeElapsed} internally and returns its returning value). With only one parameter which belongs to the \"timeToCompare\" parameter of the {@link CB_GraphicSprites#getTimeElapsed} method. If the \"time\" property of the sub-sprite is not found, it will use the \"time\" property from its sprite parent. * @property {function} getZIndex - Read-only property which is a method that returns the z-index (\"z-index\" property) of the sub-sprite (calls {@link CB_GraphicSprites#getZIndexSubSprite} internally and returns its returning value). With only one parameter which belongs to the \"returnValueOnFail\" parameter of the {@link CB_GraphicSprites#getZIndexSubSprite} method. * @property {function} setZIndex - Read-only property which is a method to set the z-index (\"z-index\" property) of the sub-sprite (calls {@link CB_GraphicSprites#setZIndexSubSprite} internally and returns its returning value). With only one parameter which belongs to the \"zIndex\" parameter of the {@link CB_GraphicSprites#setZIndexSubSprite} method. * @property {function} isDisabled - Read-only property which is a method that tells whether the sub-sprite is disabled or not (calls {@link CB_GraphicSprites#isDisabledSubSprite} internally and returns its returning value). With no parameters. A sub-sprite is considered disabled if its sprite parent is disabled (a sprite is considered disabled if its sprites group parent is also disabled). * @property {function} setDisabled - Read-only property which is a method to disable or enable the sub-sprite (calls {@link CB_GraphicSprites#setDisabledSubSprite} internally and returns its returning value). With three parameters (\"disabled\", \"affectParents\" and \"affectParentsChildren\") which belong to the parameters with the same name of the {@link CB_GraphicSprites#setDisabledSubSprite} method. */ /** * An object with the information that belongs to a certain graphic sprite, being able to contain more than one source used by this graphic sprite (inside sub-sprites). * @example { //'my_sprite_1': id: \"my_sprite_1\", src: \"path/to/image.gif\", srcType: CB_GraphicSprites.SRC_TYPES.IMAGE, srcLeft: 10, srcTop: 20, srcWidth: 64, srcHeight: 32, left: 10, top: 20, width: 64, height: 32, disabled: false, data: { datum_1 : \"value_1\", datum_2 : 2, datum_3: [ \"a\", \"b\", \"c\" ] }, subSprites: [ //'my_subsprite_1': { id: \"my_subsprite_1\", srcLeft: 10, srcTop: 20, zIndex: 1 }, //'my_subsprite_2': { id: \"my_subsprite_2\", srcLeft: 20, srcTop: 40, zIndex: 2 } ] } * @memberof CB_GraphicSprites * @typedef {Object} CB_GraphicSprites.SPRITE_OBJECT * @property {string|*} [id='CB_GraphicSprites.sprite_' + CB_GraphicSprites._idSpriteUnique++] - Identifier of the sprite. It should be unique. Recommended. It must be a value which evaluates to true. By default, it is generated automatically (with an internal counter). * @property {*} [src=this.parent.src|\"\"] - Source of origin. Can be a path or identifier of an image, text, bitmap, 3D object, etc. They can be used for any kind of source you may think of, including (but not limited to) one sprites sheet or more, one atlas or more, etc. or even a mix of all of them. If not provided, as default it will use the value from the sprites group that it belongs to. * @property {string} [srcType=this.parent.srcType|{@link CB_GraphicSprites.SRC_TYPES_DEFAULT}] - Type of the source of origin. If not provided, as default it will use the value from the sprites group that it belongs to. It should point to a property of the {@link CB_GraphicSprites.SRC_TYPES} object. You can use other values of the {@link CB_GraphicSprites.SRC_TYPES} object or create new ones. * @property {number} [srcLeft=this.parent.srcLeft|{@link CB_GraphicSprites.LEFT_SOURCE_DEFAULT}] - Left (horizontal) position in the original source (having in mind its real width and height). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprites group that it belongs to. * @property {number} [srcTop=this.parent.srcTop|{@link CB_GraphicSprites.TOP_SOURCE_DEFAULT}] - Top (vertical) position in the original source (having in mind its real width and height). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprites group that it belongs to. * @property {number} [srcWidth=this.parent.srcWidth|{@link CB_GraphicSprites.WIDTH_SOURCE_DEFAULT}] - Width of the original source. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprites group that it belongs to. * @property {number} [srcHeight=this.parent.srcHeight|{@link CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT}] - Height of the original source. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprites group that it belongs to. * @property {number} [left={@link CB_GraphicSprites.LEFT_DEFAULT}] - Left (horizontal) position in the destiny (inside the sprites group). Unit agnostic (only numeric values are allowed). * @property {number} [top={@link CB_GraphicSprites.TOP_DEFAULT}] - Top (vertical) position in the destiny (inside the sprites group). Unit agnostic (only numeric values are allowed). * @property {number} [width=this.parent.width|{@link CB_GraphicSprites.WIDTH_DEFAULT}] - Width of the destiny (inside the sprites group). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprites group that it belongs to. * @property {number} [height=this.parent.height|{@link CB_GraphicSprites.HEIGHT_DEFAULT}] - Height of the destiny (inside the sprites group). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprites group that it belongs to. * @property {number} [zIndex=this.parent.zIndex|{@link CB_GraphicSprites.ZINDEX_DEFAULT}] - The z-index for the destiny (inside the sprites group). Only numeric values which are not zero (0) are allowed. If not provided, as default it will use the value from the sprites group that it belongs to. To change the value of this property, use the \"setZIndex\" method of the sprite or the {@link CB_GraphicSprites#setZIndexSprite} method (which will call the {@link CB_GraphicSpritesScene#updateSpritesByZIndex} method internally). * @property {boolean} [disabled=this.parent.disabled|false] - Tells whether this sprite is disabled or not. Regardless its value, it will be considered disabled if its sprites group parent is also disabled. If not provided, as default it will use the value from the sprites group that it belongs to. * @property {object} [data=CB_combineJSON(this.parent.data, this.data)||this.parent.data||{ 'that' : CB_GraphicSprites.SPRITES_OBJECT, 'getThis' = function() { return this.that; } }] - Object with any additional data desired which can be any kind. If not provided, missing properties as default will use the value from the sprites group that it belongs to. It will always have a \"that\" property pointing to the {@link CB_GraphicSprites.SPRITE_OBJECT} object where it belongs to and a function in its \"getThis\" property returning the same value (added automatically). These properties (\"that\" and \"getThis\") cannot be overridden. * @property {array} [subSprites=[]] - Numeric array containing {@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects with the sub-sprites that this sprite uses. * @property {array} subSpritesByZIndex - Read-only property containing a numeric array of all the {@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects of the sprite ordered by their z-index (\"zIndex\" property). It is updated automatically when the z-index of a sub-sprite is set with its \"setZIndex\" method (or when calling the {@link CB_GraphicSprites#setZIndexSubSprite} method) or when inserting/removing sub-sprites through the {@link CB_GraphicSprites#insertSubSprites}, {@link CB_GraphicSprites#insertSubSprite}, {@link CB_GraphicSprites#removeSubSprite} or {@link CB_GraphicSprites#removeSubSpriteById} methods. * @property {boolean} [byReference=false] - If set to true, when inserting the sprite, its \"subSprites\" property will use exactly the object given for that property (without making a copy) and the same sprite itself ({@link CB_GraphicSprites.SPRITE_OBJECT} object) will be inserted internally directly without making a copy of itself. * @property {CB_GraphicSprites.SPRITES_OBJECT} parent - Read-only property pointing to its parent ({@link CB_GraphicSprites.SPRITES_OBJECT} object). * @property {CB_GraphicSprites} container - Read-only property pointing to the {@link CB_GraphicSprites} object which contains it. * @property {boolean} isSprite - Read-only property which is always set to true to help identify this type of object. * @property {'sprite'} type - Read-only property indicating the type of object (always \"sprite\"). * @property {integer} position - Read-only property indicating the position of this sprite in the array which is set the \"sprites\" property of the sprites group parent ({@link CB_GraphicSprites.SPRITES_OBJECT} object). * @property {integer} positionByZIndex - Read-only property indicating the position of this sprite in the array which is set the \"spritesByZIndex\" property of the sprites group parent ({@link CB_GraphicSprites.SPRITES_OBJECT} object). * @property {integer} time - Property which stores the time in milliseconds when the sprite was started being pointed for the last time (time elapsed since the [time origin]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin} which was obtained calling the {@link CB_Device.getTiming} function internally). Note that it could being not pointed anymore. If it has never being pointed before, it will be set to 0. * @property {function} setTime - Read-only property which is a method that updates the \"time\" property of the sprite (calls {@link CB_GraphicSprites#setTime} internally and returns its returning value). With only one parameter which belongs to the \"time\" parameter of the {@link CB_GraphicSprites#setTime} method. * @property {function} getTime - Read-only property which is a method that returns the \"time\" property of the sprite (calls {@link CB_GraphicSprites#getTime} internally and returns its returning value). With only one parameter which belongs to the \"returnValueOnFail\" parameter of the {@link CB_GraphicSprites#getTime} method. * @property {function} getTimeElapsed - Read-only property which is a method that returns how many milliseconds elapsed since the sprite was or will be pointed (checking its \"time\" property), comparing with the time given in milliseconds (time elapsed since the [time origin]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin} which can be obtained calling the {@link CB_Device.getTiming} function) or with the current one if none is given (calls {@link CB_GraphicSprites#getTimeElapsed} internally and returns its returning value). With only one parameter which belongs to the \"timeToCompare\" parameter of the {@link CB_GraphicSprites#getTimeElapsed} method. * @property {function} removeAll - Read-only property which is a method that removes all the internal sub-sprites ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects) from the sprite which are in the \"subSprites\" property (calls {@link CB_GraphicSprites#removeSubSprites} internally and returns its returning value). With no parameters. * @property {function} removeSubSprites - Alias for the \"removeAll\" method. * @property {function} insertSubSprites - Read-only property which is a method that inserts the given sub-sprites ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects) in the sprite, adding them to the \"subSprites\" property (calls {@link CB_GraphicSprites#insertSubSprites} internally and returns its returning value). With only one parameter which belongs to the \"subSprites\" parameter of the {@link CB_GraphicSprites#insertSubSprites} method. * @property {function} remove - Read-only property which is a method that removes an internal sub-sprite ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} object) by its index (position in the \"subSprites\" array) from the sprite, removing it from the \"subSprites\" property (calls {@link CB_GraphicSprites#removeSubSprite} internally and returns its returning value). With only one parameter which belongs to the \"index\" parameter of the {@link CB_GraphicSprites#removeSubSprite} method. * @property {function} removeById - Read-only property which is a method that removes an internal sub-sprite ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} object) by its identifier from the sprite, removing it from the \"subSprites\" property (calls {@link CB_GraphicSprites#removeSubSpriteById} internally and returns its returning value). With only one parameter which belongs to the \"id\" parameter of the {@link CB_GraphicSprites#removeSubSpriteById} method. * @property {function} insert - Read-only property which is a method that inserts a given sub-sprite ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} object) in the sprite, adding it to the \"subSprites\" property (calls {@link CB_GraphicSprites#insertSubSprite} internally and returns its returning value). With only one parameter which belongs to the \"subSprite\" parameter of the {@link CB_GraphicSprites#insertSubSprite} method. * @property {function} getAll - Read-only property which is a method that returns all the internal sub-sprites ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects) in the sprite, getting them from the \"subSprites\" property (calls {@link CB_GraphicSprites#getAll} internally and returns its returning value). With two parameters (\"orderedByZIndex\" and \"returnValueOnFail\") which belong to the parameters with the same name of the {@link CB_GraphicSprites#getAll} method. * @property {function} getSubSprites - Alias for the \"getAll\" method. * @property {function} get - Read-only property which is a method that returns a sub-sprite ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} object) by its index (position in the \"subSprites\" array) from the sprite, getting it from the \"subSprites\" property (calls {@link CB_GraphicSprites#getSubSprite} internally and returns its returning value). With two parameters (\"index\" and \"returnValueOnFail\") which belong to the parameters with the same name of the {@link CB_GraphicSprites#getSubSprite} method. * @property {function} getById - Read-only property which is a method that returns a sub-sprite ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} object) by its identifier from the sprite, getting it from the \"subSprites\" property (calls {@link CB_GraphicSprites#getSubSpriteById} internally and returns its returning value). With two parameters (\"id\" and \"returnValueOnFail\") which belong to the parameters with the same name of the {@link CB_GraphicSprites#getSubSpriteById} method. * @property {function} getIndexById - Read-only property which is a method that returns the index (position in the \"subSprites\" array) of a sub-sprite ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} object) by its identifier (calls {@link CB_GraphicSprites#getSubSpriteIndexById} internally and returns its returning value). With only one parameter which belongs to the \"id\" parameter of the {@link CB_GraphicSprites#getSubSpriteIndexById} method. * @property {function} executeFunctionAll - Read-only property which is a method that executes the desired function for each sub-sprite ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects which are in the \"subSprites\" property) in the sprite (calls {@link CB_GraphicSprites#executeFunctionAllSubSprites} internally and returns its returning value). With five parameters (\"functionEach\", \"orderedByZIndex\", \"delayBetweenEach\", \"returnSetTimeoutsArray\", \"delayBetweenEachAffectsFirst\" and \"functionFinish\") which belong to the parameters with the same name of the {@link CB_GraphicSprites#executeFunctionAllSubSprites} method. * @property {function} executeAll - Alias for the \"executeFunctionAll\" method. * @property {function} forEach - Alias for the \"executeFunctionAll\" method. * @property {function} getZIndex - Read-only property which is a method that returns the z-index (\"z-index\" property) of the sprite (calls {@link CB_GraphicSprites#getZIndexSprite} internally and returns its returning value). With only one parameter which belongs to the \"returnValueOnFail\" parameter of the {@link CB_GraphicSprites#getZIndexSprite} method. * @property {function} setZIndex - Read-only property which is a method to set the z-index (\"z-index\" property) of the sprite (calls {@link CB_GraphicSprites#setZIndexSprite} internally and returns its returning value). With only one parameter which belongs to the \"zIndex\" parameter of the {@link CB_GraphicSprites#setZIndexSprite} method. * @property {function} isDisabled - Read-only property which is a method that tells whether the sprite is disabled or not (calls {@link CB_GraphicSprites#isDisabledSprite} internally and returns its returning value). With no parameters. A sprite is considered disabled if its sprites group parent is also disabled. * @property {function} setDisabled - Read-only property which is a method to disable or enable the sprite (calls {@link CB_GraphicSprites#setDisabledSprite} internally and returns its returning value). With four parameters (\"disabled\", \"affectSubSprites\", \"affectParent\" and \"affectParentChildren\") which belong to the parameters with the same name of the {@link CB_GraphicSprites#setDisabledSprite} method. * @property {function} getPointer - Read-only property which is a method that gets the current position of the pointer. It belongs to an index of the {@link CB_GraphicSprites#spritesGroup.sprites} array where a {@link CB_GraphicSprites.SPRITE_OBJECT} object is placed (containing a sprite). Internally, it uses the {@link CB_GraphicSprites#pointer} property. Calls {@link CB_GraphicSprites#getPointer} internally and returns its returning value. With no parameters. * @property {function} getCurrentPosition - Alias for the \"getPointer\" method. * @property {function} getPointerPrevious - Read-only property which is a method that gets the previous position of the pointer. Internally, it uses the {@link CB_GraphicSprites#pointerPrevious} property. Calls {@link CB_GraphicSprites#getPointerPrevious} internally and returns its returning value. With no parameters. * @property {function} getPreviousPosition - Alias for the \"getPointerPrevious\" method. * @property {function} setPointer - Read-only property which is a method that sets the pointer to the desired position (if possible). The position should belong to an index of the {@link CB_GraphicSprites#spritesGroup.sprites} array where a {@link CB_GraphicSprites.SPRITE_OBJECT} object is placed (containing a sprite). Internally, it modifies the {@link CB_GraphicSprites#pointer} property (if possible). If the position was updated, it will also reset the {@link CB_GraphicSprites#time} property (setting the current time in milliseconds). Calls {@link CB_GraphicSprites#setPointer} internally and returns the sprite (a {@link CB_GraphicSprites.SPRITE_OBJECT} object) which is being currently pointed (by the pointer set in the {@link CB_GraphicSprites#pointer} property). With two parameters (\"position\" and \"loop\") which belong to the parameters with the same name of the {@link CB_GraphicSprites#setPointer} method. * @property {function} setCurrentPosition - Alias for the \"setPointer\" method. * @property {function} getCurrent - Read-only property which is a method that gets the sprite (a {@link CB_GraphicSprites.SPRITE_OBJECT} object) which is being currently pointed (by the pointer set in the {@link CB_GraphicSprites#pointer} property). Calls {@link CB_GraphicSprites#getCurrent} internally and returns its returning value. With no parameters. * @property {function} current - Alias for the \"getCurrent\" method. * @property {function} now - Alias for the \"getCurrent\" method. * @property {function} getPrevious - Read-only property which is a method that gets the sprite which was previously pointed if any or returns null otherwise. It does not modify the {@link CB_GraphicSprites#pointer} property. Calls {@link CB_GraphicSprites#getPrevious} internally and returns its returning value. With no parameters. * @property {function} setPrevious - Read-only property which is a method that makes the pointer to go back to the previous position (if possible) and returns the sprite located there (if any). The position should belong to an index of the {@link CB_GraphicSprites#spritesGroup.sprites} array where a {@link CB_GraphicSprites.SPRITE_OBJECT} object is placed (containing a sprite) and it will be returned if found. Internally, it modifies the {@link CB_GraphicSprites#pointer} property (if possible). If the position was updated, it will update also the {@link CB_GraphicSprites#time} property (setting the current time in milliseconds). Calls {@link CB_GraphicSprites#setPrevious} internally and returns its returning value. With only one parameter which belongs to the \"loop\" parameter of the {@link CB_GraphicSprites#setPrevious} method. * @property {function} previous - Alias for the \"setPrevious\" method. * @property {function} setNext - Read-only property which is a method that makes the pointer to advance to the next position (if possible) and returns the sprite located there (if any). The position should belong to an index of the {@link CB_GraphicSprites#spritesGroup.sprites} array where a {@link CB_GraphicSprites.SPRITE_OBJECT} object is placed (containing a sprite) and it will be returned if found. Internally, it modifies the {@link CB_GraphicSprites#pointer} property (if possible). If the position was updated, it will also update the {@link CB_GraphicSprites#time} property (setting the current time in milliseconds). Calls {@link CB_GraphicSprites#setNext} internally and returns its returning value. With only one parameter which belongs to the \"loop\" parameter of the {@link CB_GraphicSprites#setNext} method. * @property {function} next - Alias for the \"setNext\" method. * @property {function} setPropertyCascade - Read-only property which is a method that sets the desired value of a given property name to the sprite itself and all of its sub-sprites (if any). Calls {@link CB_GraphicSprites#setPropertyCascade} internally and returns its returning value. With two parameters (\"propertyName\" and \"value\") which belong to the parameters with the same name of the {@link CB_GraphicSprites#setPropertyCascade} method. */ /** * An object with the information that belongs to a group of graphic sprites. * @example { //'my_sprites_1': id: \"my_sprites_1\", src: \"path/to/image.gif\", srcType: CB_GraphicSprites.SRC_TYPES.IMAGE, srcLeft: 10, srcTop: 20, srcWidth: 64, srcHeight: 32, left: 10, top: 20, width: 64, height: 32, data: { datum_1: \"value_1\", datum_2: 2, datum_3: [ \"a\", \"b\", \"c\" ] }, sprites: [ //'my_sprite_1': { id: \"my_sprite_1\", subSprites: [ //'my_subsprite_1': { id: \"my_subsprite_1\", srcLeft: 10, srcTop: 20, zIndex: 1 }, //'my_subsprite_2': { id: \"my_subsprite_2\", srcLeft: 20, srcTop: 40, zIndex: 2 } ] }, //'my_sprite_2': { id: \"my_sprite_2\", subSprites: [ //'my_subsprite_3': { id: \"my_subsprite_3\", srcLeft: 30, srcTop: 60, zIndex: 1 }, //'my_subsprite_4': { id: \"my_subsprite_4\", srcLeft: 40, srcTop: 80, zIndex: 2 } ] } ] } * @memberof CB_GraphicSprites * @typedef {Object} CB_GraphicSprites.SPRITES_OBJECT * @property {string|*} [id='CB_GraphicSprites_' + CB_GraphicSprites._idUnique++] - Identifier of the group of graphic sprites (also used as the {@link CB_GraphicSprites.id} property for the {@link CB_GraphicSprites} object). It should be unique. Recommended. It must be a value which evaluates to true. By default, it is generated automatically (with an internal counter). * @property {*} [src=\"\"] - Source of origin. Can be a path or identifier of an image, text, bitmap, 3D object, etc. They can be used for any kind of source you may think of, including (but not limited to) one sprites sheet or more, one atlas or more, etc. or even a mix of all of them. * @property {string} [srcType={@link CB_GraphicSprites.SRC_TYPES_DEFAULT}] - Type of the source of origin. It should point to a property of the {@link CB_GraphicSprites.SRC_TYPES} object. You can use other values of the {@link CB_GraphicSprites.SRC_TYPES} object or create new ones. * @property {number} [srcLeft={@link CB_GraphicSprites.LEFT_SOURCE_DEFAULT}] - Left (horizontal) position in the original source (having in mind its real width and height). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from {@link CB_GraphicSprites.LEFT_SOURCE_DEFAULT}. * @property {number} [srcTop={@link CB_GraphicSprites.TOP_SOURCE_DEFAULT}] - Top (vertical) position in the original source (having in mind its real width and height). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from {@link CB_GraphicSprites.TOP_SOURCE_DEFAULT}. * @property {number} [srcWidth={@link CB_GraphicSprites.WIDTH_SOURCE_DEFAULT}] - Width of the original source. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from {@link CB_GraphicSprites.WIDTH_SOURCE_DEFAULT}. * @property {number} [srcHeight={@link CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT}] - Height of the original source. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from {@link CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT}. * @property {number} [left={@link CB_GraphicSprites.LEFT_DEFAULT}] - Left (horizontal) position in the destiny. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from {@link CB_GraphicSprites.LEFT_DEFAULT}. * @property {number} [top={@link CB_GraphicSprites.TOP_DEFAULT}] - Top (vertical) position in the destiny. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from {@link CB_GraphicSprites.TOP_DEFAULT}. * @property {number} [width={@link CB_GraphicSprites.WIDTH_DEFAULT}] - Width of the destiny. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from {@link CB_GraphicSprites.WIDTH_DEFAULT}. * @property {number} [height={@link CB_GraphicSprites.HEIGHT_DEFAULT}] - Height of the destiny. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from {@link CB_GraphicSprites.HEIGHT_DEFAULT}. * @property {number} [zIndex={@link CB_GraphicSprites.ZINDEX_DEFAULT}] - The z-index for the destiny (only numeric values which are not zero (0) are allowed). Also used as the {@link CB_GraphicSprites.zIndex} property for the {@link CB_GraphicSprites} object. If not provided, as default it will use the value from {@link CB_GraphicSprites.ZINDEX_DEFAULT}. To change the value of this property, use the {@link CB_GraphicSprites#setZIndex} method (which will call the {@link CB_GraphicSpritesScene#updateGraphicSpritesByZIndex} method internally if there is a {@link CB_GraphicSpritesScene} parent object). * @property {boolean} [disabled=false] - Tells whether this sprites group (and the {@link CB_GraphicSprites} object itself) is disabled or not. If not provided, as default it will be false (which means it is enabled). * @property {object} [data={ 'that' : CB_GraphicSprites.SPRITES_OBJECT, 'getThis' = function() { return this.that; } }] - Object with any additional data desired which can be any kind. It will always have a \"that\" property pointing to the {@link CB_GraphicSprites.SPRITES_OBJECT} object where it belongs to and a function in its \"getThis\" property returning the same value (added automatically). These properties (\"that\" and \"getThis\") cannot be overridden. * @property {array} [sprites=[]] - Numeric array containing {@link CB_GraphicSprites.SPRITE_OBJECT} objects with all the sprites that will be used. Recommended at least to provide one {@link CB_GraphicSprites.SPRITE_OBJECT} object in the first index. * @property {array} spritesByZIndex - Read-only property containing a numeric array of all the {@link CB_GraphicSprites.SPRITE_OBJECT} objects ordered by their z-index (\"zIndex\" property). It is updated automatically when the z-index of a sprite is set with its \"setZIndex\" method (or when calling the {@link CB_GraphicSprites#setZIndexSprite} method) or when inserting/removing sprites through the {@link CB_GraphicSprites#insertSprites}, {@link CB_GraphicSprites#insertSprite}, {@link CB_GraphicSprites#removeSprite} or {@link CB_GraphicSprites#removeSpriteById} methods. * @property {boolean} [byReference_DEFAULT=false] - Default value to use as the \"byReference\" parameter for the constructor and for the {@link CB_GraphicSprites#insertSprites} method. If a boolean value is not provided, it will be parsed to boolean (resulting undefined to be false). * @property {*} [parent=undefined|{@link CB_GraphicSpritesScene}] - Property pointing to or containing its parent (also used as the {@link CB_GraphicSprites.parent} property for the {@link CB_GraphicSprites} object). It could be a {@link CB_GraphicSpritesScene} object. * @property {CB_GraphicSprites} container - Read-only property pointing to the {@link CB_GraphicSprites} object which contains it. * @property {boolean} isSpritesGroup - Read-only property which is always set to true to help identify this type of object. * @property {'spritesGroup'} type - Read-only property indicating the type of object (always \"spritesGroup\"). * @property {integer} [position=undefined] - Read-only property indicating the position of this {@link CB_GraphicSprites} object in the array which is set the \"items\" property inside the {@link CB_GraphicSpritesScene#spritesGroups} object which is in the {@link CB_GraphicSpritesScene} object parent (if any). * @property {integer} [positionByZIndex=undefined] - Read-only property indicating the position of this {@link CB_GraphicSprites} object in the array which is set the \"itemsByZIndex\" property inside the {@link CB_GraphicSpritesScene#spritesGroups} object which is in the {@link CB_GraphicSpritesScene} object parent (if any). */ /** * Class to manage a group of graphic sprites (2D or 3D). * @class * @classdesc Class to manage a group of graphic sprites (2D or 3D). * @param {CB_GraphicSprites.SPRITES_OBJECT} [spritesGroup] - Object with the desired sprites. The information will be used for the {@link CB_GraphicSprites#spritesGroup} property. Used as the \"spritesGroup\" parameter when calling the {@link CB_GraphicSprites#insertSprites} method internally. * @param {boolean} [byReference=!!{@link CB_GraphicSprites.SPRITES_OBJECT.byReference_DEFAULT}] - This value will be used as the default value when the \"byReference\" property is not given in the sprites ({@link CB_GraphicSprites.SPRITE_OBJECT} objects) or sub-sprites ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects). The value will be stored in the {@link CB_GraphicSprites#byReference_DEFAULT} property. If a boolean value is not provided, it will use the value of the {@link CB_GraphicSprites.SPRITES_OBJECT.byReference_DEFAULT} property of the given {@link CB_GraphicSprites.SPRITES_OBJECT} object (parsed to boolean). * @returns {CB_GraphicSprites} Returns a new {@link CB_GraphicSprites} object. * @todo Think about a \"createCopy\" parameter on different the insert methods (to insert sprites groups/graphic sprites objects, etc.) so it will make a copy of the object to avoid using/modifying the original one. If the \"createCopy\" is set to false, it should always use the object as reference (using/modifying it). * @todo Think about a method to remove a sprite when the same sprite is received by parameter. The same with sub-sprites, receiving the sub-sprite by parameter. The same to remove the sprites group object, receiving a sprites group object by parameter. Only remove them if they match exactly. */ var CB_GraphicSprites = function(spritesGroup, byReference) { //Creates an instance of this object and returns it in the case that it is being called from an unexpected context: if (this === window || !(this instanceof CB_GraphicSprites)) { return new CB_GraphicSprites(spritesGroup, byReference); } //Properties and variables: /** * Identifier of the sprites group object (the \"id\" property of the {@link CB_GraphicSprites.SPRITES_OBJECT} stored in the {@link CB_GraphicSprites#spritesGroup} property) and the {@link CB_GraphicSprites} object itself (same one). It should be unique. It must be a value which evaluates to true. By default, it is generated automatically (with an internal counter). * @var * @readonly * @type {string|*} * @default 'CB_GraphicSprites_' + CB_GraphicSprites._idUnique++ */ this.id = \"\"; /** * Property pointing to or containing its parent. It could be a {@link CB_GraphicSpritesScene} object. It is the same as the \"parent\" property of the {@link CB_GraphicSprites.SPRITES_OBJECT} stored in the {@link CB_GraphicSprites#spritesGroup} property. * @var * @readonly * @type {*} * @default */ this.parent = undefined; /** * Z-index of the sprites group object (the \"zIndex\" property of the {@link CB_GraphicSprites.SPRITES_OBJECT} stored in the {@link CB_GraphicSprites#spritesGroup} property) and the {@link CB_GraphicSprites} object itself (same one). To change the value of this property, use the {@link CB_GraphicSprites#setZIndex} method (which will call the {@link CB_GraphicSpritesScene#updateGraphicSpritesByZIndex} method internally if there is a {@link CB_GraphicSpritesScene} parent object). Only numeric values which are not zero (0) are allowed. * @var * @readonly * @type {number} * @default CB_GraphicSprites.ZINDEX_DEFAULT */ this.zIndex = CB_GraphicSprites.ZINDEX_DEFAULT; /** * Object with information about the sprites. * @var * @readonly * @type {CB_GraphicSprites.SPRITES_OBJECT} * @default */ this.spritesGroup = {}; /** * Pointer with the position of the current sprite (belongs to an index of the {@link CB_GraphicSprites#spritesGroup.sprites} array). * @var * @readonly * @type {integer} * @default */ this.pointer = -1; /** * Keeps the previous value of the {@link CB_GraphicSprites#pointer} property (if any). * @var * @readonly * @type {integer} * @default */ this.pointerPrevious = -1; /** * Stores the time in milliseconds when the current sprite was started being pointed (time elapsed since the [time origin]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin} which will be obtained calling the {@link CB_Device.getTiming} function internally). * @var * @readonly * @type {integer} * @default */ this.time = 0; /** * This value will be used as the default value when the \"byReference\" property is not given in the sprites ({@link CB_GraphicSprites.SPRITE_OBJECT} objects) or sub-sprites ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects). * @var * @type {boolean} * @default */ this.byReference_DEFAULT = false; //Calls the constructor of the object when creates an instance: return this._init(spritesGroup, byReference); } //Constants: /** * Property which is always set to true to help identify this type of object. * @constant * @type {boolean} * @default */ CB_GraphicSprites.prototype.isSprites = true; /** * Indicates the type of object (always \"sprites\"). * @constant * @type {string} * @default */ CB_GraphicSprites.prototype.type = \"sprites\"; /** * Object with some \"srcType\". Each property of this object belong to one source type, having an integer as value which represents it. You can define more source types here. * @constant * @type {object} * @default */ CB_GraphicSprites.SRC_TYPES = { DEFAULT: 0, IMAGE: 0, TEXT: 1, SEGMENT: 2, PIXEL: 3, RECTANGLE: 4, CIRCLE: 5, ARC: 6, ELLIPSE: 7, TRIANGLE: 8, BEZIER_CURVE: 9, QUADRATIC_BEZIER_CURVE: 10, BITMAP: 11, MAP: 12 } /** * Alias for {@link CB_GraphicSprites.SRC_TYPES_DEFAULT}. * @constant CB_GraphicSprites.SRC_TYPES.DEFAULT * @see {@link CB_GraphicSprites.SRC_TYPES_DEFAULT} */ /** * Default \"srcType\", the type of the original source. * @constant * @type {integer} * @default {@link CB_GraphicSprites.SRC_TYPES.IMAGE} */ CB_GraphicSprites.SRC_TYPES_DEFAULT = CB_GraphicSprites.SRC_TYPES.DEFAULT = CB_GraphicSprites.SRC_TYPES.IMAGE; /** * Default width (\"srcWidth\") of the original source. Unit agnostic. * @constant * @type {number} * @default */ CB_GraphicSprites.WIDTH_SOURCE_DEFAULT = 32; /** * Default height (\"srcHeight\") of the original source. Unit agnostic. * @constant * @type {number} * @default */ CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT = 32; /** * Default left (\"srcLeft\", horizontal position) in the original source. Unit agnostic. * @constant * @type {number} * @default */ CB_GraphicSprites.LEFT_SOURCE_DEFAULT = 0; /** * Default top (\"srcTop\", vertical position) in the original source. Unit agnostic. * @constant * @type {number} * @default */ CB_GraphicSprites.TOP_SOURCE_DEFAULT = 0; /** * Default \"width\" of the destiny. Unit agnostic. * @constant * @type {number} * @default */ CB_GraphicSprites.WIDTH_DEFAULT = CB_GraphicSprites.WIDTH_SOURCE_DEFAULT; /** * Default \"height\" of the destiny. Unit agnostic. * @constant * @type {number} * @default */ CB_GraphicSprites.HEIGHT_DEFAULT = CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT; /** * Default \"left\" (horizontal position) in the destiny. Unit agnostic. * @constant * @type {number} * @default */ CB_GraphicSprites.LEFT_DEFAULT = 0; /** * Default \"top\" (vertical position) in the destiny. Unit agnostic. * @constant * @type {number} * @default */ CB_GraphicSprites.TOP_DEFAULT = 0; /** * Default \"zIndex\" in the destiny. * @constant * @type {number} * @default */ CB_GraphicSprites.ZINDEX_DEFAULT = 1; //Variables: CB_GraphicSprites._idUnique = 0; //Counter to make the sprites group id unique. CB_GraphicSprites._idSpriteUnique = 0; //Counter to make the sprite id unique. CB_GraphicSprites._idSubSpriteUnique = 0; //Counter to make the sub-sprite id unique. //Constructor: CB_GraphicSprites.prototype._init = function(spritesGroup, byReference) { this.insertSprites(spritesGroup, byReference); //Inserts the given sprites group. return this; } /** * Destroys the graphic sprites object (removing all the sprites and their sub-sprites, etc.) and frees memory. * @function */ CB_GraphicSprites.prototype.destructor = function() { //Resets properties to their default value: this.removeSprites(); } /** * Alias for {@link CB_GraphicSprites#removeSprites}. * @function CB_GraphicSprites#removeAll * @see {@link CB_GraphicSprites#removeSprites} */ /** * Alias for {@link CB_GraphicSprites#removeSprites}. * @function CB_GraphicSprites#removeSpritesGroup * @see {@link CB_GraphicSprites#removeSprites} */ /** * Alias for {@link CB_GraphicSprites#removeSprites}. * @function CB_GraphicSprites#removeSpritesAll * @see {@link CB_GraphicSprites#removeSprites} */ /** * Removes all the sprites by clearing the {@link CB_GraphicSprites#spritesGroup} property. * @function */ CB_GraphicSprites.prototype.removeSprites = CB_GraphicSprites.prototype.removeSpritesAll = CB_GraphicSprites.prototype.removeSpritesGroup = CB_GraphicSprites.prototype.removeAll = function() { this.spritesGroup = {}; this.pointer = this.pointerPrevious = -1; } /** * Alias for {@link CB_GraphicSprites#insertSprites}. * @function CB_GraphicSprites#insertSpritesGroup * @see {@link CB_GraphicSprites#insertSprites} */ /** * Adds the desired group of graphic sprites. Calls the {@link CB_GraphicSprites#insertSprite} and {@link CB_GraphicSprites#updateSpritesByZIndex} methods internally. * @function * @param {CB_GraphicSprites.SPRITES_OBJECT} [spritesGroup] - Object with the desired sprites. They will be stored in the {@link CB_GraphicSprites#spritesGroup} property. * @param {boolean} [byReference=!!{@link CB_GraphicSprites.SPRITES_OBJECT.byReference_DEFAULT}] - This value will be used as the default value when the \"byReference\" property is not given in the sprites ({@link CB_GraphicSprites.SPRITE_OBJECT} objects) or sub-sprites ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects). The value will be stored in the {@link CB_GraphicSprites#byReference_DEFAULT} property. If a boolean value is not provided, it will use the value of the {@link CB_GraphicSprites.SPRITES_OBJECT.byReference_DEFAULT} property of the given {@link CB_GraphicSprites.SPRITES_OBJECT} object (parsed to boolean). * @returns {CB_GraphicSprites.SPRITES_OBJECT} Returns the {@link CB_GraphicSprites#spritesGroup} property after updating it. */ CB_GraphicSprites.prototype.insertSprites = CB_GraphicSprites.prototype.insertSpritesGroup = function(spritesGroup, byReference) { //Sets the properties (sanitizing them): this.byReference_DEFAULT = (byReference === true || byReference === false) ? byReference : !!spritesGroup.byReference_DEFAULT; this.spritesGroup = this.spritesGroup || {}; spritesGroup = spritesGroup || {}; this.spritesGroup.isSpritesGroup = true; this.spritesGroup.type = \"spritesGroup\"; this.spritesGroup.container = this; this.parent = this.spritesGroup.parent = spritesGroup.parent; this.id = this.spritesGroup.id = spritesGroup.id = spritesGroup.id || \"CB_GraphicSprites_\" + CB_GraphicSprites._idUnique++; this.spritesGroup.src = spritesGroup.src = spritesGroup.src || !isNaN(spritesGroup.src) &amp;&amp; spritesGroup.src !== null ? spritesGroup.src : \"\"; this.spritesGroup.srcType = spritesGroup.srcType = spritesGroup.srcType || CB_GraphicSprites.SRC_TYPES_DEFAULT; spritesGroup.srcLeft = parseFloat(spritesGroup.srcLeft); this.spritesGroup.srcLeft = spritesGroup.srcLeft = !isNaN(spritesGroup.srcLeft) ? spritesGroup.srcLeft : parseFloat(CB_GraphicSprites.LEFT_SOURCE_DEFAULT) || 0; spritesGroup.left = parseFloat(spritesGroup.left); this.spritesGroup.left = spritesGroup.left = !isNaN(spritesGroup.left) ? spritesGroup.left : parseFloat(CB_GraphicSprites.LEFT_DEFAULT) || 0; spritesGroup.srcTop = parseFloat(spritesGroup.srcTop); this.spritesGroup.srcTop = spritesGroup.srcTop = !isNaN(spritesGroup.srcTop) ? spritesGroup.srcTop : parseFloat(CB_GraphicSprites.TOP_SOURCE_DEFAULT) || 0; spritesGroup.top = parseFloat(spritesGroup.top); this.spritesGroup.top = spritesGroup.top = !isNaN(spritesGroup.top) ? spritesGroup.top : parseFloat(CB_GraphicSprites.TOP_DEFAULT) || 0; spritesGroup.srcWidth = parseFloat(spritesGroup.srcWidth); this.spritesGroup.srcWidth = spritesGroup.srcWidth = !isNaN(spritesGroup.srcWidth) ? spritesGroup.srcWidth : parseFloat(CB_GraphicSprites.WIDTH_SOURCE_DEFAULT) || 0; spritesGroup.width = parseFloat(spritesGroup.width); this.spritesGroup.width = spritesGroup.width = !isNaN(spritesGroup.width) ? spritesGroup.width : CB_GraphicSprites.WIDTH_DEFAULT; spritesGroup.srcHeight = parseFloat(spritesGroup.srcHeight); this.spritesGroup.srcHeight = spritesGroup.srcHeight = !isNaN(spritesGroup.srcHeight) ? spritesGroup.srcHeight : parseFloat(CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT) || 0; spritesGroup.height = parseFloat(spritesGroup.height); this.spritesGroup.height = spritesGroup.height = !isNaN(spritesGroup.height) ? spritesGroup.height : parseFloat(CB_GraphicSprites.HEIGHT_DEFAULT) || 0; this.zIndex = spritesGroup.zIndex = parseFloat(spritesGroup.zIndex); this.spritesGroup.disabled = !!spritesGroup.disabled; this.spritesGroup.zIndex = spritesGroup.zIndex = !isNaN(spritesGroup.zIndex) ? spritesGroup.zIndex : parseFloat(CB_GraphicSprites.ZINDEX_DEFAULT) || 0; this.spritesGroup.data = typeof(spritesGroup.data) === \"object\" &amp;&amp; spritesGroup.data !== null ? CB_copyObject(spritesGroup.data, false) : {}; //Accepts any object but not other values. this.spritesGroup.data.that = this.spritesGroup; this.spritesGroup.data.getThis = function() { return this.that; }; spritesGroup.sprites = CB_isArray(spritesGroup.sprites) ? spritesGroup.sprites : []; //Inserts the given sprites, one by one: var spritesGroupLength = spritesGroup.sprites.length; for (var x = 0; x &lt; spritesGroupLength; x++) { this.insertSprite(spritesGroup.sprites[x], true); } //Updates the array with the sprites ordered by z-index: this.updateSpritesByZIndex(); //Returns the sprites: return this.spritesGroup; } /** * Updates (sorts again) the \"spritesByZIndex\" property (which is an array with the sprites ordered by z-index, whose data comes from the array in the \"sprites\" property of the {@link CB_GraphicSprites#spritesGroup} object) of the {@link CB_GraphicSprites#spritesGroup} object. * @function * @returns {array} Returns the \"spritesByZIndex\" array of the {@link CB_GraphicSprites#spritesGroup} object after updating it. Returns null if the property could not be obtained or updated. */ CB_GraphicSprites.prototype.updateSpritesByZIndex = function() { this.spritesGroup.sprites = this.spritesGroup.sprites || null; if (this.spritesGroup.sprites) { var spritesGroupLength = this.spritesGroup.sprites.length; if (spritesGroupLength) { var elementIndex = null; this.spritesGroup.spritesByZIndex = []; for (var x = 0; x &lt; spritesGroupLength; x++) { elementIndex = CB_GraphicSpritesScene._choosePositionByZIndex(this.spritesGroup.spritesByZIndex, this.spritesGroup.sprites[x]); this.spritesGroup.spritesByZIndex = CB_Arrays.insertElement(this.spritesGroup.spritesByZIndex, elementIndex, this.spritesGroup.sprites[x]); this.spritesGroup.sprites[x].positionByZIndex = elementIndex; } return this.spritesGroup.spritesByZIndex; } } return null; } /** * Alias for {@link CB_GraphicSprites#removeSprite}. * @function CB_GraphicSprites#remove * @see {@link CB_GraphicSprites#removeSprite} */ /** * Removes a sprite by its index (its position in the {@link CB_GraphicSprites#spritesGroup.sprites} array). Calls the {@link CB_GraphicSprites#updateSpritesByZIndex} method internally. * @function * @param {integer} [index=0] - The index where the sprite is located (its position in the {@link CB_GraphicSprites#spritesGroup.sprites} array). * @returns {boolean} Returns true if the sprite has been deleted or false otherwise. */ CB_GraphicSprites.prototype.removeSprite = CB_GraphicSprites.prototype.remove = function(index) { var removed = false; var spritesLeft = CB_Arrays.removeElementByPosition(this.spritesGroup.sprites, index, function() { removed = true; }); if (removed) { this.spritesGroup.sprites = spritesLeft; //Keeps the pointer if the position is valid or sets to the last position if the position was greater than the current limit or uses the first position otherwise: this.setPointer(this.getPointer()); //Updates the array with the sprites ordered by z-index: this.updateSpritesByZIndex(); } return removed; } /** * Alias for {@link CB_GraphicSprites#removeSpriteById}. * @function CB_GraphicSprites#removeById * @see {@link CB_GraphicSprites#removeSpriteById} */ /** * Removes a sprite by its identifier. Calls the {@link CB_GraphicSprites#updateSpritesByZIndex} method internally. * @function * @param {string|*} [id=undefined] - The identifier of the sprite. * @returns {boolean} Returns true if the sprite has been deleted or false otherwise. * @todo Optimize it (perhaps using a cache matching the IDs with their position, maybe using the \"position\" or \"positionByZIndex\" properties). */ CB_GraphicSprites.prototype.removeSpriteById = CB_GraphicSprites.prototype.removeById = function(id) { var removed = false; var spritesLeft = CB_Arrays.removeDuplicated(this.spritesGroup.sprites, function(value, position, array) { if (value &amp;&amp; value.id === id) { removed = true; return true; }; return false; }, true); if (removed) { this.spritesGroup.sprites = spritesLeft; //Keeps the pointer if the position is valid or sets to the last position if the position was greater than the current limit or uses the first position otherwise: this.setPointer(this.getPointer()); //Updates the array with the sprites ordered by z-index: this.updateSpritesByZIndex(); } return removed; } /** * Alias for {@link CB_GraphicSprites#insertSprite}. * @function CB_GraphicSprites#insert * @see {@link CB_GraphicSprites#insertSprite} */ /** * Adds the desired graphic sprite. Calls {@link CB_GraphicSprites#insertSubSprites} internally. If a sprite with the same identifier already exists, it will be replaced by the new one in its same position. * @function * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite] - Object with the desired sprite. It will be stored inside the {@link CB_GraphicSprites#spritesGroup} property. * @param {boolean} [avoidUpdatingSpritesByZIndex=false] - If set to true, it will not call the {CB_GraphicSprites#updateSpritesByZIndex} method internally. Internal usage recommended only. * @returns {CB_GraphicSprites.SPRITE_OBJECT} Returns the {@link CB_GraphicSprites.SPRITE_OBJECT} object which has been inserted (it could have been modified/sanitized from the given one and some missing properties or those which were wrong could have been inherited). */ CB_GraphicSprites.prototype.insertSprite = CB_GraphicSprites.prototype.insert = function(sprite, avoidUpdatingSpritesByZIndex) { //Sets the properties (sanitizing them): this.spritesGroup = this.spritesGroup || {}; sprite = sprite || {}; if (sprite.byReference !== true &amp;&amp; sprite.byReference !== false) { sprite.byReference = this.byReference_DEFAULT; } sprite = sprite.byReference ? sprite : CB_copyObject(sprite); sprite.isSprite = true; sprite.type = \"sprite\"; sprite.container = this; sprite.parent = this.spritesGroup; sprite.time = !isNaN(parseInt(sprite.time)) ? parseInt(sprite.time) : 0; sprite.id = sprite.id || \"CB_GraphicSprites.sprite_\" + CB_GraphicSprites._idSpriteUnique++; sprite.src = sprite.src || !isNaN(sprite.src) &amp;&amp; sprite.src !== null ? sprite.src : this.spritesGroup.src || !isNaN(this.spritesGroup.src) &amp;&amp; this.spritesGroup.src !== null ? this.spritesGroup.src : \"\"; sprite.srcType = sprite.srcType || this.spritesGroup.srcType || CB_GraphicSprites.SRC_TYPES_DEFAULT; sprite.srcLeft = parseFloat(sprite.srcLeft); sprite.srcLeft = !isNaN(sprite.srcLeft) ? sprite.srcLeft : parseFloat(this.spritesGroup.srcLeft); sprite.srcLeft = !isNaN(sprite.srcLeft) ? sprite.srcLeft : parseFloat(CB_GraphicSprites.LEFT_SOURCE_DEFAULT) || 0; sprite.left = parseFloat(sprite.left); //sprite.left = !isNaN(sprite.left) ? sprite.left : parseFloat(this.spritesGroup.left); sprite.left = !isNaN(sprite.left) ? sprite.left : parseFloat(CB_GraphicSprites.LEFT_DEFAULT) || 0; sprite.srcTop = parseFloat(sprite.srcTop); sprite.srcTop = !isNaN(sprite.srcTop) ? sprite.srcTop : parseFloat(this.spritesGroup.srcTop); sprite.srcTop = !isNaN(sprite.srcTop) ? sprite.srcTop : parseFloat(CB_GraphicSprites.TOP_SOURCE_DEFAULT) || 0; sprite.top = parseFloat(sprite.top); //sprite.top = !isNaN(sprite.top) ? sprite.top : parseFloat(this.spritesGroup.top); sprite.top = !isNaN(sprite.top) ? sprite.top : parseFloat(CB_GraphicSprites.TOP_DEFAULT) || 0; sprite.srcWidth = parseFloat(sprite.srcWidth); sprite.srcWidth = !isNaN(sprite.srcWidth) ? sprite.srcWidth : parseFloat(this.spritesGroup.srcWidth); sprite.srcWidth = !isNaN(sprite.srcWidth) ? sprite.srcWidth : parseFloat(CB_GraphicSprites.WIDTH_SOURCE_DEFAULT) || 0; sprite.width = parseFloat(sprite.width); sprite.width = !isNaN(sprite.width) ? sprite.width : parseFloat(this.spritesGroup.width); sprite.width = !isNaN(sprite.width) ? sprite.width : parseFloat(CB_GraphicSprites.WIDTH_DEFAULT) || 0; sprite.srcHeight = parseFloat(sprite.srcHeight); sprite.srcHeight = !isNaN(sprite.srcHeight) ? sprite.srcHeight : parseFloat(this.spritesGroup.srcHeight); sprite.srcHeight = !isNaN(sprite.srcHeight) ? sprite.srcHeight : parseFloat(CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT) || 0; sprite.height = parseFloat(sprite.height); sprite.height = !isNaN(sprite.height) ? sprite.height : parseFloat(this.spritesGroup.height); sprite.height = !isNaN(sprite.height) ? sprite.height : parseFloat(CB_GraphicSprites.HEIGHT_DEFAULT) || 0; sprite.zIndex = parseFloat(sprite.zIndex); sprite.zIndex = !isNaN(sprite.zIndex) ? sprite.zIndex : parseFloat(this.spritesGroup.zIndex); sprite.zIndex = !isNaN(sprite.zIndex) ? sprite.zIndex : parseFloat(CB_GraphicSprites.ZINDEX_DEFAULT) || 0; sprite.disabled = !!sprite.disabled || !!this.spritesGroup.disabled; if (!sprite.disabled &amp;&amp; this.isDisabled()) { this.setDisabled(false); } //If it is enabled and its sprites group parent is not, all the sprites group must be enabled. sprite.data = typeof(sprite.data) === \"object\" &amp;&amp; sprite.data !== null ? sprite.data : this.spritesGroup.data; if (typeof(this.spritesGroup.data) === \"object\" &amp;&amp; this.spritesGroup.data !== null) { sprite.data = CB_combineJSON(this.spritesGroup.data, sprite.data); } //Combine objects. sprite.data = typeof(sprite.data) === \"object\" &amp;&amp; sprite.data !== null ? CB_copyObject(sprite.data, false) : {}; sprite.data.that = sprite; sprite.data.getThis = function() { return this.that; }; sprite.subSprites = CB_isArray(sprite.subSprites) ? (sprite.byReference ? sprite.subSprites : CB_Arrays.copy(sprite.subSprites)) : []; //Inserts the methods: sprite.removeAll = sprite.removeSubSprites = function() { return CB_GraphicSprites.prototype.removeSubSprites.call(this.container, sprite); } sprite.insertSubSprites = function(subSprites) { return CB_GraphicSprites.prototype.insertSubSprites.call(this.container, subSprites, sprite); } sprite.remove = function(index) { return CB_GraphicSprites.prototype.removeSubSprite.call(this.container, index, sprite); } sprite.removeById = function(id) { return CB_GraphicSprites.prototype.removeSubSpriteById.call(this.container, id, sprite); } sprite.insert = function(subSprite) { return CB_GraphicSprites.prototype.insertSubSprite.call(this.container, subSprite, sprite); } sprite.getAll = sprite.getSubSprites = function(orderedByZIndex, returnValueOnFail) { return CB_GraphicSprites.prototype.getSubSprites.call(this.container, sprite, orderedByZIndex, returnValueOnFail); } sprite.get = function(index, returnValueOnFail) { return CB_GraphicSprites.prototype.getSubSprite.call(this.container, index, sprite, returnValueOnFail); } sprite.getById = function(id, returnValueOnFail) { return CB_GraphicSprites.prototype.getSubSpriteById.call(this.container, id, sprite, returnValueOnFail); } sprite.getIndexById = function(id) { return CB_GraphicSprites.prototype.getSubSpriteIndexById.call(this.container, id, sprite); } sprite.executeFunctionAll = sprite.executeAll = sprite.forEach = function(functionEach, orderedByZIndex, delayBetweenEach, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, functionFinish) { return CB_GraphicSprites.prototype.executeFunctionAllSubSprites.call(this.container, functionEach, orderedByZIndex, delayBetweenEach, sprite, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, functionFinish); } sprite.getZIndex = function(returnValueOnFail) { return CB_GraphicSprites.prototype.getZIndexSprite.call(this.container, sprite, returnValueOnFail); } sprite.setZIndex = function(zIndex) { return CB_GraphicSprites.prototype.setZIndexSprite.call(this.container, sprite, zIndex); } sprite.isDisabled = function() { return CB_GraphicSprites.prototype.isDisabledSprite.call(this.container, sprite); } sprite.setDisabled = function(disabled, affectSubSprites, affectParent, affectParentChildren) { return CB_GraphicSprites.prototype.setDisabledSprite.call(this.container, sprite, disabled, affectSubSprites, affectParent, affectParentChildren); } sprite.setTime = function(time) { return CB_GraphicSprites.prototype.setTime.call(this, time, false, false); } sprite.getTime = function(returnValueOnFail) { return CB_GraphicSprites.prototype.getTime.call(this, returnValueOnFail); } sprite.getTimeElapsed = function(timeToCompare) { return CB_GraphicSprites.prototype.getTimeElapsed.call(this, timeToCompare); } sprite.getPointer = sprite.getCurrentPosition = function() { return CB_GraphicSprites.prototype.getPointer.call(this.container); } sprite.getPointerPrevious = sprite.getPreviousPosition = function() { return CB_GraphicSprites.prototype.getPointerPrevious.call(this.container); } sprite.setPointer = sprite.setCurrentPosition = function(position, loop) { CB_GraphicSprites.prototype.setPointer.call(this.container, position, loop); return this.getCurrent(); } sprite.getCurrent = sprite.current = sprite.now = function() { return CB_GraphicSprites.prototype.getCurrent.call(this.container); } sprite.setNext = sprite.next = function(loop) { return CB_GraphicSprites.prototype.setNext.call(this.container, loop); } sprite.setPrevious = sprite.previous = function(loop) { return CB_GraphicSprites.prototype.setPrevious.call(this.container, loop); } sprite.getPrevious = function() { return CB_GraphicSprites.prototype.getPrevious.call(this.container); } sprite.setPropertyCascade = function(propertyName, value) { return CB_GraphicSprites.prototype.setPropertyCascade.call(this, propertyName, value, false); } //Inserts the given sub-sprites, one by one: this.insertSubSprites(sprite.subSprites, sprite); //Inserts the sprite: this.spritesGroup.sprites = this.spritesGroup.sprites || []; ////CB_Arrays.copy(this.spritesGroup.sprites); var position = this.getSpriteIndexById(sprite.id); //If there is a sprite with the same ID, it will be replaced by the new one (in the same position): position = position !== -1 ? position : this.spritesGroup.sprites.length; sprite.position = position; this.spritesGroup.sprites[position] = sprite; //If desired, updates the array with the sprites ordered by z-index: if (!avoidUpdatingSpritesByZIndex) { this.updateSpritesByZIndex(); } this.spritesGroup.sprites = this.spritesGroup.sprites; //Keeps the pointer if the position is valid or sets to the last position if the position was greater than the current limit or uses the first position otherwise: this.setPointer(this.getPointer()); //Returns the sprite: return sprite; } /** * Alias for {@link CB_GraphicSprites#removeSubSprites}. * @function CB_GraphicSprites#removeSubSpritesAll * @see {@link CB_GraphicSprites#removeSubSprites} */ /** * Removes all the sub-sprites from a given sprite ({@link CB_GraphicSprites.SPRITE_OBJECT} object) by clearing its \"subSprites\" property (leaving an empty array). * @function * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite=CB_GraphicSprites#getCurrent()] - Object with the sprite whose sub-sprites we want to remove. If not provided, it will use the {@link CB_GraphicSprites.SPRITE_OBJECT} object which the pointer (set in the {@link CB_GraphicSprites#pointer} property) is currently pointing to (using the returning value of the {@link CB_GraphicSprites#getCurrent} method internally). * @returns {boolean} Returns true if the sub-sprites have been deleted or false otherwise. */ CB_GraphicSprites.prototype.removeSubSprites = CB_GraphicSprites.prototype.removeSubSpritesAll = function(sprite) { var removed = false; sprite = sprite || this.getCurrent(); if (sprite) { if (this.spritesGroup &amp;&amp; this.spritesGroup.sprites) { var spritesLength = this.spritesGroup.sprites.length; for (var x = 0; x &lt; spritesLength; x++) { if (this.spritesGroup.sprites[x] === sprite) { this.spritesGroup.sprites[x].subSprites = []; this.spritesGroup.sprites[x].subSpritesByZIndex = []; removed = true; break; } //Just removes one. } } } return removed; } /** * Adds the given sub-sprites to the desired sprite. Calls the {@link CB_GraphicSprites#insertSubSprite} and {@link CB_GraphicSprites#updateSubSpritesByZIndex} methods internally. * @function * @param {array} subSprites - Numeric array with the desired sub-sprites ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects). They will be stored inside the given sprite. * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite=CB_GraphicSprites#getCurrent()] - Object with the desired sprite. If not provided, it will use the {@link CB_GraphicSprites.SPRITE_OBJECT} object which the pointer (set in the {@link CB_GraphicSprites#pointer} property) is currently pointing to (using the returning value of the {@link CB_GraphicSprites#getCurrent} method internally). * @returns {array} Returns an array with the {@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects which have been inserted (they could have been modified/sanitized from the given one and some missing properties or those which were wrong could have been inherited). */ CB_GraphicSprites.prototype.insertSubSprites = function(subSprites, sprite) { //Sets the properties (sanitizing them): sprite = sprite || this.getCurrent(); subSprites = CB_isArray(subSprites) ? subSprites : []; //Inserts the given sub-sprites, one by one: var subSpritesInserted = []; var subSpritesLength = subSprites.length; for (var x = 0; x &lt; subSpritesLength; x++) { subSpritesInserted[subSpritesInserted.length] = this.insertSubSprite(subSprites[x], sprite, true); } //Updates the array with the sub-sprites ordered by z-index: this.updateSubSpritesByZIndex(sprite); return subSpritesInserted; } /** * Updates (sorts again) the \"subSpritesByZIndex\" property (which is an array with the sub-sprites ordered by z-index, whose data comes from the array in the \"subSprites\" property of the given {@link CB_GraphicSprites.SPRITE_OBJECT} object)) of the desired sprite. * @function * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite=CB_GraphicSprites#getCurrent()] - Object with the sprite whose sub-sprites we want to remove. If not provided, it will use the {@link CB_GraphicSprites.SPRITE_OBJECT} object which the pointer (set in the {@link CB_GraphicSprites#pointer} property) is currently pointing to (using the returning value of the {@link CB_GraphicSprites#getCurrent} method internally). * @returns {array} Returns the \"subSpritesByZIndex\" array after updating it. Returns null if the property could not be obtained or updated. */ CB_GraphicSprites.prototype.updateSubSpritesByZIndex = function(sprite) { sprite = sprite || this.getCurrent(); if (sprite &amp;&amp; sprite.subSprites) { var subSpritesLength = sprite.subSprites.length; if (subSpritesLength) { var elementIndex = null; sprite.subSpritesByZIndex = []; for (var x = 0; x &lt; subSpritesLength; x++) { indexElement = CB_GraphicSpritesScene._choosePositionByZIndex(sprite.subSpritesByZIndex, sprite.subSprites[x]); sprite.subSpritesByZIndex = CB_Arrays.insertElement(sprite.subSpritesByZIndex, indexElement, sprite.subSprites[x]); sprite.subSprites[x].positionByZIndex = indexElement; } return sprite.subSpritesByZIndex; } } return null; } /** * Removes a sub-sprite from a given sprite ({@link CB_GraphicSprites.SPRITE_OBJECT} object) by its index (its position in the array which is in the \"subSprites\" property of the given {@link CB_GraphicSprites.SPRITE_OBJECT} object). Calls the {@link CB_GraphicSprites#updateSubSpritesByZIndex} method internally. * @function * @param {integer} [index=0] - The index where the sub-sprite is located (its position in the array which is in the \"subSprites\" property of the given {@link CB_GraphicSprites.SPRITE_OBJECT} object). * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite=CB_GraphicSprites#getCurrent()] - Object with the sprite whose sub-sprites we want to remove. If not provided, it will use the {@link CB_GraphicSprites.SPRITE_OBJECT} object which the pointer (set in the {@link CB_GraphicSprites#pointer} property) is currently pointing to (using the returning value of the {@link CB_GraphicSprites#getCurrent} method internally). * @returns {boolean} Returns true if the sub-sprite has been deleted or false otherwise. */ CB_GraphicSprites.prototype.removeSubSprite = function(index, sprite) { var removed = false; if (this.spritesGroup &amp;&amp; this.spritesGroup.sprites) { sprite = sprite || this.getCurrent(); if (sprite) { index = parseInt(index); index = isNaN(index) ? 0 : index; if (index &lt; 0) { index *= -1; } //It must be a positive integer. var subSpritesLeft = null; var spritesLength = this.spritesGroup.sprites.length; for (var x = 0; x &lt; spritesLength; x++) { if (this.spritesGroup.sprites[x] === sprite) { removed = false; subSpritesLeft = CB_Arrays.removeElementByPosition(this.spritesGroup.sprites[x].subSprites, index, function() { removed = true; }); if (removed) { this.spritesGroup.sprites[x].subSprites = subSpritesLeft; //Updates the array with the sub-sprites ordered by z-index: this.updateSubSpritesByZIndex(sprite); break; //Just removes it from one. } } } } } return removed; } /** * Removes a sub-sprite from a given sprite ({@link CB_GraphicSprites.SPRITE_OBJECT} object) by its identifier. Calls the {@link CB_GraphicSprites#updateSubSpritesByZIndex} method internally. * @function * @param {string|*} [id=undefined] - The identifier of the sprite. * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite=CB_GraphicSprites#getCurrent] - Object with the sprite whose sub-sprites we want to remove. * @returns {boolean} Returns true if the sub-sprite has been deleted or false otherwise. * @todo Optimize it (perhaps using a cache matching the IDs with their position, maybe using the \"position\" or \"positionByZIndex\" properties). */ CB_GraphicSprites.prototype.removeSubSpriteById = function(id, sprite) { var removed = false; if (this.spritesGroup &amp;&amp; this.spritesGroup.sprites) { sprite = sprite || this.getCurrent(); if (sprite) { var subSpritesLeft = null; var spritesLength = this.spritesGroup.sprites.length; for (var x = 0; x &lt; spritesLength; x++) { if (this.spritesGroup.sprites[x] === sprite) { removed = false; subSpritesLeft = CB_Arrays.removeDuplicated(this.spritesGroup.sprites[x].subSprites, function(value, position, array) { if (value &amp;&amp; value.id === id) { removed = true; return true; }; return false; }, true); if (removed) { this.spritesGroup.sprites[x].subSprites = subSpritesLeft; //Updates the array with the sub-sprites ordered by z-index: this.updateSubSpritesByZIndex(sprite); break; //Just removes it from one. } } } } } return removed; } /** * Adds the given sub-sprite to the desired sprite. If a sub-sprite with the same identifier already exists, it will be replaced by the new one in its same position. * @function * @param {CB_GraphicSprites.SUBSPRITE_OBJECT} subSprite - Object with the desired sub-sprite. It will be stored inside the given sprite. * @param {CB_GraphicSprites.SPRITE_OBJECT} sprite - Object with the desired sprite. * @param {boolean} [avoidUpdatingSubSpritesByZIndex=false] - If set to true, it will not call the {CB_GraphicSprites#updateSubSpritesByZIndex} method internally. Internal usage recommended only. * @returns {CB_GraphicSprites.SUBSPRITE_OBJECT} Returns the {@link CB_GraphicSprites.SUBSPRITE_OBJECT} object which has been inserted (it could have been modified/sanitized from the given one and some missing properties or those which were wrong could have been inherited). */ CB_GraphicSprites.prototype.insertSubSprite = function(subSprite, sprite, avoidUpdatingSubSpritesByZIndex) { //Sets the properties (sanitizing them): this.spritesGroup = this.spritesGroup || {}; sprite = sprite || {}; subSprite = subSprite || {}; if (sprite.byReference !== true &amp;&amp; sprite.byReference !== false) { sprite.byReference = this.byReference_DEFAULT; } subSprite = subSprite.byReference ? subSprite : CB_copyObject(subSprite); sprite.isSubSprite = true; subSprite.type = \"subSprite\"; subSprite.container = this; subSprite.parent = sprite; subSprite.time = !isNaN(parseInt(subSprite.time)) ? parseInt(subSprite.time) : !isNaN(parseInt(sprite.time)) ? parseInt(sprite.time) : 0; subSprite.id = subSprite.id || \"CB_GraphicSprites.subSprite_\" + CB_GraphicSprites._idSubSpriteUnique++; subSprite.src = subSprite.src || !isNaN(subSprite.src) &amp;&amp; subSprite.src !== null ? subSprite.src : sprite.src || !isNaN(sprite.src) &amp;&amp; sprite.src !== null ? sprite.src : this.spritesGroup.src || !isNaN(this.spritesGroup.src) &amp;&amp; this.spritesGroup.src !== null ? this.spritesGroup.src : \"\"; subSprite.srcType = subSprite.srcType || sprite.srcType || this.spritesGroup.srcType || CB_GraphicSprites.SRC_TYPES_DEFAULT; subSprite.srcLeft = parseFloat(subSprite.srcLeft); subSprite.srcLeft = !isNaN(subSprite.srcLeft) ? subSprite.srcLeft : parseFloat(sprite.srcLeft); subSprite.srcLeft = !isNaN(subSprite.srcLeft) ? subSprite.srcLeft : parseFloat(this.spritesGroup.srcLeft); subSprite.srcLeft = !isNaN(subSprite.srcLeft) ? subSprite.srcLeft : parseFloat(CB_GraphicSprites.LEFT_SOURCE_DEFAULT) || 0; subSprite.left = parseFloat(subSprite.left); //subSprite.left = !isNaN(subSprite.left) ? subSprite.left : parseFloat(sprite.left); //subSprite.left = !isNaN(subSprite.left) ? subSprite.left : parseFloat(this.spritesGroup.left); subSprite.left = !isNaN(subSprite.left) ? subSprite.left : parseFloat(CB_GraphicSprites.LEFT_DEFAULT) || 0; subSprite.srcTop = parseFloat(subSprite.srcTop); subSprite.srcTop = !isNaN(subSprite.srcTop) ? subSprite.srcTop : parseFloat(sprite.srcTop); subSprite.srcTop = !isNaN(subSprite.srcTop) ? subSprite.srcTop : parseFloat(this.spritesGroup.srcTop); subSprite.srcTop = !isNaN(subSprite.srcTop) ? subSprite.srcTop : parseFloat(CB_GraphicSprites.TOP_SOURCE_DEFAULT) || 0; subSprite.top = parseFloat(subSprite.top); //subSprite.top = !isNaN(subSprite.top) ? subSprite.top : parseFloat(sprite.top); //subSprite.top = !isNaN(subSprite.top) ? subSprite.top : parseFloat(this.spritesGroup.top); subSprite.top = !isNaN(subSprite.top) ? subSprite.top : parseFloat(CB_GraphicSprites.TOP_DEFAULT) || 0; subSprite.srcWidth = parseFloat(subSprite.srcWidth); subSprite.srcWidth = !isNaN(subSprite.srcWidth) ? subSprite.srcWidth : parseFloat(sprite.srcWidth); subSprite.srcWidth = !isNaN(subSprite.srcWidth) ? subSprite.srcWidth : parseFloat(this.spritesGroup.srcWidth); subSprite.srcWidth = !isNaN(subSprite.srcWidth) ? subSprite.srcWidth : parseFloat(CB_GraphicSprites.WIDTH_SOURCE_DEFAULT) || 0; subSprite.width = parseFloat(subSprite.width); subSprite.width = !isNaN(subSprite.width) ? subSprite.width : parseFloat(sprite.width); subSprite.width = !isNaN(subSprite.width) ? subSprite.width : parseFloat(this.spritesGroup.width); subSprite.width = !isNaN(subSprite.width) ? subSprite.width : parseFloat(CB_GraphicSprites.WIDTH_DEFAULT) || 0; subSprite.srcHeight = parseFloat(subSprite.srcHeight); subSprite.srcHeight = !isNaN(subSprite.srcHeight) ? subSprite.srcHeight : parseFloat(sprite.srcHeight); subSprite.srcHeight = !isNaN(subSprite.srcHeight) ? subSprite.srcHeight : parseFloat(this.spritesGroup.srcHeight); subSprite.srcHeight = !isNaN(subSprite.srcHeight) ? subSprite.srcHeight : parseFloat(CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT) || 0; subSprite.height = parseFloat(subSprite.height); subSprite.height = !isNaN(subSprite.height) ? subSprite.height : parseFloat(sprite.height); subSprite.height = !isNaN(subSprite.height) ? subSprite.height : parseFloat(this.spritesGroup.height); subSprite.height = !isNaN(subSprite.height) ? subSprite.height : parseFloat(CB_GraphicSprites.HEIGHT_DEFAULT) || 0; subSprite.zIndex = parseFloat(subSprite.zIndex); subSprite.zIndex = !isNaN(subSprite.zIndex) ? subSprite.zIndex : parseFloat(sprite.zIndex); subSprite.zIndex = !isNaN(subSprite.zIndex) ? subSprite.zIndex : parseFloat(this.spritesGroup.zIndex); subSprite.zIndex = !isNaN(subSprite.zIndex) ? subSprite.zIndex : parseFloat(CB_GraphicSprites.ZINDEX_DEFAULT) || 0; subSprite.disabled = !!subSprite.disabled || !!sprite.disabled || !!this.spritesGroup.disabled; if (!subSprite.disabled &amp;&amp; this.isDisabledSprite(sprite)) { this.setDisabled(false); } //If it is enabled but its sprite parent is not, all the sprites group must be enabled. subSprite.data = typeof(subSprite.data) === \"object\" &amp;&amp; subSprite.data !== null ? subSprite.data : sprite.data; if (typeof(sprite.data) === \"object\" &amp;&amp; sprite.data !== null) { subSprite.data = CB_combineJSON(sprite.data, subSprite.data); } //Combine objects. subSprite.data = typeof(subSprite.data) === \"object\" &amp;&amp; subSprite.data !== null ? subSprite.data : this.spritesGroup.data; if (typeof(this.spritesGroup.data) === \"object\" &amp;&amp; this.spritesGroup.data !== null) { subSprite.data = CB_combineJSON(this.spritesGroup.data, subSprite.data); } //Combine objects. subSprite.data = typeof(subSprite.data) === \"object\" &amp;&amp; subSprite.data !== null ? CB_copyObject(subSprite.data, false) : {}; subSprite.data.that = subSprite; subSprite.data.getThis = function() { return this.that; }; //Inserts the methods: subSprite.getZIndex = function(returnValueOnFail) { return CB_GraphicSprites.prototype.getZIndexSubSprite.call(this.container, subSprite, returnValueOnFail); } subSprite.setZIndex = function(zIndex) { return CB_GraphicSprites.prototype.setZIndexSubSprite.call(this.container, subSprite, zIndex); } subSprite.isDisabled = function() { return CB_GraphicSprites.prototype.isDisabledSubSprite.call(this.container, subSprite); } subSprite.setDisabled = function(disabled, affectParents, affectParentsChildren) { return CB_GraphicSprites.prototype.setDisabledSubSprite.call(this.container, subSprite, disabled, affectParents, affectParentsChildren); } subSprite.setTime = function(time) { return CB_GraphicSprites.prototype.setTime.call(this, time, false, false); } subSprite.getTime = function(returnValueOnFail) { return CB_GraphicSprites.prototype.getTime.call(this, returnValueOnFail, true); } subSprite.getTimeElapsed = function(timeToCompare) { return CB_GraphicSprites.prototype.getTimeElapsed.call(this, timeToCompare, true); } //Inserts the sub-sprite: sprite.subSprites = CB_isArray(sprite.subSprites) ? (sprite.byReference ? sprite.subSprites : CB_Arrays.copy(sprite.subSprites)) : []; var position = this.getSubSpriteIndexById(subSprite.id, sprite); //If there is a sub-sprite with the same ID, it will be replaced by the new one (in the same position). position = position !== -1 ? position : sprite.subSprites.length; subSprite.position = position; sprite.subSprites[position] = subSprite; //If desired, updates the array with the sub-sprites ordered by z-index: if (!avoidUpdatingSubSpritesByZIndex) { this.updateSubSpritesByZIndex(sprite); } //Returns the sub-sprite: return subSprite; } /** * Gets the sprites group object (the internal {@link CB_GraphicSprites.SPRITES_OBJECT} object, if any). * @function * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @returns {CB_GraphicSprites.SPRITES_OBJECT|*} Returns a {@link CB_GraphicSprites.SPRITES_OBJECT} object with all the sprites or the value of \"returnValueOnFail\" otherwise. */ CB_GraphicSprites.prototype.getSpritesGroup = function(returnValueOnFail) { return this.spritesGroup || returnValueOnFail; } /** * Alias for {@link CB_GraphicSprites#getSprites}. * @function CB_GraphicSprites#getAll * @see {@link CB_GraphicSprites#getSprites} */ /** * Alias for {@link CB_GraphicSprites#getSprites}. * @function CB_GraphicSprites#getSpritesAll * @see {@link CB_GraphicSprites#getSprites} */ /** * Gets all the sprites (the \"sprites\" property of the internal {@link CB_GraphicSprites.SPRITES_OBJECT} object, if any). * @function * @param {boolean} [orderedByZIndex=false] - If set to true, it will return the sprites sorted by their z-index (ascending order). * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @returns {array|*} Returns an array with all the {@link CB_GraphicSprites.SPRITE_OBJECT} objects or the value of \"returnValueOnFail\" otherwise. */ CB_GraphicSprites.prototype.getSprites = CB_GraphicSprites.prototype.getSpritesAll = CB_GraphicSprites.prototype.getAll = function(orderedByZIndex, returnValueOnFail) { if (this.spritesGroup) { if (!orderedByZIndex) { return (this.spritesGroup.sprites) ? this.spritesGroup.sprites : returnValueOnFail; } else { return (this.spritesGroup.spritesByZIndex) ? this.spritesGroup.spritesByZIndex : returnValueOnFail; } } return returnValueOnFail; } /** * Alias for {@link CB_GraphicSprites#getSprite}. * @function CB_GraphicSprites#get * @see {@link CB_GraphicSprites#getSprite} */ /** * Gets a desired sprite object through its index (its position in the {@link CB_GraphicSprites#spritesGroup.sprites} array). Faster than getting it through its identifier with the {@link CB_GraphicSprites#getSpriteById} method. * @function * @param {integer} [index=0] - The index where the desired sprite must be located (its position in the {@link CB_GraphicSprites#spritesGroup.sprites} array). * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @returns {CB_GraphicSprites.SPRITE_OBJECT|*} Returns a {@link CB_GraphicSprites.SPRITE_OBJECT} object if found or the value of \"returnValueOnFail\" otherwise. */ CB_GraphicSprites.prototype.getSprite = CB_GraphicSprites.prototype.get = function(index, returnValueOnFail) { index = parseInt(index); index = isNaN(index) ? 0 : index; if (index &lt; 0) { index *= -1; } //It must be a positive integer. return this.spritesGroup &amp;&amp; this.spritesGroup.sprites &amp;&amp; this.spritesGroup.sprites[index] ? this.spritesGroup.sprites[index] : returnValueOnFail; } /** * Alias for {@link CB_GraphicSprites#getSpriteById}. * @function CB_GraphicSprites#getById * @see {@link CB_GraphicSprites#getSpriteById} */ /** * Gets a desired sprite object through its identifier. Slower than getting it through its index with the {@link CB_GraphicSprites#getSprite} method. * @function * @param {string|*} [id=undefined] - The identifier of the sprite that we want to get. * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @returns {CB_GraphicSprites.SPRITE_OBJECT|*} Returns a {@link CB_GraphicSprites.SPRITE_OBJECT} object if found or the value of \"returnValueOnFail\" otherwise. */ CB_GraphicSprites.prototype.getSpriteById = CB_GraphicSprites.prototype.getById = function(id, returnValueOnFail) { var index = this.getSpriteIndexById(id); return index !== -1 ? this.spritesGroup.sprites[index] : returnValueOnFail; } /** * Alias for {@link CB_GraphicSprites#getSpriteIndexById}. * @function CB_GraphicSprites#getIndexById * @see {@link CB_GraphicSprites#getSpriteIndexById} */ /** * Gets the index (the position in the {@link CB_GraphicSprites#spritesGroup.sprites} array) of a desired sprite by its identifier. * @function * @param {string|*} [id=undefined] - The identifier of the sprite whose index we want to get. * @returns {integer} Returns the index (the position in the {@link CB_GraphicSprites#spritesGroup.sprites} array) of the desired sprite or -1 if not found. * @todo Optimize it (perhaps using a cache matching the IDs with their position, maybe using the \"position\" or \"positionByZIndex\" properties). */ CB_GraphicSprites.prototype.getSpriteIndexById = CB_GraphicSprites.prototype.getIndexById = function(id) { if (this.spritesGroup &amp;&amp; this.spritesGroup.sprites) { var spritesLength = this.spritesGroup.sprites.length; for (var x = 0; x &lt; spritesLength; x++) { if (this.spritesGroup.sprites[x].id === id) { return x; } } } return -1; } /** * Gets an array with all the {@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects of a given {@link CB_GraphicSprites.SPRITE_OBJECT} object. * @function * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite=CB_GraphicSprites#getCurrent()] - The {@link CB_GraphicSprites.SPRITE_OBJECT} object which contains the sprite and its sub-sprites. If not provided, it will use the {@link CB_GraphicSprites.SPRITE_OBJECT} object which the pointer (set in the {@link CB_GraphicSprites#pointer} property) is currently pointing to (using the returning value of the {@link CB_GraphicSprites#getCurrent} method internally). * @param {boolean} [orderedByZIndex=false] - If set to true, it will return the sub-sprites sorted by their z-index (ascending order). * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @returns {array|*} Returns an array with all the {@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects of the given {@link CB_GraphicSprites.SPRITE_OBJECT} object or the value of \"returnValueOnFail\" otherwise. */ CB_GraphicSprites.prototype.getSubSprites = function(sprite, orderedByZIndex, returnValueOnFail) { sprite = sprite || this.getCurrent(); if (sprite) { if (!orderedByZIndex) { return sprite.subSprites ? sprite.subSprites : returnValueOnFail; } else { return sprite.subSpritesByZIndex ? sprite.subSpritesByZIndex : returnValueOnFail; } } return returnValueOnFail; } /** * Gets a desired sub-sprite object through its index (its position in the array which is in the \"subSprites\" property of the given {@link CB_GraphicSprites.SPRITE_OBJECT} object). Faster than getting it through its identifier with the {@link CB_GraphicSprites#getSubSpriteById} method. * @function * @param {integer} [index=0] - The index where the desired sub-sprite must be located (its position in the array which is in the \"subSprites\" property of the given {@link CB_GraphicSprites.SPRITE_OBJECT} object). * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite=CB_GraphicSprites#getCurrent()] - The {@link CB_GraphicSprites.SPRITE_OBJECT} object which contains the sprite and its sub-sprites. If not provided, it will use the {@link CB_GraphicSprites.SPRITE_OBJECT} object which the pointer (set in the {@link CB_GraphicSprites#pointer} property) is currently pointing to (using the returning value of the {@link CB_GraphicSprites#getCurrent} method internally). * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @returns {CB_GraphicSprites.SUBSPRITE_OBJECT|*} Returns a {@link CB_GraphicSprites.SUBSPRITE_OBJECT} object if found or the value of \"returnValueOnFail\" otherwise. */ CB_GraphicSprites.prototype.getSubSprite = function(index, sprite, returnValueOnFail) { index = parseInt(index); index = isNaN(index) ? 0 : index; if (index &lt; 0) { index *= -1; } //It must be a positive integer. sprite = sprite || this.getCurrent(); return sprite &amp;&amp; sprite.subSprites &amp;&amp; sprite.subSprites[index] ? sprite.subSprites[index] : returnValueOnFail; } /** * Gets a desired sub-sprite object through its identifier from the given {@link CB_GraphicSprites.SPRITE_OBJECT} object. Slower than getting it through its index with the {@link CB_GraphicSprites#getSubSprite} method. * @function * @param {string|*} [id=undefined] - The identifier of the sub-sprite that we want to get. * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite=CB_GraphicSprites#getCurrent()] - The {@link CB_GraphicSprites.SPRITE_OBJECT} object which contains the sprite and its sub-sprites. If not provided, it will use the {@link CB_GraphicSprites.SPRITE_OBJECT} object which the pointer (set in the {@link CB_GraphicSprites#pointer} property) is currently pointing to (using the returning value of the {@link CB_GraphicSprites#getCurrent} method internally). * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @returns {CB_GraphicSprites.SUBSPRITE_OBJECT|*} Returns a {@link CB_GraphicSprites.SUBSPRITE_OBJECT} object if found or the value of \"returnValueOnFail\" otherwise. */ CB_GraphicSprites.prototype.getSubSpriteById = function(id, sprite, returnValueOnFail) { sprite = sprite || this.getCurrent(); var index = this.getSubSpriteIndexById(id, sprite); return index !== -1 ? sprite.subSprites[index] : returnValueOnFail; } /** * Gets the index (its position in the array which is in the \"subSprites\" property of the given {@link CB_GraphicSprites.SPRITE_OBJECT} object) of a desired sub-sprite by its identifier. * @function * @param {string|*} [id=undefined] - The identifier of the sub-sprite whose index we want to get. * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite=CB_GraphicSprites#getCurrent()] - The {@link CB_GraphicSprites.SPRITE_OBJECT} object which contains the sprite and its sub-sprites. If not provided, it will use the {@link CB_GraphicSprites.SPRITE_OBJECT} object which the pointer (set in the {@link CB_GraphicSprites#pointer} property) is currently pointing to (using the returning value of the {@link CB_GraphicSprites#getCurrent} method internally). * @returns {integer} Returns the index (its position in the array which is in the \"subSprites\" property of the given {@link CB_GraphicSprites.SPRITE_OBJECT} object) of the desired sub-sprite or -1 if not found. * @todo Optimize it (perhaps using a cache matching the IDs with their position, maybe using the \"position\" or \"positionByZIndex\" properties). */ CB_GraphicSprites.prototype.getSubSpriteIndexById = function(id, sprite) { sprite = sprite || this.getCurrent(); if (sprite &amp;&amp; sprite.subSprites) { var subSpritesLength = sprite.subSprites.length; for (var x = 0; x &lt; subSpritesLength; x++) { if (sprite.subSprites[x].id === id) { return x; } } } return -1; } /** * Alias for {@link CB_GraphicSprites#executeFunctionAll}. * @function CB_GraphicSprites#executeAll * @see {@link CB_GraphicSprites#executeFunctionAll} */ /** * Alias for {@link CB_GraphicSprites#executeFunctionAll}. * @function CB_GraphicSprites#forEach * @see {@link CB_GraphicSprites#executeFunctionAll} */ /** * Alias for {@link CB_GraphicSprites#executeFunctionAll}. * @function CB_GraphicSprites#forEachSprite * @see {@link CB_GraphicSprites#executeFunctionAll} */ /** * Performs a desired action, using the provided function, on all the existing sprites ({@link CB_GraphicSprites.SPRITE_OBJECT} objects) or on the desired ones (if provided). Calls the {@link CB_Arrays.executeFunctionAll} function internally and returns its returning value. * @function * @param {CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} functionEach - Function that will be called for each sprite ({@link CB_GraphicSprites.SPRITE_OBJECT} object). As the first parameter it receives the {@link CB_GraphicSprites.SPRITE_OBJECT} object of the \"sprites\" being looped, as the second parameter the position of this {@link CB_GraphicSprites.SPRITE_OBJECT} object in the \"sprites\" array provided (or, if not provided, in the array returned by the {@link CB_GraphicSprites#getSprites} method), the third parameter is the array being looped and the fourth parameter will be the \"delayBetweenEach\" being used, being \"this\" the {@link CB_GraphicSprites.SPRITE_OBJECT} object itself. * @param {boolean} [orderedByZIndex=false] - If set to true, it will loop the sprites sorted by their z-index (ascending order). * @param {number|CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} [delayBetweenEach=0] - If a value greater than zero is used, it will be used as the delay desired between each call to the \"functionEach\" function (calling them using the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function internally). If not provided or the value is 0 (zero) or lower, each call to the \"functionEach\" function will be performed immediately one after the other. If a function is provided, it will be called with the same parameters as the \"functionEach\" function and its returning value will be used as the delay (executed every loop for each {@link CB_GraphicSprites.SPRITE_OBJECT} object). * @param {array} [sprites={@link CB_GraphicSprites#getSprites}()] - A numeric array containing the sprites ({@link CB_GraphicSprites.SPRITE_OBJECT} objects) that we want to loop. It should contain only {@link CB_GraphicSprites.SPRITE_OBJECT} objects which are already in the current {@link CB_GraphicSprites} object. If not provided, it will use all the {@link CB_GraphicSprites.SPRITE_OBJECT} objects contained in the {@link CB_GraphicSprites} object. * @param {boolean} [returnSetTimeoutsArray=false] - Defines whether we want the method to return an integer or a numeric array with information of each [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} call. Returning an array with information of each [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} call is only useful when the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function is called internally, which happens when the \"delayBetweenEach\" parameter is greater than 0 (zero). * @param {boolean} [delayBetweenEachAffectsFirst=false] - If set to true, the desired delay (if any) will also affect the first call to the \"functionEach\" function. * @param {CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK} [functionFinish] - Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. * @returns {integer|array} If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the {@link CB_GraphicSprites.SPRITE_OBJECT} objects given in the \"sprites\" parameter). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a {@link CB_Arrays.executeFunctionAll_OBJECT} object for each {@link CB_GraphicSprites.SPRITE_OBJECT} given. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function. * @todo Think about only allowing {@link CB_GraphicSprites.SPRITE_OBJECT} objects (in the \"sprites\" parameter) which are already in the {@link CB_GraphicSprites} (identify them by their ID), to avoid problems. */ CB_GraphicSprites.prototype.executeFunctionAll = CB_GraphicSprites.prototype.executeAll = CB_GraphicSprites.prototype.forEachSprite = CB_GraphicSprites.prototype.forEach = function(functionEach, orderedByZIndex, delayBetweenEach, sprites, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, functionFinish) { return CB_Arrays.executeFunctionAll(CB_isArray(sprites) ? sprites : this.getSprites(orderedByZIndex, []), functionEach, delayBetweenEach, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, functionFinish); } /** * Alias for {@link CB_AudioFileSpritesPool#executeFunctionAllSubSprites}. * @function CB_AudioFileSpritesPool#executeAllSubSprites * @see {@link CB_AudioFileSpritesPool#executeFunctionAllSubSprites} */ /** * Alias for {@link CB_AudioFileSpritesPool#executeFunctionAllSubSprites}. * @function CB_AudioFileSpritesPool#forEachSubSprite * @see {@link CB_AudioFileSpritesPool#executeFunctionAllSubSprites} */ /** * Performs a desired action, using the provided function, on all the existing sub-sprites ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects) from a given sprite ({@link CB_GraphicSprites.SPRITE_OBJECT} object). Calls the {@link CB_Arrays.executeFunctionAll} function internally and returns its returning value. * @function * @param {CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} functionEach - Function that will be called for each sub-sprite ({@link CB_GraphicSprites.SUBSPRITE_OBJECT} object) from the given sprite ({@link CB_GraphicSprites.SPRITE_OBJECT} object). As the first parameter it receives the {@link CB_GraphicSprites.SUBSPRITE_OBJECT} object of the sub-sprites being looped, as the second parameter the position of this {@link CB_GraphicSprites.SUBSPRITE_OBJECT} object in the \"subSprites\" property of the sprite ({@link CB_GraphicSprites.SPRITE_OBJECT} object) provided (which is an array), the third parameter is the array being looped and the fourth parameter will be the \"delayBetweenEach\" being used, being \"this\" the {@link CB_GraphicSprites.SUBSPRITE_OBJECT} object itself. * @param {boolean} [orderedByZIndex=false] - If set to true, it will loop the sub-sprites sorted by their z-index (ascending order). * @param {number|CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} [delayBetweenEach=0] - If a value greater than zero is used, it will be used as the delay desired between each call to the \"functionEach\" function (calling them using the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function internally). If not provided or the value is 0 (zero) or lower, each call to the \"functionEach\" function will be performed immediately one after the other. If a function is provided, it will be called with the same parameters as the \"functionEach\" function and its returning value will be used as the delay (executed every loop for each {@link CB_GraphicSprites.SUBSPRITE_OBJECT} object). * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite=CB_GraphicSprites#getCurrent()] - The {@link CB_GraphicSprites.SPRITE_OBJECT} object which contains the sprite and its sub-sprites. If not provided, it will use the {@link CB_GraphicSprites.SPRITE_OBJECT} object which the pointer (set in the {@link CB_GraphicSprites#pointer} property) is currently pointing to (using the returning value of the {@link CB_GraphicSprites#getCurrent} method internally). * @param {boolean} [returnSetTimeoutsArray=false] - Defines whether we want the method to return an integer or a numeric array with information of each [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} call. Returning an array with information of each [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} call is only useful when the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function is called internally, which happens when the \"delayBetweenEach\" parameter is greater than 0 (zero). * @param {boolean} [delayBetweenEachAffectsFirst=false] - If set to true, the desired delay (if any) will also affect the first call to the \"functionEach\" function. * @param {CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK} [functionFinish] - Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. * @returns {integer|array} If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the existing {@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects in the given {@link CB_GraphicSprites.SPRITE_OBJECT} object). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a {@link CB_Arrays.executeFunctionAll_OBJECT} object for each {@link CB_GraphicSprites.SUBSPRITE_OBJECT}. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function. * @todo Think about only allowing {@link CB_GraphicSprites.SPRITE_OBJECT} objects (in the \"sprite\" parameter) which are already in the {@link CB_GraphicSprites.SPRITE_OBJECT} (identify them by their ID), to avoid problems. */ CB_GraphicSprites.prototype.executeFunctionAllSubSprites = CB_GraphicSprites.prototype.executeAllSubSprites = CB_GraphicSprites.prototype.forEachSubSprite = function(functionEach, orderedByZIndex, delayBetweenEach, sprite, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, functionFinish) { return CB_Arrays.executeFunctionAll(this.getSubSprites(sprite, orderedByZIndex, []), functionEach, delayBetweenEach, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, functionFinish); } /** * Alias for {@link CB_GraphicSprites#getPointerPrevious}. * @function CB_GraphicSprites#getPreviousPosition * @see {@link CB_GraphicSprites#getPointerPrevious} */ /** * Gets the previous position of the pointer. It belongs to an index of the {@link CB_GraphicSprites#spritesGroup.sprites} array where a {@link CB_GraphicSprites.SPRITE_OBJECT} object is placed (containing a sprite). Internally, it uses the {@link CB_GraphicSprites#pointerPrevious} property. * @function * @returns {integer} Returns the position where the pointer was previously pointing to. It belongs to an index of the {@link CB_GraphicSprites#spritesGroup.sprites} array where a {@link CB_GraphicSprites.SPRITE_OBJECT} object is placed (containing a sprite). If not found, returns -1 by default. */ CB_GraphicSprites.prototype.getPointerPrevious = CB_GraphicSprites.prototype.getPreviousPosition = function() { return this.pointerPrevious === 0 || parseInt(this.pointerPrevious) &amp;&amp; this.pointerPrevious &gt; 0 ? this.pointerPrevious : -1; } /** * Alias for {@link CB_GraphicSprites#getPointer}. * @function CB_GraphicSprites#getCurrentPosition * @see {@link CB_GraphicSprites#getPointer} */ /** * Gets the current position of the pointer. It belongs to an index of the {@link CB_GraphicSprites#spritesGroup.sprites} array where a {@link CB_GraphicSprites.SPRITE_OBJECT} object is placed (containing a sprite). Internally, it uses the {@link CB_GraphicSprites#pointer} property. * @function * @returns {integer} Returns the position where the pointer is currently pointing to. It belongs to an index of the {@link CB_GraphicSprites#spritesGroup.sprites} array where a {@link CB_GraphicSprites.SPRITE_OBJECT} object is placed (containing a sprite). If not found, returns zero (0) by default. */ CB_GraphicSprites.prototype.getPointer = CB_GraphicSprites.prototype.getCurrentPosition = function() { return parseInt(this.pointer) &amp;&amp; this.pointer &gt; 0 ? this.pointer : 0; } /** * Alias for {@link CB_GraphicSprites#setPointer}. * @function CB_GraphicSprites#setCurrentPosition * @see {@link CB_GraphicSprites#setPointer} */ /** * Sets the pointer to the desired position (if possible). The position should belong to an index of the {@link CB_GraphicSprites#spritesGroup.sprites} array where a {@link CB_GraphicSprites.SPRITE_OBJECT} object is placed (containing a sprite). Internally, it modifies the {@link CB_GraphicSprites#pointer} property (if possible). If the position was updated, it will also reset the {@link CB_GraphicSprites#time} property (setting the current time in milliseconds). * @function * @param {integer} [position=0|CB_GraphicSprites#spritesGroup.sprites.length-1|position%CB_GraphicSprites#spritesGroup.sprites.length] - The position that we want the pointer to use. The position should belong to an index of the {@link CB_GraphicSprites#spritesGroup.sprites} array where a {@link CB_GraphicSprites.SPRITE_OBJECT} object is placed (containing a sprite). * @param {boolean} [loop=false] - If set to false and the \"position\" given is greater than the current number of sprites, the \"position\" used will be the one which belongs to the last sprite. If set to false and the \"position\" given is lower than zero, the \"position\" used will be zero (the first position). Otherwise, if set to true and the \"position\" given is greater than the current number of sprites or lower than zero, it will modify the given \"position\" making it cycle (from the end to the beginning) treating always the \"position\" as a positive number. This parameter is ignored when the given \"position\" has not reached the limit. * @returns {integer} Returns the position where the pointer is currently pointing to. It belongs to an index of the {@link CB_GraphicSprites#spritesGroup.sprites} array where a {@link CB_GraphicSprites.SPRITE_OBJECT} object is placed (containing a sprite). */ CB_GraphicSprites.prototype.setPointer = CB_GraphicSprites.prototype.setCurrentPosition = function(position, loop) { if (this.spritesGroup &amp;&amp; this.spritesGroup.sprites &amp;&amp; this.spritesGroup.sprites.length) { position = position || 0; if (loop) { if (position &lt; 0) { position = position * -1; } //Converts it to a positive number. position %= this.spritesGroup.sprites.length; } else if (position &lt; 0) { position = 0; } else if (position &gt;= this.spritesGroup.sprites.length) { position = this.spritesGroup.sprites.length - 1; } if (this.pointer !== position) { this.pointerPrevious = this.pointer; this.pointer = position; this.setTime(undefined, true, true); } //Updates the pointer and \"resets\" the time. } return this.pointer || 0; } /** * Gets the sprite (a {@link CB_GraphicSprites.SPRITE_OBJECT} object) which was previously pointed (by the previous value of the pointer set in the {@link CB_GraphicSprites#pointer} property, whose value is now in the {@link CB_GraphicSprites#pointerPrevious} property). * @function * @returns {CB_GraphicSprites.SPRITE_OBJECT|null} Returns the {@link CB_GraphicSprites.SPRITE_OBJECT} object which was previously pointed by the pointer (by the previous value of the pointer set in the {@link CB_GraphicSprites#pointer} property, whose value is now in the {@link CB_GraphicSprites#pointerPrevious} property). Returns null if not found. */ CB_GraphicSprites.prototype.getPrevious = function() { if (this.pointerPrevious === 0 || parseInt(this.pointerPrevious) &amp;&amp; this.pointerPrevious &gt; 0) { return this.getSprite(this.pointerPrevious, null); } else { return null; } } /** * Alias for {@link CB_GraphicSprites#getCurrent}. * @function CB_GraphicSprites#now * @see {@link CB_GraphicSprites#getCurrent} */ /** * Alias for {@link CB_GraphicSprites#getCurrent}. * @function CB_GraphicSprites#current * @see {@link CB_GraphicSprites#getCurrent} */ /** * Gets the sprite (a {@link CB_GraphicSprites.SPRITE_OBJECT} object) which is being currently pointed (by the pointer set in the {@link CB_GraphicSprites#pointer} property). * @function * @returns {CB_GraphicSprites.SPRITE_OBJECT|null} Returns the {@link CB_GraphicSprites.SPRITE_OBJECT} object which is currently pointed by the pointer (set in the {@link CB_GraphicSprites#pointer} property). Returns null if not found. */ CB_GraphicSprites.prototype.getCurrent = CB_GraphicSprites.prototype.current = CB_GraphicSprites.prototype.now = function() { return this.getSprite(this.getPointer(), null); } /** * Alias for {@link CB_GraphicSprites#setPrevious}. * @function CB_GraphicSprites#previous * @see {@link CB_GraphicSprites#setPrevious} */ /** * Makes the pointer to go back to the previous position (if possible) and returns the sprite located there (if any). The position should belong to an index of the {@link CB_GraphicSprites#spritesGroup.sprites} array where a {@link CB_GraphicSprites.SPRITE_OBJECT} object is placed (containing a sprite) and it will be returned if found. Internally, it modifies the {@link CB_GraphicSprites#pointer} property (if possible). If the position was updated, it will update also the {@link CB_GraphicSprites#time} property (setting the current time in milliseconds). * @function * @param {boolean} [loop=false] - If set to false and the previous position is lower than zero, it will return null. Otherwise, if set to true and the position is lower than zero, it will modify the position making it cycle (from the beginning to the end). This parameter is ignored when the position has not reached the limit. * @returns {CB_GraphicSprites.SPRITE_OBJECT|null} Makes it to point to the previous {@link CB_GraphicSprites.SPRITE_OBJECT} object (making it the current one) and returns it. Returns null if it cannot be found. */ CB_GraphicSprites.prototype.setPrevious = CB_GraphicSprites.prototype.previous = function(loop) { var pointer = this.getPointer() - 1; if (pointer &lt; 0) { if (loop &amp;&amp; this.spritesGroup &amp;&amp; this.spritesGroup.sprites &amp;&amp; this.spritesGroup.sprites.length) { pointer = this.spritesGroup.sprites.length + pointer; } else { return null; } } var sprite = this.getSprite(pointer, null); if (sprite !== null &amp;&amp; this.pointer !== pointer) { this.pointerPrevious = this.pointer; this.pointer = pointer; this.setTime(undefined, true, true); } //Updates the pointer and \"resets\" the time. return sprite; } /** * Alias for {@link CB_GraphicSprites#setNext}. * @function CB_GraphicSprites#next * @see {@link CB_GraphicSprites#setNext} */ /** * Makes the pointer to advance to the next position (if possible) and returns the sprite located there (if any). The position should belong to an index of the {@link CB_GraphicSprites#spritesGroup.sprites} array where a {@link CB_GraphicSprites.SPRITE_OBJECT} object is placed (containing a sprite) and it will be returned if found. Internally, it modifies the {@link CB_GraphicSprites#pointer} property (if possible). If the position was updated, it will also update the {@link CB_GraphicSprites#time} property (setting the current time in milliseconds). * @function * @param {boolean} [loop=false] - If set to false and the next position is greater than the current number of sprites, it will return null. Otherwise, if set to true and the position is greater than the current number of sprites, it will modify the position making it cycle (from the end to the beginning). This parameter is ignored when the position has not reached the limit. * @returns {CB_GraphicSprites.SPRITE_OBJECT|null} Makes it to point to the next {@link CB_GraphicSprites.SPRITE_OBJECT} object (making it the current one) and returns it. Returns null if it cannot be found. */ CB_GraphicSprites.prototype.setNext = CB_GraphicSprites.prototype.next = function(loop) { var pointer = this.getPointer() + 1; if (loop &amp;&amp; this.spritesGroup &amp;&amp; this.spritesGroup.sprites &amp;&amp; this.spritesGroup.sprites.length) { pointer %= this.spritesGroup.sprites.length; } var sprite = this.getSprite(pointer, null); if (sprite !== null &amp;&amp; this.pointer !== pointer) { this.pointerPrevious = this.pointer; this.pointer = pointer; this.setTime(undefined, true, true); } //Updates the pointer and \"resets\" the time. return sprite; } /** * Gets the z-index (\"zIndex\" property) of the sprites group object (and the {@CB_GraphicSprites} object itself). * @function * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @returns {number} Returns the z-index (\"zIndex\") of the sprites group object (and the {@CB_GraphicSprites} object itself). If not found, returns the value of the {@link CB_GraphicSprites.ZINDEX_DEFAULT} property of evaluates to true or \"returnValueOnFail\" otherwise. */ CB_GraphicSprites.prototype.getZIndex = function(returnValueOnFail) { return parseFloat(this.zIndex) || CB_GraphicSprites.ZINDEX_DEFAULT || returnValueOnFail; } /** * Sets the desired z-index (\"zIndex\" property) of the sprites group object (and the {@CB_GraphicSprites} object itself). If there is a {@link CB_GraphicSpritesScene} parent object (set in the {@link CB_GraphicSprites.parent} property), it will also call its {@link CB_GraphicSpritesScene#updateGraphicSpritesByZIndex} method internally. * @function * @param {number} [zIndex=parseFloat(zIndex)||CB_GraphicSprites.ZINDEX_DEFAULT||1] - The z-index value we want. It must be a number but never zero (0). If no valid number is given, it will use the value of the {@link CB_GraphicSprites.ZINDEX_DEFAULT} property of evaluates to true or 1 otherwise. * @returns {number} Returns the z-index (\"zIndex\") of the sprites group object (and the {@CB_GraphicSprites} object itself) after setting it (it could have been sanitized). */ CB_GraphicSprites.prototype.setZIndex = function(zIndex) { this.zIndex = parseFloat(zIndex) || CB_GraphicSprites.ZINDEX_DEFAULT || 1; if (this.spritesGroup) { this.spritesGroup.zIndex = this.zIndex; } //If there is a parent (CB_GraphicSpritesScene object), updates the array with its CB_GraphicSprites ordered by z-index: if (this.parent &amp;&amp; typeof(this.parent.updateGraphicSpritesByZIndex) === \"function\") { this.parent.updateGraphicSpritesByZIndex.call(this.parent); } return this.zIndex; } /** * Gets the z-index (\"zIndex\" property) of a given sprite object. * @function * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite=CB_GraphicSprites#getCurrent()] - The {@link CB_GraphicSprites.SPRITE_OBJECT} object which contains the sprite. If not provided, it will use the {@link CB_GraphicSprites.SPRITE_OBJECT} object which the pointer (set in the {@link CB_GraphicSprites#pointer} property) is currently pointing to (using the returning value of the {@link CB_GraphicSprites#getCurrent} method internally). * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @returns {number} Returns the z-index (\"zIndex\") of the given sprite. If not found, returns the value of the {@link CB_GraphicSprites.ZINDEX_DEFAULT} property of evaluates to true or \"returnValueOnFail\" otherwise. */ CB_GraphicSprites.prototype.getZIndexSprite = function(sprite, returnValueOnFail) { sprite = sprite || this.getCurrent(); return sprite &amp;&amp; parseFloat(sprite.zIndex) ? sprite.zIndex : CB_GraphicSprites.ZINDEX_DEFAULT || returnValueOnFail; } /** * Sets the desired z-index (\"zIndex\") of the given sprite object. Calls the {@link CB_GraphicSprites#updateSpritesByZIndex} method internally. * @function * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite=CB_GraphicSprites#getCurrent()] - The {@link CB_GraphicSprites.SPRITE_OBJECT} object which contains the sprite. If not provided, it will use the {@link CB_GraphicSprites.SPRITE_OBJECT} object which the pointer (set in the {@link CB_GraphicSprites#pointer} property) is currently pointing to (using the returning value of the {@link CB_GraphicSprites#getCurrent} method internally). * @param {number} [zIndex=parseFloat(zIndex)||CB_GraphicSprites.ZINDEX_DEFAULT||1] - The z-index value we want. It must be a number but never zero (0). If no valid number is given, it will use the value of the {@link CB_GraphicSprites.ZINDEX_DEFAULT} property of evaluates to true or 1 otherwise. * @returns {number} Returns the z-index (\"zIndex\") of the given sprite after setting it (it could have been sanitized). */ CB_GraphicSprites.prototype.setZIndexSprite = function(sprite, zIndex) { sprite = sprite || this.getCurrent(); if (sprite &amp;&amp; sprite.parent) { sprite.zIndex = parseFloat(zIndex) || CB_GraphicSprites.ZINDEX_DEFAULT || 1; //Updates the array with the sprites ordered by z-index: this.updateSpritesByZIndex(); } return sprite.zIndex; } /** * Gets the z-index (\"zIndex\" property) of a given sub-sprite object. * @function * @param {CB_GraphicSprites.SUBSPRITE_OBJECT} subSprite - The {@link CB_GraphicSprites.SUBSPRITE_OBJECT} object which contains the sub-sprite. * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @returns {number} Returns the z-index (\"zIndex\") of the given sub-sprite. If not found, returns the value of the {@link CB_GraphicSprites.ZINDEX_DEFAULT} property of evaluates to true or \"returnValueOnFail\" otherwise. */ CB_GraphicSprites.prototype.getZIndexSubSprite = function(subSprite, returnValueOnFail) { return subSprite &amp;&amp; parseFloat(subSprite.zIndex) ? subSprite.zIndex : CB_GraphicSprites.ZINDEX_DEFAULT || returnValueOnFail; } /** * Sets the desired z-index (\"zIndex\") of the given sub-sprite object. Calls the {@link CB_GraphicSprites#updateSubSpritesByZIndex} method internally. * @function * @param {CB_GraphicSprites.SUBSPRITE_OBJECT} sprite - The {@link CB_GraphicSprites.SUBSPRITE_OBJECT} object which contains the sub-sprite. * @param {number} [zIndex=parseFloat(zIndex)||CB_GraphicSprites.ZINDEX_DEFAULT||0] - The z-index value we want. It must be a number but never zero (0). If no valid number is given, it will use the value of the {@link CB_GraphicSprites.ZINDEX_DEFAULT} property of evaluates to true or 1 otherwise. * @returns {number} Returns the z-index (\"zIndex\") of the given sub-sprite after setting it (it could have been sanitized). */ CB_GraphicSprites.prototype.setZIndexSubSprite = function(subSprite, zIndex) { if (subSprite &amp;&amp; subSprite.parent) { subSprite.zIndex = parseFloat(zIndex) || CB_GraphicSprites.ZINDEX_DEFAULT || 1; //Updates the array with the sub-sprites ordered by z-index: this.updateSubSpritesByZIndex(subSprite.parent); } return subSprite.zIndex; } /** * Tells whether the sprites group object (and the {@CB_GraphicSprites} object itself) is disabled or not. Internally, it checks the \"{@link CB_GraphicSprites.spritesGroup}.disabled\" property. * @function * @returns {boolean} Returns whether the sprites group object (and the {@link CB_GraphicSprites} object itself) is disabled or not. */ CB_GraphicSprites.prototype.isDisabled = function() { return !!this.getSpritesGroup({}).disabled; } /** * Sets whether the sprites group object (and the {@CB_GraphicSprites} object itself) is disabled or enabled. Internally, it edits the \"{@link CB_GraphicSprites.spritesGroup}.disabled\" property. * @function * @param {boolean} [disabled=false] - Set to true to disable it or false to enable it. * @param {boolean} [affectChildren=disabled] - If this parameter is set to true, it will also modify the \"disabled\" property of all the sprites and their sub-sprites. By default, it is false if the \"disabled\" parameter is set to false or it is true otherwise. */ CB_GraphicSprites.prototype.setDisabled = function(disabled, affectChildren) { disabled = !!disabled; if (typeof(affectChildren) === \"undefined\" || affectChildren === null) { affectChildren = disabled; } this.spritesGroup = this.spritesGroup || {}; this.spritesGroup.disabled = disabled; if (affectChildren) { this.executeFunctionAll(function() { if (this.setDisabled &amp;&amp; typeof(this.setDisabled) === \"function\") { this.setDisabled(disabled, true, false, false); } }); } } /** * Tells whether the given sprite is disabled or not. Internally, it checks its \"disabled\" property and also the \"{@link CB_GraphicSprites.spritesGroup}.disabled\" property (calling the {@link CB_GraphicSprites#isDisabled} method internally). A sprite is considered disabled if its sprites group parent is also disabled. * @function * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite=CB_GraphicSprites#getCurrent()] - The {@link CB_GraphicSprites.SPRITE_OBJECT} object which contains the sprite. If not provided, it will use the {@link CB_GraphicSprites.SPRITE_OBJECT} object which the pointer (set in the {@link CB_GraphicSprites#pointer} property) is currently pointing to (using the returning value of the {@link CB_GraphicSprites#getCurrent} method internally). * @returns {boolean} Returns whether the sprite is disabled or not. A sprite is considered disabled if its sprites group parent is also disabled. */ CB_GraphicSprites.prototype.isDisabledSprite = function(sprite) { sprite = sprite || this.getCurrent() || {}; return !!sprite.disabled || this.isDisabled(); } /** * Sets a given sprite disabled or enabled. Internally, it edits its \"disabled\" property. * @function * @param {CB_GraphicSprites.SPRITE_OBJECT} [sprite=CB_GraphicSprites#getCurrent()] - The {@link CB_GraphicSprites.SPRITE_OBJECT} object which contains the sprite. If not provided, it will use the {@link CB_GraphicSprites.SPRITE_OBJECT} object which the pointer (set in the {@link CB_GraphicSprites#pointer} property) is currently pointing to (using the returning value of the {@link CB_GraphicSprites#getCurrent} method internally). * @param {boolean} [disabled=false] - Set to true to disable it or false to enable it. * @param {boolean} [affectSubSprites=disabled] - If this parameter is set to true, it will also modify the \"disabled\" property of all the sub-sprites of the given sprite. This parameter will be ignored if the \"affectParent\" parameter is set to true (as all existing sprites and sub-sprites in the {@link CB_GraphicSprites} object will be affected anyway). By default, it is false if the \"disabled\" parameter is set to false or it is true otherwise. * @param {boolean} [affectParent=affectParentChildren|!disabled] - If this parameter is set to true, it will also modify the \"disabled\" property of the sprites group object (which is considered the status of the whole {@CB_GraphicSprites} object). By default, it is true if either the \"affectParentChildren\" parameter is set to true or the \"disabled\" parameter is set to false and it is false otherwise. * @param {boolean} [affectParentChildren=!disabled] - Defines whether to also affect the sprites and sub-sprites of the sprites group object (which is considered the status of the whole {@CB_GraphicSprites} object) or not. If it is set to true and the \"affectParent\" is also set to true, it will also modify the \"disabled\" property of all the existing sprites and sub-sprites in the {@link CB_GraphicSprites} object. This parameter is ignored if the \"affectParent\" parameter is set to false. By default, it is false if the \"disabled\" parameter is set to true or it is false otherwise. */ CB_GraphicSprites.prototype.setDisabledSprite = function(sprite, disabled, affectSubSprites, affectParent, affectParentChildren) { disabled = !!disabled; if (typeof(affectParentChildren) === \"undefined\" || affectParentChildren === null) { affectParentChildren = !disabled; } if (typeof(affectParent) === \"undefined\" || affectParent === null) { affectParent = affectParentChildren || !disabled; } sprite = sprite || this.getCurrent(); if (sprite) { sprite.disabled = disabled; if (typeof(affectSubSprites) === \"undefined\" || affectSubSprites === null) { affectSubSprites = disabled; } if (affectSubSprites) { if (typeof(sprite.executeFunctionAll) === \"function\") { sprite.executeFunctionAll(function() { if (this.setDisabled &amp;&amp; typeof(this.setDisabled) === \"function\") { this.setDisabled(disabled, false, false); } }); } } if (affectParent &amp;&amp; sprite &amp;&amp; sprite.parent) { return this.setDisabled(disabled, affectParentChildren); //Disables/enables the sprites group parent (and also its children). } } } /** * Tells whether the given sub-sprite is disabled or not. Internally, it checks its \"disabled\" property and also whether its sprite parent is disabled (calling the {@link CB_GraphicSprites#isDisabledSprite} method internally, for its sprite parent). A sub-sprite is considered disabled if its sprite parent is disabled (a sprite is considered disabled if its sprites group parent is also disabled). * @function * @param {CB_GraphicSprites.SUBSPRITE_OBJECT} subSprite - The {@link CB_GraphicSprites.SUBSPRITE_OBJECT} object which contains the sub-sprite. * @returns {boolean} Returns whether the sub-sprite is disabled or not. A sub-sprite is considered disabled if its sprite parent is disabled (a sprite is considered disabled if its sprites group parent is also disabled). */ CB_GraphicSprites.prototype.isDisabledSubSprite = function(subSprite) { subSprite = subSprite || {}; return !!subSprite.disabled || this.isDisabledSprite(subSprite.parent || {}); } /** * Sets a given sub-sprite disabled or enabled. Internally, it edits its \"disabled\" property. * @function * @param {CB_GraphicSprites.SUBSPRITE_OBJECT} subSprite - The {@link CB_GraphicSprites.SUBSPRITE_OBJECT} object which contains the sub-sprite. * @param {boolean} [disabled=false] - Set to true to disable it or false to enable it. * @param {boolean} [affectParents=affectParentsChildren|!disabled] - If this parameter is set to true, it will also modify the \"disabled\" property of the sprite parent and of the sprites group object (which is considered the status of the whole {@CB_GraphicSprites} object). By default, it is true if either the \"affectParentChildren\" parameter is set to true or the \"disabled\" parameter is set to false and it is false otherwise. * @param {boolean} [affectParentsChildren=!disabled] - Defines whether to also affect the sprites and sub-sprites of the sprite parent and its sprites group object (which is considered the status of the whole {@CB_GraphicSprites} object) or not. If it is set to true and the \"affectParents\" is also set to true, it will also modify the \"disabled\" property of all the existing sprites and sub-sprites in the {@link CB_GraphicSprites} object. This parameter is ignored if the \"affectParents\" parameter is set to false. By default, it is false if the \"disabled\" parameter is set to true or it is false otherwise. */ CB_GraphicSprites.prototype.setDisabledSubSprite = function(subSprite, disabled, affectParents, affectParentsChildren) { disabled = !!disabled; if (typeof(affectParentsChildren) === \"undefined\" || affectParentsChildren === null) { affectParentsChildren = !disabled; } if (typeof(affectParents) === \"undefined\" || affectParents === null) { affectParents = affectParentsChildren || !disabled; } if (subSprite) { subSprite.disabled = disabled; if (affectParents &amp;&amp; subSprite.parent) { return this.setDisabledSprite(subSprite.parent, disabled, affectParentsChildren, true, affectParentsChildren); } } } /** * Sets (updates) the time in milliseconds when the current sprite or a sub-sprite started being pointed. * @function * @param {number} [time=CB_Device.getTiming()] - The time that we want to set, in milliseconds (time elapsed since the [time origin]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin} which can be obtained calling the {@link CB_Device.getTiming} function). It must be a positive number (or zero). If not provided, it will use the current time (by calling the {@link CB_Device.getTiming} function internally). * @param {boolean} [updateTimeCurrentSprite=false] - If set to true, it will also update the \"time\" property of the {@link CB_GraphicSprites.SPRITE_OBJECT} object which is currently pointed by the pointer (set in the {@link CB_GraphicSprites#pointer} property). * @param {boolean} [updateTimeCurrentSpriteSubSprites=false] - If set to true and the \"updateTimeCurrentSprite\" is set to true, it will also update the \"time\" property of the {@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects that belong to the sprite which is currently pointed by the pointer (set in the {@link CB_GraphicSprites#pointer} property). This parameter is ignored if the \"updateTimeCurrentSprite\" parameter is set to false. * @returns {number} Returns the time in milliseconds when the current sprite or a sub-sprite started being pointed (time elapsed since the [time origin]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin} which can be obtained calling the {@link CB_Device.getTiming} function). */ CB_GraphicSprites.prototype.setTime = function(time, updateTimeCurrentSprite, updateTimeCurrentSpriteSubSprites) { time = parseFloat(time); time = !isNaN(time) &amp;&amp; time &gt;= 0 ? time : CB_Device.getTiming(); this.time = time; if (updateTimeCurrentSprite) { var sprite = this.getSprite(this.getPointer(), null); if (sprite !== null) { sprite.time = time; if (updateTimeCurrentSpriteSubSprites) { sprite.forEach(function() { this.time = time; }); } } } return this.time; } /** * Gets the time in milliseconds when the current sprite or a sub-sprite started being pointed (time elapsed since the [time origin]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin} which was obtained calling the {@link CB_Device.getTiming} function internally). * @function * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @param {boolean} [parentTimeFallback=false] - If the \"time\" property of \"this\" is not found, it will try to get the \"time\" property of \"this.time\" before returning \"returnValueOnFail\". * @returns {number} Returns the time in milliseconds when the current sprite or a sub-sprite started being pointed (time elapsed since the [time origin]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin} which was obtained calling the {@link CB_Device.getTiming} function internally). If it could not be found, it will return \"returnValueOnFail\". */ CB_GraphicSprites.prototype.getTime = function(returnValueOnFail, parentTimeFallback) { if (parentTimeFallback) { returnValueOnFail = this.parent.time || returnValueOnFail; } return this.time || returnValueOnFail; } /** * Tells how many milliseconds elapsed since the current sprite or a sub-sprite was or will be pointed (checking the {@link CB_GraphicSprites#time} property), comparing with the time given in milliseconds (time elapsed since the [time origin]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin} which can be obtained calling the {@link CB_Device.getTiming} function) or with the current one if none is given. * @function * @param {number} [timeToCompare=CB_Device.getTiming()] - The time (time elapsed since the [time origin]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin} which can obtained calling the {@link CB_Device.getTiming} function) that we want to compare to (normally, it will be a newer time than the one stored in the {@link CB_GraphicSprites#time} property). It must be a positive number (or zero). If not provided, it will use the current time (by calling the {@link CB_Device.getTiming} function internally). * @param {boolean} [parentTimeFallback=false] - If the \"time\" property of \"this\" is not found, it will try to get the \"time\" property of \"this.time\" before using \"returnValueOnFail\". * @returns {number} Returns how many milliseconds elapsed since the current sprite or a sub-sprite was or will be pointed, comparing with the time given (in milliseconds) or with the current one if none was given. This is just the given \"timeToCompare\" minus the returning value of calling the {@link CB_GraphicSprites#getTime} method. */ CB_GraphicSprites.prototype.getTimeElapsed = function(timeToCompare, parentTimeFallback) { timeToCompare = parseFloat(timeToCompare); timeToCompare = !isNaN(timeToCompare) &amp;&amp; timeToCompare &gt;= 0 ? timeToCompare : CB_Device.getTiming(); return timeToCompare - this.getTime(timeToCompare, parentTimeFallback); } /** * Sets the desired value of a given property name to the {@link CB_GraphicSprites.SPRITES_OBJECT} object as well to its children elements ({@link CB_GraphicSprites.SPRITE_OBJECT} and {@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects). * @function * @param {number} propertyName - The name of the property we want to affect. * @param {*} [value=undefined] - The value desired for the given property. * @param {boolean} [onlyCurrent=false] - If set to true, it will only affect the current sprite and its sub-sprites (and also the {@link CB_GraphicSprites.SPRITES_OBJECT} object). * @returns {integer} Returns the number of elements affected (counting the {@link CB_GraphicSprites.SPRITES_OBJECT} object). */ CB_GraphicSprites.prototype.setPropertyCascade = function(propertyName, value, onlyCurrent) { if (!propertyName) { return; } if (this.spritesGroup) { this.spritesGroup[propertyName] = value; } else { this[propertyName] = value; } var affected = 1; if (onlyCurrent) { var currentSprite = this.getCurrent(); if (currentSprite !== null) { currentSprite[propertyName] = value; affected++; currentSprite.forEach(function(subSprite) { subSprite[propertyName] = value; affected++; }); } } else { this.forEach ( function(element) { element[propertyName] = value; affected++; if (typeof(element.forEach) === \"function\") { element.forEach(function(subElement) { subElement[propertyName] = value; affected++; }); } } ); } return affected; } /** * Gets a new copy of this object with the same attributes (all sub-objects will be a copy, they will not the same reference). * @function * @param {boolean} [avoidCopyingPointer=false] - If set to true, it will not copy the {@link CB_GraphicSprites#pointer} property of the object. * @param {boolean} [avoidCopyingTimes=false] - If set to true, it will not copy neither the {@link CB_GraphicSprites#time} property property of the object nor the \"time\" property of each of its sprites ({@link CB_GraphicSprites.SPRITE_OBJECT} objects). * @param {boolean} [clearReferences=false] - If set to true, it will not copy neither the \"container\" nor the \"parent\" nor the \"data.that\" nor the \"data.getThis\" properties of any element. Useful to be able to stringify the object preventing the \"TypeError: cyclic object value\" error. When set to true, calls the {@link CB_GraphicSprites.clearReferences} function internally. If set to true and the \"filterProperties\" parameter is also set to true, the {@link CB_GraphicSprites.filterProperties} will always be called before calling the {@link CB_GraphicSprites.clearReferences} function. * @param {boolean} [filterProperties=false] - If set to true, it will call the {@link CB_GraphicSprites.filterProperties} function internally to filter the properties that we do not want to keep (using the given \"propertiesToKeepObject\" as the parameter to call it). When set to true, calls the {@link CB_GraphicSprites.filterProperties} function internally. If set to true and the \"clearReferences\" parameter is also set to true, the {@link CB_GraphicSprites.filterProperties} will always be called before calling the {@link CB_GraphicSprites.clearReferences} function. * @param {CB_GraphicSprites.filterProperties_propertiesToKeepObject_TYPE} [propertiesToKeepObject=CB_GraphicSprites.filterProperties_DEFAULT_PROPERTIES] - The object with the properties that we want to keep. Only used when the \"filterProperties\" parameter is set to true, as the \"propertiesToKeepObject\" when calling the {@link CB_GraphicSprites.filterProperties} function internally. * @returns {CB_GraphicSprites} Returns a copy of this object with the same attributes (all sub-objects will be a copy, not the same reference). */ CB_GraphicSprites.prototype.getCopy = function(avoidCopyingPointer, avoidCopyingTimes, clearReferences, filterProperties, propertiesToKeepObject) { var spritesGroupCopy = CB_copyObject(this.spritesGroup); var newCopy = new CB_GraphicSprites(spritesGroupCopy, false); //If desired, sets the same pointer: if (!avoidCopyingPointer) { newCopy.pointer = this.pointer; newCopy.pointerPrevious = this.pointerPrevious; } //If desired, sets the same times: if (!avoidCopyingTimes) { newCopy.time = this.time; } CB_GraphicSprites._copyNeededProperties(newCopy, this) //Copies the needed properties from the original element. CB_GraphicSprites._copyNeededProperties(newCopy.spritesGroup, this.spritesGroup) //Copies the needed properties from the original element. this.forEach ( function(sprite, index) { //If desired, sets the same times: if (!avoidCopyingTimes) { newCopy.get(index).time = this.time; } CB_GraphicSprites._copyNeededProperties(newCopy.get(index), sprite) //Copies the needed properties from the original element. sprite.forEach ( function(subSprite, subSpriteIndex) { CB_GraphicSprites._copyNeededProperties(sprite.get(index).get(subSpriteIndex), subSprite) //Copies the needed properties from the original element. //If desired, sets the same times: if (!avoidCopyingTimes) { sprite.get(subSpriteIndex).time = this.time; } } ); } ); //Sets the same parent and positions: newCopy.parent = this.parent; newCopy.position = this.position; newCopy.positionByZIndex = this.positionByZIndex; //If we want to, filters the properties keeping just the desired ones: if (filterProperties) { newCopy = CB_GraphicSprites.filterProperties(newCopy, propertiesToKeepObject); } //If we want to, clears the references: if (clearReferences) { CB_GraphicSprites.clearReferences(newCopy); } return newCopy; } CB_GraphicSprites._copyNeededPropertiesData = { spritesScene: [\"id\"], spritesGroups: [\"id\", \"byReference_DEFAULT\", \"src\", \"srcType\", \"srcLeft\", \"left\", \"srcTop\", \"top\", \"srcWidth\", \"width\", \"srcHeight\", \"height\", \"zIndex\"], sprites: [\"id\", \"byReference_DEFAULT\", \"zIndex\", \"pointer\", \"pointerPrevious\", \"pointer\", \"pointerPrevious\", \"position\", \"positionByZIndex\", \"_attributes\"], spritesGroup: [\"id\", \"byReference_DEFAULT\", \"src\", \"srcType\", \"srcLeft\", \"left\", \"srcTop\", \"top\", \"srcWidth\", \"width\", \"srcHeight\", \"height\", \"zIndex\", \"disabled\"], sprite: [\"id\", \"byReference\", \"src\", \"srcType\", \"srcLeft\", \"left\", \"srcTop\", \"top\", \"srcWidth\", \"width\", \"srcHeight\", \"height\", \"zIndex\", \"disabled\", \"position\", \"positionByZIndex\", \"_timeDisappeared\", \"_usingRelativePosition\", \"_clearPreviousFirstPerformed\", \"_widthOriginal\", \"_heightOriginal\", \"_leftOriginal\", \"_topOriginal\", \"_attributes\"], subSprite: [\"id\", \"byReference\", \"time\", \"src\", \"srcType\", \"srcLeft\", \"left\", \"srcTop\", \"top\", \"srcWidth\", \"width\", \"srcHeight\", \"height\", \"zIndex\", \"disabled\", \"position\", \"positionByZIndex\", \"_timeDisappeared\", \"_usingRelativePosition\", \"_attributes\"] }; CB_GraphicSprites._copyNeededProperties = function(element, elementOriginal) { if (!element.type || element.type !== elementOriginal.type) { return; } if (!CB_isArray(CB_GraphicSprites._copyNeededPropertiesData[element.type])) { return; } for (var x = CB_GraphicSprites._copyNeededPropertiesData[element.type].length; x &gt;= 0; x--) { propertyName = CB_GraphicSprites._copyNeededPropertiesData[element.type][x]; element[propertyName] = elementOriginal[propertyName]; } return element; } /** * Clears the \"container\", the \"parent\" and the \"data.that\" properties (sets to null) of the given object and its sub-objects (works recursively, internally). * @function * @param {*} element - The object whose properties we want to clear. It can be different kinds ({@link CB_GraphicSpritesScene}, {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT}, {@link CB_GraphicSprites}, {@link CB_GraphicSprites.SPRITES_OBJECT}, {@link CB_GraphicSprites.SPRITE_OBJECT}, {@link CB_GraphicSprites.SUBSPRITE_OBJECT}, etc.). * @returns {*} Returns the same object with the the \"container\", the \"parent\", \"data.that\" and the \"data.getThis\" properties cleared (set to null), if possible. */ CB_GraphicSprites.clearReferences = function(element) { if (typeof(element) !== \"object\" || element === null) { return element; } if (typeof(element.forEach) === \"function\") { element.forEach.call ( element, function(subElement) { CB_GraphicSprites.clearReferences(subElement); } ); } if (element.container) { element.container = null; } if (element.parent) { element.container = null; } if (element.data) { if (element.data.that) { element.data.that = null; } if (element.data.getThis) { element.data.getThis = null; } } return element; } /** * Object used to know what properties keep when calling the {@link CB_GraphicSprites.filterProperties} function (type used for its \"propertiesToKeepObject\" parameter). Its properties must have the name that matches the value returned by the \"type\" property of each element, being their value an array of strings with the name of the properties we want to keep. The property names which start with a \"_\" symbol will not considered inherited from the element's parent and will always be copied. The other properties (which do not start with the \"_\" symbol) will only be copied when the element contains a value which is different from the same property of its parent. * @memberof CB_GraphicSprites * @typedef {Object} CB_GraphicSprites.filterProperties_propertiesToKeepObject_TYPE * @property {array} [spritesScene] Array of strings with the name of the properties to keep for the {@link CB_GraphicSpritesScene} objects. If no provided, no properties will be kept for this kind of element. * @property {array} [spritesGroups] Array of strings with the name of the properties to keep for the {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} objects. If no provided, no properties will be kept for this kind of element. * @property {array} [sprites] Array of strings with the name of the properties to keep for the {@link CB_GraphicSprites} objects. If no provided, no properties will be kept for this kind of element. * @property {array} [spritesGroup] Array of strings with the name of the properties to keep for the {@link CB_GraphicSprites.SPRITES_OBJECT} objects. If no provided, no properties will be kept for this kind of element. * @property {array} [sprite] Array of strings with the name of the properties to keep for the {@link CB_GraphicSprites.SPRITE_OBJECT} objects. If no provided, no properties will be kept for this kind of element. * @property {array} [subSprite] Array of strings with the name of the properties to keep for the {@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects. If no provided, no properties will be kept for this kind of element. */ /** * Object used as the default value for the \"propertiesToKeepObject\" parameter if not provided when calling the {@link CB_GraphicSprites.filterProperties} function. * @constant * @type {CB_GraphicSprites.filterProperties_propertiesToKeepObject_TYPE} * @default */ CB_GraphicSprites.filterProperties_DEFAULT_PROPERTIES = { spritesScene: [\"id\", \"spritesGroups\"], spritesGroups: [\"id\", \"byReference_DEFAULT\", \"src\", \"srcType\", \"srcLeft\", \"left\", \"srcTop\", \"top\", \"srcWidth\", \"width\", \"srcHeight\", \"height\", \"zIndex\", \"data\", \"spritesGroups\", \"items\"], sprites: [\"id\", \"byReference_DEFAULT\", \"spritesGroup\", \"zIndex\", \"pointer\", \"pointerPrevious\", \"time\", \"pointer\", \"pointerPrevious\", \"position\", \"positionByZIndex\", \"_attributes\"], spritesGroup: [\"id\", \"byReference_DEFAULT\", \"src\", \"srcType\", \"srcLeft\", \"left\", \"srcTop\", \"top\", \"srcWidth\", \"width\", \"srcHeight\", \"height\", \"zIndex\", \"data\", \"disabled\", \"sprites\"], sprite: [\"id\", \"byReference\", \"time\", \"src\", \"srcType\", \"srcLeft\", \"left\", \"srcTop\", \"top\", \"srcWidth\", \"width\", \"srcHeight\", \"height\", \"zIndex\", \"data\", \"disabled\", \"position\", \"positionByZIndex\", \"subSprites\", \"_timeDisappeared\", \"_usingRelativePosition\", \"_clearPreviousFirstPerformed\", \"_widthOriginal\", \"_heightOriginal\", \"_leftOriginal\", \"_topOriginal\", \"_attributes\"], subSprite: [\"id\", \"byReference\", \"time\", \"src\", \"srcType\", \"srcLeft\", \"left\", \"srcTop\", \"top\", \"srcWidth\", \"width\", \"srcHeight\", \"height\", \"zIndex\", \"data\", \"disabled\", \"position\", \"positionByZIndex\", \"_timeDisappeared\", \"_usingRelativePosition\", \"_attributes\"] }; //Object to detect type of elements in an array according to the property name they belong to (which contains the array): CB_GraphicSprites.filterProperties_types = { \"spritesGroups\": \"spritesGroup\", \"items\": \"sprites\", \"sprites\": \"sprite\", \"subSprites\": \"subSprite\" }; /** * Gets a new object with the properties filtered of a given element and its sub-elements, keeping only the ones that are in the given \"propertiesToKeepObject\" (works recursively, internally). * @function * @param {*} element - The object whose properties we want to clear. It can be different kinds ({@link CB_GraphicSpritesScene}, {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT}, {@link CB_GraphicSprites}, {@link CB_GraphicSprites.SPRITES_OBJECT}, {@link CB_GraphicSprites.SPRITE_OBJECT}, {@link CB_GraphicSprites.SUBSPRITE_OBJECT}, etc.). * @param {CB_GraphicSprites.filterProperties_propertiesToKeepObject_TYPE} [propertiesToKeepObject=CB_GraphicSprites.filterProperties_DEFAULT_PROPERTIES] - The object with the properties that we want to keep. * @returns {*} Returns a new object with the properties filtered of a given element and its sub-elements, keeping only the ones that are in the given \"propertiesToKeepObject\". If no valid \"element\" is provided, returns null. * @todo Implement a boolean property and when it is true it will not keep the properties whose values are the default ones (for example, if \"byReference\" property is false it will not be kept as it is its default value). So the output can be reduced this way. */ CB_GraphicSprites.filterProperties = function(element, propertiesToKeepObject) { if (typeof(element) !== \"object\" || element === null) { return null; } propertiesToKeepObject = (typeof(propertiesToKeepObject) === \"object\" &amp;&amp; propertiesToKeepObject !== null) ? propertiesToKeepObject : CB_GraphicSprites.filterProperties_DEFAULT_PROPERTIES; if (element.type === \"spritesGroup\") { element.isSpritesGroup = true; } else if (element.type === \"sprites\") { element.isSprites = true; } else if (element.type === \"sprite\") { element.isSprite = true; } else if (element.type === \"subSprite\") { element.isSubSprite = true; } var newObject = {}; for (var propertyName in element) { if (propertiesToKeepObject[element.type] &amp;&amp; CB_Arrays.indexOf(propertiesToKeepObject[element.type], propertyName) !== -1) { //If the property starts with \"_\", or there is no parent or the value of the property of the parent is different from the value of the current element, copies the value: if (propertyName.charAt(0) === \"_\" || !element.parent || element._avoidParent || element.parent &amp;&amp; element.parent[propertyName] !== element[propertyName]) //The hidden properties (which start with \"_\") are not inherited. { if (element.isSpritesScene &amp;&amp; propertyName === \"spritesGroups\") { element.spritesGroups.type = \"spritesGroups\"; element._avoidParent = true; //It will not let it inherit from its parent. newObject.spritesGroups = CB_GraphicSprites.filterProperties(element.spritesGroups, propertiesToKeepObject); element._avoidParent = undefined; } else if (element.isSpritesGroups &amp;&amp; (propertyName === \"spritesGroups\" || propertyName === \"items\") || element.isSpritesGroup &amp;&amp; propertyName === \"sprites\" || element.isSprite &amp;&amp; propertyName === \"subSprites\") { var type = CB_GraphicSprites.filterProperties_types[propertyName]; var currentElement = null; newObject[propertyName] = []; if (CB_isArray(element[propertyName])) { for (var x = 0; x &lt; element[propertyName].length; x++) { element[propertyName][x].type = type; element[propertyName][x]._avoidParent = true; //It will not let it inherit from its parent. newObject[propertyName][x] = CB_GraphicSprites.filterProperties(element[propertyName][x], propertiesToKeepObject); element[propertyName][x]._avoidParent = undefined; } } } else if (element.isSprites &amp;&amp; propertyName === \"spritesGroup\") { element.spritesGroup.type = \"spritesGroup\"; element._avoidParent = true; //It will not let it inherit from its parent. newObject.spritesGroup = CB_GraphicSprites.filterProperties(element.spritesGroup, propertiesToKeepObject); element._avoidParent = undefined; } else if (propertyName === \"data\" &amp;&amp; element.data) { newObject.data = {}; for (var dataPropertyName in element.data) { if (dataPropertyName === \"that\" || dataPropertyName === \"getThis\") { continue; } newObject.data[dataPropertyName] = element.data[dataPropertyName]; } } else { newObject[propertyName] = element[propertyName]; } } } } propertyName = element.isSprites ? \"sprites\" : element.isSprite ? \"subSprites\" : \"\"; if (propertyName !== \"\" &amp;&amp; CB_Arrays.indexOf(propertiesToKeepObject[element.type], propertyName) !== -1 &amp;&amp; typeof(element.forEach) === \"function\") { newObject[propertyName] = []; element.forEach.call ( element, function(subElement) { //subElement._avoidParent = true; //It will not let it inherit from its parent. newObject[propertyName][newObject[propertyName].length] = CB_GraphicSprites.filterProperties(subElement, propertiesToKeepObject); //subElement._avoidParent = undefined; } ); } return newObject; } × Search results Close "},"CrossBase_CrossBase.js.html":{"id":"CrossBase_CrossBase.js.html","title":"Source: CrossBase/CrossBase.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/CrossBase.js /** * @file Main CrossBase module file. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ //Credits of the module: var CB_CrossBaseCredits = \"[CB] - CrossBase module by Joan Alba Maldonado&lt;br /&gt;\" + \"[CB] -- Array.* polyfills by Mozilla Foundation (MDN)&lt;br /&gt;\" + \"[CB] -- JSON 3 by Kit Cambridge&lt;br /&gt;\" + \"[CB] -- bluebird by Petka Antonov&lt;br /&gt;\" + \"[CB] -- BrowserDetect by Peter-Paul Koch&lt;br /&gt;\" + \"[CB] -- performance.now polyfill by Paul Irish, Aaron Levine and Joan Alba Maldonado&lt;br /&gt;\" + \"[CB] -- requestAnimationFrame polyfill by Erik Moller (fixes from Paul Irish, Tino Zijdel, Andrew Mao, Klemen Slavic, Darius Bacon, Tim Hall and Joan Alba Maldonado)&lt;br /&gt;\" + \"[CB] -- typedarray.js polyfill by Linden Research, Inc. and Joshua Bell&lt;br /&gt;\" + \"[CB] -- Base64Binary by Daniel Guerrero&lt;br /&gt;\" + \"[CB] -- localStorage polyfill by Morten Houmøller Nygaard&lt;br /&gt;\" + \"[CB] -- lz-string (including base64-string) by pieroxy&lt;br /&gt;\" + \"[CB] -- Canbox by Robert Inglin&lt;br /&gt;\" + \"[CB] -- ExplorerCanvas by Google Inc.&lt;br /&gt;\" + \"[CB] -- SLCanvas by David Anson and Jon Davis&lt;br /&gt;\" + \"[CB] -- FlashCanvas by Tim Cameron Ryan and Shinya Muramatsu&lt;br /&gt;\" + \"[CB] -- canvas-text by Fabien Ménager&lt;br /&gt;\" + \"[CB] -- Detect-zoom by yonran (maintained by tombigel)&lt;br /&gt;\" + \"[CB] -- AudioContext-MonkeyPatch by Chris Wilson&lt;br /&gt;\" + \"[CB] -- WAAPISim by g200kg&lt;br /&gt;\" + \"[CB] -- timbre.js and subcollider.js by mohayonao&lt;br /&gt;\" + \"[CB] -- Band.js by Cody Lundquist and various contributors&lt;br /&gt;\" + \"[CB] -- jsfx by Egon Elbre&lt;br /&gt;\" + \"[CB] -- SoundManager 2 by Scott Schiller&lt;br /&gt;\" + \"[CB] -- fetch-ie8 by Cam Song&lt;br /&gt;\" + \"[CB] -- SockJS-client by Marek, Bryce Kahle, Michael Bridgen, Luigi Pinca and others&lt;br /&gt;\" + \"[CB] -- Pressure.js by Stuart Yamartino&lt;br /&gt;\" + \"[CB] -- Hammer.js by Jorik Tangelder&lt;br /&gt;\" + \"[CB] -- Hammer Time by Alexander Schmitz and other contributors&lt;br /&gt;\" + \"[CB] -- wii-js by Ryan McGrath&lt;br /&gt;\" + \"[CB] -- gamepad-plus by Chris Van Wiemeersch (MozVR)&lt;br /&gt;\" + \"[CB] -- NoSleep.js by Rich Tibbett&lt;br /&gt;\"; //CrossBase constants and variables: /** * Keeps the name of the CrossBase module. * @constant * @type {string} * @default */ var CB_BASE_NAME = \"CrossBase\"; /** Property that contains an object with the options for the main script. * @namespace CB_Configuration.CrossBase */ CB_Configuration[CB_BASE_NAME] = { /** * Path to the CrossBase module, relative to the CrossBrowdy folder. * @memberof CB_Configuration.CrossBase * @constant * @type {string} * @default {@link CB_BASE_NAME} + \"/\" */ SCRIPT_PATH: CB_BASE_NAME + \"/\", /** * Defines whether to have in mind possible [iframes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} that could contain the script or not. Used by some functions of {@link CB_Client}, {@link CB_Events}, etc. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ MIND_IFRAMES: true, /** * Defines whether to allow to extend the DOM if needed or not. If set to true and some methods (as for example [Array.indexOf]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf}, [Array.lastIndexOf]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf}, [Array.isArray]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray}, [Array.forEach]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach}, [NodeList.forEach]{@link https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach}, [HTMLCollection.forEach]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach}, etc.) are not supported natively, they will be added. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ EXTEND_DOM: false, /** * Defines whether to use high precision in the CB_Device.getTime (returning '[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 not (returning '[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). * @memberof CB_Configuration.CrossBase * @constant * @type {string} * @default */ CB_Device_getTime_HIGH_PRECISION: true, /** * Defines whether to use cache for the function {@link CB_Elements.id} by default. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_Elements_id_USE_CACHE: true, /** * Defines whether to use cache for the {@link CB_Elements.tag} function by default. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_Elements_tag_USE_CACHE: true, /** * Defines whether to use cache for the function {@link CB_Elements.classes} by default. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_Elements_classes_USE_CACHE: true, /** * Default language to use for {@link CB_Client} when no language can be detected (very strange case!). * @memberof CB_Configuration.CrossBase * @constant * @type {string} * @default */ CB_Client_language_DEFAULT: \"en\", /** * Default value for the \"allowNavigatorLanguages\" parameter for {@link CB_Client.getLanguage} and {@link CB_Client.getLanguages} functions. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_Client_allowNavigatorLanguages_DEFAULT: false, /** * Tells whether the {@link CB_Client.getLanguage} and {@link CB_Client.getLanguages} functions will use the accepted languages detected by PHP (if any) as the first option by default or not. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_Client_PHPAcceptedLanguagesFirst_DEFAULT: true, /** * Defines whether the URL for the proxy (defined in {@link CB_Configuration.CrossBase.CB_Net_XHR_PROXY_URL}) is relative to the main script folder or not. If it is relative, the \"onCall\" event of the CrossBase module will append the value of the \"scriptPathGiven\" parameter at the beginning. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_Net_XHR_PROXY_URL_RELATIVE: true, /** * Defines whether we want to prevent the Firefox bug that affects [SockJS library]{@link https://github.com/sockjs/sockjs-client/} (see {@link https://github.com/sockjs/sockjs-client/issues/18}) or not. Used by {@link CB_Keyboard}. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_Net_Sockets_PREVENT_FIREFOX_ESC_BUG: true, /** * Defines whether to allow Nintendo Wii codes (from the Wiimote) set in the {@link CB_Keyboard.extended.WII} object to be defined in the key aliases even if they use codes which belong to other keys. Used by {@link CB_Keyboard}. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_Keyboard_extended_WII_allowDuplicateKeyAliases: true, /** * Defines whether to allow Sony Playstation 4 codes set in the {@link CB_Keyboard.extended.PS4CB_Keyboard.extended.PS4} object to be defined in the key aliases even if they use codes which belong to other keys. Used by {@link CB_Keyboard}. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_Keyboard_extended_PS4_allowDuplicateKeyAliases: false, /** * Defines whether to allow Smart TV codes (from the remote control) and virtual key codes set in the {@link CB_Keyboard.extended.VK} object to be defined in the key aliases even if they use codes which belong to other keys. Used by {@link CB_Keyboard}. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_Keyboard_extended_VK_allowDuplicateKeyAliases: true, /** * Defines whether to allow Samsung TV key codes (from the remote control) set in the {@link CB_Keyboard.extended.SAMSUNG_TV} object to be defined in the key aliases even if they use codes which belong to other keys. Used by {@link CB_Keyboard}. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_Keyboard_extended_SAMSUNG_TV_allowDuplicateKeyAliases: false, /** * Default value for the \"avoidProprietary\" proprietary when calling different functions of the {@link CB_Controllers} static class, as the {@link CB_Controllers.getButtonsDown}, the {@link CB_Controllers.isButtonDown} and the {@link CB_Controllers.getGamePads} functions, etc. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_Controllers_avoidProprietary_DEFAULT: false, /** * Allowed width margin of the total screen available to consider whether it is in full screen or not. Needed by old web clients without Fullscreen API support, mainly. Used by the {@link CB_Screen.isFullScreen} function. * @memberof CB_Configuration.CrossBase * @constant * @type {float} * @default */ CB_Screen_isFullScreen_ALLOWED_WIDTH_MARGIN_PERCENTAGE: 3.9, /** * Allowed height margin of the total screen available to consider whether it is in full screen or not. Needed by old web clients without Fullscreen API support, mainly. Used by the {@link CB_Screen.isFullScreen} function. * @memberof CB_Configuration.CrossBase * @constant * @type {float} * @default */ CB_Screen_isFullScreen_ALLOWED_HEIGHT_MARGIN_PERCENTAGE: 3.5, /** * Defines whether to allow using \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}) emulation (it will use [WAAPISim]{@link https://github.com/g200kg/WAAPISim} if needed) or not. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ WAAPI_EMULATION_ALLOWED: true, /** * Default volume for CB_Speaker (from 0 to 100). * @memberof CB_Configuration.CrossBase * @constant * @type {integer} * @default */ CB_Speaker_DEFAULT_VOLUME: 100, /** * Milliseconds that a file is played (with volume set to 0) automatically when an audio file is loaded. Needed for some web clients which cannot find out the duration otherwise. Used by {@link CB_AudioFile}. * @memberof CB_Configuration.CrossBase * @constant * @type {integer} * @default */ CB_AudioFile_AUTOPLAY_SILENTLY_ON_LOAD_MS: 500, /** * Milliseconds to wait before declaring a sound as failed if it cannot be loaded before. Used by {@link CB_AudioFile_API.SM2}. * @memberof CB_Configuration.CrossBase * @constant * @type {integer} * @default */ CB_AudioFile_ONLOAD_TIMEOUT_MS: 15000, /** * Tells whether CB_AudioFile[\"AAPI\"] uses [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} (instead of [timeupdate]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/timeupdate_event} event) to detect when the given \"stopAt\" is reached. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_AudioFile_AAPI_USE_TIMEOUT_TO_DETECT_STOPAT: true, /** * Default value for maximum delay (in milliseconds) to wait for a sound to start playing or start next loop (if the time expires, the sound will never be played). Used by {@link CB_AudioFile_API.WAAPI}, {@link CB_AudioFile_API.AAPI}, {@link CB_AudioFile_API.SM2}, {@link CB_AudioFile_API.ACMP} and {@link CB_AudioFileCache}. * @memberof CB_Configuration.CrossBase * @constant * @type {integer} * @default */ CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT: 150, /** * Tells whether to mute or not the audio files when they load or are checking. Note: Audio cache does not work properly on BlackBerry PlayBook's default browser if the sounds are muted when load or are checking. Used by {@link CB_AudioFile}, {@link CB_AudioFile_API.WAAPI}, {@link CB_AudioFile_API.AAPI}, {@link CB_AudioFile_API.SM2}, {@link CB_AudioFile_API.ACMP} and {@link CB_AudioFileCache}. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default !(navigator.userAgent.indexOf(\"PlayBook\") !== -1 &amp;&amp; navigator.userAgent.indexOf(\"Tablet OS\") !== -1) */ CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING: !(navigator.userAgent.indexOf(\"PlayBook\") !== -1 &amp;&amp; navigator.userAgent.indexOf(\"Tablet OS\") !== -1), //Audio cache does not work properly on BlackBerry PlayBook's default browser if the sounds are muted when load or are checking. /** * Defines whether to use {@link CB_Speaker._volume} as default volume. Used by {@link CB_AudioFile}, {@link CB_AudioFile_API.WAAPI}, {@link CB_AudioFile_API.AAPI}, {@link CB_AudioFile_API.SM2}, {@link CB_AudioFile_API.ACMP} and {@link CB_AudioFileCache}. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT: true, /** * Defines whether to use {@link CB_Speaker._volume} as maximum volume. Used by {@link CB_AudioFile}, {@link CB_AudioFile_API.WAAPI}, {@link CB_AudioFile_API.AAPI}, {@link CB_AudioFile_API.SM2} and {@link CB_AudioFile_API.ACMP}. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM: false, /** * Array with the default desired canvas emulation methods by order of preference. Used by {@link CB_Canvas}. * @memberof CB_Configuration.CrossBase * @constant * @type {array} * @default */ CB_Canvas_PREFERRED_EMULATION_METHODS: [ \"FLASH\", //FlashCanvas. \"VML\", //ExplorerCanvas. \"DHTML\", //Canbox. \"SILVERLIGHT\" //SLCanvas. ], /** * Value by default when the \"allowEmulation\" parameter is not provided in the {@link CB_AudioDetector.getPreferredAPI}, the {@link CB_AudioDetector.getSupportedAPIs} or the {@link CB_AudioDetector.isAPISupported} function. * @memberof CB_Configuration.CrossBase * @constant * @type {boolean} * @default */ CB_AudioDetector_allowEmulation_DEFAULT: false, /** * Array with the default preferred audio APIs by order of preference. Used by {@link CB_AudioFileCache} and {@link CB_AudioDetector}. Possible audio APIs are \"WAAPI\" ([HTML5 Web Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API}), \"SM2\" ([SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}), \"ACMP\" ([Apache Cordova Media Plugin]{@link https://github.com/apache/cordova-plugin-media}) or \"AAPI\" ([HTML5 Audio API]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio}). Note: since Internet Explorer 9 works better with SM2 than with AAPI, if it is detected then the default value will be: [ \"WAAPI\", \"SM2\", \"ACMP\", \"AAPI\" ] * @memberof CB_Configuration.CrossBase * @constant * @type {array} * @default [\"WAAPI\", \"AAPI\", \"ACMP\", \"SM2\"] */ CB_AudioFileCache_PREFERRED_AUDIO_APIS: navigator.appVersion.indexOf(\"MSIE 9\") === -1 ? [ \"WAAPI\", //HTML5 Web Audio API. \"AAPI\", //HTML5 Audio API. \"ACMP\", //Apache Cordova Media Plugin. \"SM2\" //SoundManager 2. ] : [ \"WAAPI\", \"SM2\", \"ACMP\", \"AAPI\" ], //IE9 have works better with SM2 than with AAPI. /** * Array with the default preferred audio formats by order of preference. Used by {@link CB_AudioFileCache} and {@link CB_AudioDetector}. NOTE: some web clients do not support to specify codecs so it is better to also provide strings without codecs. * @memberof CB_Configuration.CrossBase * @constant * @type {array} * @default */ CB_AudioFileCache_PREFERRED_AUDIO_FORMATS: [ 'audio/ogg; codecs=\"vorbis\"', //audio/ogg with Vorbis codec. 'audio/ogg; codecs=\"speex\"', //audio/ogg with Speex codec. 'audio/ogg; codecs=\"flac\"', //audio/ogg with FLAC codec. 'audio/ogg', //audio/ogg is for .oga, .ogg. 'audio/mpeg; codecs=\"mp3\"', //audio/mpeg with MP3 codec (?). 'audio/mpeg', //audio/mpeg is for .mp1, .mp2, .mp3, .mpg, .mpeg. 'audio/mp4; codecs=\"mp4a.40.5\"', //audio/mp4 with mp4a.40.5 codec. 'audio/mp4; codecs=\"mp4a.40.2\"', //audio/mp4 with mp4a.40.2 codec. 'audio/mp4; codecs=\"mp4a.40.05\"', //audio/mp4 with mp4a.40.05 codec. 'audio/mp4; codecs=\"mp4a.40.02\"', //audio/mp4 with mp4a.40.02 codec. 'audio/mp4; codecs=\"mp4a.69\"', //audio/mp4 with mp4a.69 codec. 'audio/mp4; codecs=\"mp4a.6B\"', //audio/mp4 with mp4a.6B codec. 'audio/mp4; codecs=\"mp4a.67\"', //audio/mp4 with mp4a.67 codec. 'audio/mp4; codecs=\"mp4a.a6\"', //audio/mp4 with mp4a.a6 codec. 'audio/mp4; codecs=\"mp4a.a5\"', //audio/mp4 with mp4a.a5 codec. 'audio/mp4; codecs=\"aac51\"', //audio/mp4 with aac51 codec. 'audio/mp4; codecs=\"ac-3\"', //audio/mp4 with ac-3 codec. 'audio/mp4; codecs=\"ec-3\"', //audio/mp4 with ec-3 codec. 'audio/mp4', //audio/mp4 is for .mp4, .m4a. 'audio/aac; codecs=\"aac\"', //audio.aac with AAC codec (?). 'audio/aac; codecs=\"mp4a.40.5\"', //audio/aac with mp4a.40.5 codec (?). 'audio/aac; codecs=\"vorbis\"', //audio.aac with Vorbis codec (?). 'audio/aac', //audio/acc is for .aac. 'audio/x-aac; codecs=\"aac\"', 'audio/x-aac', 'audio/x-m4b; codecs=\"aac\"', 'audio/x-m4b', 'audio/x-m4p; codecs=\"aac\"', 'audio/x-m4p', 'audio/webm; codecs=\"vorbis\"', //audio/webm with Vorbis codec. 'audio/webm', //audio/webm is for .webm. 'audio/3gpp; codecs=\"samr\"', //audio/3gpp with SAMR codec. 'audio/3gpp', //audio/3gpp is for .3gpp. 'audio/wav; codecs=\"1\"', //audio/wav with 1 codec (?). 'audio/wav', //audio/wav is for .wav. 'audio/x-wav; codecs=\"1\"', //audio/x-wav with 1 codec (?). 'audio/x-wav', //audio/x-wav is for .wav. 'audio/x-pn-wav; codecs=\"1\"', //audio/x-pn-wav with 1 codec (?). 'audio/x-pn-wav', //audio/x-pn-wav is for .wav 'audio/wave; codecs=\"1\"', //audio/wave with 1 codec (?). 'audio/wave', //audio/wave is for .wav. 'audio/x-wave; codecs=\"1\"', //audio/x-wave with 1 codec (?). 'audio/x-wave' //audio/x-wave is for .wav. ] }; /** * URL for the proxy to prevent cross-domain issues through AJAX, used by {@link CB_Net.XHR.callProxy} function. Can be relative to the main script folder or not, depending on {@link CB_Configuration.CrossBase.CB_Net_XHR_PROXY_URL_RELATIVE}. &lt;br /&gt; NOTE: Edit the \"CB_proxy.config.php\" file to configure the default proxy. Apart from configuring it, adding some security measures is highly recommended. Have in mind that, for safety reasons, the default proxy only allows to request the URLs defined in the \"$allowedURLs\" array in the \"CB_proxy.config.php\" file. Just edit it to allow other URLs. * @memberof CB_Configuration.CrossBase * @name CB_Net_XHR_PROXY_URL * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"net/proxy/CB_proxy.php\" */ CB_Configuration[CB_BASE_NAME].CB_Net_XHR_PROXY_URL = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"net/proxy/CB_proxy.php\"; CB_Configuration[CB_BASE_NAME].needsWAAPISimLastReturn = null; //Cache to return always the same result. /** * Detects whether the web client needs [WAAPISim]{@link https://github.com/g200kg/WAAPISim} or not. * @memberof CB_Configuration.CrossBase * @name needsWAAPISim * @function * @returns {boolean} */ CB_Configuration[CB_BASE_NAME].needsWAAPISim = function() { //If the last result is in the cache, we return again the same result: if (typeof(CB_Configuration[CB_BASE_NAME].needsWAAPISimLastReturn) !== \"undefined\" &amp;&amp; CB_Configuration[CB_BASE_NAME].needsWAAPISimLastReturn !== null) { return CB_Configuration[CB_BASE_NAME].needsWAAPISimLastReturn; } //...otherwise (it is the first time), we calculate if we need it or not: else { var waapisimForceSim = window.waapisimForceSim || undefined; CB_Configuration[CB_BASE_NAME].needsWAAPISimLastReturn = //Note: copied from waapisim.js //TODO: see what IE versions are compatible. (navigator.appVersion.indexOf(\"MSIE 5\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 6\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 7\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 8\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 9\") === -1) &amp;&amp; ( typeof(waapisimForceSim) !== \"undefined\" &amp;&amp; waapisimForceSim || ( typeof(window.AudioContext) !== \"undefined\" &amp;&amp; typeof(window.AudioContext.prototype.createOscillator) === \"undefined\" //Be careful! Pale Moon browser does not have createOscillator method. &amp;&amp; (typeof(waapisimForceSimWhenLackOsc) === \"undefined\" || (typeof(waapisimForceSimWhenLackOsc) !== \"undefined\" &amp;&amp; waapisimForceSimWhenLackOsc)) ) || ( typeof(window.webkitAudioContext) !== \"undefined\" &amp;&amp; typeof(window.webkitAudioContext.prototype.createOscillator) === \"undefined\" //Be careful! Pale Moon browser does not have createOscillator method. &amp;&amp; (typeof(waapisimForceSimWhenLackOsc) === \"undefined\" || (typeof(waapisimForceSimWhenLackOsc) !== \"undefined\" &amp;&amp; waapisimForceSimWhenLackOsc)) ) || typeof(window.AudioContext) === \"undefined\" &amp;&amp; typeof(window.webkitAudioContext) === \"undefined\" ); return CB_Configuration[CB_BASE_NAME].needsWAAPISimLastReturn; } } CB_Configuration[CB_BASE_NAME]._supportsCanvasLastReturn = null; //Cache to return always the same result. CB_Configuration[CB_BASE_NAME]._supportsCanvasElement = null; CB_Configuration[CB_BASE_NAME]._supportsCanvas = function() { //If the last result is in the cache, we return again the same result: if (typeof(CB_Configuration[CB_BASE_NAME]._supportsCanvasLastReturn) !== \"undefined\" &amp;&amp; CB_Configuration[CB_BASE_NAME]._supportsCanvasLastReturn !== null) { return CB_Configuration[CB_BASE_NAME]._supportsCanvasLastReturn; } //...otherwise (it is the first time), we calculate if we need it or not: else { CB_Configuration[CB_BASE_NAME]._supportsCanvasElement = CB_Configuration[CB_BASE_NAME]._supportsCanvasElement || document.createElement(\"canvas\"); //If canvas is supported: if (typeof(CB_Configuration[CB_BASE_NAME]._supportsCanvasElement) !== \"undefined\" &amp;&amp; CB_Configuration[CB_BASE_NAME]._supportsCanvasElement !== null) { if (typeof(CB_Configuration[CB_BASE_NAME]._supportsCanvasElement.getContext) !== \"undefined\" &amp;&amp; CB_Configuration[CB_BASE_NAME]._supportsCanvasElement.getContext !== null) { try //Uses try-catch to avoid some problems with some web clients (as BeZilla / Bon Echo 2.0.0.22Pre on Haiku OS): { //If fillText exists: if (typeof(CB_Configuration[CB_BASE_NAME]._supportsCanvasElement.getContext(\"2d\")) !== \"undefined\" &amp;&amp; CB_Configuration[CB_BASE_NAME]._supportsCanvasElement.getContext(\"2d\") !== null) { CB_Configuration[CB_BASE_NAME]._supportsCanvasLastReturn = true; //Canvas is supported. return CB_Configuration[CB_BASE_NAME]._supportsCanvasLastReturn; } } catch(E) { CB_Configuration[CB_BASE_NAME]._supportsCanvasLastReturn = false; return CB_Configuration[CB_BASE_NAME]._supportsCanvasLastReturn; } } } CB_Configuration[CB_BASE_NAME]._supportsCanvasLastReturn = false; //If we arrived here, canvas is not supported. return CB_Configuration[CB_BASE_NAME]._supportsCanvasLastReturn; } } CB_Configuration[CB_BASE_NAME].needsCanboxLastReturn = null; //Cache to return always the same result. /** * Detects whether the web client needs [Canbox]{@link https://github.com/robertinglin/CanBox} or not. * @memberof CB_Configuration.CrossBase * @name needsCanbox * @function * @returns {boolean} */ CB_Configuration[CB_BASE_NAME].needsCanbox = function() { //If the last result is in the cache, we return again the same result: if (typeof(CB_Configuration[CB_BASE_NAME].needsCanboxLastReturn) !== \"undefined\" &amp;&amp; CB_Configuration[CB_BASE_NAME].needsCanboxLastReturn !== null) { return CB_Configuration[CB_BASE_NAME].needsCanboxLastReturn; } //...otherwise (it is the first time), we calculate if we need it or not: else { //We need it only if canvas is not already supported by the web client (and it is not IE5/5.5 since it doesn't support Canbox): //CB_Configuration[CB_BASE_NAME].needsCanboxLastReturn = (typeof(document.createElement(\"canvas\").getContext) === \"undefined\" &amp;&amp; navigator.appVersion.indexOf(\"MSIE 5\") === -1); CB_Configuration[CB_BASE_NAME].needsCanboxLastReturn = (!CB_Configuration[CB_BASE_NAME]._supportsCanvas() &amp;&amp; navigator.appVersion.indexOf(\"MSIE 5\") === -1); return CB_Configuration[CB_BASE_NAME].needsCanboxLastReturn; } } CB_Configuration[CB_BASE_NAME].needsExplorerCanvasLastReturn = null; //Cache to return always the same result. /** * Detects whether the web client needs [ExplorerCanvas]{@link https://github.com/arv/explorercanvas} or not. * @memberof CB_Configuration.CrossBase * @name needsExplorerCanvas * @function * @returns {boolean} */ CB_Configuration[CB_BASE_NAME].needsExplorerCanvas = function() { //If the last result is in the cache, we return again the same result: if (typeof(CB_Configuration[CB_BASE_NAME].needsExplorerCanvasLastReturn) !== \"undefined\" &amp;&amp; CB_Configuration[CB_BASE_NAME].needsExplorerCanvasLastReturn !== null) { return CB_Configuration[CB_BASE_NAME].needsExplorerCanvasLastReturn; } //...otherwise (it is the first time), we calculate if we need it or not: else { //We need it only if canvas is not already supported by the web client and the web client is IE 6, 7, 8 or 9 (IE9 doesn't support canvas in quirks mode and IE5/5.5 doesn't support ExplorerCanvas): //CB_Configuration[CB_BASE_NAME].needsExplorerCanvasLastReturn = (typeof(document.createElement(\"canvas\").getContext) === \"undefined\" &amp;&amp; navigator.userAgent.indexOf('MSIE') !== -1 &amp;&amp; (navigator.appVersion.indexOf(\"MSIE 6\") !== -1 || navigator.appVersion.indexOf(\"MSIE 7\") !== -1 || navigator.appVersion.indexOf(\"MSIE 8\") !== -1 || navigator.appVersion.indexOf(\"MSIE 9\") !== -1)); CB_Configuration[CB_BASE_NAME].needsExplorerCanvasLastReturn = (!CB_Configuration[CB_BASE_NAME]._supportsCanvas() &amp;&amp; navigator.userAgent.indexOf('MSIE') !== -1 &amp;&amp; (navigator.appVersion.indexOf(\"MSIE 6\") !== -1 || navigator.appVersion.indexOf(\"MSIE 7\") !== -1 || navigator.appVersion.indexOf(\"MSIE 8\") !== -1 || navigator.appVersion.indexOf(\"MSIE 9\") !== -1)); return CB_Configuration[CB_BASE_NAME].needsExplorerCanvasLastReturn; } } //CB_Configuration[CB_BASE_NAME].needsSLCanvasLastReturn = null; //Cache to return always the same result. /** * Detects whether the web client needs [SLCanvas]{@link https://slcanvas.codeplex.com/} or not. * @memberof CB_Configuration.CrossBase * @name needsSLCanvas * @function * @returns {boolean} */ CB_Configuration[CB_BASE_NAME].needsSLCanvas = function() { return !CB_Configuration[CB_BASE_NAME]._supportsCanvas(); /* //If the last result is in the cache, we return again the same result: if (typeof(CB_Configuration[CB_BASE_NAME].needsSLCanvasLastReturn) !== \"undefined\" &amp;&amp; CB_Configuration[CB_BASE_NAME].needsSLCanvasLastReturn !== null) { return CB_Configuration[CB_BASE_NAME].needsSLCanvasLastReturn; } //...otherwise (it is the first time), we calculate if we need it or not: else { //We need it only if canvas is not already supported by the web client: //CB_Configuration[CB_BASE_NAME].needsSLCanvasLastReturn = (typeof(document.createElement(\"canvas\").getContext) === \"undefined\");// &amp;&amp; navigator.appVersion.indexOf(\"MSIE 5\") === -1); CB_Configuration[CB_BASE_NAME].needsSLCanvasLastReturn = !CB_Configuration[CB_BASE_NAME]._supportsCanvas();// &amp;&amp; navigator.appVersion.indexOf(\"MSIE 5\") === -1); return CB_Configuration[CB_BASE_NAME].needsSLCanvasLastReturn; } */ } CB_Configuration[CB_BASE_NAME].needsFlashCanvasLastReturn = null; //Cache to return always the same result. /** * Detects whether the web client needs [FlashCanvas]{@link https://github.com/everlaat/flashcanvas} or not. * @memberof CB_Configuration.CrossBase * @name needsFlashCanvas * @function * @returns {boolean} */ CB_Configuration[CB_BASE_NAME].needsFlashCanvas = function() { //If the last result is in the cache, we return again the same result: if (typeof(CB_Configuration[CB_BASE_NAME].needsFlashCanvasLastReturn) !== \"undefined\" &amp;&amp; CB_Configuration[CB_BASE_NAME].needsFlashCanvasLastReturn !== null) { return CB_Configuration[CB_BASE_NAME].needsFlashCanvasLastReturn; } //...otherwise (it is the first time), we calculate if we need it or not: else { //We need it only if ActiveXObject is available (it has to be IE) and it is not compatible with canvas: CB_Configuration[CB_BASE_NAME].needsFlashCanvasLastReturn = (typeof(window.ActiveXObject) !== \"undefined\" &amp;&amp; typeof(window.CanvasRenderingContext2D) === \"undefined\"); return CB_Configuration[CB_BASE_NAME].needsFlashCanvasLastReturn; } } CB_Configuration[CB_BASE_NAME].needsCanvasTextLastReturn = null; //Cache to return always the same result. /** * Detects whether the web client needs [canvas-text]{@link https://github.com/PhenX/canvas-text} or not. * @memberof CB_Configuration.CrossBase * @name needsCanvasText * @function * @returns {boolean} */ CB_Configuration[CB_BASE_NAME].needsCanvasText = function() { //If the last result is in the cache, we return again the same result: if (typeof(CB_Configuration[CB_BASE_NAME].needsCanvasTextLastReturn) !== \"undefined\" &amp;&amp; CB_Configuration[CB_BASE_NAME].needsCanvasTextLastReturn !== null) { return CB_Configuration[CB_BASE_NAME].needsCanvasTextLastReturn; } //...otherwise (it is the first time), we calculate if we need it or not: else { //CB_Configuration[CB_BASE_NAME]._supportsCanvasElement = CB_Configuration[CB_BASE_NAME]._supportsCanvasElement || document.createElement(\"canvas\"); //If canvas is supported: //if (typeof(CB_Configuration[CB_BASE_NAME]._supportsCanvasElement) !== \"undefined\" &amp;&amp; CB_Configuration[CB_BASE_NAME]._supportsCanvasElement !== null) //{ //if (typeof(CB_Configuration[CB_BASE_NAME]._supportsCanvasElement.getContext) !== \"undefined\" &amp;&amp; CB_Configuration[CB_BASE_NAME]._supportsCanvasElement.getContext !== null) //{ if (CB_Configuration[CB_BASE_NAME]._supportsCanvas()) { try //Uses try-catch to avoid some problems with some web clients (as BeZilla / Bon Echo 2.0.0.22Pre on Haiku OS). { //If fillText exists: if (typeof(CB_Configuration[CB_BASE_NAME]._supportsCanvasElement.getContext(\"2d\").fillText) !== \"undefined\" &amp;&amp; CB_Configuration[CB_BASE_NAME]._supportsCanvasElement.getContext(\"2d\").fillText !== null) { CB_Configuration[CB_BASE_NAME].needsCanvasTextLastReturn = false; //We don't need canvas-text. return CB_Configuration[CB_BASE_NAME].needsCanvasTextLastReturn; } else { CB_Configuration[CB_BASE_NAME].needsCanvasTextLastReturn = true; return CB_Configuration[CB_BASE_NAME].needsCanvasTextLastReturn; } } catch(E) { CB_Configuration[CB_BASE_NAME].needsCanvasTextLastReturn = true; return CB_Configuration[CB_BASE_NAME].needsCanvasTextLastReturn; } } //} //} CB_Configuration[CB_BASE_NAME].needsCanvasTextLastReturn = false; return CB_Configuration[CB_BASE_NAME].needsCanvasTextLastReturn; } } /** * Detects whether the web client needs [timbre.js]{@link https://mohayonao.github.io/timbre.js/} (including [subcollider.js]{@link https://github.com/mohayonao/subcollider}) or not. * @function * @memberof CB_Configuration.CrossBase * @name needsTimbreJS * @returns {boolean} */ CB_Configuration[CB_BASE_NAME].needsTimbreJS = function() { //TODO: see what IE versions are compatible. return (navigator.appVersion.indexOf(\"MSIE 5\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 6\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 7\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 8\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 9\") === -1); } /** * Detects whether the web client needs [jsfx]{@link https://github.com/loov/jsfx} or not. * @memberof CB_Configuration.CrossBase * @name needsJsfx * @function * @returns {boolean} */ CB_Configuration[CB_BASE_NAME].needsJsfx = function() { //TODO: see what IE versions are compatible. return (navigator.appVersion.indexOf(\"MSIE 5\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 6\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 7\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 8\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 9\") === -1); } /** * Detects whether the web client needs [Pressure.js]{@link https://pressurejs.com/} or not. * @memberof CB_Configuration.CrossBase * @name needsPressureJS * @function * @returns {boolean} */ CB_Configuration[CB_BASE_NAME].needsPressureJS= function() { //TODO: see what IE versions are compatible. return (navigator.appVersion.indexOf(\"MSIE 5\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 6\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 7\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 8\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 9\") === -1); } /** * Detects whether the web client needs [Hammer.js]{@link http://hammerjs.github.io/} or not. * @memberof CB_Configuration.CrossBase * @name needsHammerJS * @function * @returns {boolean} */ CB_Configuration[CB_BASE_NAME].needsHammerJS = function() { //TODO: see what IE versions are compatible. return (navigator.appVersion.indexOf(\"MSIE 5\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 6\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 7\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 8\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 9\") === -1); } /** * Detects whether the web client needs [gamepad-plus]{@link https://github.com/MozVR/gamepad-plus} or not. * @memberof CB_Configuration.CrossBase * @name needsGamepadPlus * @function * @returns {boolean} * @todo Find a better way for this as old Firefox versions can only detect GamePad API support when the events are fired, so we cannot relay on navigator.getGamepads/navigator.webkitGetGamepads/navigator.webkitGamepads. */ CB_Configuration[CB_BASE_NAME].needsGamepadPlus = function() { //TODO: Find a better way for this as old Firefox versions can only detect GamePad API support when the events are fired, so we cannot relay on navigator.getGamepads/navigator.webkitGetGamepads/navigator.webkitGamepads. return !!(typeof(navigator) === \"object\" &amp;&amp; navigator !== null &amp;&amp; (navigator.getGamepads || navigator.webkitGetGamepads || navigator.webkitGamepads)); } /** * Detects whether the web client needs [NoSleep.js]{@link https://github.com/richtr/NoSleep.js} or not. * @function * @memberof CB_Configuration.CrossBase * @name needsSleepJS * @returns {boolean} */ CB_Configuration[CB_BASE_NAME].needsSleepJS = function() { return (navigator.appVersion.indexOf(\"MSIE 5\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 6\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 7\") === -1 &amp;&amp; navigator.appVersion.indexOf(\"MSIE 8\") === -1); } //SockJS parameters: /** * Directory that contains the [SockJS library]{@link https://github.com/sockjs/sockjs-client/} files. * @memberof CB_Configuration.CrossBase * @name SOCKJS_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"net/sockets/SockJS/\" */ CB_Configuration[CB_BASE_NAME].SOCKJS_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"net/sockets/SockJS/\"; /** * The script file path for the [SockJS library]{@link https://github.com/sockjs/sockjs-client/}. As the newer [SockJS library]{@link https://github.com/sockjs/sockjs-client/} versions do not work in old Internet Explorer versions (6, 7 or 8), if they are detected it will use the [SockJS library]{@link https://github.com/sockjs/sockjs-client/} 0.3.4 version instead. * @memberof CB_Configuration.CrossBase * @name SOCKJS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration[CB_BASE_NAME].SOCKJS_PATH} + SOCKJS_SCRIPT_FILE, where \"SOCKJS_SCRIPT_FILE\" is sockjs-0.3.4.min.js (SockJS 0.3.4), sockjs-1.1.1.min.js (SockJS 1.1.1) or sockjs.min.js (last version) depending on the client detected. */ CB_Configuration[CB_BASE_NAME].SOCKJS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].SOCKJS_PATH; if (navigator.appVersion.indexOf(\"MSIE 5\") !== -1 || navigator.appVersion.indexOf(\"MSIE 6\") !== -1 || navigator.appVersion.indexOf(\"MSIE 7\") !== -1 || navigator.appVersion.indexOf(\"MSIE 8\") !== -1) { CB_Configuration[CB_BASE_NAME].SOCKJS_PATH_SCRIPT_FILE += \"sockjs-0.3.4.min.js\"; } else if (navigator.appVersion.indexOf(\"MSIE 9\") !== -1) { CB_Configuration[CB_BASE_NAME].SOCKJS_PATH_SCRIPT_FILE += \"sockjs-1.1.1.min.js\"; } else { CB_Configuration[CB_BASE_NAME].SOCKJS_PATH_SCRIPT_FILE += \"sockjs.min.js\"; } //Intel XDK parameters: /** * Defines whether to load or not intelxdk.js (used by [Intel XDK]{@link https://en.wikipedia.org/wiki/Intel_XDK}). * @memberof CB_Configuration.CrossBase * @name INTELXDKJS_LOAD * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].INTELXDKJS_LOAD = false; //CB_Configuration[CB_BASE_NAME].needsIntelXDKJS(); /** * Directory that contains the \"intelxdk.js\" file (used by [Intel XDK]{@link https://en.wikipedia.org/wiki/Intel_XDK}). * @memberof CB_Configuration.CrossBase * @name INTELXDKJS_PATH * @constant * @type {string} * @default */ CB_Configuration[CB_BASE_NAME].INTELXDKJS_PATH = \"../\"; /** * The script file path for intelxdk.js (used by [Intel XDK]{@link https://en.wikipedia.org/wiki/Intel_XDK}). * @memberof CB_Configuration.CrossBase * @name INTELXDKJS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.INTELXDKJS_PATH} + \"intelxdk.js\" */ CB_Configuration[CB_BASE_NAME].INTELXDKJS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].INTELXDKJS_PATH + \"intelxdk.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.INTELXDKJS_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name INTELXDKJS_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].INTELXDKJS_PATH_ABSOLUTE = false; /** * Defines whether to try to load or not init-dev.js (used by [Intel XDK]{@link https://en.wikipedia.org/wiki/Intel_XDK}). If set to true, the checker defined at {@link CB_Configuration.CrossBase.INTELXDK_INITDEVJS_LOAD_CHECKER} will finally decide whether to load it or not. * @memberof CB_Configuration.CrossBase * @name INTELXDK_INITDEVJS_LOAD * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].INTELXDK_INITDEVJS_LOAD = false; //CB_Configuration[CB_BASE_NAME].needsIntelXDKJS(); /** * Callback checker to determine whether init-dev.js (used by [Intel XDK]{@link https://en.wikipedia.org/wiki/Intel_XDK}) is needed or not. Requires {@link CB_Configuration.CrossBase.INTELXDK_INITDEVJS_LOAD} set to true. * @memberof CB_Configuration.CrossBase * @name INTELXDK_INITDEVJS_LOAD_CHECKER * @constant * @type {CB_Modules.neededFile_LOAD_CHECKER} * @default false */ CB_Configuration[CB_BASE_NAME].INTELXDK_INITDEVJS_LOAD_CHECKER = false; //function(currentPath, info) { return (typeof(dev) === \"undefined\" || dev === null || typeof(dev.initDeviceReady) !== \"function\"); }; /** * Directory that contains the \"init-dev.js\" (used by [Intel XDK]{@link https://en.wikipedia.org/wiki/Intel_XDK}). * @memberof CB_Configuration.CrossBase * @name INTELXDK_INITDEVJS_PATH * @constant * @type {string} * @default */ CB_Configuration[CB_BASE_NAME].INTELXDK_INITDEVJS_PATH = \"../xdk/\"; /** * The script file path for init-dev.js file (used by [Intel XDK]{@link https://en.wikipedia.org/wiki/Intel_XDK}). * @memberof CB_Configuration.CrossBase * @name INTELXDK_INITDEVJS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.INTELXDK_INITDEVJS_PATH} + \"init-dev.js\" */ CB_Configuration[CB_BASE_NAME].INTELXDK_INITDEVJS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].INTELXDK_INITDEVJS_PATH + \"init-dev.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.INTELXDK_INITDEVJS_PATH} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name INTELXDK_INITDEVJS_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].INTELXDK_INITDEVJS_PATH_ABSOLUTE = false; //PhoneGap parameters: /** * Defines whether to load or not phonegap.js (used by [Adobe PhoneGap]{@link https://phonegap.com/}). * @memberof CB_Configuration.CrossBase * @name PHONEGAPJS_LOAD * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].PHONEGAPJS_LOAD = false; //CB_Configuration[CB_BASE_NAME].needsPhoneGapJS(); /** * Directory that contains the \"phonegap.js\" (used by [Adobe PhoneGap]{@link https://phonegap.com/}) file. * @memberof CB_Configuration.CrossBase * @name PHONEGAPJS_PATH * @constant * @type {string} * @default */ CB_Configuration[CB_BASE_NAME].PHONEGAPJS_PATH = \"../\"; /** * The script file path for phonegap.js (used by [Adobe PhoneGap]{@link https://phonegap.com/}). * @memberof CB_Configuration.CrossBase * @name PHONEGAPJS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.PHONEGAPJS_PATH} + \"phonegap.js\" */ CB_Configuration[CB_BASE_NAME].PHONEGAPJS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].PHONEGAPJS_PATH + \"phonegap.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.PHONEGAPJS_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name PHONEGAPJS_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].PHONEGAPJS_PATH_ABSOLUTE = false; //Apache Cordova parameters: /** * Defines whether to try to load or not cordova.js (used by [Apache Cordova]{@link https://cordova.apache.org/}). It should not be loaded together with phonegap.js, normally. If set to true, the checker defined at {@link CB_Configuration.CrossBase.CORDOVAJS_LOAD_CHECKER} will finally decide whether to load it or not. * @memberof CB_Configuration.CrossBase * @name CORDOVAJS_LOAD * @constant * @type {boolean} * @default !{@link CB_Configuration.CrossBase.PHONEGAPJS_LOAD} */ CB_Configuration[CB_BASE_NAME].CORDOVAJS_LOAD = !CB_Configuration[CB_BASE_NAME].PHONEGAPJS_LOAD &amp;&amp; window.location &amp;&amp; window.location.protocol !== \"http:\" &amp;&amp; window.location.protocol !== \"https:\" &amp;&amp; navigator.userAgent.indexOf(\"Electron\") === -1 &amp;&amp; ( typeof(require) !== \"function\" || (typeof(nw) === \"undefined\" &amp;&amp; (nw === null || !nw.App) &amp;&amp; typeof(require(\"nw.gui\")) === \"undefined\") ); //CB_Configuration[CB_BASE_NAME].needsCordovaJS(); /** * Callback checker to determine whether cordova.js (used by [Apache Cordova]{@link https://cordova.apache.org/}) is needed or not. Requires {@link CB_Configuration.CrossBase.CORDOVAJS_LOAD} set to true. * @memberof CB_Configuration.CrossBase * @name CORDOVAJS_LOAD_CHECKER * @constant * @type {CB_Modules.neededFile_LOAD_CHECKER} * @default function(currentPath, info) { return (typeof(window.cordova) === \"undefined\"); } */ CB_Configuration[CB_BASE_NAME].CORDOVAJS_LOAD_CHECKER = function(currentPath, info) { return (typeof(window.cordova) === \"undefined\"); }; /** * Directory that contains the \"cordova.js\" file (used by [Apache Cordova]{@link https://cordova.apache.org/}). * @memberof CB_Configuration.CrossBase * @name CORDOVAJS_PATH * @constant * @type {string} * @default */ CB_Configuration[CB_BASE_NAME].CORDOVAJS_PATH = \"../\"; /** * The script file path for the cordova.js file (used by [Apache Cordova]{@link https://cordova.apache.org/}). * @memberof CB_Configuration.CrossBase * @name CORDOVAJS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.CORDOVAJS_PATH} + \"cordova.js\" */ CB_Configuration[CB_BASE_NAME].CORDOVAJS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].CORDOVAJS_PATH + \"cordova.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.CORDOVAJS_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name CORDOVAJS_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].CORDOVAJS_PATH_ABSOLUTE = false; //localStorage polyfill parameters: /** * Defines whether to load or not [localStorage polyfill]{@link https://github.com/mortzdk/localStorage}. * @memberof CB_Configuration.CrossBase * @name LOCALSTORAGE_POLYFILL_LOAD * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].LOCALSTORAGE_POLYFILL_LOAD = true; /** * Directory that contains the [localStorage polyfill]{@link https://github.com/mortzdk/localStorage} files. * @memberof CB_Configuration.CrossBase * @name LOCALSTORAGE_POLYFILL_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"general/localStorage/\" */ CB_Configuration[CB_BASE_NAME].LOCALSTORAGE_POLYFILL_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"general/localStorage/\"; /** * Directory that contains the SWF for [localStorage polyfill]{@link https://github.com/mortzdk/localStorage}. The value of the \"scriptPathGiven\" parameter will be attached at the beginning automatically. Belongs to the \"swfURL\" parameter (URL \"GET\" parameter) of the library when the localStorage script file is attached. * @memberof CB_Configuration.CrossBase * @name LOCALSTORAGE_POLYFILL_PATH_SWF * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.LOCALSTORAGE_POLYFILL_PATH} + \"localStorage.swf\" */ CB_Configuration[CB_BASE_NAME].LOCALSTORAGE_POLYFILL_PATH_SWF_FILE = CB_Configuration[CB_BASE_NAME].LOCALSTORAGE_POLYFILL_PATH + \"localStorage.swf\"; //CB_Configuration[CB_BASE_NAME].LOCALSTORAGE_POLYFILL_PATH_SWF_FILE = \"localStorage.swf\"; /** * The script file path for [localStorage polyfill]{@link https://github.com/mortzdk/localStorage}. * @memberof CB_Configuration.CrossBase * @name LOCALSTORAGE_POLYFILL_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.LOCALSTORAGE_POLYFILL_PATH} + \"localStorage.min.js?swfURL=\" + CB_Configuration[CB_BASE_NAME].LOCALSTORAGE_POLYFILL_PATH_SWF_FILE */ CB_Configuration[CB_BASE_NAME].LOCALSTORAGE_POLYFILL_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].LOCALSTORAGE_POLYFILL_PATH + \"localStorage.min.js?swfURL=\" + CB_Configuration[CB_BASE_NAME].LOCALSTORAGE_POLYFILL_PATH_SWF_FILE; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.LOCALSTORAGE_POLYFILL_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name LOCALSTORAGE_POLYFILL_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].LOCALSTORAGE_POLYFILL_PATH_ABSOLUTE = false; //WAAPISim parameters: /** * Defines whether to load or not [WAAPISim]{@link https://github.com/g200kg/WAAPISim}. * @memberof CB_Configuration.CrossBase * @name WAAPISIM_LOAD * @constant * @type {boolean} * @default {@link CB_Configuration.CrossBase.WAAPI_EMULATION_ALLOWED} &amp;&amp; {@link CB_Configuration.CrossBase.needsWAAPISim}() */ CB_Configuration[CB_BASE_NAME].WAAPISIM_LOAD = CB_Configuration[CB_BASE_NAME].WAAPI_EMULATION_ALLOWED &amp;&amp; CB_Configuration[CB_BASE_NAME].needsWAAPISim(); /** * Directory that contains the [WAAPISim]{@link https://github.com/g200kg/WAAPISim} files (script and SWF). * @memberof CB_Configuration.CrossBase * @name WAAPISIM_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"audiovisual/audio/WAAPISim/\" */ CB_Configuration[CB_BASE_NAME].WAAPISIM_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/audio/WAAPISim/\"; /** * The script file path for the [WAAPISim]{@link https://github.com/g200kg/WAAPISim} script file. * @memberof CB_Configuration.CrossBase * @name WAAPISIM_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.WAAPISIM_PATH} + \"waapisim.min.js\" */ CB_Configuration[CB_BASE_NAME].WAAPISIM_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].WAAPISIM_PATH + \"waapisim.min.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.WAAPISIM_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name WAAPISIM_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].WAAPISIM_PATH_ABSOLUTE = false; //timbre.js (including subcollider.js) parameters: /** * Defines whether to load or not [timbre.js]{@link https://mohayonao.github.io/timbre.js/}. * @memberof CB_Configuration.CrossBase * @name TIMBREJS_LOAD * @constant * @type {boolean} * @default {@link CB_Configuration.CrossBase.needsTimbreJS}() */ CB_Configuration[CB_BASE_NAME].TIMBREJS_LOAD = CB_Configuration[CB_BASE_NAME].needsTimbreJS(); /** * Directory that contains the [timbre.js]{@link https://mohayonao.github.io/timbre.js/} files (script and SWF). * @memberof CB_Configuration.CrossBase * @name TIMBREJS_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"audiovisual/audio/timbre.js/\" */ CB_Configuration[CB_BASE_NAME].TIMBREJS_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/audio/timbre.js/\"; /** * The script file path for [timbre.js]{@link https://mohayonao.github.io/timbre.js/}. * @memberof CB_Configuration.CrossBase * @name TIMBREJS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.TIMBREJS_PATH} + \"timbre.js\" */ CB_Configuration[CB_BASE_NAME].TIMBREJS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].TIMBREJS_PATH + \"timbre.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.TIMBREJS_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name TIMBREJS_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].TIMBREJS_PATH_ABSOLUTE = false; /** * Defines whether to load or not [subcollider.js]{@link https://github.com/mohayonao/subcollider}. * @memberof CB_Configuration.CrossBase * @name SUBCOLLIDERJS_LOAD * @constant * @type {boolean} * @default {@link CB_Configuration.CrossBase.TIMBREJS_LOAD} */ CB_Configuration[CB_BASE_NAME].SUBCOLLIDERJS_LOAD = CB_Configuration[CB_BASE_NAME].TIMBREJS_LOAD; /** * Directory that contains the [subcollider.js]{@link https://github.com/mohayonao/subcollider} script. * @memberof CB_Configuration.CrossBase * @name SUBCOLLIDERJS_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.TIMBREJS_PATH} + \"subcollider/\" */ CB_Configuration[CB_BASE_NAME].SUBCOLLIDERJS_PATH = CB_Configuration[CB_BASE_NAME].TIMBREJS_PATH + \"subcollider/\"; /** * The script file path for [subcollider.js]{@link https://github.com/mohayonao/subcollider}. * @memberof CB_Configuration.CrossBase * @name SUBCOLLIDERJS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SUBCOLLIDERJS_PATH} + \"subcollider.js\" */ CB_Configuration[CB_BASE_NAME].SUBCOLLIDERJS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].SUBCOLLIDERJS_PATH + \"subcollider.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.SUBCOLLIDERJS_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name SUBCOLLIDERJS_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].SUBCOLLIDERJS_PATH_ABSOLUTE = false; //Band.js parameters: /** * Defines whether to load or not [Band.js]{@link https://github.com/meenie/band.js/}. * @memberof CB_Configuration.CrossBase * @name BANDJS_LOAD * @constant * @type {boolean} * @default typeof(window.AudioContext) !== \"undefined\" || typeof(window.webkitAudioContext) !== \"undefined\" */ CB_Configuration[CB_BASE_NAME].BANDJS_LOAD = typeof(window.AudioContext) !== \"undefined\" || typeof(window.webkitAudioContext) !== \"undefined\"; /** * Directory that contains the [Band.js]{@link https://github.com/meenie/band.js/} files. * @memberof CB_Configuration.CrossBase * @name BANDJS_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"audiovisual/audio/band.js/\" */ CB_Configuration[CB_BASE_NAME].BANDJS_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/audio/band.js/\"; /** * The script file path for [Band.js]{@link https://github.com/meenie/band.js/}. * @memberof CB_Configuration.CrossBase * @name BANDJS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.BANDJS_PATH} + \"band.min.js\" */ CB_Configuration[CB_BASE_NAME].BANDJS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].BANDJS_PATH + \"band.min.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.BANDJS_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name BANDJS_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].BANDJS_PATH_ABSOLUTE = false; //SoundManager 2 parameters: /** * Defines whether to load or not [SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}. * @memberof CB_Configuration.CrossBase * @name SM2_LOAD * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].SM2_LOAD = true; /** * Directory that contains the [SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/} files. * @memberof CB_Configuration.CrossBase * @name SM2_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"audiovisual/audio/soundmanager2/\" */ CB_Configuration[CB_BASE_NAME].SM2_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/audio/soundmanager2/\"; /** * The script file path for [SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}. * @memberof CB_Configuration.CrossBase * @name SM2_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SM2_PATH} + \"script/soundmanager2-nodebug-jsmin.js\" */ CB_Configuration[CB_BASE_NAME].SM2_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].SM2_PATH + \"script/soundmanager2-nodebug-jsmin.js\"; /** * Directory that contains the SWF's for [SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}. The value of the \"scriptPathGiven\" parameter will be attached at the beginning automatically. Belongs to the \"url\" parameter of the library when [soundManager.setup]{@link http://www.schillmania.com/projects/soundmanager2/doc/#soundmanager-setup} function is called. More information: http://www.schillmania.com/projects/soundmanager2/doc/#soundmanager-url * @memberof CB_Configuration.CrossBase * @name SM2_PATH_SWF * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SM2_PATH} + \"swf/\" */ CB_Configuration[CB_BASE_NAME].SM2_PATH_SWF = CB_Configuration[CB_BASE_NAME].SM2_PATH + \"swf/\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.SM2_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name SM2_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].SM2_PATH_ABSOLUTE = false; /** * Object with the required formats for [SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}. If the format is required and the web client doesn't support it, [SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/} will use [Flash]{@link https://en.wikipedia.org/wiki/Adobe_Flash_Player}. More information: http://www.schillmania.com/projects/soundmanager2/doc/#soundmanager-audioformats * @memberof CB_Configuration.CrossBase * @name SM2_AUDIO_FORMATS_REQUIRED * @constant * @type {Object} * @property {boolean} mp3=false - Defines MP3 format as required. * @property {boolean} mp4=false - Defines MP4 format as required. * @property {boolean} ogg=false - Defines OGG format as required. * @property {boolean} opus=false - Defines OPUS format as required. * @property {boolean} wav=false - Defines WAV format as required. * @default */ CB_Configuration[CB_BASE_NAME].SM2_AUDIO_FORMATS_REQUIRED = { \"mp3\" : false, \"mp4\" : false, \"ogg\" : false, \"opus\" : false, \"wav\" : false }; /** * Defines whether to use or not high performance mode in [SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/} (may cause a flash object to be visible). Belongs to the \"useHighPerformance\" parameter of the library when [soundManager.setup]{@link http://www.schillmania.com/projects/soundmanager2/doc/#soundmanager-setup} function is called. More information: http://www.schillmania.com/projects/soundmanager2/doc/#soundmanager-highperformance * @memberof CB_Configuration.CrossBase * @name SM2_USE_HIGH_PERFORMANCE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].SM2_USE_HIGH_PERFORMANCE = true; /** * Milliseconds to wait after loading [SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/} to define it as not supported if there is no response. Belongs to the \"flashLoadTimeout\" parameter of the library when [soundManager.setup]{@link http://www.schillmania.com/projects/soundmanager2/doc/#soundmanager-setup} function is called. More information: http://www.schillmania.com/projects/soundmanager2/doc/#soundmanager-flashloadtimeout * @memberof CB_Configuration.CrossBase * @name SM2_TIMEOUT_MS * @constant * @type {integer} * @default */ CB_Configuration[CB_BASE_NAME].SM2_TIMEOUT_MS = 6000; //CB_Configuration[CB_BASE_NAME].SM2_USE_FAST_POLLING = true; //Defines whether to use fast polling (useFastPolling) in [SoundManager 2]{@link http://schillmania.com/projects/soundmanager2/}. //jsfx parameters: /** * Defines whether to load or not [jsfx]{@link https://github.com/loov/jsfx}. * @memberof CB_Configuration.CrossBase * @name JSFX_LOAD * @constant * @type {boolean} * @default {@link CB_Configuration.CrossBase.needsJsfx}() */ CB_Configuration[CB_BASE_NAME].JSFX_LOAD = CB_Configuration[CB_BASE_NAME].needsJsfx(); /** * Directory that contains the [jsfx]{@link https://github.com/loov/jsfx} files. * @memberof CB_Configuration.CrossBase * @name JSFX_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"audiovisual/audio/jsfx/\" */ CB_Configuration[CB_BASE_NAME].JSFX_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/audio/jsfx/\"; /** * The script file path for [jsfx]{@link https://github.com/loov/jsfx}. * @memberof CB_Configuration.CrossBase * @name JSFX_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.JSFX_PATH} + \"jsfx.js\" */ CB_Configuration[CB_BASE_NAME].JSFX_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].JSFX_PATH + \"jsfx.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.JSFX_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name JSFX_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].JSFX_PATH_ABSOLUTE = false; //NoSleep.js parameters: /** * Defines whether to load or not [NoSleep.js]{@link https://github.com/richtr/NoSleep.js}. * @memberof CB_Configuration.CrossBase * @name NOSLEEP_LOAD * @constant * @type {boolean} * @default {@link CB_Configuration.CrossBase.needsSleepJS}() */ CB_Configuration[CB_BASE_NAME].NOSLEEP_LOAD = CB_Configuration[CB_BASE_NAME].needsSleepJS(); /** * Directory that contains the [NoSleep.js]{@link https://github.com/richtr/NoSleep.js} files. * @memberof CB_Configuration.CrossBase * @name NOSLEEP_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"audiovisual/image/NoSleep/\" */ CB_Configuration[CB_BASE_NAME].NOSLEEP_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/image/NoSleep/\"; /** * The script file path for [NoSleep.js]{@link https://github.com/richtr/NoSleep.js}. * @memberof CB_Configuration.CrossBase * @name NOSLEEP_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.NOSLEEP_PATH} + \"NoSleep.min.js\" */ CB_Configuration[CB_BASE_NAME].NOSLEEP_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].NOSLEEP_PATH + \"NoSleep.min.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.NOSLEEP_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name NOSLEEP_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].NOSLEEP_PATH_ABSOLUTE = false; //Pressure.js parameters: /** * Defines whether to load or not [Pressure.js]{@link https://pressurejs.com/}. * @memberof CB_Configuration.CrossBase * @name PRESSUREJS_LOAD * @constant * @type {boolean} * @default {@link CB_Configuration.CrossBase.needsPressureJS}() */ CB_Configuration[CB_BASE_NAME].PRESSUREJS_LOAD = CB_Configuration[CB_BASE_NAME].needsPressureJS(); /** * Directory that contains the [Pressure.js]{@link https://pressurejs.com/} files. * @memberof CB_Configuration.CrossBase * @name PRESSUREJS_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"input/pressure.js/\" */ CB_Configuration[CB_BASE_NAME].PRESSUREJS_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"input/pressure.js/\"; /** * The script file path for [Pressure.js]{@link https://pressurejs.com/}. * @memberof CB_Configuration.CrossBase * @name PRESSUREJS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.PRESSUREJS_PATH} + \"pressure.min.js\" */ CB_Configuration[CB_BASE_NAME].PRESSUREJS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].PRESSUREJS_PATH + \"pressure.min.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.PRESSUREJS_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name PRESSUREJS_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].PRESSUREJS_PATH_ABSOLUTE = false; //Hammer.js and Hammer Time parameters: /** * Defines whether to load or not [Hammer.js]{@link http://hammerjs.github.io/} and [Hammer Time]{@link https://github.com/hammerjs/hammer-time}. * @memberof CB_Configuration.CrossBase * @name HAMMERJS_LOAD * @constant * @type {boolean} * @default {@link CB_Configuration.CrossBase.needsHammerJS}() */ CB_Configuration[CB_BASE_NAME].HAMMERJS_LOAD = CB_Configuration[CB_BASE_NAME].needsHammerJS(); /** * Directory that contains the [Hammer.js]{@link http://hammerjs.github.io/} and [Hammer Time]{@link https://github.com/hammerjs/hammer-time} files. * @memberof CB_Configuration.CrossBase * @name HAMMERJS_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"input/hammer.js/\" */ CB_Configuration[CB_BASE_NAME].HAMMERJS_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"input/hammer.js/\"; /** * The script file path for [Hammer.js]{@link http://hammerjs.github.io/}. * @memberof CB_Configuration.CrossBase * @name HAMMERJS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.HAMMERJS_PATH} + \"hammer.min.js\" */ CB_Configuration[CB_BASE_NAME].HAMMERJS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].HAMMERJS_PATH + \"hammer.min.js\"; /** * The script file path for [Hammer Time]{@link https://github.com/hammerjs/hammer-time}. * @memberof CB_Configuration.CrossBase * @name HAMMERJS_HAMMER_TIME_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.HAMMERJS_PATH} + \"hammer-time/hammer-time.min.js\" */ CB_Configuration[CB_BASE_NAME].HAMMERJS_HAMMER_TIME_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].HAMMERJS_PATH + \"hammer-time/hammer-time.min.js\"; /** * Defines whether the paths defined in {@link CB_Configuration.CrossBase.HAMMERJS_PATH_SCRIPT_FILE} and {@link CB_Configuration.CrossBase.HAMMERJS_HAMMER_TIME_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name HAMMERJS_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].HAMMERJS_PATH_ABSOLUTE = false; //wii-js parameters: /** * Defines whether to load or not [wii-js]{@link https://github.com/ryanmcgrath/wii-js}. * @memberof CB_Configuration.CrossBase * @name WII_JS_LOAD * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].WII_JS_LOAD = true; /** * Directory that contains the [wii-js]{@link https://github.com/ryanmcgrath/wii-js} script. * @memberof CB_Configuration.CrossBase * @name WII_JS_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"input/controllers/wii-js/\" */ CB_Configuration[CB_BASE_NAME].WII_JS_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"input/controllers/wii-js/\"; /** * The script file path for [wii-js]{@link https://github.com/ryanmcgrath/wii-js}. * @memberof CB_Configuration.CrossBase * @name WII_JS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.WII_JS_PATH} + \"wii.min.js\" */ CB_Configuration[CB_BASE_NAME].WII_JS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].WII_JS_PATH + \"wii.min.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.WII_JS_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name WII_JS_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].WII_JS_PATH_ABSOLUTE = false; //gamepad-plus parameters: /** * Defines whether to load or not [gamepad-plus]{@link https://github.com/MozVR/gamepad-plus}. * @memberof CB_Configuration.CrossBase * @name GAMEPAD_PLUS_LOAD * @constant * @type {boolean} * @default {@link CB_Configuration.CrossBase.needsGamepadPlus}() */ CB_Configuration[CB_BASE_NAME].GAMEPAD_PLUS_LOAD = CB_Configuration[CB_BASE_NAME].needsGamepadPlus(); /** * Directory that contains the [gamepad-plus]{@link https://github.com/MozVR/gamepad-plus} files. * @memberof CB_Configuration.CrossBase * @name GAMEPAD_PLUS_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"input/controllers/gamepad-plus/\" */ CB_Configuration[CB_BASE_NAME].GAMEPAD_PLUS_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"input/controllers/gamepad-plus/\"; /** * The script file path for [gamepad-plus]{@link https://github.com/MozVR/gamepad-plus}. * @memberof CB_Configuration.CrossBase * @name GAMEPAD_PLUS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.GAMEPAD_PLUS_PATH} + \"gamepads.js\" */ CB_Configuration[CB_BASE_NAME].GAMEPAD_PLUS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].GAMEPAD_PLUS_PATH + \"gamepads.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.GAMEPAD_PLUS_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name GAMEPAD_PLUS_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].GAMEPAD_PLUS_PATH_ABSOLUTE = false; //Canbox parameters: /** * Defines whether to load or not [Canbox]{@link https://github.com/robertinglin/CanBox}. * @memberof CB_Configuration.CrossBase * @name CANBOX_LOAD * @constant * @type {boolean} * @default {@link CB_Configuration.CrossBase.needsCanbox}() */ CB_Configuration[CB_BASE_NAME].CANBOX_LOAD = CB_Configuration[CB_BASE_NAME].needsCanbox(); /** * Directory that contains the [Canbox]{@link https://github.com/robertinglin/CanBox} files. * @memberof CB_Configuration.CrossBase * @name CANBOX_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"audiovisual/image/canvas/canbox/\" */ CB_Configuration[CB_BASE_NAME].CANBOX_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/image/canvas/canbox/\"; /** * The script file path for [Canbox]{@link https://github.com/robertinglin/CanBox}. * @memberof CB_Configuration.CrossBase * @name CANBOX_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.CANBOX_PATH} + \"canbox.0.2.1.js\" */ CB_Configuration[CB_BASE_NAME].CANBOX_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].CANBOX_PATH + \"canbox.0.2.1.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.CANBOX_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name CANBOX_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].CANBOX_PATH_ABSOLUTE = false; //FlashCanvas parameters: /** * Defines whether to load or not [FlashCanvas]{@link https://github.com/everlaat/flashcanvas}. * @memberof CB_Configuration.CrossBase * @name FLASHCANVAS_LOAD * @constant * @type {boolean} * @default {@link CB_Configuration.CrossBase.needsFlashCanvas}() */ CB_Configuration[CB_BASE_NAME].FLASHCANVAS_LOAD = CB_Configuration[CB_BASE_NAME].needsFlashCanvas(); /** * Defines whether to allow to run [FlashCanvas]{@link https://github.com/everlaat/flashcanvas} locally or not (because the \".swf\" file folder needs to be added to 'trusted files' in Flash global configuration to work locally in some operating systems). * @memberof CB_Configuration.CrossBase * @name FLASHCANVAS_ALLOW_RUN_LOCALLY_DEFAULT * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].FLASHCANVAS_ALLOW_RUN_LOCALLY_DEFAULT = false; /** * Directory that contains the [FlashCanvas]{@link https://github.com/everlaat/flashcanvas} files. * @memberof CB_Configuration.CrossBase * @name FLASHCANVAS_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"audiovisual/image/canvas/FlashCanvas/pro/\" */ CB_Configuration[CB_BASE_NAME].FLASHCANVAS_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/image/canvas/FlashCanvas/pro/\"; /** * The script file path for [FlashCanvas]{@link https://github.com/everlaat/flashcanvas}. * @memberof CB_Configuration.CrossBase * @name FLASHCANVAS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.FLASHCANVAS_PATH} + \"bin/flashcanvas.js\" */ CB_Configuration[CB_BASE_NAME].FLASHCANVAS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].FLASHCANVAS_PATH + \"bin/flashcanvas.js\"; /** * Directory that contains the SWF's for [FlashCanvas]{@link https://github.com/everlaat/flashcanvas}. The value of the \"scriptPathGiven\" parameter will be attached at the beginning automatically. Belongs to the \"swfPath\" parameter of the library set on the \"window.FlashCanvasOptions\" object. More information: https://web.archive.org/web/20180604011002/http://flashcanvas.net/docs/config * @memberof CB_Configuration.CrossBase * @name FLASHCANVAS_PATH_SWF * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.FLASHCANVAS_PATH} + \"bin/\" */ CB_Configuration[CB_BASE_NAME].FLASHCANVAS_PATH_SWF = CB_Configuration[CB_BASE_NAME].FLASHCANVAS_PATH + \"bin/\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.FLASHCANVAS_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name FLASHCANVAS_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].FLASHCANVAS_PATH_ABSOLUTE = false; /** * Disables the context menu when the right mouse button is clicked on any canvas using [FlashCanvas]{@link https://github.com/everlaat/flashcanvas}' SWF. Belongs to the \"disableContextMenu\" parameter of the library set on the \"window.FlashCanvasOptions\" object. More information: https://web.archive.org/web/20180604011002/http://flashcanvas.net/docs/config * @memberof CB_Configuration.CrossBase * @name FLASHCANVAS_DISABLE_CONTEXT_MENU * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].FLASHCANVAS_DISABLE_CONTEXT_MENU = false; /** * Uses turbo mode to speed up [FlashCanvas]{@link https://github.com/everlaat/flashcanvas}. Belongs to the \"turbo\" parameter of the library set on the \"window.FlashCanvasOptions\" object. More information: https://web.archive.org/web/20180604011002/http://flashcanvas.net/docs/config * @memberof CB_Configuration.CrossBase * @name FLASHCANVAS_TURBO_MODE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].FLASHCANVAS_TURBO_MODE = true; /** * Maximum size for the image cache used by [FlashCanvas]{@link https://github.com/everlaat/flashcanvas}. Belongs to the \"imageCacheSize\" parameter of the library set on the \"window.FlashCanvasOptions\" object. More information: https://web.archive.org/web/20180604011002/http://flashcanvas.net/docs/config * @memberof CB_Configuration.CrossBase * @name FLASHCANVAS_IMAGE_CACHE_SIZE * @constant * @type {integer} * @default */ CB_Configuration[CB_BASE_NAME].FLASHCANVAS_IMAGE_CACHE_SIZE = 100; //SLCanvas parameters: /** * Defines whether to load or not [SLCanvas]{@link https://slcanvas.codeplex.com/}. * @memberof CB_Configuration.CrossBase * @name SLCANVAS_LOAD * @constant * @type {boolean} * @default {@link CB_Configuration.CrossBase.needsSLCanvas}() */ CB_Configuration[CB_BASE_NAME].SLCANVAS_LOAD = CB_Configuration[CB_BASE_NAME].needsSLCanvas(); /** * Directory that contains the [SLCanvas]{@link https://slcanvas.codeplex.com/} files. * @memberof CB_Configuration.CrossBase * @name SLCANVAS_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"audiovisual/image/canvas/slcanvas/\" */ CB_Configuration[CB_BASE_NAME].SLCANVAS_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/image/canvas/slcanvas/\"; /** * The script file path for [SLCanvas]{@link https://slcanvas.codeplex.com/}. * @memberof CB_Configuration.CrossBase * @name SLCANVAS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SLCANVAS_PATH} + \"slcanvas.js\" */ CB_Configuration[CB_BASE_NAME].SLCANVAS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].SLCANVAS_PATH + \"slcanvas.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.SLCANVAS_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name SLCANVAS_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].SLCANVAS_PATH_ABSOLUTE = false; //ExplorerCanvas parameters: /** * Defines whether to load or not [ExplorerCanvas]{@link https://github.com/arv/explorercanvas}. * @memberof CB_Configuration.CrossBase * @name EXCANVAS_LOAD * @constant * @type {boolean} * @default {@link CB_Configuration.CrossBase.needsExplorerCanvas}() */ CB_Configuration[CB_BASE_NAME].EXCANVAS_LOAD = CB_Configuration[CB_BASE_NAME].needsExplorerCanvas(); /** * Directory that contains the [ExplorerCanvas]{@link https://github.com/arv/explorercanvas} files. * @memberof CB_Configuration.CrossBase * @name EXCANVAS_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"audiovisual/image/canvas/excanvas_with_canvas_text/\" */ CB_Configuration[CB_BASE_NAME].EXCANVAS_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/image/canvas/excanvas_with_canvas_text/\"; /** * The script file path for [ExplorerCanvas]{@link https://github.com/arv/explorercanvas}. * @memberof CB_Configuration.CrossBase * @name EXCANVAS_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.EXCANVAS_PATH} + \"excanvas.js\" */ CB_Configuration[CB_BASE_NAME].EXCANVAS_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].EXCANVAS_PATH + \"excanvas.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.EXCANVAS_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name EXCANVAS_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].EXCANVAS_PATH_ABSOLUTE = false; //canvas-text parameters: /** * Defines whether to load or not [canvas-text]{@link https://github.com/PhenX/canvas-text}. * @memberof CB_Configuration.CrossBase * @name CANVAS_TEXT_LOAD * @constant * @type {boolean} * @default {@link CB_Configuration.CrossBase.needsCanvasText}() */ CB_Configuration[CB_BASE_NAME].CANVAS_TEXT_LOAD = CB_Configuration[CB_BASE_NAME].needsCanvasText(); /** * Directory that contains the [canvas-text]{@link https://github.com/PhenX/canvas-text} files. * @memberof CB_Configuration.CrossBase * @name CANVAS_TEXT_PATH * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.SCRIPT_PATH} + \"audiovisual/image/canvas/excanvas_with_canvas_text/\" */ CB_Configuration[CB_BASE_NAME].CANVAS_TEXT_PATH = CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/image/canvas/excanvas_with_canvas_text/\"; /** * The script file path for [canvas-text]{@link https://github.com/PhenX/canvas-text}. * @memberof CB_Configuration.CrossBase * @name CANVAS_TEXT_PATH_SCRIPT_FILE * @constant * @type {string} * @default {@link CB_Configuration.CrossBase.CANVAS_TEXT_PATH} + \"canvas.text.js\" */ CB_Configuration[CB_BASE_NAME].CANVAS_TEXT_PATH_SCRIPT_FILE = CB_Configuration[CB_BASE_NAME].CANVAS_TEXT_PATH + \"canvas.text.js\"; /** * Defines whether the path defined in {@link CB_Configuration.CrossBase.CANVAS_TEXT_PATH_SCRIPT_FILE} is either absolute or relative to the CrossBrowdy script path. * @memberof CB_Configuration.CrossBase * @name CANVAS_TEXT_PATH_ABSOLUTE * @constant * @type {boolean} * @default */ CB_Configuration[CB_BASE_NAME].CANVAS_TEXT_PATH_ABSOLUTE = false; //Applies the options set by the user (if any): CB_applyOptions(CB_BASE_NAME, this); //Module basic configuration: CB_Modules.modules[CB_BASE_NAME] = { //Name of the module: \"name\" : CB_BASE_NAME, //Status (UNKNOWN, UNLOADED, LOADING, LOADED, READY or FAILED): \"status\" : CB_Modules.STATUSES.UNLOADED, //Function to call as soon as the module is called (before loading its scripts): \"onCall\" : function(scriptPathGiven) { if (CB_Configuration[CB_BASE_NAME].CB_Net_XHR_PROXY_URL_RELATIVE) { CB_Configuration[CB_BASE_NAME].CB_Net_XHR_PROXY_URL = scriptPathGiven + CB_Configuration[CB_BASE_NAME].CB_Net_XHR_PROXY_URL; } if (CB_Configuration[CB_BASE_NAME].FLASHCANVAS_LOAD) { CB_prepareFlashCanvas(scriptPathGiven); } CB_Modules.setStatus(\"CrossBase\", CB_Modules.STATUSES.LOADED); }, //Callback function to call when the module has been loaded successfully: \"onLoad\" : function(scriptPathGiven) { var checkReadyFunction = function() { var loopAgain = true; if (CB_Configuration[CB_BASE_NAME].SM2_LOAD &amp;&amp; !CB_startSoundManager2Called) { CB_startSoundManager2(scriptPathGiven); } if (typeof(detectZoom) !== \"undefined\" &amp;&amp; detectZoom !== null &amp;&amp; detectZoom &amp;&amp; typeof(detectZoom.device) !== \"undefined\" &amp;&amp; detectZoom.device !== null &amp;&amp; detectZoom.device &amp;&amp; typeof(detectZoom.device) === \"function\") { if (typeof(BrowserDetect) !== \"undefined\" &amp;&amp; BrowserDetect !== null &amp;&amp; typeof(BrowserDetect.browser) !== \"undefined\" &amp;&amp; BrowserDetect.browser !== null) { if (CB_soundManager2Loaded || !CB_Configuration[CB_BASE_NAME].SM2_LOAD) //If SM2 has been loaded or we don't need it: { if (window.localStorage) //Needed for safe use of localStorage polyfill. { if (CB_initializeStaticObjects()) //Initializes all static objects (returns false until it loads totally). { CB_Modules.setStatus(\"CrossBase\", CB_Modules.STATUSES.READY); loopAgain = false; } } } } } if (loopAgain) { setTimeout(checkReadyFunction, 1); } }; checkReadyFunction(); }, //Callback function to call when the module is ready: \"onReady\" : null, //Callback function to call when module has not been loaded successfully: //\"onFail\" =&gt; null, //Needed files: //Following files doesn't support IE5.0: // detect_zoom.js, CB_others.js, CB_events.js, CB_Screen.js, CB_Configuration[CB_BASE_NAME].FLASHCANVAS_PATH_SCRIPT_FILE, // CB_Configuration[CB_BASE_NAME].CANVAS_TEXT_PATH_SCRIPT_FILE, CB_Configuration[CB_BASE_NAME].SM2_PATH_SCRIPT_FILE \"neededFiles\" : { //Format: \"needed_file\" : { load: needs_to_be_loaded, [mandatory: needed_to_begin_CrossBrowdy], [absolutePath: relative_to_CrossBrowdy_path_or_absolute], [loadChecker: function that will be called and return true if the file needs to be loaded], [id: file_identifier_string], [requires: array_with_required_ids_of_files_required] } //Mandatory files: \"CrossBase/general/others/BrowserDetect.js\" : { load: true, mandatory: true }, //BrowserDetect by Peter-Paul Koch. \"CrossBase/general/others/performanceAndrequestAnimationFrame.js\" : { load: true, mandatory: true, id: \"performanceAndrequestAnimationFrame\" }, //performance.now polyfill by Paul Irish, Aaron Levine and Joan Alba Maldonado, requestAnimationFrame polyfill by Erik Moller (fixes from Paul Irish, Tino Zijdel, Andrew Mao, Klemen Slavic, Darius Bacon, Tim Hall and Joan Alba Maldonado). \"CrossBase/general/others/typedarray.js\" : { load: true, mandatory: true, id: \"typedarray\" }, //typedarray.js polyfill by Linden Research, Inc. and Joshua Bell and Joshua Bell. \"CrossBase/general/others/base64-binary.js\" : { load: true, mandatory: true }, //Base64Binary by Daniel Guerrero. \"CrossBase/general/lz-string/lz-string.min.js\" : { load: true, mandatory: true }, //lz-string (including base64-string) by pieroxy. \"CrossBase/general/lz-string/base64-string.js\" : { load: true, mandatory: true }, //lz-string (including base64-string) by pieroxy. \"CrossBase/general/bluebird/bluebird.min.js\" : { load: typeof(window.Promise) === \"undefined\", mandatory: true }, //bluebird by Petka Antonov. \"CrossBase/general/JSON3/json3.min.js\" : { load: true, mandatory: true, id: \"json3\" }, //JSON3 by Kit Cambridge. \"CrossBase/audiovisual/image/detect_zoom/detect_zoom.js\" : { load: true, mandatory: true }, //Detect-zoom by yonran (maintained by tombigel). \"CrossBase/audiovisual/audio/AudioContextMonkeyPatch/AudioContextMonkeyPatch.js\" : { load: true, mandatory: true }, //AudioContext-MonkeyPatch by Chris Wilson. \"CrossBase/general/CB_others.js\" : { load: true, mandatory: true }, //Other functions (such as trim(), etc). \"CrossBase/general/CB_Arrays.js\" : { load: true, mandatory: true }, //Arrays functions. \"CrossBase/general/CB_Client.js\" : { load: true, mandatory: true }, //Functions related with the client (browser, WebView, etc.). \"CrossBase/general/CB_data.js\" : { load: true, mandatory: true }, //Functions related with data (cookies, URL parameters, etc.). \"CrossBase/general/CB_Elements.js\" : { load: true, mandatory: true }, //Elements functions. \"CrossBase/general/CB_Events.js\" : { load: true, mandatory: true }, //Event functions. \"CrossBase/general/CB_Collisions.js\" : { load: true, mandatory: true }, //Collisions detection. \"CrossBase/device/CB_Device.js\" : { load: true, mandatory: true }, //CB_Device static class. \"CrossBase/audiovisual/image/CB_Screen.js\" : { load: true, mandatory: true }, //CB_Screen static class. \"CrossBase/audiovisual/image/CB_GraphicSprites.js\" : { load: true, mandatory: true }, //CB_GraphicSprites class. \"CrossBase/audiovisual/image/CB_GraphicSpritesScene.js\" : { load: true, mandatory: true }, //CB_GraphicSpritesScene class. \"CrossBase/audiovisual/image/canvas/CB_Canvas.js\" : { load: true, mandatory: true }, //CB_Canvas class. \"CrossBase/input/CB_Keyboard.js\" : { load: true, mandatory: true }, //CB_Keyboard static class. \"CrossBase/input/CB_Mouse.js\" : { load: true, mandatory: true }, //CB_Mouse static class. \"CrossBase/input/CB_Touch.js\" : { load: true, mandatory: true }, //CB_Touch static class. \"CrossBase/input/CB_Pointer.js\" : { load: true, mandatory: true }, //CB_Pointer static class. \"CrossBase/input/controllers/CB_Controllers_Proprietary_WII.js\" : { load: true, mandatory: true, requires: [\"performanceAndrequestAnimationFrame\"] }, //CB_Controllers_Proprietary_WII.js static class. \"CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js\" : { load: true, mandatory: true, requires: [\"performanceAndrequestAnimationFrame\"] }, //CB_Controllers_Proprietary_WII_U.js static class. \"CrossBase/input/controllers/CB_Controllers.js\" : { load: true, mandatory: true }, //CB_Controllers static class. \"CrossBase/net/fetch/fetch-ie8/fetch.js\" : { load: typeof(window.fetch) === \"undefined\", mandatory: true }, //fetch-ie8 by Cam Song. \"CrossBase/net/CB_Net.js\" : { load: true, mandatory: true }, //CB_Net. \"CrossBase/net/fetch/CB_Net_Fetch.js\" : { load: true, mandatory: true }, //CB_Net.Fetch static class. \"CrossBase/net/XHR/CB_Net_XHR.js\" : { load: true, mandatory: true }, //CB_Net.XHR static class (AJAX). \"CrossBase/net/sockets/CB_Net_Sockets.js\" : { load: true, mandatory: true }, //CB_Net.Sockets static class. \"CrossBase/net/REST/CB_Net_REST.js\" : { load: true, mandatory: true }, //CB_Net.REST static class. \"CrossBase/audiovisual/audio/CB_AudioDetector.js\" : { load: true, mandatory: true }, //CB_AudioDetector static class. \"CrossBase/audiovisual/audio/CB_AudioFile.js\" : { load: true, mandatory: true }, //CB_AudioFile class. \"CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js\" : { load: true, mandatory: true }, //CB_AudioFile_API[\"WAAPI\"] class. \"CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js\" : { load: true, mandatory: true }, //CB_AudioFile_API[\"AAPI\"] class. \"CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js\" : { load: CB_Configuration[CB_BASE_NAME].SM2_LOAD, mandatory: true }, //CB_AudioFile_API[\"SM2\"] class. //\"CrossBase/audiovisual/audio/CB_AudioFile_API_IXDKPP.js\" : { load: true, mandatory: true }, //CB_AudioFile_API[\"IXDKPP\"] class. \"CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js\" : { load: true, mandatory: true }, //CB_AudioFile_API[\"ACMP\"] class. \"CrossBase/audiovisual/audio/CB_AudioFileCache.js\" : { load: true, mandatory: true }, //CB_AudioFileCache class. \"CrossBase/audiovisual/audio/CB_AudioFileSprites.js\" : { load: true, mandatory: true }, //CB_AudioFileSprites class. \"CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js\" : { load: true, mandatory: true }, //CB_AudioFileSpritesPool class. \"CrossBase/audiovisual/audio/CB_Speaker.js\" : { load: true, mandatory: true }, //CB_Speaker static class. \"CrossBase/general/PHP/PHP_detector.php\" : { load: true, mandatory: false }, //Dynamic filepath: \"VALUEOF_CB_Configuration.CrossBase.LOCALSTORAGE_POLYFILL_PATH_SCRIPT_FILE\" : { load: true, mandatory: true }, //localStorage polyfill by Morten Houmøller Nygaard. \"VALUEOF_CB_Configuration.CrossBase.SOCKJS_PATH_SCRIPT_FILE\" : { load: true, mandatory: true, requires: [\"json3\"] }, //SockJS-client by Marek, Bryce Kahle, Michael Bridgen, Luigi Pinca and others. //Optional files: \"VALUEOF_CB_Configuration.CrossBase.CANBOX_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].CANBOX_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].CANBOX_PATH_ABSOLUTE }, //Canbox by Robert Inglin. \"VALUEOF_CB_Configuration.CrossBase.SLCANVAS_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].SLCANVAS_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].SLCANVAS_PATH_ABSOLUTE }, //SLCanvas by David Anson and Jon Davis. \"VALUEOF_CB_Configuration.CrossBase.FLASHCANVAS_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].FLASHCANVAS_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].FLASHCANVAS_PATH_ABSOLUTE }, //FlashCanvas by Tim Cameron Ryan and Shinya Muramatsu. \"VALUEOF_CB_Configuration.CrossBase.EXCANVAS_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].EXCANVAS_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].EXCANVAS_PATH_ABSOLUTE }, //ExplorerCanvas by Google Inc. \"VALUEOF_CB_Configuration.CrossBase.CANVAS_TEXT_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].CANVAS_TEXT_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].CANVAS_TEXT_PATH_ABSOLUTE }, //canvas-text by Fabien Menager. \"VALUEOF_CB_Configuration.CrossBase.SM2_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].SM2_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].SM2_PATH_ABSOLUTE }, //SoundManager 2 by Scott Schiller. \"VALUEOF_CB_Configuration.CrossBase.NOSLEEP_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].NOSLEEP_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].NOSLEEP_PATH_ABSOLUTE }, //NoSleep.js by Rich Tibbett. \"VALUEOF_CB_Configuration.CrossBase.PHONEGAPJS_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].PHONEGAPJS_LOAD, mandatory: false, absolutePath: CB_Configuration[CB_BASE_NAME].PHONEGAPJS_PATH_ABSOLUTE }, //Script necessary for PhoneGap. \"VALUEOF_CB_Configuration.CrossBase.CORDOVAJS_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].CORDOVAJS_LOAD, loadChecker: CB_Configuration[CB_BASE_NAME].CORDOVAJS_LOAD_CHECKER, mandatory: false, absolutePath: CB_Configuration[CB_BASE_NAME].CORDOVAJS_PATH_ABSOLUTE }, //Script necessary for Apache Cordova. \"VALUEOF_CB_Configuration.CrossBase.INTELXDKJS_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].INTELXDKJS_LOAD, mandatory: false, absolutePath: CB_Configuration[CB_BASE_NAME].INTELXDKJS_PATH_ABSOLUTE }, //Script necessary for Intel XDK. \"VALUEOF_CB_Configuration.CrossBase.INTELXDK_INITDEVJS_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].INTELXDK_INITDEVJS_LOAD, loadChecker: CB_Configuration[CB_BASE_NAME].INTELXDK_INITDEVJS_LOAD_CHECKER, mandatory: false, absolutePath: CB_Configuration[CB_BASE_NAME].INTELXDK_INITDEVJS_PATH_ABSOLUTE }, //Script necessary for Intel XDK. \"VALUEOF_CB_Configuration.CrossBase.TIMBREJS_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].TIMBREJS_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].TIMBREJS_PATH_ABSOLUTE, id: \"timbrejs\", requires: [\"typedarray\"] }, //timbre.js by mohayonao. \"VALUEOF_CB_Configuration.CrossBase.SUBCOLLIDERJS_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].SUBCOLLIDERJS_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].SUBCOLLIDERJS_PATH_ABSOLUTE, requires: [\"timbrejs\"] }, //subcollider.js by mohayonao. \"VALUEOF_CB_Configuration.CrossBase.WAAPISIM_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].WAAPISIM_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].WAAPISIM_PATH_ABSOLUTE }, //WAAPISim by g200kg. \"VALUEOF_CB_Configuration.CrossBase.BANDJS_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].BANDJS_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].BANDJS_PATH_ABSOLUTE }, //Band.js by Cody Lundquist and various contributors. \"VALUEOF_CB_Configuration.CrossBase.JSFX_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].JSFX_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].JSFX_PATH_ABSOLUTE }, //jsfx by Egon Elbre. \"VALUEOF_CB_Configuration.CrossBase.PRESSUREJS_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].PRESSUREJS_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].PRESSUREJS_PATH_ABSOLUTE }, //Pressure.js by Stuart Yamartino. \"VALUEOF_CB_Configuration.CrossBase.HAMMERJS_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].HAMMERJS_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].HAMMERJS_PATH_ABSOLUTE }, //Hammer.js by Jorik Tangelder. \"VALUEOF_CB_Configuration.CrossBase.HAMMERJS_HAMMER_TIME_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].HAMMERJS_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].HAMMERJS_PATH_ABSOLUTE }, //Hammer Time by Alexander Schmitz and other contributors. \"VALUEOF_CB_Configuration.CrossBase.WII_JS_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].WII_JS_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].WII_JS_PATH_ABSOLUTE }, //wii-js by Ryan McGrath. \"VALUEOF_CB_Configuration.CrossBase.GAMEPAD_PLUS_PATH_SCRIPT_FILE\" : { load: CB_Configuration[CB_BASE_NAME].GAMEPAD_PLUS_LOAD, mandatory: true, absolutePath: CB_Configuration[CB_BASE_NAME].GAMEPAD_PLUS_PATH_ABSOLUTE, requires: [\"performanceAndrequestAnimationFrame\"] } //gamepad-plus by Chris Van Wiemeersch (MozVR). //TODO: think about requiring xhr.js }, //Needed modules: \"neededModules\" : null, //Credits: \"credits\" : CB_CrossBaseCredits }; //Adds the credits to the default ones: CB_addCredits(CB_Modules.modules[\"CrossBase\"][\"credits\"]); //Function that initializes (builds) all static objects required (returns true when finishes totally): var CB_initializeStaticObjects_LOADED = { \"CB_Arrays\" : false, //CB_Arrays static class. \"CB_Elements\" : false, //CB_Elements static class. \"CB_Events\" : false, //CB_Events static class. \"CB_Client\" : false, //CB_Client static class. \"CB_Device\" : false, //CB_Device static class. \"CB_Net\" : false, //CB_Net static class. \"CB_Net.Fetch\" : false, //CB_Net.Fetch static class. \"CB_Net.XHR\" : false, //CB_Net.XHR static class. \"CB_Net.REST\" : false, //CB_Net.REST static class. \"CB_Net.Sockets\" : false, //CB_Net.Sockets static class. \"CB_Screen\" : false, //CB_Screen static class. \"CB_Collisions\" : false, //CB_Collisions static class. \"CB_Keyboard\" : false, //CB_Keyboard static class. \"CB_Mouse\" : false, //CB_Mouse static class. \"CB_Touch\" : false, //CB_Touch static class. \"CB_Pointer\" : false, //CB_Pointer static class. \"CB_Controllers\" : false, //CB_Controllers static class. \"CB_Speaker\" : false, //CB_Speaker static class. \"CB_AudioDetector\" : false //CB_AudioDetector static class. }; function CB_initializeStaticObjects(containerObject) { if (typeof(containerObject) === \"undefined\" || containerObject === null) { containerObject = CB_this || window; } var allIndexes = null; var allIndexesLength = null; var currentObject = null; for (var staticObject in CB_initializeStaticObjects_LOADED) { if (!CB_initializeStaticObjects_LOADED[staticObject]) { allIndexes = staticObject.split(\".\"); allIndexesLength = allIndexes.length; currentObject = containerObject[allIndexes[0]]; for (var x = 1; x &lt; allIndexesLength; x++) { if (typeof(currentObject[allIndexes[x]]) !== \"undefined\" &amp;&amp; currentObject[allIndexes[x]] !== null) { currentObject = currentObject[allIndexes[x]]; } else { return false; } } if (currentObject &amp;&amp; typeof(currentObject.init) === \"function\") { currentObject.init(); CB_initializeStaticObjects_LOADED[staticObject] = true; } else { return false; } } } return true; } //Function that prepares FlashCanvas options (it needs to be done before loading the FlashCanvas script): function CB_prepareFlashCanvas(scriptPathGiven) { document.createElement(\"canvas\"); //According to FlashCanvas web site: ensure that document.createElement(\"canvas\") is executed before any canvas element appears. window.FlashCanvasOptions = { swfPath: scriptPathGiven + CB_Configuration[CB_BASE_NAME].FLASHCANVAS_PATH_SWF, disableContextMenu: CB_Configuration[CB_BASE_NAME].FLASHCANVAS_DISABLE_CONTEXT_MENU, turbo: CB_Configuration[CB_BASE_NAME].FLASHCANVAS_TURBO_MODE, imageCacheSize: CB_Configuration[CB_BASE_NAME].FLASHCANVAS_IMAGE_CACHE_SIZE }; } //Function that starts SoundManager 2: var CB_startSoundManager2Called = false; //Defines whether CB_startSoundManager2 function has been called or not. var CB_soundManager2Loaded = false; //Defines whether SoundManager 2 has been loaded successfully or not. var CB_soundManager2Supported = false; //Defines whether SoundManager 2 is supported or not. function CB_startSoundManager2(scriptPathGiven) { CB_startSoundManager2Called = true; var CB_soundManager2TimeoutFunction = function() { CB_soundManager2Loaded = true; //SoundManager 2 has been loaded succesfully (but is not supported). CB_soundManager2Supported = false; //SoundManager 2 is not supported. }; var CB_startSoundManager2Function = function() { if (typeof(soundManager) !== \"undefined\" &amp;&amp; soundManager !== null) { //If the browser can't play the formats required using HTML5, it will force to load Flash: soundManager.audioFormats = { 'mp3': { 'type': ['audio/mpeg; codecs=\"mp3\"', 'audio/mpeg', 'audio/mp3', 'audio/MPA', 'audio/mpa-robust'], 'required': CB_Configuration[CB_BASE_NAME].SM2_AUDIO_FORMATS_REQUIRED[\"mp3\"] }, 'mp4': { 'related': ['aac', 'm4a'], 'type': ['audio/mp4; codecs=\"mp4a.40.2\"', 'audio/aac', 'audio/x-m4a', 'audio/MP4A-LATM', 'audio/mpeg4-generic'], 'required': CB_Configuration[CB_BASE_NAME].SM2_AUDIO_FORMATS_REQUIRED[\"mp4\"] }, 'ogg': { 'type': ['audio/ogg; codecs=vorbis'], 'required': CB_Configuration[CB_BASE_NAME].SM2_AUDIO_FORMATS_REQUIRED[\"ogg\"] }, 'opus': { 'type': ['audio/ogg; codecs=opus', 'audio/opus'], 'required': CB_Configuration[CB_BASE_NAME].SM2_AUDIO_FORMATS_REQUIRED[\"opus\"] }, 'wav': { 'type': ['audio/wav; codecs=\"1\"', 'audio/wav', 'audio/wave', 'audio/x-wav'], 'required': CB_Configuration[CB_BASE_NAME].SM2_AUDIO_FORMATS_REQUIRED[\"wav\"] } }; soundManager.setup( { debugMode: false, flashLoadTimeout: CB_Configuration[CB_BASE_NAME].SM2_TIMEOUT_MS, useHighPerformance: CB_Configuration[CB_BASE_NAME].SM2_USE_HIGH_PERFORMANCE, //useFastPolling: CB_Configuration[CB_BASE_NAME].SM2_USE_FAST_POLLING, url: scriptPathGiven + CB_Configuration[CB_BASE_NAME].SM2_PATH_SWF, onready: function() { clearTimeout(CB_soundManager2Timeout); CB_soundManager2Loaded = true; //SoundManager 2 has been loaded succesfully (and is supported). CB_soundManager2Supported = true; //SoundManager 2 is supported. }, ontimeout: CB_soundManager2TimeoutFunction }); //Ensure start-up in case document.readyState and/or DOMContentLoaded are unavailable: soundManager.beginDelayedInit(); } else if (!CB_soundManager2Loaded) { setTimeout(CB_startSoundManager2Function, 1); } }; CB_startSoundManager2Function(); //Since ontimeout event of SoundManager 2 seems not working on some platforms using Intel XDK (and maybe other Cordova-based engines), we have our own onntimeout: var CB_soundManager2Timeout = setTimeout(CB_soundManager2TimeoutFunction, CB_Configuration[CB_BASE_NAME].SM2_TIMEOUT_MS); } × Search results Close "},"CrossBase_audiovisual_image_canvas_CB_Canvas.js.html":{"id":"CrossBase_audiovisual_image_canvas_CB_Canvas.js.html","title":"Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js /** * @file Canvas management (including emulation fallbacks). Contains the {@link CB_Canvas} class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Class to manage a canvas. * @class * @classdesc Class to manage a canvas. For clients which do not support native [canvas]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas}, it provides [Adobe Flash (formerly Macromedia Flash)]{@link https://en.wikipedia.org/wiki/Adobe_Flash_Player} emulation with [FlashCanvas]{@link https://github.com/everlaat/flashcanvas}, Microsoft Silverlight emulation with [SLCanvas]{@link https://slcanvas.codeplex.com/}, VML emulation with [ExplorerCanvas]{@link https://github.com/arv/explorercanvas} (reinforced with [canvas-text]{@link https://github.com/PhenX/canvas-text}) and DHTML (DOM elements) emulation with [CanBox]{@link https://github.com/robertinglin/CanBox}. NOTE: To make the VML emulation work without errors (using [ExplorerCanvas]{@link https://github.com/arv/explorercanvas}), it is recommended to always load [FlashCanvas]{@link https://github.com/everlaat/flashcanvas} (which already includes [ExplorerCanvas]{@link https://github.com/arv/explorercanvas}) in your HTML code (without using lazy-load, as [ExplorerCanvas]{@link https://github.com/arv/explorercanvas} does not support it). This is recommended even when we are not going to use [Adobe Flash (formerly Macromedia Flash)]{@link https://en.wikipedia.org/wiki/Adobe_Flash_Player} emulation with [FlashCanvas]{@link https://github.com/everlaat/flashcanvas}. This is an example (should be placed before loading the main \"CrossBrowdy\" script): &amp;lt;!-- Loads FlashCanvas (Flash emulation) before CrossBrowdy. Needed also to use ExplorerCanvas (VML emulation) without problems: --&amp;gt; &amp;lt;script type=\"text/javascript\" src=\"CrossBrowdy/CrossBase/audiovisual/image/canvas/FlashCanvas/pro/bin/flashcanvas.js\"&amp;gt;&amp;lt;/script&amp;gt;&amp;lt;!-- FlashCanvas/ExplorerCanvas do not support lazy load. --&amp;gt; * @param {string} canvasId - The desired ID for the canvas. * @param {('2d'|'webgl'|'experimental-webgl'|'webgl2'|'experimental-webgl2'|'bitmaprenderer')} [contextType='2d'] - The contextType desired by default. More information: [HTMLCanvasElement.getContext]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext}. Note that most emulation methods will only support \"2d\". * @param {integer} [canvasWidth={@link CB_Canvas.WIDTH_DEFAULT}] - The desired width (horizontal size) in pixels for the canvas. * @param {integer} [canvasHeight={@link CB_Canvas.HEIGHT_DEFAULT}] - The desired height (vertical size) in pixels for the canvas. * @param {function} [onLoad] - Callback function that will be called when the canvas is finally loaded. It will not receive parameters, being \"this\" the {@link CB_Canvas} object itself. * @param {function} [onError] - Callback function that will be called when there is an error creating or loading the canvas. Being \"this\" the {@link CB_Canvas} object itself, the unique parameter received will be a string describing the error (if it could be determined). * @param {Element} [canvasParent=document.body] - The parent element desired to adopt the canvas. * @param {array} [alternativeCanvasEmulationPreferredOrder={@link CB_Configuration.CrossBase.CB_Canvas_PREFERRED_EMULATION_METHODS}] - Numeric array listing the desired alternative emulation methods for rendering the canvas, in order of preference. Supported emulation methods: \"FLASH\", \"VML\", \"DHTML\" and \"SILVERLIGHT\". * @param {boolean} [forceFirstEmulationMethod=false] - If set to true, it will force to use the first alternative emulation method desired (even when this alternative emulation method could be not supported and even when native [canvas]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas} support could be supported). * @param {boolean} [addOtherMethods=true] - If set to true, it will add other alternative methods (if any is missing) at the end of the desired alternative emulation methods so they will also be checked and used if the previous ones are not finally used. The order they will be added will be the one used in the {@link CB_Configuration.CrossBase.CB_Canvas_PREFERRED_EMULATION_METHODS} constant. * @param {boolean} [allowFlashCanvasLocally={@link CB_Configuration.CrossBase.FLASHCANVAS_ALLOW_RUN_LOCALLY_DEFAULT}] - If set to true, it will allow to use [Adobe Flash (formerly Macromedia Flash)]{@link https://en.wikipedia.org/wiki/Adobe_Flash_Player} emulation (if needed) even when it is running locally. Uses the {@link CB_Client.isRunningLocally} function internally. * @returns {CB_Canvas} Returns a new {@link CB_Canvas} object. */ var CB_Canvas = function(canvasId, contextType, canvasWidth, canvasHeight, onLoad, onError, canvasParent, alternativeCanvasEmulationPreferredOrder, forceFirstEmulationMethod, addOtherMethods, allowFlashCanvasLocally) { //Creates an instance of this object and returns it in the case that it is being called from an unexpected context: if (this === window || !(this instanceof CB_Canvas)) { return new CB_Canvas(canvasId, contextType, canvasWidth, canvasHeight, canvasParent, alternativeCanvasEmulationPreferredOrder, forceFirstEmulationMethod, addOtherMethods, allowFlashCanvasLocally); } //Properties: this._parent = undefined; //The parents of the canvas. this._id = undefined; //The ID of the canvas element. this.canvas = undefined; //Canvas element itself. this.context = undefined; //Context of the canvas element. this._contextType = undefined; //Type of the context of the canvas element. this._supported = false; //Defines whether Canvas works. this._width = undefined; //Canvas width. this._height = undefined; //Canvas height. this._mode = \"NONE\"; //Stores the mode used for the canvas ('NONE', 'NORMAL', 'FLASH', 'SILVERLIGHT', 'VML' or 'DHTML'). this._ready = false; //Stores whether the canvas is ready to be used or not (useful for SLCanvas). this._loading = true; //Stores whether the canvas is loading or not (useful for SLCanvas). //Calls the constructor of the object when creates an instance: return this._init(canvasId, contextType, canvasWidth, canvasHeight, onLoad, onError, canvasParent, alternativeCanvasEmulationPreferredOrder, forceFirstEmulationMethod, addOtherMethods, allowFlashCanvasLocally); } /* //Static properties and functions: CB_Canvas._MODES = { \"NONE\" : 0, \"VML\" : 1, \"FLASH\" : 2, \"SILVERLIGHT\" : 3, \"DHTML\" : 4 }; //Defines rendering mode. CB_Canvas._MODES_STRING = [ \"NONE\", \"VML\", \"FLASH\", \"SILVERLIGHT\", \"DHTML\" ]; CB_Canvas.getModeString = function(mode) { if (typeof(CB_Canvas._MODES_STRING[mode]) !== \"undefined\") { return CB_Canvas._MODES_STRING[mode]; } else { return \"UNKNOWN\"; } }; */ //Constants: /** * Default canvas width in pixels. * @constant * @type {integer} * @default */ CB_Canvas.WIDTH_DEFAULT = 320; //Default canvas width. /** * Default canvas height in pixels. * @constant * @type {integer} * @default */ CB_Canvas.HEIGHT_DEFAULT = 240; //Default canvas height. CB_Canvas.prototype._allowedContextTypes = [\"2d\", \"webgl\", \"experimental-webgl\", \"webgl2\", \"experimental-webgl2\", \"bitmaprenderer\"]; //Allowed context types. //Constructor: CB_Canvas.prototype._init = function(canvasId, contextType, canvasWidth, canvasHeight, onLoad, onError, canvasParent, alternativeCanvasEmulationPreferredOrder, forceFirstEmulationMethod, addOtherMethods, allowFlashCanvasLocally) { //If they have not been sent, uses default parameters: if (typeof(canvasParent) === \"undefined\" || canvasParent === null) { canvasParent = document.body; } //Gets the best emulation method: alternativeCanvasEmulation = CB_Canvas.bestEmulation(alternativeCanvasEmulationPreferredOrder, forceFirstEmulationMethod, addOtherMethods, allowFlashCanvasLocally); //Defines the parent given: this._parent = canvasParent; //Defines the canvas element by using the ID given: this.setId(canvasId); this.set(this.getId(), canvasWidth, canvasHeight, onLoad, onError, alternativeCanvasEmulation, forceFirstEmulationMethod); //Detects whether Canvas works: if (this.isSupported()) { //Defines the canvas context: this.setContextType(contextType); this.getContext(this.getContextType()); } else { //There is no mode unless we are using Silverlight (since SLCanvas needs time to load): if (this._mode !== \"SILVERLIGHT\" &amp;&amp; !this._loading) { this._mode = \"NONE\"; //This will be changed when SLCanvas loads (if it does). } } return this; } /** * Tells whether the current client needs canvas emulation or not. Uses {@link CB_Client.supportsCanvas} internally. * @function * @returns {boolean} Returns whether the current client needs canvas emulation or not. */ CB_Canvas.needsEmulation = function() { return !CB_Client.supportsCanvas(); } /** * Calculates and returns the best alternative canvas emulation. * @function * @param {array|string} [preferredOrder={@link CB_Configuration.CrossBase.CB_Canvas_PREFERRED_EMULATION_METHODS}] - Numeric array listing the desired alternative emulation methods for rendering the canvas, in order of preference. Possible emulation methods: \"FLASH\", \"VML\", \"DHTML\" and \"SILVERLIGHT\". It can also be a string with the unique desired canvas emulation method or with \"NO\" or \"NONE\" value (meaning no emulation method is desired and then the returning value will always be \"NONE\"). * @param {boolean} [forceFirstEmulationMethod=false] - If set to true, it will force to return the first alternative emulation method desired which is detected as supported without being too strict (even when this alternative emulation method could be not really supported and even when native [canvas]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas} support could be supported). * @param {boolean} [addOtherMethods=true] - If set to true, it will add other alternative methods (if any is missing) at the end of the desired alternative emulation methods so they will also be checked and used if the previous ones are not finally used. The order they will be added will be the one used in the {@link CB_Configuration.CrossBase.CB_Canvas_PREFERRED_EMULATION_METHODS} constant. * @param {boolean} [allowFlashCanvasLocally={@link CB_Configuration.CrossBase.FLASHCANVAS_ALLOW_RUN_LOCALLY_DEFAULT}] - If set to true, it will allow to use [Adobe Flash (formerly Macromedia Flash)]{@link https://en.wikipedia.org/wiki/Adobe_Flash_Player} emulation (if needed) even when it is running locally. Uses the {@link CB_Client.isRunningLocally} function internally. * @returns {'NONE'|'FLASH'|'SILVERLIGHT'|'VML'|'DHTML'} Returns \"NONE\" if no canvas emulation is needed/supported (and no emulation method is forced). Otherwise, it returns the best emulation method calculated (\"FLASH\", \"SILVERLIGHT\", \"VML\" or \"DHTML\"). */ CB_Canvas.bestEmulation = function(preferredOrder, forceFirstEmulationMethod, addOtherMethods, allowFlashCanvasLocally) { //If not given, sets the default parameters: if (typeof(addOtherMethods) === \"undefined\" || addOtherMethods === null) { addOtherMethods = true; } if (typeof(allowFlashCanvasLocally) === \"undefined\" || allowFlashCanvasLocally === null) { allowFlashCanvasLocally = CB_Configuration[CB_BASE_NAME].FLASHCANVAS_ALLOW_RUN_LOCALLY_DEFAULT; } //If we don't want to force emulation and we don't need any emulation, exits: if (!forceFirstEmulationMethod &amp;&amp; !CB_Canvas.needsEmulation()) { return \"NONE\"; } //Defines all allowed canvas emulation methods and the default order or preference (to use in case it was not provided): var allEmulationMethods = CB_Configuration[CB_BASE_NAME].CB_Canvas_PREFERRED_EMULATION_METHODS; //If not given, uses the default order of preference: if (typeof(preferredOrder) === \"undefined\" || preferredOrder === null) { //If we want to force the first emulation method, we exit returning the first one: //if (forceFirstEmulationMethod) { return allEmulationMethods[0]; } //We can be sure it is a valid one. preferredOrder = allEmulationMethods; //Uses the default order with all methods. addOtherMethods = false; //There is no need to add other methods since it contains all. } //...if the preferred order is not an array, we force it to be one: else if (!CB_isArray(preferredOrder)) { preferredOrder = [(preferredOrder+\"\").toUpperCase()]; } //Parses it as a string and to upper case. //If the user doesn't want any emulation method, we exit: if (preferredOrder[0] === \"NO\" || preferredOrder[0] === \"NONE\") { return \"NONE\"; } //If not all emulation methods has been given in the preferred order, adds them (at the end) if we wanted: if (addOtherMethods &amp;&amp; preferredOrder !== allEmulationMethods || preferredOrder[0] === \"AUTO\") //We don't need to add them if already has all methods. { var allEmulationMethodsLength = allEmulationMethods.length; for (var x = 0; x &lt; allEmulationMethodsLength; x++) { //If the current emulation method of this loop is not in the given preferred order, we add it at the end of the array: if (CB_indexOf(preferredOrder, allEmulationMethods[x]) === -1) { preferredOrder[preferredOrder.length] = allEmulationMethods[x]; } } } //Check the emulation methods availability according to the preferred order given: var preferredOrderLength = preferredOrder.length; var chosenEmulationMethod = \"NONE\"; var currentEmulationMethod; for (x = 0; x &lt; preferredOrderLength; x++) { currentEmulationMethod = CB_trim(preferredOrder[x]).toUpperCase(); //If we want to force the first emulation method and it is available (not being strict): if (forceFirstEmulationMethod &amp;&amp; CB_Canvas.supportsEmulationMethod(currentEmulationMethod, false)) { chosenEmulationMethod = currentEmulationMethod; break; } //...otherwise, if the method is available (being strict): else if (CB_Canvas.supportsEmulationMethod(currentEmulationMethod, true)) { chosenEmulationMethod = currentEmulationMethod; break; } } //Returns the chosen emulation method (if any): return chosenEmulationMethod; } /** * Tells whether the current client is compatible with a given canvas emulation method or not. * @function * @param {string} emulationMethod - Emulation method we want to check. Possible emulation methods: \"FLASH\", \"VML\", \"DHTML\" and \"SILVERLIGHT\". * @param {boolean} [strictMode=true] - If set to true, the compatibility will be checked more carefully. If set to false (not recommended), the method could return true even when sometimes the canvas emulation method is not totally supported by the current client. * @returns {boolean} Returns whether the current client is compatible with the given canvas emulation method or not. */ CB_Canvas.supportsEmulationMethod = function(emulationMethod, strictMode) { //If not given, uses the default parameters: if (typeof(strictMode) === \"undefined\" || strictMode === null) { strictMode = true; } emulationMethod = CB_trim(emulationMethod).toUpperCase(); var isAvailable = false; //If we want to try Flash (FlashCanvas): if (emulationMethod === \"FLASH\") { //If FlashCanvas is present: var FlashCanvas = window.FlashCanvas || undefined; if (typeof(FlashCanvas) !== \"undefined\") { //If we don't want to be strict, the method is supported: if (!strictMode) { isAvailable = true; } //...otherwise, if Flash is installed and version is 9 or newer: else if (CB_Client.supportsFlash() &amp;&amp; CB_Client.getFlashVersion()[0] &gt;= 9) { //If the script is not running locally or it is running but we allow running FlashCanvas anyway: if (!CB_Client.isRunningLocally() || CB_Client.isRunningLocally() &amp;&amp; allowFlashCanvasLocally) { isAvailable = true; } } } } //...otherwise, if we want to try SILVERLIGHT (SLCanvas): else if (emulationMethod === \"SILVERLIGHT\") { //If SLCanvas is present: var slcanvas = window.slcanvas || undefined; if (typeof(slcanvas) !== \"undefined\") { //If we don't want to be strict, the method is supported: if (!strictMode) { isAvailable = true; } //...otherwise, if Silverlight is installed: if (CB_Client.supportsSilverlight()) { isAvailable = true; } } } //...otherwise, if we want to try VML (ExplorerCanvas): else if (emulationMethod === \"VML\") { //If ExplorerCanvas is present: var G_vmlCanvasManager = window.G_vmlCanvasManager || undefined; if (typeof(G_vmlCanvasManager) !== \"undefined\" &amp;&amp; G_vmlCanvasManager.initElement.toString().indexOf(\"macromedia\") === -1) //We make sure that the object has not been created by FlashCanvas. { //If we don't want to be strict, the method is supported: if (!strictMode) { isAvailable = true; } //...otherwise, if we are not using Internet Explorer 5 (ExplorerCanvas doesn't work with IE5/IE5.5): if (navigator.appVersion.indexOf(\"MSIE 5\") === -1) { isAvailable = true; } } } //...otherwise, if we want to try DHTML (Canbox): else if (emulationMethod === \"DHTML\") { //If Canbox is present: var _CanboxManager = window._CanboxManager || undefined; if (typeof(_CanboxManager) !== \"undefined\") { //If we don't want to be strict, the method is supported: if (!strictMode) { isAvailable = true; } //...otherwise, if we are not using Internet Explorer 5 (Canbox doesn't work with IE5/IE5.5): else if (navigator.appVersion.indexOf(\"MSIE 5\") === -1) { isAvailable = true; } } } return isAvailable; } /** * Sets the desired identifier (ID) of the canvas element. Since this method is called by the constructor already, it is not needed to be called unless the canvas element wants to be defined again through the {@link CB_Canvas#set} method. Note that changing the ID after the canvas has been set could lead to some problems when using certain emulation methods so it is not recommended. * @function * @param {string} canvasId - Identifier (ID) for the canvas element. */ CB_Canvas.prototype.setId = function(canvasId) { this._id = CB_trim(canvasId); if (typeof(this.canvas) !== \"undefined\" &amp;&amp; this.canvas !== null &amp;&amp; typeof(this.canvas.setAttribute) === \"function\") { this.canvas.setAttribute(\"id\", canvasId); } } /** * Returns the identifier (ID) of the canvas element. * @function * @returns {string} Returns the identifier (ID) of the canvas element. */ CB_Canvas.prototype.getId = function() { return this._id; } /** * Defines the canvas element. Since this method is called by the constructor already, it is not needed to be called unless the canvas element wants to be defined again. * @function * @param {string} canvasId - The desired ID for the canvas. * @param {integer} [canvasWidth={@link CB_Canvas.WIDTH_DEFAULT}] - The desired width (horizontal size) in pixels for the canvas. * @param {integer} [canvasHeight={@link CB_Canvas.HEIGHT_DEFAULT}] - The desired height (vertical size) in pixels for the canvas. * @param {function} [onLoad] - Callback function that will be called when the canvas is finally loaded. It will not receive parameters, being \"this\" the {@link CB_Canvas} object itself. * @param {function} [onError] - Callback function that will be called when there is an error creating or loading the canvas. Being \"this\" the {@link CB_Canvas} object itself, the unique parameter received will be a string describing the error (if it could be determined). * @param {string} [alternativeCanvasEmulation={@link CB_Canvas.bestEmulation}()] - Emulation method we want to use in the case that the native [canvas]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas} is not supported or if the \"forceEmulation\" parameter is set to true. Possible emulation methods: \"FLASH\", \"VML\", \"DHTML\" and \"SILVERLIGHT\". * @param {boolean} [forceEmulation=false] - If set to true, it will force to use the emulation method defined in the \"alternativeCanvasEmulation\" parameter (even when this alternative emulation method could be not supported and even when native [canvas]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas} support could be supported). */ CB_Canvas.prototype.set = function(canvasId, canvasWidth, canvasHeight, onLoad, onError, alternativeCanvasEmulation, forceEmulation) { //If not given, sets the default parameters: if (typeof(canvasWidth) === \"undefined\" || canvasWidth === null || isNaN(canvasWidth)) { canvasWidth = CB_Canvas.WIDTH_DEFAULT; } if (typeof(canvasHeight) === \"undefined\" || canvasHeight === null || isNaN(canvasHeight)) { canvasHeight = CB_Canvas.HEIGHT_DEFAULT; } if (typeof(alternativeCanvasEmulation) === \"undefined\" || alternativeCanvasEmulation === null || CB_trim(alternativeCanvasEmulation).toUpperCase() === \"AUTO\") { alternativeCanvasEmulation = CB_Canvas.bestEmulation(); } alternativeCanvasEmulation = CB_trim(alternativeCanvasEmulation).toUpperCase(); //Just in case there was a previous onload (action) listener before (used in SLCanvas), we kill it: if (typeof(this.canvas) !== \"undefined\" &amp;&amp; typeof(this.canvas.action) === \"function\") { this.canvas.action = function() {}; } //The canvas is still not ready and it is loading: this._ready = false; this._loading = true; //If the element with the ID given exists, just takes it: this.canvas = CB_Elements.id(canvasId); //this._mode = \"unknown\"; //Mode is still unknown (unless we create the element later). this._mode = \"NORMAL\"; var needsEmulation = CB_Canvas.needsEmulation(); //If we are going to use DHTML emulation (forced or needed): if ((needsEmulation || forceEmulation) &amp;&amp; alternativeCanvasEmulation === \"DHTML\") { //Canbox doesn't work with an existing \"canvas\" TAG, so we have to destroy it and create a DIV with that id: //CB_Elements.idRemove(canvasId); //Destroys the existing element. if (this.canvas !== null) { //this.canvas.outerHTML = this.canvas.outerHTML.replace(/canvas/g, \"div\"); CB_Elements.idRemove(canvasId); this.canvas = null; } //this.canvas = null; //We force to create a new element. } //If the element already exists, in determines the emulation mode (if any): if (typeof(this.canvas) !== \"undefined\" &amp;&amp; this.canvas !== null) { //this._mode = \"NORMAL\"; //If the element is using FlashCanvas (Flash) emulation: //var G_vmlCanvasManager = window.G_vmlCanvasManager || undefined; //if (this.canvas.innerHTML.indexOf(\"flashcanvas\") !== -1) { this._mode = \"FLASH\"; } //...otherwise, if ExplorerCanvas (VML) is available, the element must be using it: //else if (typeof(G_vmlCanvasManager) !== \"undefined\") { this._mode = \"VML\"; } } //...otherwise, it will try to create the element with the ID given: else { //Creates the canvas: var tagName = \"canvas\"; //By default, the tag name is \"canvas\". if ((needsEmulation || forceEmulation) &amp;&amp; alternativeCanvasEmulation === \"DHTML\") { tagName = \"div\"; } //If we are using DHTML emulation, it is better if the tag name is \"div\" (to make it work in web clients with canvas support). this.canvas = document.createElement(tagName); this.canvas.setAttribute(\"id\", canvasId); this.canvas.innerHTML = \"CrossBrowdy canvas not supported! (no emulation)\"; this._parent.appendChild(this.canvas); this.canvas = CB_Elements.id(canvasId); } //If we need emulation: if (needsEmulation || forceEmulation) { //If the emulation method is available (it will be only if we need it), we apply it: if (CB_Canvas.supportsEmulationMethod(alternativeCanvasEmulation, false)) //Not being strict. { this._mode = alternativeCanvasEmulation; try { this.canvas.innerHTML = \"\"; } catch(E) {} //If we want to use Flash (FlashCanvas), inits the canvas properly: if (alternativeCanvasEmulation === \"FLASH\") { this.canvas = FlashCanvas.initElement(this.get()); //Provides the canvas context with some methods (in case it needs it): this.prepareContext(); } //...otherwise, if we want to use Silverlight (SLCanvas), inits the canvas properly: else if (alternativeCanvasEmulation === \"SILVERLIGHT\") { var that = this; var functionOnLoad = function(sender) { if (that.isSupported()) { that._mode = \"SILVERLIGHT\"; //Provides the canvas context with some methods (in case it needs it): that.prepareContext(); //The canvas is ready for use: that._ready = true; that._loading = false; //Calls the onLoad function (if any): if (typeof(onLoad) === \"function\") { onLoad.call(that); } } else { //Calls the onError function (if any): //if (typeof(onError) === \"function\") { onLoad.call(this); } if (typeof(onError) === \"function\") { onError.call(that, \"'\" + alternativeCanvasEmulation + \"' canvas emulation failed.\"); } } }; var SLCanvasDiv = slcanvas.createCanvasDiv(canvasWidth, canvasHeight, functionOnLoad); CB_Elements.idRemove(canvasId); SLCanvasDiv.setAttribute(\"id\", canvasId); //IE5/5+, IE6, IE7 and IE8 (I still have to check other newer IE versions) doesn't send keyboard events to the web client when a Silverlight object is clicked. So we have to put a transparent div over it that prevents to click it in order to not focus the Silverlight object: if (CB_Client.supportsSilverlight() &amp;&amp; navigator.userAgent.indexOf('MSIE') !== -1 &amp;&amp; (navigator.appVersion.indexOf(\"MSIE 5\") !== -1 || navigator.appVersion.indexOf(\"MSIE 6\") !== -1 || navigator.appVersion.indexOf(\"MSIE 7\") !== -1 || navigator.appVersion.indexOf(\"MSIE 8\") !== -1)) { var SLCanvasDivForeground = document.createElement(\"div\"); SLCanvasDivForeground.style.position = \"absolute\"; SLCanvasDivForeground.style.padding = \"0px\"; SLCanvasDivForeground.style.filter = 'alpha(opacity=0)'; SLCanvasDivForeground.style.backgroundColor = \"#ffffff\"; SLCanvasDivForeground.style.border = \"0px\"; SLCanvasDivForeground.innerHTML = \"\"; //It will always check if the canvas is moved, in order to be always placed above it: setInterval( function() { if (SLCanvasDivForeground !== null &amp;&amp; SLCanvasDiv !== null) { SLCanvasDivForeground.style.top = CB_Elements.getTop(SLCanvasDiv) + \"px\"; SLCanvasDivForeground.style.left = CB_Elements.getLeft(SLCanvasDiv) + \"px\"; SLCanvasDivForeground.style.width = CB_Elements.getWidth(SLCanvasDiv) + \"px\"; SLCanvasDivForeground.style.height = CB_Elements.getHeight(SLCanvasDiv) + \"px\"; var zIndex = SLCanvasDiv.currentStyle.zIndex; if (typeof(zIndex) !== \"undefined\" &amp;&amp; zIndex !== null &amp;&amp; !isNaN(zIndex)) { zIndex++; } SLCanvasDivForeground.style.zIndex = zIndex; } }, 100); document.body.appendChild(SLCanvasDivForeground); } //Sets the new canvas: this.canvas = SLCanvasDiv; this._parent.appendChild(this.canvas); } //...otherwise, if we want to use VML (ExplorerCanvas), inits the canvas properly: else if (alternativeCanvasEmulation === \"VML\") { this.canvas = G_vmlCanvasManager.initElement(this.get()); //Provides the canvas context with some methods (in case it needs it): this.prepareContext(); } //...otherwise, if we want to use DHTML (Canbox), inits the canvas properly: else if (alternativeCanvasEmulation === \"DHTML\") { //try //{ this.canvas = _CanboxManager.initElement(this.get()); //} catch(E) {} //Provides the canvas context with some methods (in case it needs it): this.prepareContext(); } else { this.canvas.innerHTML = \"CrossBrowdy canvas not supported! (with \" + alternativeCanvasEmulation + \" emulation)\"; } } else { try { this.canvas.innerHTML = \"CrossBrowdy canvas not supported! (without emulation)\"; } catch(E) {} if (alternativeCanvasEmulation !== \"NONE\") { this.canvas.innerHTML += \" - tried \" + alternativeCanvasEmulation + \" but failed\"; } } } //Defines canvas width and height: this.setWidth(canvasWidth); this.setHeight(canvasHeight); //If the canvas is supported (it worked) and we are not using SLCanvas (because it needs time to be ready): if (this.isSupported()) { //The canvas is ready and not loading anymore: this._ready = true; this._loading = false; //Calls the onLoad function (if any): if (typeof(onLoad) === \"function\") { onLoad.call(this); } } //...otherwise, if we didn't used the Silverlight emulation method (SLCanvas): else if (alternativeCanvasEmulation !== \"SILVERLIGHT\") { //If we are here it means that canvas is not supported and it is not loading anymore: this._loading = false; //Calls the onError function (if any): //if (typeof(onError) === \"function\") { onLoad.call(this); } if (typeof(onError) === \"function\") { onError.call(this, \"'\" + alternativeCanvasEmulation + \"' canvas emulation failed!\"); } } } /** * Alias for {@link CB_Canvas#prepareContext}. * @function CB_Canvas.prototype.normalizeContext * @see {@link CB_Canvas#prepareContext} */ /** * Provides the canvas [context]{@link https://developer.mozilla.org/en-US/docs/Web/API/RenderingContext} with some methods and properties, in case it needs it (as some canvas emulation methods lack of some methods and properties). Since this method is called by the {@link CB_Canvas#set} method already (and this one is called by the constructor automatically), it is not needed to be called again normally. * @function * @param {RenderingContext|Object} [context={@link CB_Canvas#getContext}()] - The [context]{@link https://developer.mozilla.org/en-US/docs/Web/API/RenderingContext} object that we want to prepare (different type if a canvas emulation method is being used). If not defined, calls the {@link CB_Canvas#getContext} method internally. * @returns {RenderingContext|Object} Returns the canvas [context]{@link https://developer.mozilla.org/en-US/docs/Web/API/RenderingContext} (different type if a canvas emulation method is being used). * @todo Add more methods and properties needed by some emulation methods. */ CB_Canvas.prototype.prepareContext = CB_Canvas.prototype.normalizeContext = function(context) { //Gets the context: if (typeof(context) === \"undefined\" || context === null) { context = this.getContext(); } //If the context is not defined or null, exits the function: if (typeof(context) === \"undefined\" || context === null) { return; } //Canbox doesn't support setTransform, so we create a fake function in order not to crash: try { if (typeof(context.setTransform) === \"undefined\") { context.setTransform = function() {} } } catch(E) { CB_console(\"The 'setTransform' method could not be added to the given canvas context.\"); } try { //SLCanvas doesn't support font, so we create a fake function in order not to crash: if (typeof(context.font) === \"undefined\") { context.font = \"10px sans-serif\"; } } catch(E) { CB_console(\"The 'font' property could not be added to the given canvas context.\"); } try { //SLCanvas doesn't support fillText, so we create a fake function in order not to crash: if (typeof(context.fillText) === \"undefined\") { context.fillText = function() {} } } catch(E) { CB_console(\"The 'fillText' method could not be added to the given canvas context.\"); } try { //Internet Explorer 11 (and lower) does not support \"ellipse\" method, so we try to simulate it: if (typeof(context.drawEllipse) === \"undefined\") { context.drawEllipse = this._context_drawEllipse; } } catch(E) { CB_console(\"The 'ellipse' method could not be added to the given canvas context.\"); } return context; } /** * Returns the canvas element (if any). * @function * @returns {Element|null} Returns the canvas element (if any). If not found, null will be returned. */ CB_Canvas.prototype.get = function() { return this.canvas || null; } /** * Defines and returns the canvas [context]{@link https://developer.mozilla.org/en-US/docs/Web/API/RenderingContext}. It could call the {@link CB_Canvas#prepareContext} method internally. * @function * @param {('2d'|'webgl'|'experimental-webgl'|'webgl2'|'experimental-webgl2'|'bitmaprenderer')} [contextType=CB_Canvas#._contextType|'2d'] - The [context]{@link https://developer.mozilla.org/en-US/docs/Web/API/RenderingContext} type desired. More information: [HTMLCanvasElement.getContext]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext}. Note that most emulation methods will only support \"2d\". * @returns {RenderingContext|Object} Returns the canvas [context]{@link https://developer.mozilla.org/en-US/docs/Web/API/RenderingContext} (different type if a canvas emulation method is being used). */ CB_Canvas.prototype.getContext = function(contextType) { //Defines 2D if any other context type has defined: if (typeof(contextType) === \"undefined\" || contextType === null) { contextType = this._contextType; if (typeof(contextType) === \"undefined\" || contextType === null) { contextType = \"2d\"; } } contextType = CB_trim(contextType).toLowerCase(); //If the context type inserted is not allowed, uses the \"2d\" type by default: //if (contextType === \"\" || contextType !== \"webgl\" &amp;&amp; contextType !== \"2d\") if (CB_indexOf(CB_Canvas.prototype._allowedContextTypes, contextType) === -1) { contextType = \"2d\"; } if (typeof(this.get().getContext) === \"function\") { try //Uses try-catch to avoid some problems with some web clients (as BeZilla / Bon Echo 2.0.0.22Pre on Haiku OS): { return this.context = this.prepareContext(this.get().getContext(contextType)); //////////////return this.context = this.get().getContext(contextType); } catch(E) { return this.context = null; } } else { return this.context = null; } } /** * Defines the desired canvas [context]{@link https://developer.mozilla.org/en-US/docs/Web/API/RenderingContext} type. Internally, it only defines the {@link CB_Canvas#._contextType} property. * @function * @param {('2d'|'webgl'|'experimental-webgl'|'webgl2'|'experimental-webgl2'|'bitmaprenderer')} [contextType='2d'] - The [context]{@link https://developer.mozilla.org/en-US/docs/Web/API/RenderingContext} type desired. More information: [HTMLCanvasElement.getContext]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext}. Note that most emulation methods will only support \"2d\". * @returns {string} Returns the context type just applied. */ CB_Canvas.prototype.setContextType = function(contextType) { contextType = CB_trim(contextType).toLowerCase(); //If the context type inserted is not allowed, uses the \"2d\" type by default: if (CB_indexOf(CB_Canvas.prototype._allowedContextTypes, contextType) === -1) { contextType = \"2d\"; } this._contextType = contextType; return this._contextType; } /** * Tells the current canvas [context]{@link https://developer.mozilla.org/en-US/docs/Web/API/RenderingContext} type used. Internally, it returns the value of the {@link CB_Canvas#._contextType} property. * @function * @returns {string} Tells the current canvas [context]{@link https://developer.mozilla.org/en-US/docs/Web/API/RenderingContext} type used. More information: [HTMLCanvasElement.getContext]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext}. */ CB_Canvas.prototype.getContextType = function() { return this._contextType; } /** * Tells whether the canvas works or not. The internal test used could be not totally reliable. * @function * @returns {boolean} Returns whether the canvas works or not. The internal test used could be not totally reliable. */ CB_Canvas.prototype.isSupported = function() { //this._supported = (this.canvas &amp;&amp; this.canvas.getContext) ? true : false; //return this._supported; if (this.canvas &amp;&amp; this.canvas.getContext) { try //Uses try-catch to avoid some problems with some web clients (as BeZilla / Bon Echo 2.0.0.22Pre on Haiku OS): { this._supported = (typeof(this.canvas.getContext(\"2d\")) !== \"undefined\" &amp;&amp; this.canvas.getContext(\"2d\") !== null); } catch(E) { this._supported = false; } } return this._supported || false; } /** * Defines the desired canvas width. * @function * @param {integer} [canvasWidth={@link CB_Canvas.WIDTH_DEFAULT}] - The desired width (horizontal size) in pixels for the canvas. * @returns {number} Returns the canvas width (horizontal size) being used in pixels. It could return zero (0) if cannot be calculated. */ CB_Canvas.prototype.setWidth = function(canvasWidth) { //Is not defined or it is wrong, uses default size: if (typeof(canvasWidth) === \"undefined\" || canvasWidth === null || isNaN(canvasWidth)) { canvasWidth = CB_Canvas.WIDTH_DEFAULT; } //Detects if a percentage has been received: /* canvasWidth = canvasWidth.toString(); var isPercentage = false; if (canvasWidth.indexOf(\"%\") !== -1) { isPercentage = true; } canvasWidth = canvasWidth.replace(\"%\", \"\"); canvasWidth = canvasWidth.replace(\"px\", \"\"); */ //Applies changes to the canvas: var canvas = this.get(); if (typeof(canvas) !== \"undefined\" &amp;&amp; canvas !== null) { //this._width = canvasWidth + (isPercentage ? \"%\" : \"\"); this._width = canvasWidth; //this.get().style.width = this._width + (isPercentage ? \"%\" : \"px\"); canvas.style.width = canvasWidth + \"px\"; canvas.setAttribute('width', canvasWidth); //this.get().setAttribute('width', canvasWidth); } return this.getWidth(); } /** * Tells the canvas width (horizontal size) being used in pixels. * @function * @returns {number} Returns the canvas width (horizontal size) being used in pixels. It could return zero (0) if cannot be calculated. */ CB_Canvas.prototype.getWidth = function() { return this._width || 0; } /** * Defines the desired canvas height. * @function * @param {integer} [canvasHeight={@link CB_Canvas.HEIGHT_DEFAULT}] - The desired height (vertical size) in pixels for the canvas. * @returns {number} Returns the canvas height (vertical size) being used in pixels. It could return zero (0) if cannot be calculated. */ CB_Canvas.prototype.setHeight = function(canvasHeight) { //Is not defined or it is wrong, uses default size: if (typeof(canvasHeight) === \"undefined\" || canvasHeight === null || isNaN(canvasHeight)) { canvasHeight = CB_Canvas.HEIGHT_DEFAULT; } //Detects if a percentage has been received: /* canvasHeight = canvasHeight.toString(); var isPercentage = false; if (canvasHeight.indexOf(\"%\") !== -1) { isPercentage = true; } canvasHeight = canvasHeight.replace(\"%\", \"\"); canvasHeight = canvasHeight.replace(\"px\", \"\"); */ //Applies changes to the canvas: var canvas = this.get(); if (typeof(canvas) !== \"undefined\" &amp;&amp; canvas !== null) { //this._height = canvasHeight.toString() + (isPercentage ? \"%\" : \"\"); this._height = canvasHeight; //this.get().style.height = this._height + (isPercentage ? \"%\" : \"px\"); canvas.style.height = canvasHeight + \"px\"; canvas.setAttribute('height', canvasHeight); //this.get().setAttribute('height', this._height); } return this.getHeight(); } /** * Tells the canvas height (vertical size) being used in pixels. * @function * @returns {number} Returns the canvas height (vertical size) being used in pixels. It could return zero (0) if cannot be calculated. */ CB_Canvas.prototype.getHeight = function() { return this._height || 0; } /** * Tells the mode used to create the canvas. * @function * @returns {'NONE'|'NORMAL'|'FLASH'|'SILVERLIGHT'|'VML'|'DHTML'} Returns the mode used to create the canvas. Returns \"NONE\" if no method is used yet (possible when no method is supported at all or when it is still loading). Returns \"NORMAL\" if native [canvas]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas} is used (no canvas emulation method). */ CB_Canvas.prototype.getMode = function() { return this._mode || \"NONE\"; } /** * Tells whether the canvas is ready to be used or not. Some canvas emulation methods can take some time until they are ready to be used. * @function * @returns {boolean} Returns whether the canvas is ready to be used or not. */ CB_Canvas.prototype.isReady = function() { return this._ready; } /** * Tells whether the canvas is loading or not. Some canvas emulation methods can take some time until they finish loading. * @function * @returns {boolean} Returns whether the canvas is loading or not. */ CB_Canvas.prototype.isLoading = function() { return this._loading; } /** * Alias for {@link CB_Canvas#clear}. * @function CB_Canvas.prototype.clearCanvas * @see {@link CB_Canvas#clear} */ /** * Clear the canvas entirely. * @function * @param {boolean} [keepTransform=false] - If set to true, it will [save]{@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/save} and [restore]{@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/restore} the current transformation. * @param {string} [backgroundFillStyle] - The style used (color, gradient, pattern...) to fill the canvas background. If defined, it will be used as the value for the [fillStyle]{@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle} property of the [context]{@link https://developer.mozilla.org/en-US/docs/Web/API/RenderingContext} object, internally. * @returns {boolean} Returns true if the action could be performed or false otherwise. */ CB_Canvas.prototype.clear = CB_Canvas.prototype.clearCanvas = function(keepTransform, backgroundFillStyle) { //Gets the context: var context = this.getContext(); //If the context is not defined or null, exits the function: if (typeof(context) === \"undefined\" || context === null) { return false; } //If defined, saves the current transform: if (keepTransform) { context.save(); context.setTransform(1, 0, 0, 1, 0, 0); } //this.get().width = this.get().width + 1; //+1 for WebKit compatibility. //this.get().width = this.get().width; context.clearRect(0, 0, this.getWidth(), this.getHeight()); if (typeof(backgroundFillStyle) !== \"undefined\" &amp;&amp; backgroundFillStyle !== null) { context.globalAlpha = 1; context.fillStyle = backgroundFillStyle; context.fillRect(0, 0, this.getWidth(), this.getHeight()); } /* else { context.clearRect(0, 0, this.getWidth(), this.getHeight()); } */ //If defined, restores the transform: if (keepTransform) { context.restore(); } return true; } /** * Disables anti-aliasing. Useful to work with image sprites (to avoid problems showing adjacent ones), for example. * @function * @param {boolean} [performTranslate=false] - If set to true, it will also call the [transform]{@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/transform} method. * @returns {boolean} Returns true if the action could be performed or false otherwise. */ CB_Canvas.prototype.disableAntiAliasing = function(performTranslate) { //Gets the context: var context = this.getContext(); //If the context is not defined or null, exits the function: if (typeof(context) === \"undefined\" || context === null) { return false; } if (performTranslate) { context.translate(0.5, 0.5); /*context.lineWidth = 0.5;*/ } context.khtmlImageSmoothingEnabled = false; context.oImageSmoothingEnabled = false; context.msImageSmoothingEnabled = false; context.webkitImageSmoothingEnabled = false; context.mozImageSmoothingEnabled = false; context.imageSmoothingEnabled = false; return true; } //Internet Explorer 11 (and lower) does not support \"ellipse\" method, so we try to simulate it: //* Solution by Steve Tranby. Source: https://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas/2173084#2173084 //TODO: Add parameters and modify their order to mimic (polyfill) the native ellipse function (https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/ellipse). CB_Canvas.prototype._context_drawEllipse = function drawEllipse(x, y, w, h) //NOTE: must be called being \"this\" the canvas context desired. { var kappa = .5522848; var ox = (w / 2) * kappa; //Control point offset horizontal. var oy = (h / 2) * kappa; //Control point offset vertical. var xe = x + w; //x-end. var ye = y + h; //y-end. var xm = x + w / 2; //x-middle. var ym = y + h / 2; //y-middle. this.beginPath(); this.moveTo(x, ym); this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); //this.closePath(); // not used correctly, see comments (use to close off open path) //this.stroke(); }; //CB_CanvasFileLoaded = true; //This file has been loaded. //CB_filesNeeded[\"screen/canvas/CB_Canvas.js\"] = true; //This file has been loaded. × Search results Close "},"CrossBase_general_CB_Client.js.html":{"id":"CrossBase_general_CB_Client.js.html","title":"Source: CrossBase/general/CB_Client.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/general/CB_Client.js /** * @file Web client (browser or engine) management. Contains the {@link CB_Client} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage the current client. It will return itself if it is tried to be instantiated. It can use [BrowserDetect]{@link https://quirksmode.org/js/detect.html} ([source code rescued]{@link https://gist.github.com/mitchellhislop/2018348}). * @namespace * @todo Think about implementing a getDocumentParents function (similar to {@link CB_Client.getWindowParents}). * @todo Think about implementing \"onClose\" event (to fire when app/web is going to be closed). */ var CB_Client = function() { return CB_Client; }; { CB_Client.initialized = false; //It will tells whether the object has been initialized or not. //Initializes all values: CB_Client.init = function() { //If this is the fist time: if (CB_Client.initialized) { return CB_Client; } //The object has been initialized: CB_Client.initialized = true; return CB_Client; } //Returns the most preferred language: CB_Client._getLanguagePreferred = function(allowNavigatorLanguages, PHPAcceptedLanguagesFirst) { return CB_Client._getLanguagesPreferred(allowNavigatorLanguages, PHPAcceptedLanguagesFirst)[0]; }; /** * Returns the most preferred language as a string. * @function * @param {boolean} [allowNavigatorLanguages={@link CB_Configuration.CrossBase.CB_Client_allowNavigatorLanguages_DEFAULT}] - Defines whether to allow using the [window.navigator.languages]{@link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/languages} property (if not available, it will proceed normally). * @param {boolean} [PHPAcceptedLanguagesFirst={@link CB_Configuration.CrossBase.CB_Client_PHPAcceptedLanguagesFirst_DEFAULT}] - If it is set to true, it will try to return the accepted languages found out by [PHP]{@link https://en.wikipedia.org/wiki/PHP} (if [PHP]{@link https://en.wikipedia.org/wiki/PHP} is available) in [$_SERVER]{@link http://php.net/manual/en/reserved.variables.server.php}['HTTP_ACCEPT_LANGUAGE'] or it will proceed normally otherwise. * @returns {string} * @todo Use other back-end ways to calculate the language (using Node.js, for example). */ CB_Client.getLanguage = function(allowNavigatorLanguages, PHPAcceptedLanguagesFirst) { return CB_Client._getLanguagePreferred(allowNavigatorLanguages, PHPAcceptedLanguagesFirst); } //Returns the most preferred languages (an array): CB_Client._getLanguagesPreferred = function(allowNavigatorLanguages, PHPAcceptedLanguagesFirst) { if (typeof(PHPAcceptedLanguagesFirst) !== true &amp;&amp; PHPAcceptedLanguagesFirst !== false) { PHPAcceptedLanguagesFirst = CB_Configuration[CB_BASE_NAME].CB_Client_PHPAcceptedLanguagesFirst_DEFAULT; } if (PHPAcceptedLanguagesFirst &amp;&amp; typeof(CB_PHPAcceptedLanguages) !== \"undefined\" &amp;&amp; CB_isArray(CB_PHPAcceptedLanguages) &amp;&amp; CB_PHPAcceptedLanguages.length &gt; 0) { return CB_PHPAcceptedLanguages; } if (allowNavigatorLanguages !== true &amp;&amp; allowNavigatorLanguages !== false) { allowNavigatorLanguages = CB_Configuration[CB_BASE_NAME].CB_Client_allowNavigatorLanguages_DEFAULT; } if (allowNavigatorLanguages &amp;&amp; window.navigator.languages) { return window.navigator.languages; } var languages = []; if (window.navigator.language &amp;&amp; CB_indexOf(languages, window.navigator.language) === -1) { languages[languages.length] = window.navigator.language; } if (window.navigator.userLanguage &amp;&amp; CB_indexOf(languages, window.navigator.userLanguage) === -1) { languages[languages.length] = window.navigator.userLanguage; } if (window.navigator.browserLanguage &amp;&amp; CB_indexOf(languages, window.navigator.browserLanguage) === -1) { languages[languages.length] = window.navigator.browserLanguage; } if (window.navigator.systemLanguage &amp;&amp; CB_indexOf(languages, window.navigator.systemLanguage) === -1) { languages[languages.length] = window.navigator.systemLanguage; } if (languages.length &gt; 0) { return languages; } else { return [CB_Configuration[CB_BASE_NAME].CB_Client_language_DEFAULT]; } }; /** * Returns the most preferred languages as an array of strings. * @function * @param {boolean} [allowNavigatorLanguages={@link CB_Configuration.CrossBase.CB_Client_allowNavigatorLanguages_DEFAULT}] - Defines whether to allow using the [window.navigator.languages]{@link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/languages} property (if not available, it will proceed normally). * @param {boolean} [PHPAcceptedLanguagesFirst={@link CB_Configuration.CrossBase.CB_Client_PHPAcceptedLanguagesFirst_DEFAULT}] - If it is set to true, it will try to return the accepted languages found out by [PHP]{@link https://en.wikipedia.org/wiki/PHP} (if [PHP]{@link https://en.wikipedia.org/wiki/PHP} is available) in [$_SERVER]{@link http://php.net/manual/en/reserved.variables.server.php}['HTTP_ACCEPT_LANGUAGE'] or it will proceed normally otherwise. * @returns {array} * @todo Use other back-end ways to calculate languages (using Node.js, for example). */ CB_Client.getLanguages = function(allowNavigatorLanguages, PHPAcceptedLanguagesFirst) { return CB_Client._getLanguagesPreferred(allowNavigatorLanguages, PHPAcceptedLanguagesFirst); } /** * Sets a function to execute when the [languagechange]{@link https://developer.mozilla.org/en-US/docs/Web/Events/languagechange} event is fired (only for some web clients) or removes it. * @function * @param {function|null} eventFunction - Function that represents the event listener that will be called when the event is fired. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether to also keep the previous listeners or remove them otherwise. * @param {boolean} [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. */ CB_Client.onLanguageChanges = function(eventFunction, keepOldFunction, useCapture) { CB_Client._setEvent(\"languagechange\", eventFunction, keepOldFunction, useCapture, window); } /** * Alias for {@link CB_Client.get}. * @function CB_Client.getBrowser * @see {@link CB_Client.get} */ /** * Returns the current web client (if possible) as a string. It uses [BrowserDetect]{@link https://quirksmode.org/js/detect.html} ([source code rescued]{@link https://gist.github.com/mitchellhislop/2018348}) internally. * @function * @returns {string} */ CB_Client.get = CB_Client.getBrowser = function() { return BrowserDetect.browser; } /** * Alias for {@link CB_Client.getVersion}. * @function CB_Client.getBrowserVersion * @see {@link CB_Client.getVersion} */ /** * Returns the current web client version (if possible) as a string. It uses [BrowserDetect]{@link https://quirksmode.org/js/detect.html} ([source code rescued]{@link https://gist.github.com/mitchellhislop/2018348}) internally. * @function * @returns {string} */ CB_Client.getVersion = CB_Client.getBrowserVersion = function() { return BrowserDetect.version + \"\"; } /** * Alias for {@link CB_Client.getVersionMain}. * @function CB_Client.getBrowserVersionMain * @see {@link CB_Client.getVersionMain} */ /** * Returns the current web client main version (first number), if possible, as an integer. It uses [BrowserDetect]{@link https://quirksmode.org/js/detect.html} ([source code rescued]{@link https://gist.github.com/mitchellhislop/2018348}) internally. * @function * @returns {integer} */ CB_Client.getVersionMain = CB_Client.getBrowserVersionMain = function() { return parseInt(CB_Client.getBrowserVersion().split(\".\")[0]); } CB_Client._getWindowParentsReturnCache; //Stores the return result in order to optimize the execution next times. /** * Returns all the [window]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window} objects, parents and last son (main one) in an array (with the topmost parent in the highest index). Useful in case the script is running in an [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} or more. * @function * @returns {array} */ CB_Client.getWindowParents = function() { //If it is not the first time we execute this function, uses the cache to return always the same: if (typeof(CB_Client._getWindowParentsReturnCache) !== \"undefined\" &amp;&amp; CB_Client._getWindowParentsReturnCache !== null) { return CB_Client._getWindowParentsReturnCache; } var windowParents = [ window.self ]; try { if (typeof(window.parent) !== \"undefined\" &amp;&amp; window.parent !== null) { var currentParent = windowParents[0];//windowParents[windowParents.length - 1]; while (typeof(currentParent.parent) !== \"undefined\" &amp;&amp; currentParent !== currentParent.parent) { currentParent = currentParent.parent; windowParents[windowParents.length] = currentParent; } ///////windowBase = currentParent; } } catch(E) {} CB_Client._getWindowParentsReturnCache = windowParents; return windowParents; } CB_Client._getWindowBaseReturnCache; //Stores the return result in order to optimize the execution next times. /** * Returns the [window]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window} object of the first parent (the topmost one). Useful in case the script is running in an [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} or more. * @function * @returns {Object} */ CB_Client.getWindowBase = function() { //If it is not the first time we execute this function, uses the cache to return always the same: if (typeof(CB_Client._getWindowBaseReturnCache) !== \"undefined\" &amp;&amp; CB_Client._getWindowBaseReturnCache !== null) { return CB_Client._getWindowBaseReturnCache; } //By default, uses the current window object: var windowBase = window.self; //window; //Tries to get the topmost window (it can fail if it is not in the same domain or it is running locally): try { //If defined, we use window.top to get the topmost window: if (typeof(window.top) !== \"undefined\" &amp;&amp; window.top !== null) { windowBase = window.top; } //...otherwise, we get all the parents and chose the last one (which will be the topmost): else { var windowParents = CB_Client.getWindowParents(); windowBase = windowParents[windowParents.length - 1]; } } catch(E) {} CB_Client._getWindowBaseReturnCache = windowBase; return windowBase; } CB_Client._getWindowReturnCache; //Stores the return result in order to optimize the execution next times. /** * Returns the [window]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window} object (having in mind whether the script is running in one [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} or more, if we want). * @function * @param {boolean} [mindIframes={@link CB_Configuration.CrossBase.MIND_IFRAMES}] - If set to true, it will try to get and return the topmost [window]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window} object. Useful in case the script is running in an [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} or more. * @returns {Object} */ CB_Client.getWindow = function(mindIframes) { if (typeof(mindIframes) === \"undefined\" || mindIframes === null) { mindIframes = CB_Configuration[CB_BASE_NAME].MIND_IFRAMES; } //If it is not the first time we execute this function, uses the cache to return always the same: if (!mindIframes) { return window.self; } else if (typeof(CB_Client._getWindowReturnCache) !== \"undefined\" &amp;&amp; CB_Client._getWindowReturnCache !== null) { return CB_Client._getWindowReturnCache; } //Gets the window chosen (if we arrived here, it means we mind iframes): CB_Client._getWindowReturnCache = CB_Client.getWindowBase(); //Stores the window chosen in the cache: return CB_Client._getWindowReturnCache; } /** * Returns the [document]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/document} object of the first parent (the topmost one). Useful in case the script is running in an [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} or more. * @function * @returns {Object} */ CB_Client.getDocumentBase = function() { //By default, uses the current document object: var documentBase = document; //Tries to get the document object of the topmost window (it can fail if it is not in the same domain or it is running locally): try { documentBase = CB_Client.getWindowBase().document; } catch(E) {} return documentBase; } /** * Returns the [document]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/document} object (having in mind whether the script is running in one [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} or more, if we want). * @function * @param {boolean} [mindIframes={@link CB_Configuration.CrossBase.MIND_IFRAMES}] - If set to true, it will try to get and return the topmost [document]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/document} object. Useful in case the script is running in an [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} or more. * @returns {Object} */ CB_Client.getDocument = function(mindIframes) { if (typeof(mindIframes) === \"undefined\" || mindIframes === null) { mindIframes = CB_Configuration[CB_BASE_NAME].MIND_IFRAMES; } var documentChosen = document; if (mindIframes) { documentChosen = CB_Client.getDocumentBase(); } return documentChosen; } /** * Tells whether the [canvas]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas} element is supported natively or not. * @function * @returns {boolean} */ CB_Client.supportsCanvas = function() { return CB_Configuration[CB_BASE_NAME]._supportsCanvas(); } CB_Client._supportsCSS3TransformReturnCache; /** * Tells whether [CSS3]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS3} [transform]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/transform} is supported natively or not. * @function * @returns {boolean} */ CB_Client.supportsCSS3Transform = function() { if (typeof(CB_Client._supportsCSS3TransformReturnCache) === \"undefined\" || CB_Client._supportsCSS3TransformReturnCache === null) { var documentBodyStyle = document.body.style; CB_Client._supportsCSS3TransformReturnCache = (typeof(documentBodyStyle.transform) !== \"undefined\" || typeof(documentBodyStyle.WebkitTransform) !== \"undefined\" || typeof(documentBodyStyle.MozTransform) !== \"undefined\" || typeof(documentBodyStyle.OTransform) !== \"undefined\" || typeof(documentBodyStyle.MsTransform) !== \"undefined\" || typeof(documentBodyStyle.KhtmlTransform) !== \"undefined\"); } return CB_Client._supportsCSS3TransformReturnCache; } /** * Function that tells whether [PHP]{@link https://en.wikipedia.org/wiki/PHP} is available or not. * @function * @returns {boolean} */ CB_Client.supportsPHP = function() { return (typeof(CB_supportedPHP) !== \"undefined\" &amp;&amp; CB_supportedPHP === \"YES\"); } /** * Returns the available version of [PHP]{@link https://en.wikipedia.org/wiki/PHP} (if any), as either an array of strings or as a string. * @function * @param {boolean} [asString=false] - If set to true, returns the version as a string. * @returns {array|string} */ CB_Client.getPHPVersion = function(asString) { if (typeof(CB_PHPVersion) === \"undefined\") { CB_PHPVersion = 0; } return asString ? (CB_PHPVersion + \"\") : (CB_PHPVersion + \"\").split(\".\"); } /** * Function that tells whether [Node.js]{@link https://en.wikipedia.org/wiki/Node.js} is available (checks the availability of [process.versions.node]{@link https://nodejs.org/api/process.html#process_process_versions}) or not. * @function * @returns {boolean} */ //* Source: Dan. B. @ http://stackoverflow.com/questions/17575790/environment-detection-node-js-or-browser CB_Client.supportsNodeJS = function() { return (typeof(process) === \"object\" &amp;&amp; process !== null &amp;&amp; typeof(process.versions) === \"object\" &amp;&amp; typeof(process.versions.node) !== \"undefined\"); } /** * Returns the available version of [Node.js]{@link https://en.wikipedia.org/wiki/Node.js} (if any), as either an array of strings or as a string. * @function * @param {boolean} [asString=false] - If set to true, returns the version as a string. * @returns {array|string} */ CB_Client.getNodeJSVersion = function(asString) { if (typeof(process) === \"object\" &amp;&amp; process !== null &amp;&amp; CB_isString(process.version)) { return asString ? process.version : process.version.replace(CB_regularExpressionString(\"-\", true, true), \".\").split(\".\"); } else { return asString ? \"0.0.0\" : [0, 0, 0]; } } /** * Function that tells whether [Microsoft Silverlight]{@link https://en.wikipedia.org/wiki/Microsoft_Silverlight} plugin is available or not. * @function * @returns {boolean} */ CB_Client.supportsSilverlight = function() { var isSilverlightInstalled = false; try { isSilverlightInstalled = !!(new ActiveXObject(\"AgControl.AgControl\")); } catch(E) { if (navigator.plugins[\"Silverlight Plug-In\"]) { isSilverlightInstalled = true; } else { isSilverlightInstalled = false; } } return isSilverlightInstalled; } /** * Returns the available version of [Microsoft Silverlight]{@link https://en.wikipedia.org/wiki/Microsoft_Silverlight} plugin (if any), as either an array of strings or as a string. * @function * @param {boolean} [asString=false] - If set to true, returns the version as a string. * @returns {array|string} */ CB_Client.getSilverlightVersion = function(asString) { if (navigator.plugins[\"Silverlight Plug-In\"] &amp;&amp; navigator.plugins[\"Silverlight Plug-In\"].description &amp;&amp; CB_isString(navigator.plugins[\"Silverlight Plug-In\"].description) &amp;&amp; CB_trim(navigator.plugins[\"Silverlight Plug-In\"].description) !== \"\") { return asString ? navigator.plugins[\"Silverlight Plug-In\"].description : navigator.plugins[\"Silverlight Plug-In\"].description.replace(CB_regularExpressionString(\"-\", true, true), \".\").split(\".\"); } else { return asString ? \"0.0.0\" : [0, 0, 0]; } } /** * Function that tells whether [Adobe Flash (formerly Macromedia Flash)]{@link https://en.wikipedia.org/wiki/Adobe_Flash_Player} plugin is available or not. * @function * @returns {boolean} */ CB_Client.supportsFlash = function() { var isFlashInstalled = false; if (\"ActiveXObject\" in window) { try { isFlashInstalled = !!(new ActiveXObject(\"ShockwaveFlash.ShockwaveFlash\")); } catch(E) { isFlashInstalled = false; } } if (!isFlashInstalled &amp;&amp; typeof(navigator.mimeTypes) !== \"undefined\") { var mime = navigator.mimeTypes['application/x-shockwave-flash'] if (typeof(mime) !== \"undefined\" &amp;&amp; mime !== null &amp;&amp; mime.enabledPlugin) { isFlashInstalled = true;//!!mime; } } if (!isFlashInstalled &amp;&amp; typeof(navigator.plugins) !== \"undefined\") { var plugin = navigator.plugins[\"Shockwave Flash\"]; isFlashInstalled = !!plugin; } return isFlashInstalled; } /** * Returns the available version of [Adobe Flash (formerly Macromedia Flash)]{@link https://en.wikipedia.org/wiki/Adobe_Flash_Player} plugin, if any, as either an array of strings or as a string. * @function * @param {boolean} [asString=false] - If set to true, returns the version as a string. * @returns {array|string} */ CB_Client.getFlashVersion = function(asString) { var version = \"0.0.0\"; try { try { var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6'); try { axo.AllowScriptAccess = 'always'; } catch(E) { return asString ? '6.0.0' : '6.0.0'.split('.'); } } catch(E) {} version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\\D+/g, ',').match(/^,?(.+),?$/)[1]; version = version.replace(CB_regularExpressionString(\",\", true, true), \".\"); return asString ? version : version.split('.'); } catch(E) { try { if (navigator.mimeTypes[\"application/x-shockwave-flash\"].enabledPlugin) { version = (navigator.plugins[\"Shockwave Flash 2.0\"] || navigator.plugins[\"Shockwave Flash\"]).description.replace(/\\D+/g, \",\").match(/^,?(.+),?$/)[1]; version = version.replace(CB_regularExpressionString(\",\", true, true), \".\"); return asString ? version : version.split('.'); } } catch(E) {} } return asString ? version : version.split('.'); } /** * Tells whether the script is running locally (using \"file:\" protocol) or not. * @function * @param {boolean} [mindIframes={@link CB_Configuration.CrossBase.MIND_IFRAMES}] - If set to true, it will try to check the protocol of the topmost [window]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window} object. Useful in case the script is running in an [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} or more. * @returns {boolean} */ CB_Client.isRunningLocally = function(mindIframes) { if (typeof(mindIframes) === \"undefined\" || mindIframes === null) { mindIframes = CB_Configuration[CB_BASE_NAME].MIND_IFRAMES; } var isRunningLocally = false; //We assume that the script is not running locally by default. var protocolUsed = \"\"; try { var windowObject = CB_Client.getWindow(mindIframes); if (typeof(windowObject.location) !== \"undefined\" &amp;&amp; typeof(windowObject.location.protocol) !== \"undefined\") { protocolUsed = windowObject.location.protocol; } } catch(E) { if (typeof(window.location) !== \"undefined\" &amp;&amp; typeof(window.location.protocol) !== \"undefined\") { protocolUsed = window.location.protocol; } } if (protocolUsed === \"file:\") { isRunningLocally = true; } //else if (protocolUsed === \"http:\" || protocolUsed === \"https:\") { isRunningLocally = false; } return isRunningLocally; } CB_Client._isRunningOnNWjsReturnCache = null; /** * Tells whether the script is running on [NW.js (formerly node-webkit)]{@link https://nwjs.io/} or not. * @function * @returns {boolean} */ //* Source: Kuf @ http://stackoverflow.com/questions/31968355/detect-if-web-app-is-running-in-nwjs CB_Client.isRunningOnNWjs = function() { if (typeof(CB_Client._isRunningOnNWjsReturnCache) !== \"undefined\" &amp;&amp; CB_Client._isRunningOnNWjsReturnCache !== null) { return CB_Client._isRunningOnNWjsReturnCache; } if (typeof(nw) !== \"undefined\" &amp;&amp; nw !== null) { return CB_Client._isRunningOnNWjsReturnCache = true; } try { return CB_Client._isRunningOnNWjsReturnCache = (typeof(require) === \"function\" &amp;&amp; (typeof(nw) !== \"undefined\" &amp;&amp; nw !== null &amp;&amp; nw.App || typeof(require(\"nw.gui\")) !== \"undefined\")); } catch(E) { return CB_Client._isRunningOnNWjsReturnCache = false; } } CB_Client._isRunningOnElctronReturnCache = null; /** * Tells whether the script is running on [Electron (Electron.js)]{@link https://electronjs.org/} or not. * @function * @returns {boolean} */ //* Source: cheton @ https://github.com/cheton/is-electron/blob/master/index.js CB_Client.isRunningOnElectron = function() { if (typeof(CB_Client._isRunningOnElectronReturnCache) !== \"undefined\" &amp;&amp; CB_Client._isRunningOnElectronReturnCache !== null) { return CB_Client._isRunningOnElectronReturnCache; } //if (typeof(nw) !== \"undefined\" &amp;&amp; nw !== null) { return CB_Client._isRunningOnElectronReturnCache = true; } try { return CB_Client._isRunningOnElectronReturnCache = (typeof(navigator) === \"object\" &amp;&amp; navigator !== null &amp;&amp; typeof(navigator.userAgent) === \"string\" &amp;&amp; navigator.userAgent.indexOf(\"Electron\") !== -1); } catch(E) { return CB_Client._isRunningOnElectronReturnCache = false; } } /** * Exits and finishes the script. In a browser, it will try to close the window or at least abandon it redirecting to an empty one (or to a desired URL). In an app ([NW.js (formerly node-webkit)]{@link https://nwjs.io/}/[Electron (Electron.js)]{@link https://electronjs.org/}/[Apache Cordova]{@link https://cordova.apache.org/}/[Adobe PhoneGap]{@link https://phonegap.com/}/[Appcelerator Titanium SDK]{@link https://en.wikipedia.org/wiki/Appcelerator_Titanium}/[Appcelerator TideSDK (Titanium Desktop)]{@link https://github.com/appcelerator-archive/titanium_desktop}/[Weixin (WeChat)]{@link https://en.wikipedia.org/wiki/WeChat}/etc.), it will try to close the app. * @function * @param {boolean} [allowWindowCloseFallback=true] - Defines whether to allow using the [window.close]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/close} method as a fallback. * @param {boolean} [allowRedirectionFallback=true] - Defines whether to redirect the current client as a fallback (to the URL defined in the \"redirectionAddress\" parameter). * @param {boolean} [redirectionAddress='about:blank'] - Defines the URL where the current client will be redirected to in the case that the window cannot be closed. Only used if the \"allowRedirectionFallback\" parameter is set to true. * @todo Have in mind iframes (think about it). */ CB_Client.exit = function(allowWindowCloseFallback, allowRedirectionFallback, redirectionAddress) { if (typeof(allowRedirectionFallback) === \"undefined\" || allowRedirectionFallback === null) { allowRedirectionFallback = true; } if (typeof(allowWindowCloseFallback) === \"undefined\" || allowWindowCloseFallback === null) { allowWindowCloseFallback = true; } if (typeof(redirectionAddress) === \"undefined\" || redirectionAddress === null) { redirectionAddress = \"about:blank\"; } var useFallback = true; //Tries to use NW.js (node-webkit) if available to quit the app: if (CB_Client.isRunningOnNWjs()) { if (typeof(nw) !== \"undefined\" &amp;&amp; nw !== null &amp;&amp; nw.App &amp;&amp; typeof(nw.App.closeAllWindows) === \"function\") { try { nw.App.closeAllWindows(); useFallback = false; } catch(E) { useFallback = true; } } if (useFallback &amp;&amp; typeof(require) === \"function\") { try { var gui = require(\"nw.gui\"); if (typeof(gui) !== \"undefined\" &amp;&amp; gui !== null &amp;&amp; gui.App) { if (typeof(gui.App.closeAllWindows) === \"function\") { try { gui.App.closeAllWindows(); useFallback = false; } catch(E) { useFallback = true; } } if (useFallback &amp;&amp; typeof(gui.App.quit) === \"function\") { try { gui.App.quit(); useFallback = false; } catch(E) { useFallback = true; } } } } catch(E) { useFallback = true; } } if (useFallback &amp;&amp; typeof(nw) !== \"undefined\" &amp;&amp; nw !== null &amp;&amp; nw.App &amp;&amp; typeof(nw.App.quit) === \"function\") { try { nw.App.quit(); useFallback = false; } catch(E) { useFallback = true; } } } //Tries to use Electron (Electron.js) if available to quit the app: if (CB_Client.isRunningOnElectron() &amp;&amp; typeof(require) === \"function\") { try { var app = require('app'); app.on(\"window-all-closed\", app.quit); app.quit(); useFallback = false; } catch(E) { useFallback = true; } } //If able, uses PhoneGap with navigator.app: if (typeof(navigator) !== \"undefined\" &amp;&amp; typeof(navigator.app) !== \"undefined\" &amp;&amp; typeof(navigator.app.exitApp) !== \"undefined\") { try { navigator.app.exitApp(); useFallback = false; } catch(E) { useFallback = true; } } //If able uses PhoneGap with navigator.device: if (typeof(navigator) !== \"undefined\" &amp;&amp; typeof(navigator.device) !== \"undefined\" &amp;&amp; typeof(navigator.device.exitApp) !== \"undefined\") { try { navigator.device.exitApp(); useFallback = false; } catch(E) { useFallback = true; } } //If able uses WeixinJSBridge (Weixin / Wechat JavaScript Bridge): if (typeof(WeixinJSBridge) !== \"undefined\" &amp;&amp; typeof(WeixinJSBridge.call) !== \"undefined\") { //WeixinJSBridge.invoke(\"closeWindow\", {}, function(e){}); try { WeixinJSBridge.call(\"closeWindow\"); useFallback = false; } catch(E) { useFallback = true; } } //If able uses Titanium/TideSDK: if (typeof(Ti) !== \"undefined\" &amp;&amp; typeof(Ti.App) !== \"undefined\" &amp;&amp; typeof(Ti.App.exit) !== \"undefined\") { try { Ti.App.exit(); useFallback = false; } catch(E) { useFallback = true; } } //If we want to close using the fallback: if (useFallback) { //Uses redirection if it is allowed: if (allowRedirectionFallback) { setTimeout(function() { location.href = redirectionAddress; }, 200); //Lets a little bit time to process window.close() (if allowed). } //Uses window.close() if it is allowed: if (allowWindowCloseFallback) { try { //if (navigator.userAgent.indexOf('MSIE') !== -1 &amp;&amp; (navigator.appVersion.indexOf(\"MSIE 5\") !== -1 || navigator.appVersion.indexOf(\"MSIE 6\") !== -1)) //{ //CB_Client.getWindow().opener = top; //CB_Client.getWindow().close(); //} //else //{ //var ventana = CB_Client.getWindow().open(\"\", \"_self\"); //ventana.close(); //} var thisWindow = window.open(allowRedirectionFallback ? redirectionAddress : \"\", \"_self\", \"\", \"true\"); thisWindow.opener = top; CB_windowCloseEncapsulated = thisWindow.close; CB_windowCloseEncapsulated(); //if (navigator.userAgent.indexOf('MSIE') !== -1 &amp;&amp; (navigator.appVersion.indexOf(\"MSIE 5\") !== -1 || navigator.appVersion.indexOf(\"MSIE 6\") !== -1)) //{ //window.opener = top; //window.close(); //} //var thisWindow = window.parent.open(allowRedirectionFallback ? redirectionAddress : location.href, \"_self\"); //window.parent.close(); //else //{ //var thisWindow = CB_Client.getWindow(true).open(allowRedirectionFallback ? redirectionAddress : \"\", \"_self\", \"\", \"true\"); //thisWindow.opener = CB_Client.getWindow().top; //CB_windowCloseEncapsulated = thisWindow.close; //CB_windowCloseEncapsulated(); //} } catch(E) { try { var thisWindow = window.open(allowRedirectionFallback ? redirectionAddress : location.href, \"_self\"); thisWindow.close(); } catch(E) { try { window.opener = top; window.close(); } catch(E) { try { window.opener = window; window.close(); } catch(E) { try { window.opener = \"CB_TryingToCloseWindow\"; window.close(); } catch(E) { try { window.close(); } catch(E) { } } } } } } } } } /** * Redirects the current client to the desired location (having in mind whether the script is running in one [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} or more, if we want). * @function * @param {string} address - The address where we want to go. * @param {string} [getData] - Any URL (GET) variables we want to send (as for example \"data1=value1&amp;data2=value2\"). * @param {boolean} [mindIframes={@link CB_Configuration.CrossBase.MIND_IFRAMES}] - If set to true, it will try to redirect the topmost [window]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window} object. Useful in case the script is running in an [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} or more. */ CB_Client.redirectTo = function(address, getData, mindIframes) { getData = CB_ltrim(CB_trim(getData), [\"&amp;\", \"?\"]); if (getData !== \"\") { if (address.indexOf(\"?\") === -1) { getData = \"?\" + getData; } else { getData = \"&amp;\" + getData; } } try { CB_Client.getWindow(mindIframes).location = address + getData; } catch(E) { window.location = address + getData; } } /** * Returns the current URL, if possible (having in mind whether the script is running in one [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} or more, if we want). * @function * @param {boolean} [mindIframes={@link CB_Configuration.CrossBase.MIND_IFRAMES}] - If set to true, it will try to get the location of the topmost [window]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window} object. Useful in case the script is running in an [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} or more. * @returns {string} */ CB_Client.getLocation = function(mindIframes) { var address = \"\"; try { address = CB_Client.getWindow(mindIframes).location.href; } catch(E) { address = \"\"; } if (!address) { address = window.location.href; } return address; } /** * Returns the given address without the file (for example, if \"http://whatever.com/index.html\" is given, it will return \"http://whatever.com/\"). * @function * @param {string} address - The address that we want to filter. * @param {string} [fallbackURL] - The address that we want it to return in the case that the given one is not allowed (used when \"allowsLocal\" does not allow a local address). If it contains a file, it will not be stripped out. * @param {boolean} [allowsLocal=true] - Defines whether to allow returning a local address or not. If it is set to false and the address is local, it will return the \"fallbackURL\" instead (without stripping out the file, if any). * @returns {string} */ CB_Client.getAddressWithoutFile = function(address, fallbackURL, allowsLocal) { if (allowsLocal !== true &amp;&amp; allowsLocal !== false) { allowsLocal = true; } address = CB_trim(address); address = CB_rtrim(address.substring(0, address.lastIndexOf(\"/\")), \"/\") + \"/\"; if (allowsLocal || address.indexOf(\"://localhost\") === -1 &amp;&amp; address.indexOf(\"://127.0.0.1\") === -1 &amp;&amp; address.indexOf(\"://192.168\") === -1 || !CB_isString(fallbackURL)) { return address; } else { return fallbackURL; } } /** * Returns the current URL without the file (for example, if \"http://whatever.com/index.html\" is the current URL, it will return \"http://whatever.com/\"), if possible (having in mind whether the script is running in one [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} or more, if we want). * @function * @param {string} [fallbackURL] - The address that we want it to return in the case that the current one is not allowed (used when \"allowsLocal\" does not allow a local address). If it contains a file, it will not be stripped out. * @param {boolean} [allowsLocal=true] - Defines whether to allow returning a local address or not. If it is set to false and the current address is local, it will return the \"fallbackURL\" instead (without stripping out the file, if any). * @param {boolean} [mindIframes={@link CB_Configuration.CrossBase.MIND_IFRAMES}] - If set to true, it will try to get the location of the topmost [window]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window} object. Useful in case the script is running in an [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} or more. * @returns {string} */ CB_Client.getLocationWithoutFile = function(fallbackURL, allowsLocal, mindIframes) { return CB_Client.getAddressWithoutFile(CB_Client.getLocation(mindIframes), fallbackURL, allowsLocal); } //var firstTimeShit = 0; /** * Gets the starting pixel of top or left coordinates for [getBoundingClientRect]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect} (it's not 0 in some Internet Explorer versions). * @function * @param {('left'|'top')} [leftOrTop='left'] - String that defines whether we want it to return the values for \"left\" or for \"top\". * @returns {integer} */ CB_Client.getBoundingClientRectMargin = function(leftOrTop) { leftOrTop = leftOrTop.toLowerCase(); if (leftOrTop === \"\" || leftOrTop !== \"left\" &amp;&amp; leftOrTop !== \"top\") { leftOrTop = \"left\"; } var getBoundingClientRectMarginDiv = CB_Elements.id(\"getBoundingClientRectMarginDiv\"); if (getBoundingClientRectMarginDiv === null) { var getBoundingClientRectMarginDiv = document.createElement(\"div\"); getBoundingClientRectMarginDiv.id = \"getBoundingClientRectMarginDiv\"; getBoundingClientRectMarginDiv.style.position = \"absolute\"; getBoundingClientRectMarginDiv.style.width = getBoundingClientRectMarginDiv.style.height = \"0px\"; getBoundingClientRectMarginDiv.style.visibility = \"hidden\"; getBoundingClientRectMarginDiv.style.left = \"0px\"; getBoundingClientRectMarginDiv.style.top = \"0px\"; var tagBody = CB_Elements.tag(\"body\", document); if (typeof(tagBody) !== \"undefined\" &amp;&amp; tagBody !== null &amp;&amp; typeof(tagBody[0]) !== \"undefined\" &amp;&amp; tagBody[0] !== null) { tagBody[0].appendChild(getBoundingClientRectMarginDiv); //firstTimeShit = true; } } if (typeof(getBoundingClientRectMarginDiv.getBoundingClientRect) !== \"undefined\" &amp;&amp; getBoundingClientRectMarginDiv.getBoundingClientRect !== null) { var rectMargin = getBoundingClientRectMarginDiv.getBoundingClientRect(); var margin = 0; if (typeof(rectMargin[leftOrTop]) !== \"undefined\" &amp;&amp; rectMargin[leftOrTop] !== null &amp;&amp; !isNaN(rectMargin[leftOrTop])) { margin = rectMargin[leftOrTop]; } } if (margin &lt; 0) { if (leftOrTop === \"left\") { margin += CB_Screen.getScrollLeft(); } else { margin += CB_Screen.getScrollTop(); } if (margin &lt; 0) { margin = 0; } } return margin; } /** * Tries to change the [document title]{@link https://developer.mozilla.org/en-US/docs/Web/API/Document/title} and returns it. * @function * @param {newTitle} newTitle - The desired new title. * @returns {string} */ CB_Client.setTitle = function(newTitle) { CB_Client.getDocumentBase().title = newTitle; //Chrome and Opera fix: var tagTitle = CB_Elements.tag(\"title\"); if (typeof(tagTitle) !== \"undefined\" &amp;&amp; tagTitle !== null &amp;&amp; typeof(tagTitle[0]) !== \"undefined\" &amp;&amp; tagTitle[0] !== null) { tagTitle = tagTitle[0]; try { tagTitle.innerHTML = newTitle; } catch(E) {} //Catch to avoid IE8 error. } titleCurrent = CB_Client.getTitle(); return titleCurrent; } /** * Returns the current [document title]{@link https://developer.mozilla.org/en-US/docs/Web/API/Document/title}. * @function * @returns {string} */ CB_Client.getTitle = function() { var title = CB_trim(CB_Client.getDocumentBase().title); if (title === \"\") { //Chrome and Opera fix: var tagTitle = CB_Elements.tag(\"title\"); if (typeof(tagTitle) !== \"undefined\" &amp;&amp; tagTitle !== null &amp;&amp; typeof(tagTitle[0]) !== \"undefined\" &amp;&amp; tagTitle[0] !== null) { tagTitle = tagTitle[0]; try { title = tagTitle.innerHTML; } catch(E) { title = \"\"; } //Catch to avoid IE8 error. } } return title; } //Sets a function to execute when a desired event is fired: CB_Client._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture, target) { //If they are not set, use default values for optional parameters: if (typeof(keepOldFunction) === \"undefined\" || keepOldFunction === null) { keepOldFunction = true; } //If not set, it keeps old function by default. if (typeof(target) === \"undefined\" || target === null) { target = window; } //If a function has been sent: if (typeof(eventFunction) === \"function\") { //If able, adds the function given to the event: CB_Events.add ( target, eventName, function(e) { e = CB_Events.normalize(e); if (typeof(eventFunction) === \"function\") { return eventFunction(e); } return true; }, useCapture, keepOldFunction, true ); } //...but if the function given is null, it will cancel the event: else if (eventFunction === null) { CB_Events.removeByName(target, eventName); } } } × Search results Close "},"CrossBase_input_CB_Mouse.js.html":{"id":"CrossBase_input_CB_Mouse.js.html","title":"Source: CrossBase/input/CB_Mouse.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/input/CB_Mouse.js /** * @file Mouse and related management. Contains the {@link CB_Mouse} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage the mouse and related. It will return itself if it is tried to be instantiated. * @namespace */ var CB_Mouse = function() { return CB_Mouse; }; { CB_Mouse.initialized = false; //It will tells whether the object has been initialized or not. CB_Mouse._x = 0; //Keeps the X position of the mouse (relative to the window). CB_Mouse._y = 0; //Keeps the X position of the mouse (relative to the window). CB_Mouse._xMovement = 0; //Keeps the X movement of the mouser when its pointer is locked. CB_Mouse._yMovement = 0; //Keeps the Y movement of the mouser when its pointer is locked. CB_Mouse._buttonsDown = { LEFT : false, MIDDLE : false, RIGHT : false }; //Object with the buttons of the mouse which being pressed. CB_Mouse._isLockedNow = false; //Contains whether the mouse pointer is locked or not. CB_Mouse._isLockedPrevious = false; //Contains whether the mouse pointer was locked before or not. CB_Mouse._lockElement = null; //Contains the element that the mouse pointer is locked to (if any). //CB_Mouse._showingCursor = {}; //Tells whether the cursor is showing or not (by default is showing). /** Property that keeps an object to manage the mouse cursor using a [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} containing an image for clients that do not support changing the cursor image by CSS. &lt;br /&gt; Caution: Performance could be dramatically decreased while using this workaround. * @namespace CB_Mouse.CursorImage */ CB_Mouse.CursorImage = {}; //Keeps the cursor object. CB_Mouse.CursorImage._cursorImageDiv = null; //DIV that contains the IMG tag for the fake cursor image. CB_Mouse.CursorImage._cursorImage = null; //IMG that contains the fake cursor image. CB_Mouse.CursorImage._showCursorImage = false; //Defines whether the fake cursor image is shown or not. CB_Mouse.CursorImage._cursorImageSpriteAnimationTimeout = null; //Initializes all values: CB_Mouse.init = function() { if (CB_Mouse.initialized) { return CB_Mouse; } //The object has been initialized: CB_Mouse.initialized = true; //Adds event that updates X and Y position of the mouse when it moves (and moves the cursor image if it is necessary): CB_Events.add(document, \"mousemove\", function(e) { e = CB_Mouse.normalizeEvent(e); CB_Mouse.getX(e); CB_Mouse.getY(e); CB_Mouse.CursorImage.move(); }, true, true, false); CB_Events.add(window, \"scroll\", function() { CB_Mouse.CursorImage.move(); }, true, true, false); //Sets the event that will check if a button is down: CB_Events.add ( document, \"mousedown\", function(e) { e = CB_Mouse.normalizeEvent(e); //Uses setCapture/releaseCapture to force IE and Firefox to release mouse buttons when dragging outside the web client window: //if (typeof(document.body) !== \"undefined\" &amp;&amp; typeof(document.body.setCapture) !== \"undefined\") if (typeof(e.target) !== \"undefined\" &amp;&amp; typeof(e.target.setCapture) !== \"undefined\") { //document.body.setCapture(); e.target.setCapture(); } CB_Mouse._updateButtonsDown(e, true); }, true, true, false ); //Sets the event that will check if a button is released: CB_Events.add ( document, \"mouseup\", function(e) { e = CB_Mouse.normalizeEvent(e); //Uses setCapture/releaseCapture to force IE and Firefox to release mouse buttons when dragging outside the web client window: //if (typeof(document.body) !== \"undefined\" &amp;&amp; typeof(document.body.releaseCapture) !== \"undefined\") if (typeof(e.target) !== \"undefined\" &amp;&amp; typeof(e.target.releaseCapture) !== \"undefined\") { //document.body.releaseCapture(); e.target.releaseCapture(); } CB_Mouse._updateButtonsDown(e, false); }, true, true, false ); //Sets the event for when the lock pointer status changes: var onPointerLockChange = function() { CB_Mouse.isLocked(true); //Also updates the cache of the current lock element (if any). }; CB_Events.add(document, \"pointerlockchange\", onPointerLockChange, true, true, false); CB_Events.add(document, \"mozpointerlockchange\", onPointerLockChange, true, true, false); CB_Events.add(document, \"webkitpointerlockchange\", onPointerLockChange, true, true, false); CB_Events.add(document, \"pointerlocklost\", onPointerLockChange, true, true, false); CB_Events.add(document, \"webkitpointerlocklost\", onPointerLockChange, true, true, false); CB_Events.add(document, \"mozpointerlocklost\", onPointerLockChange, true, true, false); //Clears buttonsDown array when the mouse leaves the web client: //CB_Events.add(window, \"mouseleave\", function() { CB_Mouse._buttonsDown = { LEFT : false, MIDDLE : false, RIGHT : false }; }, true, true, false); //CB_Events.add(document, \"mouseout\", function() { CB_Mouse._buttonsDown = { LEFT : false, MIDDLE : false, RIGHT : false }; }, true, true, false); //Sets the focus to force a mousemove event and get the proper mouse coordinates (some web clients at the start don't get the proper mouse coordinates): CB_Screen.focus(); return CB_Mouse; } /** * Tries to return the given [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent} with some properties normalized (since different clients can use different values) and perhaps some new properties added (in the case they were missing), when possible. The new attached methods and properties may include polyfills, etc. It also calls the {@link CB_Events.normalize} function internally. Some properties added or affected could be [deltaX]{@link https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaX}, [deltaY]{@link https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaY}, [deltaZ]{@link https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaZ}, [force]{@link https://developer.mozilla.org/es/docs/Web/API/MouseEvent/webkitForce}, [clientX]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientX}, [clientY]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientY}, etc. * @function * @param {Event} e - [Mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent}. If not provided, it will use the value of \"event\", \"window.event\", \"Event\" or an empty object (\"{}\"). * @returns {Event} Returns the [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent} normalized. * @todo Add more properties and methods to normalize ([pageX]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageX}, [pageY]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageY}, [offsetX]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/offsetX}, [offsetY]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/offsetY}, etc.). */ CB_Mouse.normalizeEvent = function(e) { e = CB_Events.normalize(e); //If wheel event is not supported, normalizes the event: var onWheelEventName = CB_Mouse._getOnWheelEventName(); if (onWheelEventName !== \"wheel\") { if (typeof(e.type) !== \"undefined\" &amp;&amp; e.type === \"MozMousePixelScroll\") { e.deltaMode = 0; } else { e.deltaMode = 1; } if (typeof(e.deltaX) === \"undefined\") { e.deltaX = 0; } if (typeof(e.deltaZ) === \"undefined\") { e.deltaZ = 0; } if (typeof(e.deltaY) === \"undefined\") { if (onWheelEventName === \"mousewheel\" &amp;&amp; typeof(e.wheelDelta) !== \"undefined\") { e.deltaY = -(1/40 * e.wheelDelta); //e.deltaY = e.wheelDelta / -40; //e.deltaY = e.wheelDelta / 120; if (typeof(e.wheelDeltaX) !== \"undefined\") { event.deltaX = -(1/40 * e.wheelDeltaX); } } else if (typeof(e.detail) !== \"undefined\") { e.deltaY = e.detail; //e.deltaY = -40 * e.detail; //e.deltaY = e.detail * -120; //e.deltaY = -e.detail / 3; } else { e.deltaY = 0; } } } //Normalizes the force property (if any): if (typeof(e.force) === \"undefined\" || e.force === null || isNaN(e.force)) { if (typeof(e.webkitForce) !== \"undefined\" &amp;&amp; e.webkitForce !== null &amp;&amp; !isNaN(e.webkitForce)) { e.force = e.webkitForce; } else if (CB_Touch._force !== null) { e.force = CB_Touch._force; } //Uses force detected by Pressure.js. } if (!e.forceNormalized) { e.force = CB_Touch.normalizeForce(e.force); } e.forceNormalized = true; //TODO: add more properties and methods to normalize (pageX, pageY, offsetX, offsetY, ). //Normalize other properties: //* Source: http://www.jacklmoore.com/notes/mouse-position/ if (typeof(e.clientX) === \"undefined\" &amp;&amp; typeof(e.pageX) !== \"undefined\") { e.clientX = e.pageX; } if (typeof(e.clientY) === \"undefined\" &amp;&amp; typeof(e.pageY) !== \"undefined\") { e.clientY = e.pageY; } if (document.body &amp;&amp; document.documentElement) { if (typeof(e.pageX) === \"undefined\" &amp;&amp; typeof(e.clientX) !== \"undefined\") { if (typeof(document.body.scrollLeft) !== \"undefined\" &amp;&amp; typeof(document.documentElement.scrollLeft) !== \"undefined\") { e.pageX = e.clientX + (document.body.scrollLeft) + document.documentElement.scrollLeft; } else if (typeof(document.body.scrollWidth) !== \"undefined\" &amp;&amp; typeof(document.documentElement.scrollWidth) !== \"undefined\") { e.pageX = e.clientX + (document.body.scrollWidth) + document.documentElement.scrollWidth; } } if (typeof(e.pageY) === \"undefined\" &amp;&amp; typeof(e.clientY) !== \"undefined\") { if (typeof(document.body.scrollTop) !== \"undefined\" &amp;&amp; typeof(document.documentElement.scrollTop) !== \"undefined\") { e.pageY = e.clientY + (document.body.scrollTop) + document.documentElement.scrollTop; } else if (typeof(document.body.scrollHeight) !== \"undefined\" &amp;&amp; typeof(document.documentElement.scrollHeight) !== \"undefined\") { e.pageY = e.clientY + (document.body.scrollHeight) + document.documentElement.scrollHeight; } } } try { var targetStyle = CB_Elements.getStyle(e.target, true); } catch(E) {} if (targetStyle !== null &amp;&amp; typeof(e.clientX) !== \"undefined\" &amp;&amp; e.clientX !== null &amp;&amp; typeof(e.clientY) !== \"undefined\" &amp;&amp; e.clientY !== null) { try { e.offsetX = e.clientX - parseInt(targetStyle['borderLeftWidth'], 10) - CB_Client.getBoundingClientRectMargin(\"left\"); e.offsetY = e.clientY - parseInt(targetStyle['borderTopWidth'], 10) - CB_Client.getBoundingClientRectMargin(\"top\"); } catch(E) {} } return e; } CB_Mouse._getOnWheelEventNameReturnCache = null; CB_Mouse._getOnWheelEventName = function() { if (typeof(CB_Mouse._getOnWheelEventNameReturnCache) === \"undefined\" || CB_Mouse._getOnWheelEventNameReturnCache === null) { CB_Mouse._getOnWheelEventNameReturnCache = (\"onwheel\" in document.createElement(\"div\")) ? \"wheel\" : //\"wheel\" supported. (typeof(document.onmousewheel) !== \"undefined\") ? \"mousewheel\" : //\"onmousewheel\" supported. \"DOMMouseScroll\"; //assumes \"DOMMouseScroll\" support. } return CB_Mouse._getOnWheelEventNameReturnCache; } //Returns which button is down given a mouse event: CB_Mouse._updateButtonsDown = function(e, buttonDown) { e = CB_Mouse.normalizeEvent(e); var buttonsDown = CB_Mouse._buttonsDown; if (e.which) { if (e.which === 1) { buttonsDown.LEFT = buttonDown; } else if (CB_Client.getBrowser() === \"Opera\" &amp;&amp; CB_Client.getBrowserVersionMain() &lt; 8) { if (e.which === 2) { buttonsDown.RIGHT = buttonDown; } else if (e.which === 3) { buttonsDown.MIDDLE = buttonDown; } } else { if (e.which === 2) { buttonsDown.MIDDLE = buttonDown; } else if (e.which === 3) { buttonsDown.RIGHT = buttonDown; } } } else if (e.button) { if (CB_Client.getBrowser() === \"Explorer\") { //TODO: think about performing bitwise operations. if (e.button === 1) { buttonsDown.LEFT = buttonDown; } else if (e.button === 2) { buttonsDown.RIGHT = buttonDown; } else if (e.button === 3) { buttonsDown.LEFT = buttonsDown.RIGHT = buttonDown; } else if (e.button === 4) { buttonsDown.MIDDLE = buttonDown; } else if (e.button === 5) { buttonsDown.LEFT = buttonsDown.MIDDLE = buttonDown; } else if (e.button === 6) { buttonsDown.RIGHT = buttonsDown.MIDDLE = buttonDown; } else if (e.button === 7) { buttonsDown.LEFT = buttonsDown.RIGHT = buttonsDown.MIDDLE = buttonDown; } //else if (e.button === 0) { buttonsDown.LEFT = buttonsDown.RIGHT = buttonsDown.MIDDLE = false; } } else { if (e.button === 0) { buttonsDown.LEFT = buttonDown; } else if (e.button === 1) { buttonsDown.MIDDLE = buttonDown; } else if (e.button === 2) { buttonsDown.RIGHT = buttonDown; } } } CB_Mouse._buttonsDown = buttonsDown; } /** * Alias for {@link CB_Client.getButtons}. * @function CB_Client.getButtonsDown * @see {@link CB_Client.getButtons} */ /** * Tells what mouse buttons are down (LEFT, MIDDLE and/or RIGHT buttons). * @function * @returns {Object} Returns an object using the following format (where \"true\" means that the button is being pressed): { LEFT : boolean, MIDDLE : boolean, RIGHT : boolean } */ CB_Mouse.getButtons = CB_Mouse.getButtonsDown = function() { return CB_Mouse._buttonsDown; } /** * Gets and returns the X coordinate (horizontal position) of the mouse (relative to the window in desktop) in pixels. * @function * @param {Event} [e] - [Mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent}. If not provided, the returning value will use the previously-cached value (updated the last time that the [onMouseMove]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event} event was fired). * @param {boolean} [ignoreScroll=false] - If set to true, the horizontal scroll position will not be added to the returning value. * @param {boolean} [ignoreLock=false] - If set to true, it will ignore whether the cursor is being locked or not. Otherwise, if set to false and the cursor is locked, the returning value will only have in mind the position in the locking element. * @returns {number} Returns the X coordinate (horizontal position) of the mouse (relative to the window in desktop) in pixels. */ CB_Mouse.getX = function(e, ignoreScroll, ignoreLock) { //If this function has not been called from an event, we return stored values: if (!e) { if (CB_Mouse.isLocked(false) &amp;&amp; !ignoreLock) { return CB_Mouse.getXMovement(e); } else { if (ignoreScroll) { return CB_Mouse._x; } else { return CB_Mouse._x + CB_Screen.getScrollLeft(); } } } var mouseX = 0; //If it is compatible with the W3C draft: if (typeof(e.x) !== \"undefined\") { mouseX = e.x; } //...otherwise, if we are using Internet Explorer: else if (typeof(e.clientX) !== \"undefined\") { mouseX = e.clientX;// + document.body.scrollLeft; } //...otherwise we don't use Internet Explorer: else if (typeof(e.pageX) !== \"undefined\") { //document.captureEvents(Event.MOUSEMOVE); mouseX = e.pageX; } //If the coordinate is lower than zero, it should be zero: if (mouseX &lt; 0) { mouseX = 0; } //We set the value for the property of the class: CB_Mouse._x = mouseX; //Updates the mose movement (useful when the mouse pointer is locked): CB_Mouse._xMovement = CB_Mouse.getXMovement(e); //If the mouse pointer is locked and we do not want to ignore it: if (CB_Mouse.isLocked(false) &amp;&amp; !ignoreLock) { return CB_Mouse._xMovement; } //...otherwise, returns the normal position instead of the movement: else { if (ignoreScroll) { return CB_Mouse._x; } else { return CB_Mouse._x + CB_Screen.getScrollLeft(); } } } /** * Gets and returns the Y coordinate (vertical position) of the mouse (relative to the window in desktop) in pixels. * @function * @param {Event} [e] - [Mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent}. If not provided, the returning value will use the previously-cached value (updated the last time that the [onMouseMove]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event} event was fired). * @param {boolean} [ignoreScroll=false] - If set to true, the vertical scroll position will not be added to the returning value. * @param {boolean} [ignoreLock=false] - If set to true, it will ignore whether the cursor is being locked or not. Otherwise, if set to false and the cursor is locked, the returning value will only have in mind the position in the locking element. * @returns {number} Returns the Y coordinate (vertical position) of the mouse (relative to the window in desktop) in pixels. */ CB_Mouse.getY = function(e, ignoreScroll, ignoreLock) { //If this function has not been called from an event, we return stored values: if (!e) { if (CB_Mouse.isLocked(false) &amp;&amp; !ignoreLock) { return CB_Mouse.getYMovement(e); } else { if (ignoreScroll) { return CB_Mouse._y; } else { return CB_Mouse._y + CB_Screen.getScrollTop(); } } } var mouseY = 0; //If it is compatible with the W3C draft: if (typeof(e.y) !== \"undefined\") { mouseY = e.y; } //...otherwise, if we are using Internet Explorer: else if (typeof(e.clientY) !== \"undefined\") { mouseY = e.clientY;// + document.body.scrollTop; } //...otherwise we don't use Internet Explorer: else if (typeof(e.pageY) !== \"undefined\") { //document.captureEvents(Event.MOUSEMOVE); mouseY = e.pageY; } //If the coordinate is lower than zero, it should be zero: if (mouseY &lt; 0) { mouseY = 0; } //We set the value for the property of the class: CB_Mouse._y = mouseY; //Updates the mose movement (useful when the mouse pointer is locked): CB_Mouse._yMovement = CB_Mouse.getYMovement(e); //If the mouse pointer is locked and we do not want to ignore it: if (CB_Mouse.isLocked(false) &amp;&amp; !ignoreLock) { return CB_Mouse._yMovement; } //...otherwise, returns the normal position instead of the movement: else { if (ignoreScroll) { return CB_Mouse._y; } else { return CB_Mouse._y + CB_Screen.getScrollTop(); } } } /** * Gets and returns the current X coordinate (horizontal position) in pixels of the mouse relative to a given X position. The returning value uses the previously-cached value (updated the last time that the [onMouseMove]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event} event was fired). * @function * @param {number} x - The X coordinate (horizontal position) in pixels. The returning value will be calculated relatively to it. * @param {boolean} [ignoreScroll=false] - If set to true, the horizontal scroll position will not be added to the returning value. * @returns {number} Returns the current X coordinate (horizontal position) in pixels of the mouse relative to a given X position. * @todo Think about allowing to define an \"e\" parameter with the [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent}. */ CB_Mouse.getXRelative = function(x, ignoreScroll) { //Gets the X position of the mouse: var mouseX = CB_Mouse.getX(null, ignoreScroll); if (ignoreScroll) { x -= CB_Screen.getScrollLeft(); } var mouseRelativeX = mouseX - x; return mouseRelativeX; } /** * Gets and returns the current Y coordinate (vertical position) in pixels of the mouse relative to a given Y position. The returning value uses the previously-cached value (updated the last time that the [onMouseMove]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event} event was fired). * @function * @param {number} y - The Y coordinate (vertical position) in pixels. The returning value will be calculated relatively to it. * @param {boolean} [ignoreScroll=false] - If set to true, the vertical scroll position will not be added to the returning value. * @returns {number} Returns the current Y coordinate (vertical position) in pixels of the mouse relative to a given Y position. * @todo Think about allowing to define an \"e\" parameter with the [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent}. */ CB_Mouse.getYRelative = function(y, ignoreScroll) { //Gets the Y position of the mouse: var mouseY = CB_Mouse.getY(null, ignoreScroll); if (ignoreScroll) { y -= CB_Screen.getScrollTop(); } var mouseRelativeY = mouseY - y; return mouseRelativeY; } /** * Returns the current X (horizontal) movement (useful when the mouse pointer is locked) in pixels. More information: [MouseEvent.movementX]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementX}. * @function * @param {Event} [e] - [Mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent}. If not provided, the returning value will use the previously-cached value (updated the last time that the [onMouseMove]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event} event was fired). * @returns {number} Returns the current X (horizontal) movement (useful when the mouse pointer is locked) in pixels. */ CB_Mouse.getXMovement = function(e) { //If this function has been called from an event, updates the current values: if (e) { CB_Mouse._xMovement = e.movementX || e.mozMovementX || e.webkitMovementX || 0; } return CB_Mouse._xMovement; } /** * Returns the current Y (vertical) movement (useful when the mouse pointer is locked) in pixels. More information: [MouseEvent.movementY]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementY}. * @function * @param {Event} [e] - [Mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent}. If not provided, the returning value will use the previously-cached value (updated the last time that the [onMouseMove]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event} event was fired). * @returns {number} Returns the current Y (vertical) movement (useful when the mouse pointer is locked) in pixels. */ CB_Mouse.getYMovement = function(e) { //If this function has been called from an event, updates the current values: if (e) { CB_Mouse._yMovement = e.movementY || e.mozMovementY || e.webkitMovementY || 0; } return CB_Mouse._yMovement; } /** * Sets a function to execute when a click happens ([onMouseMove]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event} event) or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent} (already normalized by the {@link CB_Mouse.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Mouse.onMove = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Mouse._setEvent(\"mousemove\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when a click happens ([onClick]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event} event) or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent} (already normalized by the {@link CB_Mouse.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Mouse.onClick = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Mouse._setEvent(\"click\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when a click happens ([onDblClick]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event} event) or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent} (already normalized by the {@link CB_Mouse.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Mouse.onDblClick = CB_Mouse.onDoubleClick = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Mouse._setEvent(\"dblclick\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when a mouse button is down ([onMouseDown]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/mousedown_event} event) or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent} (already normalized by the {@link CB_Mouse.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Mouse.onButtonDown = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Mouse._setEvent(\"mousedown\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when a mouse button is up ([onMouseUp]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseup_event} event) or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent} (already normalized by the {@link CB_Mouse.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Mouse.onButtonUp = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Mouse._setEvent(\"mouseup\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when a mouse leaves a [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} ([onMouseLeave]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseleave_event} event) or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent} (already normalized by the {@link CB_Mouse.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=window] - The target where we want to attach the event listener. */ CB_Mouse.onLeave = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Mouse._setEvent(\"mouseleave\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when a mouse is over a [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} ([onMouseOver]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseover_event} event) or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent} (already normalized by the {@link CB_Mouse.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Mouse.onOver = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Mouse._setEvent(\"mouseover\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when a mouse gets out of a [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} ([onMouseOut]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseout_event} event) or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent} (already normalized by the {@link CB_Mouse.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Mouse.onOut = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Mouse._setEvent(\"mouseout\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when the mouse wheel is used ([onWheel]{@link https://developer.mozilla.org/en-US/docs/Web/Events/wheel}, [onMouseWheel]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/mousewheel_event} or [DOMMouseScroll]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/DOMMouseScroll_event} event) or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent} (already normalized by the {@link CB_Mouse.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Mouse.onWheel = function(callbackFunction, keepOldFunction, useCapture, target) { var onWheelEventName = CB_Mouse._getOnWheelEventName(); var valueToReturn = CB_Mouse._setEvent(onWheelEventName, callbackFunction, keepOldFunction, useCapture, target); //If DOMMouseScroll is detected, adds MozMousePixelScroll event for older Firefox versions: if (onWheelEventName === \"DOMMouseScroll\") { valueToReturn = CB_Mouse._setEvent(\"MozMousePixelScroll\", callbackFunction, keepOldFunction, useCapture, target); } return valueToReturn; } CB_Mouse.isLockSupportedReturnCache = null; /** * Tells whether mouse pointer lock is supported or not. More information: [Pointer Lock API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API}. * @function * @returns {boolean} Returns whether mouse pointer lock is supported or not. */ CB_Mouse.isLockSupported = function() { if (CB_Mouse.isLockSupportedReturnCache === null) { CB_Mouse.isLockSupportedReturnCache = \"pointerLockElement\" in document || \"mozPointerLockElement\" in document || \"webkitPointerLockElement\" in document || (navigator &amp;&amp; (navigator.pointer || navigator.webkitPointer || navigator.mozPointer)); } return CB_Mouse.isLockSupportedReturnCache; } /** * Tells whether the mouse pointer is locked or not. More information: [Pointer Lock API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API}. * @function * @param {boolean} [avoidCache=false] - Used as the parameter to call the {@link CB_Mouse.getLockElement} function internally. * @returns {boolean} Returns whether the mouse pointer is locked or not. */ CB_Mouse.isLocked = function(avoidCache) { CB_Mouse._isLockedPrevious = CB_Mouse._isLockedNow; var isLockedNow = (CB_Mouse.getLockElement(avoidCache) !== null); if (!isLockedNow &amp;&amp; navigator) { navigator.pointer = navigator.pointer || navigator.webkitPointer || navigator.mozPointer; if (navigator.pointer) { if (typeof(navigator.pointer.isLocked) === \"function\") { isLockedNow = navigator.pointer.isLocked(); } else if (typeof(navigator.pointer.islocked) === \"function\") { isLockedNow = navigator.pointer.islocked(); } else if (typeof(navigator.pointer.isLocked) !== \"undefined\") { isLockedNow = navigator.pointer.isLocked; } } } CB_Mouse._isLockedNow = isLockedNow; return CB_Mouse._isLockedNow; } /** * Tells whether the mouse pointer was locked before or not when the {@link CB_Mouse.isLocked} function was called the last time. More information: [Pointer Lock API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API}. * @function * @returns {boolean} Returns whether the mouse pointer was locked before or not when the {@link CB_Mouse.isLocked} function was called the last time. */ CB_Mouse.wasLocked = function() { return CB_Mouse._isLockedPrevious; } /** * Gets the lock element for the mouse pointer (if any) or null otherwise. More information: [Pointer Lock API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API}. * @function * @param {boolean} [avoidCache=false] - If set to false, the returning value will use the previously-cached value (updated when this function is called with this parameter set to true or the [onPointerLockChange]{@link https://developer.mozilla.org/en-US/docs/Web/API/Document/pointerlockchange_event} or analog event is fired or when the {@link CB_Mouse.lock} or {@link CB_Mouse.unlock} functions are called successfully). * @returns {Element|null} Returns the lock element for the mouse pointer (if any) or null otherwise. */ CB_Mouse.getLockElement = function(avoidCache) { if (avoidCache) { if (typeof(document.pointerLockElement) !== \"undefined\" &amp;&amp; document.pointerLockElement !== null) { CB_Mouse._lockElement = document.pointerLockElement; } else if (typeof(document.mozPointerLockElement) !== \"undefined\" &amp;&amp; document.mozPointerLockElement !== null) { CB_Mouse._lockElement = document.mozPointerLockElement; } else if (typeof(document.webkitPointerLockElement) !== \"undefined\" &amp;&amp; document.webkitPointerLockElement !== null) { CB_Mouse._lockElement = document.webkitPointerLockElement; } else { CB_Mouse._lockElement = null; } return CB_Mouse._lockElement; } else { return CB_Mouse._lockElement; } } /** * Locks the mouse pointer (if possible). More information: [Pointer Lock API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API}. * @function * @param {Element} [target=document.body] - The [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} that the mouse pointer will be locked to. * @param {function} callbackOk - Function callback that will be called (without parameters) if the mouse pointer could be locked successfully. * @param {function} callbackError - Function callback that will be called (without parameters) if the mouse pointer could not be locked successfully. * @returns {Element|null} Returns the current lock element for the mouse pointer (if any) or null otherwise. */ CB_Mouse.lock = function(target, callbackOk, callbackError) { if (typeof(target) === \"undefined\" || target === null) { target = document.body; } if (typeof(target) !== \"undefined\" &amp;&amp; target !== null) { target.requestPointerLock = target.requestPointerLock || target.mozRequestPointerLock || target.webkitRequestPointerLock; if (typeof(target.requestPointerLock) === \"function\") { target.requestPointerLock(); if (CB_Mouse.isLocked(true)) //Also updates CB_Mouse.isLocked cache. { if (typeof(callbackOk) === \"function\") { callbackOk(); } } else if (typeof(callbackError) === \"function\") { callbackError(); } return CB_Mouse.getLockElement(true); } else if (navigator) { navigator.pointer = navigator.pointer || navigator.webkitPointer || navigator.mozPointer; if (navigator.pointer &amp;&amp; typeof(navigator.pointer.lock) === \"function\") { navigator.pointer.lock(target, callbackOk, callbackError); CB_Mouse.isLocked(true); //Updates CB_Mouse.isLocked cache. return CB_Mouse.getLockElement(true); } } } if (typeof(callbackError) === \"function\") { callbackError(); } CB_Mouse.isLocked(true); //Updates CB_Mouse.isLocked cache. return null; } /** * Unlocks the mouse pointer (if possible). More information: [Pointer Lock API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API}. * @function * @returns {boolean} Returns true if the mouse pointer has been unlocked or false otherwise. */ CB_Mouse.unlock = function() { document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; if (typeof(document.exitPointerLock) === \"function\") { document.exitPointerLock(); } else if (navigator) { navigator.pointer = navigator.pointer || navigator.webkitPointer || navigator.mozPointer; if (navigator.pointer &amp;&amp; typeof(navigator.pointer.unlock) === \"function\") { navigator.pointer.unlock(); } } return (!CB_Mouse.isLocked(true)); } /** * Sets a function to execute when the mouse pointer lock functionality changes its state (it has been either locked or unlocked, using [pointerlockchange]{@link [onPointerLockChange]{@link https://developer.mozilla.org/en-US/docs/Web/API/Document/pointerlockchange_event}}, [mozpointerlockchange]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API} or [webkitpointerlockchange]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API} event) or removes it. More information: [Pointer Lock API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent} (already normalized by the {@link CB_Mouse.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. */ CB_Mouse.onLockChange = function(callbackFunction, keepOldFunction, useCapture) { CB_Mouse._setEvent(\"pointerlockchange\", callbackFunction, keepOldFunction, useCapture, document); CB_Mouse._setEvent(\"mozpointerlockchange\", callbackFunction, keepOldFunction, useCapture, document); CB_Mouse._setEvent(\"webkitpointerlockchange\", callbackFunction, keepOldFunction, useCapture, document); } /** * Sets a function to execute when the mouse pointer fails to either lock or unlock (using [pointerlockerror]{@link https://developer.mozilla.org/en-US/docs/Web/API/Document/pointerlockerror_event}, [mozpointerlockerror]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API} or [webkitpointerlockerror]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API} event) or removes it. More information: [Pointer Lock API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the [mouse event object]{@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent} (already normalized by the {@link CB_Mouse.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. */ CB_Mouse.onLockError = function(callbackFunction, keepOldFunction, useCapture) { CB_Mouse._setEvent(\"pointerlockerror\", callbackFunction, keepOldFunction, useCapture, document); CB_Mouse._setEvent(\"mozpointerlockerror\", callbackFunction, keepOldFunction, useCapture, document); CB_Mouse._setEvent(\"webkitpointerlockerror\", callbackFunction, keepOldFunction, useCapture, document); } //Sets a function to execute when a desired event is fired: CB_Mouse._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture, target) { //If they are not set, use default values for optional parameters: if (typeof(keepOldFunction) === \"undefined\" || keepOldFunction === null) { keepOldFunction = true; } //If not set, it keeps old function by default. if (typeof(target) === \"undefined\" || target === null) { if (eventName === \"mouseleave\") { target = window; } else { target = document; } } //If a function has been sent: if (typeof(eventFunction) === \"function\") { //If able, adds the function given to the event: CB_Events.add ( target, eventName, function(e) { e = CB_Mouse.normalizeEvent(e); CB_Mouse.getX(e); //Updates mouse X position. CB_Mouse.getY(e); //Updates mouse Y position. if (eventName === \"mousedown\" || eventName === \"mouseup\") { CB_Mouse._updateButtonsDown(e, (eventName === \"mousedown\")); //Updates buttons down. } if (typeof(eventFunction) === \"function\") { return eventFunction(e); } return true; }, useCapture, keepOldFunction, true ); } //...but if the function given is null, it will cancel the event: else if (eventFunction === null) { CB_Events.removeByName(target, eventName); } } /** * Tells whether the mouse is over a given [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} or not. * @function * @param {Element} element - The [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} where we want to know whether the mouse is over or not. * @returns {boolean} Returns whether the mouse is over the given [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} or not. */ CB_Mouse.isOverElement = function(element) { return CB_Collisions.isPointOverElement(CB_Mouse.getX(), CB_Mouse.getY(), element); } /** * Tells whether the mouse is over a given line (infinite line) or not. * @function * @param {number} lineX1 - The X coordinate (horizontal position) of the first pixel of the line. * @param {number} lineY1 - The Y coordinate (vertical position) of the first pixel of the line. * @param {number} lineX2 - The X coordinate (horizontal position) of the second pixel of the line. * @param {number} lineY2 - The Y coordinate (vertical position) of the second pixel of the line. * @param {number} [tolerance=1] - The amount of loss of precision we can tolerate to consider a collision. * @param {Element} [element] - If a [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} is given, the mouse coordinates will be calculated relatively to the position of this [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement}. * @returns {boolean} Returns whether the mouse is over the given line (infinite line) or not. * @todo Think about using a \"width\" parameter (apart from the \"tolerance\" parameter). */ CB_Mouse.isOverLine = function(lineX1, lineY1, lineX2, lineY2, tolerance, element) { if (typeof(tolerance) === \"undefined\" || tolerance === null) { tolerance = 1; } if (typeof(element) !== \"undefined\" &amp;&amp; element !== null) { var mouseX = CB_Mouse.getXRelative(CB_Elements.getLeft(element)); var mouseY = CB_Mouse.getYRelative(CB_Elements.getTop(element)); } else { var mouseX = CB_Mouse.getX(); var mouseY = CB_Mouse.getY(); } return CB_Collisions.isPointOverLine(mouseX, mouseY, lineX1, lineY1, lineX2, lineY2, tolerance); } /** * Tells whether the mouse is over a given line segment or not. * @function * @param {number} lineX1 - The X coordinate (horizontal position) of the first pixel of the line segment. * @param {number} lineY1 - The Y coordinate (vertical position) of the first pixel of the line segment. * @param {number} lineX2 - The X coordinate (horizontal position) of the second pixel of the line segment. * @param {number} lineY2 - The Y coordinate (vertical position) of the second pixel of the line segment. * @param {number} [tolerance=1] - The amount of loss of precision we can tolerate to consider a collision. * @param {Element} [element] - If a [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} is given, the mouse coordinates will be calculated relatively to the position of this [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement}. * @returns {boolean} Returns whether the mouse is over the given line segment or not. * @todo Think about using a \"width\" parameter (apart from the \"tolerance\" parameter). */ CB_Mouse.isOverSegment = function(lineX1, lineY1, lineX2, lineY2, tolerance, element) { if (typeof(tolerance) === \"undefined\" || tolerance === null) { tolerance = 1; } if (typeof(element) !== \"undefined\" &amp;&amp; element !== null) { var mouseX = CB_Mouse.getXRelative(CB_Elements.getLeft(element)); var mouseY = CB_Mouse.getYRelative(CB_Elements.getTop(element)); } else { var mouseX = CB_Mouse.getX(); var mouseY = CB_Mouse.getY(); } return CB_Collisions.isPointOverSegment(mouseX, mouseY, lineX1, lineY1, lineX2, lineY2, tolerance); } /** * Tells whether the mouse is over a given rectangle or not. * @function * @param {number} rectangleX - The X coordinate (horizontal position) of the first pixel of the rectangle (upper left corner). * @param {number} rectangleY - The Y coordinate (vertical position) of the first pixel of the rectangle (upper left corner). * @param {number} rectangleWidth - The width of the rectangle in pixels. * @param {number} rectangleHeight - The height of the rectangle in pixels. * @param {Element} [element] - If a [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} is given, the mouse coordinates will be calculated relatively to the position of this [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement}. * @returns {boolean} Returns whether the mouse is over the given rectangle or not. */ CB_Mouse.isOverRectangle = function(rectangleX, rectangleY, rectangleWidth, rectangleHeight, element) { if (typeof(element) !== \"undefined\" &amp;&amp; element !== null) { var mouseX = CB_Mouse.getXRelative(CB_Elements.getLeft(element)); var mouseY = CB_Mouse.getYRelative(CB_Elements.getTop(element)); } else { var mouseX = CB_Mouse.getX(); var mouseY = CB_Mouse.getY(); } return CB_Collisions.isPointOverRectangle(mouseX, mouseY, rectangleX, rectangleY, rectangleWidth, rectangleHeight); } /** * Tells whether the mouse is over a given circle or not. * @function * @param {number} centreX - The X coordinate (horizontal position) of the center of the circle in pixels. * @param {number} centreY - The Y coordinate (vertical position) of the center of the circle in pixels. * @param {number} radius - The radius of the circle in pixels. * @param {Element} [element] - If a [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} is given, the mouse coordinates will be calculated relatively to the position of this [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement}. * @returns {boolean} Returns whether the mouse is over the given circle or not. */ CB_Mouse.isOverCircle = function(centreX, centreY, radius, element) { if (typeof(element) !== \"undefined\" &amp;&amp; element !== null) { mouseX = CB_Mouse.getXRelative(CB_Elements.getLeft(element)); mouseY = CB_Mouse.getYRelative(CB_Elements.getTop(element)); } else { var mouseX = CB_Mouse.getX(); var mouseY = CB_Mouse.getY(); } return CB_Collisions.isPointOverCircle(mouseX, mouseY, centreX, centreY, radius); } /** * Tells whether the mouse is over a given ellipse or not. * @function * @param {number} centreX - The \"X\" coordinate of the center of the ellipse. * @param {number} centreY - The \"Y\" coordinate of the center of the ellipse. * @param {number} radiusX - The X (horizontal) radius of the ellipse. * @param {number} radiusY - The Y (vertical) radius of the ellipse. * @param {number} [rotation=0] - The ellipse rotation. The value given will be considered either degrees or radians depending on the given \"rotationUseDegrees\" parameter (by default, it is considered radians). Not implemented yet! * @param {boolean} [rotationUseDegrees=false] - Defines whether the \"rotation\" given should be considered degrees or not (radians). Not implemented yet! * @returns {boolean} Returns whether the mouse is over the given ellipse or not. */ CB_Mouse.isOverEllipse = function(centreX, centreY, radiusX, radiusY, rotation, rotationUseDegrees, radius, element) { if (typeof(element) !== \"undefined\" &amp;&amp; element !== null) { mouseX = CB_Mouse.getXRelative(CB_Elements.getLeft(element)); mouseY = CB_Mouse.getYRelative(CB_Elements.getTop(element)); } else { var mouseX = CB_Mouse.getX(); var mouseY = CB_Mouse.getY(); } return CB_Collisions.isPointOverEllipse(mouseX, mouseY, centreX, centreY, radiusX, radiusY, rotation, rotationUseDegrees, radius); } /** * Hides the mouse cursor in a given [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} by changing its internal CSS code of the [style.cursor]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/cursor} property. * @function * @param {Element} [element=document.body] - If a [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} is given, the mouse cursor will be hidden when it is over this [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement}. Otherwise, it will be hidden in the whole document (using [document.body]{@link https://developer.mozilla.org/en-US/docs/Web/API/Document/body} as element). * @param {boolean} [recursive=true] - If it is set to true, all the child [DOM elements]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} will also be affected. * @todo Check whether the path used in the \"url\" is right or not (now it uses the {@link CB_scriptPath} variable). */ CB_Mouse.hide = function(element, recursive) { var CSS = \"url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAFBhaW50Lk5FVCB2My41LjbQg61aAAAADUlEQVQYV2P4//8/IwAI/QL/+TZZdwAAAABJRU5ErkJggg=='), url(\" + CB_scriptPath + CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"input/cursors/almost_blank.png), url(\" + CB_scriptPath + CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"input/cursors/blank.gif), url(\" + CB_scriptPath + CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"input/cursors/blank.cur), none\"; if (CB_Client.getBrowser() === \"Explorer\") { CSS = \"url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAFBhaW50Lk5FVCB2My41LjbQg61aAAAADUlEQVQYV2P4//8/IwAI/QL/+TZZdwAAAABJRU5ErkJggg=='), url(\" + CB_scriptPath + CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"input/cursors/blank.cur), url(\" + CB_scriptPath + CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"input/cursors/blank.gif), url(\" + CB_scriptPath + CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"input/cursors/almost_blank.png), none\"; } CB_Mouse.setCSS(CSS, element, recursive); //CB_Mouse._showingCursor[element||document.body] = false; } /** * Restores (unhides) the mouse cursor in a given [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} by changing its internal CSS code of the [style.cursor]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/cursor} property to the default one (using \"default\" as the CSS code). * @function * @param {Element} [element=document.body] - If a [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} is given, the mouse cursor will be restored (unhidden) when it is over this [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement}. Otherwise, it will be restored (unhidden) in the whole document (using [document.body]{@link https://developer.mozilla.org/en-US/docs/Web/API/Document/body} as the \"element\"). * @param {boolean} [recursive=true] - If it is set to true, all the child [DOM elements]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} will also be affected. */ CB_Mouse.restore = function(element, recursive) { var CSS = \"default\"; CB_Mouse.setCSS(CSS, element, recursive); //CB_Mouse._showingCursor[element||document.body] = true; } /* CB_Mouse.isShowing = function(element) { return CB_Mouse._showingCursor[element||document.body]; } */ /** * Sets the desired CSS code for the [style.cursor]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/cursor} property of the given [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement}. * @function * @param {string} [CSS=\"\"] - CSS code for the [style.cursor]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/cursor} property of the given [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement}. If not given, an empty string will be used. * @param {Element} [element=document.body] - If a [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} is given, the CSS code updated will affect the given [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement}. Otherwise, it will affect the whole document (using [document.body]{@link https://developer.mozilla.org/en-US/docs/Web/API/Document/body} as the \"element\"). * @param {boolean} [recursive=true] - If it is set to true, all the child [DOM elements]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} will also be affected. */ CB_Mouse.setCSS = function(CSS, element, recursive) { //If they are not set, use default values for optional parameters: if (typeof(CSS) === \"undefined\" || CSS === null) { CSS = \"\"; } if (typeof(element) === \"undefined\" || element === null) { element = document.body; } if (typeof(recursive) === \"undefined\" || recursive === null) { recursive = true; } //It is recursive by default. //Sets the CSS style for the given element: if (typeof(element) !== \"undefined\" &amp;&amp; element !== null &amp;&amp; typeof(element.style) !== \"undefined\" &amp;&amp; element.style !== null) { element.style.cursor = CSS; } //If it is recursive, it affects the children of the given element: if (recursive) { var elementsChildren = element.childNodes; var elementsChildrenLength = elementsChildren.length; for (var x = 0; x &lt; elementsChildrenLength; x++) { CB_Mouse.setCSS(CSS, elementsChildren[x], true); } } } /** * Uses an [IMG element]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img} inside a [DIV element]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div} (fakes the cursor) to simulate the mouse cursor (following its movements). If it was already called before and a fake cursor is already being used, the {@link CB_Mouse.CursorImage.hide} function must be called before in order to start using a different fake cursor image. &lt;br /&gt; Caution: Performance could be dramatically decreased while using this workaround. * @function * @param {boolean} [showCursorImage=true] - If set to true and a valid cursor image is given, the fake cursor functionality will be used. Otherwise, the fake cursor will stop being used. * @param {string} [cursorImage] - If a valid image path is given and \"showCursorImage\" is set to true, the fake cursor functionality will be used with the given image. Otherwise, the fake cursor will stop being used. * @param {number} [cursorImageWidth=32] - Width in pixels of the cursor image. * @param {number} [cursorImageHeight=32] - Height in pixels of the cursor image. * @param {boolean} [hideNormalCursor=true] - If set to true, hides the system cursor (calls the {@link CB_Mouse.hide} function internally). Otherwise, shows the system cursor (calls the {@link CB_Mouse.restore} function internally). * @param {boolean} [isSprite=false] - Defines whether the cursor will be animated (using sprites) or not. If so, the cursorImage must be an image containing sprites horizontally (their individual width is defined by the \"cursorImageWidth\" parameter). Once the last sprite is reached, it returns to the first one automatically and continues to the next one again (without stopping). * @param {number} [numberOfFrames=1] - Number of frames (sprites) being used from the cursor image (\"cursorImage\" parameter). Used when the \"isSprite\" parameter is set to true. * @param {number} [framesMs=100] - Number of milliseconds between each frame (between one sprite and next one). Used when the \"isSprite\" parameter is set to true. * @param {Element} [divElement=CB_Elements.id('CB_fakeCursorImageDiv')] - The ID of the [DIV element]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div} that will contain the image of the fake cursor (uses a [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} with \"CB_fakeCursorImageDiv\" ID by default). * @param {Element} [imageElement=CB_Elements.id('CB_fakeCursorImage')] - The ID of the [IMG element]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img} that will contain the fake cursor (uses a [DOM element]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement} with \"CB_fakeCursorImage\" ID by default). * @todo Allow defining an \"onMove\" parameter (a callback) to be able to call the \"move\" method with non-default parameters, etc. */ CB_Mouse.CursorImage.set = function(showCursorImage, cursorImage, cursorImageWidth, cursorImageHeight, hideNormalCursor, isSprite, numberOfFrames, framesMs, divElement, imageElement) { //If they are not set, use default values for optional parameters: if (typeof(showCursorImage) === \"undefined\" || showCursorImage === null) { showCursorImage = true; } //Shows the image by default. if (typeof(hideNormalCursor) === \"undefined\" || hideNormalCursor === null) { hideNormalCursor = true; } //Hides the cursor by default (unless we want to hide the image). if (typeof(cursorImageWidth) === \"undefined\" || cursorImageWidth === null) { cursorImageWidth = 32; } //If not set, uses the default width. if (typeof(cursorImageHeight) === \"undefined\" || cursorImageHeight === null) { cursorImageHeight = 32; } //If not set, uses the default height. if (typeof(numberOfFrames) === \"undefined\" || numberOfFrames === null) { numberOfFrames = 1; } //By default, the number of frames is only one. if (typeof(framesMs) === \"undefined\" || framesMs === null) { framesMs = 100; } //Sets the number of milliseconds between frames by default. //Select the image element or creates it if it doesn't exist yet: var CB_fakeCursorImageDiv = divElement || CB_Elements.id(\"CB_fakeCursorImageDiv\"); var CB_fakeCursorImage = imageElement || CB_Elements.id(\"CB_fakeCursorImage\"); if (typeof(CB_fakeCursorImageDiv) === \"undefined\" || CB_fakeCursorImageDiv === null || typeof(CB_fakeCursorImage) === \"undefined\" || CB_fakeCursorImage === null) { CB_fakeCursorImageDiv = document.createElement(\"div\"); //Creathes the DIV element. CB_fakeCursorImageDiv.setAttribute(\"id\", \"CB_fakeCursorImageDiv\"); //Sets DIV element id. CB_fakeCursorImage = document.createElement(\"img\"); //Creathes the IMG element. CB_fakeCursorImage.setAttribute(\"id\", \"CB_fakeCursorImage\"); //Sets IMG element id. CB_fakeCursorImageDiv.style.position = CB_fakeCursorImage.style.position = \"absolute\"; //DIV and IMG position is absolute. CB_fakeCursorImageDiv.style.visibility = \"hidden\"; //First it will be hidden. CB_fakeCursorImageDiv.style.zIndex = CB_fakeCursorImage.style.zIndex = 999999; CB_fakeCursorImageDiv.style.overflow = \"hidden\"; CB_fakeCursorImageDiv.appendChild(CB_fakeCursorImage); //DIV will contains the IMG element. document.body.appendChild(CB_fakeCursorImageDiv); //BODY will contains the DIV. } //If we don't want to show the image (or the image has not been given), we hide it: if (!showCursorImage || typeof(cursorImage) === \"undefined\" || cursorImage === null) { CB_fakeCursorImageDiv.style.visibility = \"hidden\"; CB_Mouse.CursorImage._showCursorImage = false; CB_Mouse.CursorImage._cursorImageSpriteAnimation(false); //Stops the possible sprite animation. //If set, restores the normal cursor: if (!hideNormalCursor) { CB_Mouse.restore(); } } //...otherwise, forces it to follow the cursor: else if (!CB_Mouse.CursorImage._showCursorImage) { //Sets the image given as the SRC: if (CB_fakeCursorImage.src !== cursorImage) { CB_fakeCursorImage.src = cursorImage; } //The image (sprite or not) has to start with 0px in its left: CB_fakeCursorImage.style.left = \"0px\"; //Sets the proper width and height: if (isSprite) //If it is a sprite, the IMG will be wider than the DIV: { CB_fakeCursorImageDiv.style.width = cursorImageWidth + \"px\"; CB_fakeCursorImage.style.width = (cursorImageWidth * numberOfFrames) + \"px\"; CB_fakeCursorImageDiv.style.height = CB_fakeCursorImage.style.height = cursorImageHeight + \"px\"; } else //...otherwise, if it is not a sprite, the use of pixels is not mandatory: { if (!isNaN(cursorImageWidth)) { cursorImageWidth += \"px\"; } //If it is a number, they are considered pixels. if (!isNaN(cursorImageHeight)) { cursorImageHeight += \"px\"; } //If it is a number, they are considered pixels. CB_fakeCursorImageDiv.style.width = CB_fakeCursorImage.style.width = cursorImageWidth; CB_fakeCursorImageDiv.style.height = CB_fakeCursorImage.style.height = cursorImageHeight; } //Forces the image to follow the cursor: CB_Mouse.CursorImage._showCursorImage = true; //Stores the DIV and IMG elements: CB_Mouse.CursorImage._cursorImageDiv = CB_fakeCursorImageDiv; CB_Mouse.CursorImage._cursorImage = CB_fakeCursorImage; //Refreshes the image coordinates: CB_Mouse.CursorImage.move(); //Show the image: CB_fakeCursorImageDiv.style.visibility = \"visible\"; //If set, hides the cursor: if (hideNormalCursor) { CB_Mouse.hide(); } //...otherwise, shows it: else { CB_Mouse.restore(); } //If it is a sprite, starts the animation: if (isSprite) { CB_Mouse.CursorImage._cursorImageSpriteAnimation(true, cursorImageWidth, numberOfFrames, framesMs); } } } /** * Gets the [DIV element]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div} that contains the [IMG element]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img} of the fake cursor (if any). * @function * @returns {Element} Returns the [DIV element]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div} that contains the [IMG element]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img} of the fake cursor (if any). */ CB_Mouse.CursorImage.get = function() { return CB_Mouse.CursorImage._cursorImageDiv; } /** * Gets the [IMG element]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img} of the fake cursor (if any). * @function * @returns {Element} Returns the [IMG element]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img} of the fake cursor (if any). */ CB_Mouse.CursorImage.getImage = function() { return CB_Mouse.CursorImage._cursorImage; } /** * Tells whether the fake cursor is showing or not * @function * @returns {boolean} Returns whether the fake cursor is showing or not. */ CB_Mouse.CursorImage.isShowing = function() { return CB_Mouse.CursorImage._showCursorImage; } /** * Hides the fake cursor image. * @function * @param {boolean} [showNormalCursor=true] - If set to true, restores (shows) the system cursor (calls the {@link CB_Mouse.restore} function internally). */ CB_Mouse.CursorImage.hide = function(showNormalCursor) { //If they are not set, use default values for optional parameters: if (typeof(showNormalCursor) === \"undefined\" || showNormalCursor === null) { showNormalCursor = true; } //Shows normal cursor by default. //If it is being displayed, hides the fake cursor image: if (CB_Mouse.CursorImage._showCursorImage) { CB_Mouse.CursorImage.set(false, null, null, null, !showNormalCursor); } } /** * Moves the fake cursor image (if it is not hidden). Automatically called when the [onMouseMove]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event} event is fired. * @function * @param {number} [x=CB_Mouse.getX(null, false)] - The X coordinate (horizontal position) in pixels where the fake cursor image wants to be moved to. If not provided, it will use the value returned by calling CB_Mouse.getX(null, false) internally. * @param {number} [y=CB_Mouse.getY(null, false)] - The Y coordinate (vertical position) in pixels where the fake cursor image wants to be moved to. If not provided, it will use the value returned by calling CB_Mouse.getY(null, false) internally. */ CB_Mouse.CursorImage.move = function(x, y) { if (CB_Mouse.CursorImage._showCursorImage) { if (typeof(CB_Mouse.CursorImage._cursorImageDiv) !== \"undefined\" &amp;&amp; CB_Mouse.CursorImage._cursorImageDiv !== null &amp;&amp; typeof(CB_Mouse.CursorImage._cursorImageDiv.style) !== \"undefined\") { try //IE6 throws errors sometimes. { CB_Mouse.CursorImage._cursorImageDiv.style.left = (x || CB_Mouse.getX(null, false) || 0) + \"px\"; CB_Mouse.CursorImage._cursorImageDiv.style.top = (y || CB_Mouse.getY(null, false) || 0) + \"px\"; } catch(E) {} } } } //Starts or stops the sprite animation for the fake cursor image: CB_Mouse.CursorImage._cursorImageSpriteAnimation = function(runAnimation, cursorImageWidth, numberOfFrames, framesMs) { //If the number of frames is 1, it doesn't need to do anything: if (numberOfFrames &lt;= 1) { return; } //If set, stops the animation: if (!runAnimation) { clearTimeout(CB_Mouse.CursorImage._cursorImageSpriteAnimationTimeout); CB_Mouse.CursorImage._cursorImageSpriteAnimationTimeout = null; } //...otherwise, the animation starts or continues it: else { //Continues to next frame after the given milliseconds: CB_Mouse.CursorImage._cursorImageSpriteAnimationTimeout = CB_symmetricCall ( function() { if (CB_Mouse.CursorImage._cursorImageSpriteAnimationTimeout !== null) { var cursorImageLeft = CB_Elements.getStylePropertyInteger(CB_Mouse.CursorImage._cursorImage, \"left\")[0] - cursorImageWidth; cursorImageLeft %= (cursorImageWidth * numberOfFrames); CB_Mouse.CursorImage._cursorImage.style.left = cursorImageLeft + \"px\"; CB_Mouse.CursorImage._cursorImageSpriteAnimation(runAnimation, cursorImageWidth, numberOfFrames, framesMs); } }, framesMs, \"CB_MOUSE_CURSOR_IMAGE\" ); } } } //End of the static class CB_Mouse. × Search results Close "},"CrossBase_general_CB_Collisions.js.html":{"id":"CrossBase_general_CB_Collisions.js.html","title":"Source: CrossBase/general/CB_Collisions.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/general/CB_Collisions.js /** * @file Collisions management. Contains the {@link CB_Collisions} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage collisions. It will return itself if it is tried to be instantiated. * @namespace * @todo Finish many functions for many more kinds of collisions. * @todo Add triangles, polygons, arcs, etc. * @todo Add support to more dimensions (at least to 3D). * @todo Add lacking \"touching\" functions, equivalent to the \"over\" ones. * @todo Add a boolean parameter and a border parameter to detect collision just when it hits the border (not when it is inside of the object without touching the border), for \"hollow\" shapes. * @todo Think about adding function aliases with reversed names (for example, \"isElementOverPoint\" that points to \"isPointOverElement\", etc.). Think about whether the aliases should or not have some parameters in reversed order. */ var CB_Collisions = function() { return CB_Collisions; }; { CB_Collisions.initialized = false; //It will tells whether the object has been initialized or not. //Initializes all values: CB_Collisions.init = function() { if (CB_Collisions.initialized) { return CB_Collisions; } //The object has been initialized: CB_Collisions.initialized = true; //TODO. return CB_Collisions; } //TODO: add polygons, arcs, etc. /** * Tells the distance between two points. * @function * @param {number} x - The \"X\" coordinate of the first point. * @param {number} y - The \"Y\" coordinate of the first point. * @param {number} x2 - The \"X\" coordinate of the second point. * @param {number} y2 - The \"Y\" coordinate of the second point. * @returns {number|null} Returns the distance between the two points. In the case that it could not be calculated, returns null. */ CB_Collisions.getDistancePoints = function(x, y, x2, y2) { var distance = parseFloat(Math.sqrt(Math.pow(x - x2, 2) + Math.pow(y - y2, 2))); return isNaN(distance) ? null : distance; } /** * Tells whether a given point is over a given DOM element (it will be considered a rectangle). * @function * @param {number} x - The \"X\" coordinate of the point. * @param {number} y - The \"Y\" coordinate of the point. * @param {Element} element - The DOM element that we want to check (it will be considered a rectangle). * @returns {boolean} Returns whether the point is over the given DOM element (it will be considered a rectangle). */ CB_Collisions.isPointOverElement = function(x, y, element) { if (typeof(element) === \"undefined\" || element === null) { return false; } return CB_Collisions.isPointOverRectangle(x, y, CB_Elements.getLeft(element), CB_Elements.getTop(element), CB_Elements.getWidth(element), CB_Elements.getHeight(element)); } /** * Tells whether a given point is touching (maybe over) a given DOM element (it will be considered a rectangle). This will also return true if they are adjacent (next to each other). * @function * @param {number} x - The \"X\" coordinate of the point. * @param {number} y - The \"Y\" coordinate of the point. * @param {Element} element - The DOM element that we want to check (it will be considered a rectangle). * @returns {boolean} Returns whether the point is touching (maybe over) the given DOM element (it will be considered a rectangle). This will also return true if they are adjacent (next to each other). */ CB_Collisions.isPointTouchingElement = function(x, y, element) { if (typeof(element) === \"undefined\" || element === null) { return false; } return CB_Collisions.isPointTouchingRectangle(x, y, CB_Elements.getLeft(element), CB_Elements.getTop(element), CB_Elements.getWidth(element), CB_Elements.getHeight(element)); } /** * Tells whether a point is over a line (infinite). * @function * @param {number} x - The \"X\" coordinate of the point. * @param {number} y - The \"Y\" coordinate of the point. * @param {number} lineX1 - The \"X\" coordinate of a first point of the line. * @param {number} lineY1 - The \"Y\" coordinate of a first point of the line. * @param {number} lineX2 - The \"X\" coordinate of a second point of the line. * @param {number} lineY2 - The \"Y\" coordinate of a second point of the line. * @param {number} [tolerance=0.001] - The amount of loss of precision we can tolerate to consider a collision. * @returns {boolean} Returns whether the point is over the line (infinite). * @todo Think about using a \"width\" parameter (apart from the \"tolerance\" parameter). * @todo Create a CB_Collisions.isPointTouchingLine function. */ CB_Collisions.isPointOverLine = function(x, y, lineX1, lineY1, lineX2, lineY2, tolerance) { if (typeof(tolerance) === \"undefined\" || tolerance === null) { tolerance = 0.001; } //If the line is vertical (infinite slope) or just a point: if (lineX1 === lineX2) { //If the point is in the same X axis: if (x === lineX1) { //If the line has the same Y at both ends, it's in fact just a point: if (lineY1 === lineY2) { //If the point is in the same Y axis: if (y === lineY1) { return true; } //The line is a point and the point given is the same one. } else if (lineY1 &lt; lineY2) { if (y &gt;= lineY1 &amp;&amp; y &lt;= lineY2) { return true; } } else //lineY1 &gt; lineY2 { if (y &gt;= lineY2 &amp;&amp; y &lt;= lineY1) { return true; } } } } else { var slope = (lineY2 - lineY1) / (lineX2 - lineX1); var yIntercept = lineY1 - slope * lineX1; if (Math.abs(y - (slope * x + yIntercept)) &lt;= tolerance) { return true; } } return false; } /** * Tells whether a point is over a line segment. * @function * @param {number} x - The \"X\" coordinate of the point. * @param {number} y - The \"Y\" coordinate of the point. * @param {number} segmentX1 - The \"X\" coordinate of the beginning point of the line. * @param {number} segmentY1 - The \"Y\" coordinate of the beginning point of the line. * @param {number} segmentX2 - The \"X\" coordinate of the end point of the line. * @param {number} segmentY2 - The \"Y\" coordinate of the end point of the line. * @param {number} [tolerance=0.001] - The amount of loss of precision we can tolerate to consider a collision. * @returns {boolean} Returns whether the point is over the line segment. * @todo Think about using a \"width\" parameter (apart from the \"tolerance\" parameter). * @todo Create a CB_Collisions.isPointTouchingSegment function. */ CB_Collisions.isPointOverSegment = function(x, y, segmentX1, segmentY1, segmentX2, segmentY2, tolerance) { var rectangleX1 = segmentX1; var rectangleY1 = segmentY1; var rectangleX2 = segmentX2; var rectangleY2 = segmentY2; if (segmentX2 &lt; segmentX1) { rectangleX1 = segmentX2; rectangleX2 = segmentX1; } if (segmentY2 &lt; segmentY1) { rectangleY1 = segmentY2; rectangleY2 = segmentY1; } if (CB_Collisions.isPointOverRectangle(x, y, rectangleX1, rectangleY1, rectangleX2 - rectangleX1 /*rectangleWidth*/, rectangleY2 - rectangleY1 /*rectangleHeight*/)) { return CB_Collisions.isPointOverLine(x, y, segmentX1, segmentY1, segmentX2, segmentY2, tolerance); } return false; } /** * Tells whether a point is over a rectangle. * @function * @param {number} x - The \"X\" coordinate of the point. * @param {number} y - The \"Y\" coordinate of the point. * @param {number} rectangleX - The \"X\" coordinate of the upper left corner of the rectangle. * @param {number} rectangleY - The \"Y\" coordinate of the upper left corner of the rectangle. * @param {number} rectangleWidth - The width of the rectangle. * @param {number} rectangleHeight - The height of the rectangle. * @returns {boolean} Returns whether the point is over the rectangle. * @todo Think about using a \"rotation\" parameter to accept rotated rectangles. */ CB_Collisions.isPointOverRectangle = function(x, y, rectangleX, rectangleY, rectangleWidth, rectangleHeight) { return (x &gt; rectangleX &amp;&amp; x &lt; rectangleX + rectangleWidth &amp;&amp; y &gt; rectangleY &amp;&amp; y &lt; rectangleY + rectangleHeight); } /** * Tells whether a point is touching (maybe over) a rectangle. This will also return true if they are adjacent (next to each other). * @function * @param {number} x - The \"X\" coordinate of the point. * @param {number} y - The \"Y\" coordinate of the point. * @param {number} rectangleX - The \"X\" coordinate of the upper left corner of the rectangle. * @param {number} rectangleY - The \"Y\" coordinate of the upper left corner of the rectangle. * @param {number} rectangleWidth - The width of the rectangle. * @param {number} rectangleHeight - The height of the rectangle. * @returns {boolean} Returns whether the point is touching (maybe over) the rectangle. This will also return true if they are adjacent (next to each other). * @todo Think about using a \"rotation\" parameter to accept rotated rectangles. */ CB_Collisions.isPointTouchingRectangle = function(x, y, rectangleX, rectangleY, rectangleWidth, rectangleHeight) { /* if (x &gt;= rectangleX &amp;&amp; x &lt;= rectangleX + rectangleWidth) { if (y &gt;= rectangleY &amp;&amp; y &lt;= rectangleY + rectangleHeight) { return true; } } return false; */ return (x &gt;= rectangleX &amp;&amp; x &lt;= rectangleX + rectangleWidth &amp;&amp; y &gt;= rectangleY &amp;&amp; y &lt;= rectangleY + rectangleHeight); } /** * Tells whether a point is over a circle. * @function * @param {number} x - The \"X\" coordinate of the point. * @param {number} y - The \"Y\" coordinate of the point. * @param {number} centreX - The \"X\" coordinate of the center of the circle. * @param {number} centreY - The \"Y\" coordinate of the center of the circle. * @param {number} radius - The radius of the circle. * @returns {boolean} Returns whether the point is over the circle. */ CB_Collisions.isPointOverCircle = function(x, y, centreX, centreY, radius) { //If the distance is lower than the radius, there is a collision: //return (Math.sqrt(Math.pow(centreX - x, 2) + Math.pow(centreY - y, 2)) &lt; radius); return CB_Collisions.getDistancePoints(centreX, centreY, x, y) &lt; radius; } /** * Tells whether a point is touching (maybe over) a circle. This will also return true if they are adjacent (next to each other). * @function * @param {number} x - The \"X\" coordinate of the point. * @param {number} y - The \"Y\" coordinate of the point. * @param {number} centreX - The \"X\" coordinate of the center of the circle. * @param {number} centreY - The \"Y\" coordinate of the center of the circle. * @param {number} radius - The radius of the circle. * @returns {boolean} Returns whether the point is touching (maybe over) the circle. This will also return true if they are adjacent (next to each other). */ CB_Collisions.isPointTouchingCircle = function(x, y, centreX, centreY, radius) { //If the distance is lower than the radius, there is a collision: //return (Math.sqrt(Math.pow(centreX - x, 2) + Math.pow(centreY - y, 2)) &lt; radius); return CB_Collisions.getDistancePoints(centreX, centreY, x, y) &lt;= radius; } /** * Tells whether a point is over an ellipse. * @function * @param {number} x - The \"X\" coordinate of the point. * @param {number} y - The \"Y\" coordinate of the point. * @param {number} centreX - The \"X\" coordinate of the center of the ellipse. * @param {number} centreY - The \"Y\" coordinate of the center of the ellipse. * @param {number} radiusX - The X (horizontal) radius of the ellipse. * @param {number} radiusY - The Y (vertical) radius of the ellipse. * @param {number} [rotation=0] - The ellipse rotation. The value given will be considered either degrees or radians depending on the given \"rotationUseDegrees\" parameter (by default, it is considered radians). Not implemented yet! * @param {boolean} [rotationUseDegrees=false] - Defines whether the \"rotation\" given should be considered degrees or not (radians). Not implemented yet! * @returns {boolean} Returns whether the point is over the ellipse. * @todo Make the \"rotation\" parameter work (check https://math.stackexchange.com/questions/426150/what-is-the-general-equation-of-the-ellipse-that-is-not-in-the-origin-and-rotate). */ CB_Collisions.isPointOverEllipse = function(x, y, centreX, centreY, radiusX, radiusY, rotation, rotationUseDegrees) { if (typeof(rotation) === \"undefined\" || rotation === null || isNaN(rotation)) { rotation = 0; } if (rotationUseDegrees &amp;&amp; rotation !== 0) { rotation *= Math.PI / 180 } var dx = x - centreX; var dy = y - centreY; return (dx * dx) / (radiusX * radiusX) + (dy * dy) / (radiusY * radiusY) &lt; 1; } /** * Tells whether a point is touching (maybe over) a ellipse. This will also return true if they are adjacent (next to each other). * @function * @param {number} x - The \"X\" coordinate of the point. * @param {number} y - The \"Y\" coordinate of the point. * @param {number} centreX - The \"X\" coordinate of the center of the ellipse. * @param {number} centreY - The \"Y\" coordinate of the center of the ellipse. * @param {number} radiusX - The X (horizontal) radius of the ellipse. * @param {number} radiusY - The Y (vertical) radius of the ellipse. * @param {number} [rotation=0] - The ellipse rotation. The value given will be considered either degrees or radians depending on the given \"rotationUseDegrees\" parameter (by default, it is considered radians). Not implemented yet! * @param {boolean} [rotationUseDegrees=false] - Defines whether the \"rotation\" given should be considered degrees or not (radians). Not implemented yet! * @returns {boolean} Returns whether the point is touching (maybe over) the ellipse. This will also return true if they are adjacent (next to each other). * @todo Make the \"rotation\" parameter work (check https://math.stackexchange.com/questions/426150/what-is-the-general-equation-of-the-ellipse-that-is-not-in-the-origin-and-rotate). */ CB_Collisions.isPointTouchingEllipse = function(x, y, centreX, centreY, radiusX, radiusY, rotation, rotationUseDegrees) { if (typeof(rotation) === \"undefined\" || rotation === null || isNaN(rotation)) { rotation = 0; } if (rotationUseDegrees &amp;&amp; rotation !== 0) { rotation *= Math.PI / 180 } var dx = x - centreX; var dy = y - centreY; return (dx * dx) / (radiusX * radiusX) + (dy * dy) / (radiusY * radiusY) &lt;= 1; } /** * Tells whether a rectangle is over another rectangle. * @function * @param {number} rectangleX - The \"X\" coordinate of the upper left corner of the first rectangle. * @param {number} rectangleY - The \"Y\" coordinate of the upper left corner of the first rectangle. * @param {number} rectangleWidth - The width of the first rectangle. * @param {number} rectangleHeight - The height of the first rectangle. * @param {number} rectangleX2 - The \"X\" coordinate of the upper left corner of the second rectangle. * @param {number} rectangleY2 - The \"Y\" coordinate of the upper left corner of the second rectangle. * @param {number} rectangleWidth2 - The width of the second rectangle. * @param {number} rectangleHeight2 - The height of the second rectangle. * @returns {boolean} Returns whether the rectangle is over the other rectangle. * @todo Think about using \"rotation\" and \"rotation2\" parameters to accept rotated rectangles. */ CB_Collisions.isRectangleOverRectangle = function(rectangleX, rectangleY, rectangleWidth, rectangleHeight, rectangleX2, rectangleY2, rectangleWidth2, rectangleHeight2) { return ( Math.max(rectangleX, rectangleX2) &lt; Math.min(rectangleX + rectangleWidth, rectangleX2 + rectangleWidth2) &amp;&amp; Math.max(rectangleY, rectangleY2) &lt; Math.min(rectangleY + rectangleHeight, rectangleY2 + rectangleHeight2) ); } /** * Tells whether a rectangle is touching (maybe over) another rectangle. This will also return true if they are adjacent (next to each other). * @function * @param {number} rectangleX - The \"X\" coordinate of the upper left corner of the first rectangle. * @param {number} rectangleY - The \"Y\" coordinate of the upper left corner of the first rectangle. * @param {number} rectangleWidth - The width of the first rectangle. * @param {number} rectangleHeight - The height of the first rectangle. * @param {number} rectangleX2 - The \"X\" coordinate of the upper left corner of the second rectangle. * @param {number} rectangleY2 - The \"Y\" coordinate of the upper left corner of the second rectangle. * @param {number} rectangleWidth2 - The width of the second rectangle. * @param {number} rectangleHeight2 - The height of the second rectangle. * @returns {boolean} Returns whether the rectangle is touching (maybe over) the other rectangle. This will also return true if they are adjacent (next to each other). * @todo Think about using \"rotation\" and \"rotation2\" parameters to accept rotated rectangles. */ CB_Collisions.isRectangleTouchingRectangle = function(rectangleX, rectangleY, rectangleWidth, rectangleHeight, rectangleX2, rectangleY2, rectangleWidth2, rectangleHeight2) { return ( Math.max(rectangleX, rectangleX2) &lt;= Math.min(rectangleX + rectangleWidth, rectangleX2 + rectangleWidth2) &amp;&amp; Math.max(rectangleY, rectangleY2) &lt;= Math.min(rectangleY + rectangleHeight, rectangleY2 + rectangleHeight2) ); } /** * Tells whether a rectangle is over a given DOM element (it will be considered a rectangle). * @function * @param {number} rectangleX - The \"X\" coordinate of the upper left corner of the first rectangle. * @param {number} rectangleY - The \"Y\" coordinate of the upper left corner of the first rectangle. * @param {number} rectangleWidth - The width of the first rectangle. * @param {number} rectangleHeight - The height of the first rectangle. * @param {Element} element - The DOM element that we want to check (it will be considered a rectangle). * @returns {boolean} Returns whether the rectangle is over the given DOM element (it will be considered a rectangle). * @todo Think about using a \"rotation\" parameter to accept rotated rectangles. */ CB_Collisions.isRectangleOverElement = function(rectangleX, rectangleY, rectangleWidth, rectangleHeight, element) { if (typeof(element) === \"undefined\" || element === null) { return false; } return CB_Collisions.isRectangleOverRectangle(rectangleX, rectangleY, rectangleWidth, rectangleHeight, CB_Elements.getLeft(element), CB_Elements.getTop(element), CB_Elements.getWidth(element), CB_Elements.getHeight(element)); } /** * Tells whether a rectangle is touching (maybe over) a given DOM element (it will be considered a rectangle). This will also return true if they are adjacent (next to each other). * @function * @param {number} rectangleX - The \"X\" coordinate of the upper left corner of the first rectangle. * @param {number} rectangleY - The \"Y\" coordinate of the upper left corner of the first rectangle. * @param {number} rectangleWidth - The width of the first rectangle. * @param {number} rectangleHeight - The height of the first rectangle. * @param {Element} element - The DOM element that we want to check (it will be considered a rectangle). * @returns {boolean} Returns whether the rectangle is touching (maybe over) the given DOM element (it will be considered a rectangle). This will also return true if they are adjacent (next to each other). * @todo Think about using a \"rotation\" parameter to accept rotated rectangles. */ CB_Collisions.isRectangleTouchingElement = function(rectangleX, rectangleY, rectangleWidth, rectangleHeight, element) { if (typeof(element) === \"undefined\" || element === null) { return false; } return CB_Collisions.isRectangleTouchingRectangle(rectangleX, rectangleY, rectangleWidth, rectangleHeight, CB_Elements.getLeft(element), CB_Elements.getTop(element), CB_Elements.getWidth(element), CB_Elements.getHeight(element)); } /** * Tells whether two given DOM elements are over each other (they will be considered a rectangle). * @function * @param {Element} element - The first DOM element that we want to check (it will be considered a rectangle). * @param {Element} element2 - The second DOM element that we want to check (it will be considered a rectangle). * @returns {boolean} Returns whether the two given DOM elements are over each other (they will be considered a rectangle). */ CB_Collisions.isElementOverElement = function(element, element2) { if (typeof(element) === \"undefined\" || element === null) { return false; } return CB_Collisions.isRectangleOverElement(CB_Elements.getLeft(element), CB_Elements.getTop(element), CB_Elements.getWidth(element), CB_Elements.getHeight(element), element2); } /** * Tells whether two given DOM elements are touching each other, maybe over each other (they will be considered a rectangle). This will also return true if they are adjacent (next to each other). * @function * @param {Element} element - The first DOM element that we want to check (it will be considered a rectangle). * @param {Element} element2 - The second DOM element that we want to check (it will be considered a rectangle). * @returns {boolean} Returns whether the two given DOM elements are touching each other, maybe over each other (they will be considered a rectangle). This will also return true if they are adjacent (next to each other). */ CB_Collisions.isElementTouchingElement = function(element, element2) { if (typeof(element) === \"undefined\" || element === null) { return false; } return CB_Collisions.isRectangleTouchingElement(CB_Elements.getLeft(element), CB_Elements.getTop(element), CB_Elements.getWidth(element), CB_Elements.getHeight(element), element2); } /** * Tells whether a circle is over another circle. * @function * @param {number} centreX - The \"X\" coordinate of the center of the first circle. * @param {number} centreY - The \"Y\" coordinate of the center of the first circle. * @param {number} radius - The radius of the first circle. * @param {number} centreX2 - The \"X\" coordinate of the center of the second circle. * @param {number} centreY2 - The \"Y\" coordinate of the center of the second circle. * @param {number} radius2 - The radius of the second circle. * @returns {boolean} Returns whether the circle is over the other circle. */ CB_Collisions.isCircleOverCircle = function(centreX, centreY, radius, centreX2, centreY2, radius2) { //return (Math.sqrt(Math.pow(centreX - centreX2, 2) + Math.pow(centreY - centreY2, 2)) &lt; radius + radius2); return CB_Collisions.getDistancePoints(centreX, centreY, centreX2, centreY2) &lt; radius + radius2; } /** * Tells whether a circle is touching (maybe over) another circle. This will also return true if they are adjacent (next to each other). * @function * @param {number} centreX - The \"X\" coordinate of the center of the first circle. * @param {number} centreY - The \"Y\" coordinate of the center of the first circle. * @param {number} radius - The radius of the first circle. * @param {number} centreX2 - The \"X\" coordinate of the center of the second circle. * @param {number} centreY2 - The \"Y\" coordinate of the center of the second circle. * @param {number} radius2 - The radius of the second circle. * @returns {boolean} Returns whether the circle is touching (maybe over) the other circle. This will also return true if they are adjacent (next to each other). */ CB_Collisions.isCircleTouchingCircle = function(centreX, centreY, radius, centreX2, centreY2, radius2) { //return (Math.sqrt(Math.pow(centreX - centreX2, 2) + Math.pow(centreY - centreY2, 2)) &lt;= radius + radius2); return CB_Collisions.getDistancePoints(centreX, centreY, centreX2, centreY2) &lt;= radius + radius2; } /** * Tells whether a circle is over a given rectangle. * @function * @param {number} centreX - The \"X\" coordinate of the center of the first circle. * @param {number} centreY - The \"Y\" coordinate of the center of the first circle. * @param {number} radius - The radius of the first circle. * @param {number} rectangleX - The \"X\" coordinate of the upper left corner of the first rectangle. * @param {number} rectangleY - The \"Y\" coordinate of the upper left corner of the first rectangle. * @param {number} rectangleWidth - The width of the first rectangle. * @param {number} rectangleHeight - The height of the first rectangle. * @returns {boolean} Returns whether the circle is over the rectangle. * @todo Think about using a \"rotation\" parameter to accept rotated rectangles. */ //* Source (modified): markE at https://stackoverflow.com/questions/21089959/detecting-collision-of-rectangle-with-circle CB_Collisions.isRectangleOverCircle = function(centreX, centreY, radius, rectangleX, rectangleY, rectangleWidth, rectangleHeight) { var distanceX = Math.abs(centreX - rectangleX - rectangleWidth / 2); var distanceY = Math.abs(centreY - rectangleY - rectangleHeight / 2); if (distanceX &gt; rectangleWidth / 2 + radius) { return false; } if (distanceY &gt; rectangleHeight / 2 + radius) { return false; } if (distanceX &lt; rectangleWidth / 2) { return true; } if (distanceY &lt; rectangleHeight / 2) { return true; } var dx = distanceX - rectangleWidth / 2; var dy = distanceY - rectangleHeight / 2; return (dx * dx + dy * dy &lt; radius * radius); } /** * Tells whether a circle is touching (maybe over) a given rectangle. * @function * @param {number} rectangleX - The \"X\" coordinate of the upper left corner of the first rectangle. * @param {number} rectangleY - The \"Y\" coordinate of the upper left corner of the first rectangle. * @param {number} rectangleWidth - The width of the first rectangle. * @param {number} rectangleHeight - The height of the first rectangle. * @param {number} centreX - The \"X\" coordinate of the center of the first circle. * @param {number} centreY - The \"Y\" coordinate of the center of the first circle. * @param {number} radius - The radius of the first circle. * @returns {boolean} Returns whether the circle is touching (maybe over) the rectangle. This will also return true if they are adjacent (next to each other). * @todo Think about using a \"rotation\" parameter to accept rotated rectangles. //* Source (modified): markE at https://stackoverflow.com/questions/21089959/detecting-collision-of-rectangle-with-circle */ CB_Collisions.isRectangleTouchingCircle = function(rectangleX, rectangleY, rectangleWidth, rectangleHeight, centreX, centreY, radius) { var distanceX = Math.abs(centreX - rectangleX - rectangleWidth / 2); var distanceY = Math.abs(centreY - rectangleY - rectangleHeight / 2); if (distanceX &gt; rectangleWidth / 2 + radius) { return false; } if (distanceY &gt; rectangleHeight / 2 + radius) { return false; } if (distanceX &lt;= rectangleWidth / 2) { return true; } if (distanceY &lt;= rectangleHeight / 2) { return true; } var dx = distanceX - rectangleWidth / 2; var dy = distanceY - rectangleHeight / 2; return (dx * dx + dy * dy &lt;= radius * radius); } /** * Tells whether a line (infinite) is over a given circle. * @function * @param {number} lineX1 - The \"X\" coordinate of a first point of the line. * @param {number} lineY1 - The \"Y\" coordinate of a first point of the line. * @param {number} lineX2 - The \"X\" coordinate of a second point of the line. * @param {number} lineY2 - The \"Y\" coordinate of a second point of the line. * @param {number} centreX - The \"X\" coordinate of the center of the first circle. * @param {number} centreY - The \"Y\" coordinate of the center of the first circle. * @param {number} radius - The radius of the first circle. * @returns {boolean} Returns whether the line (infinite) is over the circle. */ //* Source (modified): https://github.com/mattdesl/line-circle-collision CB_Collisions.isLineOverCircle = function(lineX1, lineY1, lineX2, lineY2, centreX, centreY, radius) { if (CB_Collisions.isPointOverCircle(lineX1, lineY1, centreX, centreY, radius)) { return true; } else if (CB_Collisions.isPointOverCircle(lineX2, lineY2, centreX, centreY, radius)) { return true; } var dx = lineX2 - lineX1; var dy = lineY2 - lineY1; var lcx = centreX - lineX1; var lcy = centreY - lineY1; var dLen2 = dx * dx + dy * dy; var px = dx; var py = dy; if (dLen2 &gt; 0) { var dp = (lcx * dx + lcy * dy) / dLen2; px *= dp; py *= dp; } var pLen2 = px * px + py * py; return CB_Collisions.isPointOverCircle(lineX1 + px, lineY1 + py, centreX, centreY, radius) &amp;&amp; pLen2 &lt; dLen2 &amp;&amp; (px * dx + py * dy) &gt; 0; //TODO: test it well (some equal signs removed). } /** * Tells whether a line (infinite) is touching (maybe over) a given circle. * @function * @param {number} lineX1 - The \"X\" coordinate of a first point of the line. * @param {number} lineY1 - The \"Y\" coordinate of a first point of the line. * @param {number} lineX2 - The \"X\" coordinate of a second point of the line. * @param {number} lineY2 - The \"Y\" coordinate of a second point of the line. * @param {number} centreX - The \"X\" coordinate of the center of the first circle. * @param {number} centreY - The \"Y\" coordinate of the center of the first circle. * @param {number} radius - The radius of the first circle. * @returns {boolean} Returns whether the line (infinite) is touching (maybe over) the circle. */ //* Source (modified): https://github.com/mattdesl/line-circle-collision CB_Collisions.isLineTouchingCircle = function(lineX1, lineY1, lineX2, lineY2, centreX, centreY, radius) { if (CB_Collisions.isPointTouchingCircle(lineX1, lineY1, centreX, centreY, radius)) { return true; } else if (CB_Collisions.isPointTouchingCircle(lineX2, lineY2, centreX, centreY, radius)) { return true; } var dx = lineX2 - lineX1; var dy = lineY2 - lineY1; var lcx = centreX - lineX1; var lcy = centreY - lineY1; var dLen2 = dx * dx + dy * dy; var px = dx; var py = dy; if (dLen2 &gt; 0) { var dp = (lcx * dx + lcy * dy) / dLen2; px *= dp; py *= dp; } var pLen2 = px * px + py * py; return CB_Collisions.isPointTouchingCircle(lineX1 + px, lineY1 + py, centreX, centreY, radius) &amp;&amp; pLen2 &lt;= dLen2 &amp;&amp; (px * dx + py * dy) &gt;= 0; } //Function that returns whether a line is over another line: CB_Collisions.isLineOverLine = function() { } //Function that returns whether a line segment is over another line segment: CB_Collisions.isSegmentOverSegment = function() { } //Function that returns whether a line is over a segment: CB_Collisions.isLineOverSegment = function() { } //Function that returns whether a line is over a rectangle: CB_Collisions.isLineOverRectangle = function() { } //Function that returns whether a line is over a circle: CB_Collisions.isLineOverCircle = function() { } //Function that returns whether a line segment is over a rectangle: CB_Collisions.isSegmentOverRectangle = function() { } //Function that returns whether a line segment is over a circle: CB_Collisions.isSegmentOverCircle = function() { } //Function that returns whether a line is touching (maybe over) another line: CB_Collisions.isLineTouchingLine = function() { } //Function that returns whether a line is touching (maybe over) a line segment: CB_Collisions.isLineTouchingSegment = function() { } //Function that returns whether a line is touching (maybe over) a rectangle: CB_Collisions.isLineTouchingRectangle = function() { } //Function that returns whether a line segment is touching (maybe over) a rectangle: CB_Collisions.isSegmentTouchingRectangle = function() { } //Function that returns whether a line segment is touching (maybe over) a circle: CB_Collisions.isSegmentTouchingCircle = function() { } } × Search results Close "},"CrossBase_input_controllers_CB_Controllers.js.html":{"id":"CrossBase_input_controllers_CB_Controllers.js.html","title":"Source: CrossBase/input/controllers/CB_Controllers.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/input/controllers/CB_Controllers.js /** * @file Controllers (gamepads, joysticks, remotes, etc.) management. Contains the {@link CB_Controllers} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage different controllers (gamepads, joysticks, remotes, etc.). It will return itself if it is tried to be instantiated. It uses [gamepad-plus]{@link https://github.com/MozillaReality/gamepad-plus}. * @namespace CB_Controllers * @todo Find a way to do button mapping (so we could use names as LEFT, RIGHT, etc.) and normalization for most web clients and gamepads (without forgetting proprietary ones as WII U, etc.). * @todo Consider using always a numeric index instead of the ID of the gamepad (array instead of object), which could be a string, for CB_Controllers._gamepads (for optimization purposes). * @todo Consider modifying {@link CB_Controllers.isButtonDown} function or add a new one to check whether any button (or axes) is down or not. */ //* Source: https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API CB_Controllers = function() { return CB_Controllers; }; { CB_Controllers.initialized = false; //It will tells whether the object has been initialized or not. CB_Controllers._gamePadHaveEvents = \"ongamepadconnected\" in window; CB_Controllers._gamepads = {}; //Object that keeps the indexes of the current gamepads and the gamepad objects as their values. CB_Controllers._eventsHolder = {}; //Keeps the functions to fire for every special event (if any). //Initializes all values: CB_Controllers.init = function() { if (CB_Controllers.initialized) { return CB_Controllers; } //Initializes proprietary controllers: CB_Controllers_Proprietary[\"WII_U\"].init(); CB_Controllers_Proprietary[\"WII\"].init(); //The object has been initialized: CB_Controllers.initialized = true; //TODO: use gamepad-plus to make it compatible with more web clients (and do not forget keyEventsEnabled property). if (!CB_Controllers._gamePadHaveEvents) { var gamePadPolling = function() { CB_Controllers._gamePadScanAll(); setTimeout(gamePadPolling, 500); }; gamePadPolling(); } else { CB_Events.add(CB_Client.getWindow(), \"gamepadconnected\", CB_Controllers._gamePadConnectHandler, true, true, false); CB_Events.add(CB_Client.getWindow(), \"gamepaddisconnected\", CB_Controllers._gamePadDisconnectHandler, true, true, false); } return CB_Controllers; } //Handler to execute when a gamepad is connected (using GamePad API): //* Source: https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API CB_Controllers._gamePadConnectHandler = function(e) { CB_Controllers._gamePadAdd(e.gamepad); } //Handler to execute when a gamepad is disconnected (using GamePad API): //* Source: https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API CB_Controllers._gamePadDisconnectHandler = function(e) { CB_Controllers._gamePadRemove(e.gamepad); } //Adds a new gamepad (using GamePad API): //* Source: https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API CB_Controllers._gamePadAdd = function(gamepad) { CB_Controllers._gamepads[gamepad.index] = gamepad; //See https://github.com/luser/gamepadtest/blob/master/index.html //requestAnimationFrame(CB_Controllers._gamePadUpdateAll); CB_Controllers._gamePadUpdateAll(); //If there is any, executes the desired event: if (typeof(CB_Controllers._eventsHolder[\"onConnect\"]) === \"function\") { CB_Controllers._eventsHolder[\"onConnect\"](gamepad, CB_Controllers._gamepads); } } //Removes a gamepad (using GamePad API): //* Source: https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API CB_Controllers._gamePadRemove = function(gamepad) { //CB_Controllers._gamepads[gamepad.index] = undefined; delete CB_Controllers._gamepads[gamepad.index]; //If there is any, executes the desired event: if (typeof(CB_Controllers._eventsHolder[\"onDisconnect\"]) === \"function\") { CB_Controllers._eventsHolder[\"onDisconnect\"](gamepad, CB_Controllers._gamepads); } } //Updates the status of all gamepads, if any (using GamePad API): //* Source: https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API CB_Controllers._gamePadUpdateAllTimeout = null; CB_Controllers._gamePadUpdateAll = function() { //TODO: normalize, when possible, values for different web clients and gamepads. clearTimeout(CB_Controllers._gamePadUpdateAllTimeout); if (!CB_Controllers._gamePadHaveEvents) { CB_Controllers._gamePadScanAll(); } var i = 0; for (var j in CB_Controllers._gamepads) { var controller = CB_Controllers._gamepads[j]; //for (i = 0; i &lt; controller.buttons.length; i++) for (i in controller.buttons) { if (typeof(controller.buttons[i]) !== \"object\" || controller.buttons[i] === null) { controller.buttons[i] = { value: controller.buttons[i], pressed: controller.buttons[i] == 1.0 }; } } /* for (i = 0; i &lt; controller.axes.length; i++) { var a = axes[i]; a.innerHTML = i + \": \" + controller.axes[i].toFixed(4); a.setAttribute(\"value\", controller.axes[i] + 1); }*/ } //requestAnimationFrame(CB_Controllers._gamePadUpdateAll); CB_Controllers._gamePadUpdateAllTimeout = setTimeout(CB_Controllers._gamePadUpdateAll, 1); } //Scans all gamepads, if any (using GamePad API): //* Source: https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API CB_Controllers._gamePadScanAll = function() { var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : (navigator.webkitGamepads ? navigator.webkitGamepads : [])); //Looks for new connected ones: for (var i = 0; i &lt; gamepads.length; i++) { if (gamepads[i]) { //if (gamepads[i].index in CB_Controllers._gamepads) { CB_Controllers._gamepads[gamepads[i].index] = gamepads[i]; } if (typeof(CB_Controllers._gamepads[gamepads[i].index]) !== \"undefined\") { CB_Controllers._gamepads[gamepads[i].index] = gamepads[i]; } else { CB_Controllers._gamePadAdd(gamepads[i]); } } } //Looks for disconnected ones: //for (i = 0; i &lt; CB_Controllers._gamepads.length; i++) for (i in CB_Controllers._gamepads) { if (CB_Controllers._gamepads[i]) { if (typeof(gamepads[CB_Controllers._gamepads[i].index]) === \"undefined\") { CB_Controllers._gamePadRemove(CB_Controllers._gamepads[i]); } } } } /** * Sets a function to execute when a gamepad is connected ([\"onGamepadConnected\"]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/ongamepadconnected} event is fired) or removes it. More information: [Gamepad API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first parameter received for this function will be the gamepad object affected and the second parameter will be an object containing all current gamepads objects (properties will be the index of each gamepad). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @todo Make it compatible with proprietary ones (if possible). */ CB_Controllers.onConnect = function(callbackFunction, keepOldFunction) { return CB_Controllers._setSpecialEventFunction(\"onConnect\", callbackFunction, keepOldFunction); } /** * Sets a function to execute when a gamepad is disconnected ([\"onGamepadDisconnected\"]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/ongamepaddisconnected} event is fired) or removes it. More information: [Gamepad API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first parameter received for this function will be the gamepad object affected and the second parameter will be an object containing all current gamepads objects (properties will be the index of each gamepad). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @todo Make it compatible with proprietary ones (if possible). */ CB_Controllers.onDisconnect = function(callbackFunction, keepOldFunction) { return CB_Controllers._setSpecialEventFunction(\"onDisconnect\", callbackFunction, keepOldFunction); } //Sets a function to execute when an event happens (a non-existing event on JavaScript): CB_Controllers._setSpecialEventFunction = function(eventName, eventFunction, keepOldFunction) { //If no function has been sent, cancel all previous functions and exits: if (typeof(eventFunction) !== \"function\") { if (eventFunction === null) { CB_Controllers._eventsHolder[eventName] = null; } return; } //If not set, it keeps old function by default: if (typeof(keepOldFunction) === \"undefined\" || keepOldFunction === null) { keepOldFunction = true; } //If we don't want to keep the old function: if (!keepOldFunction) { CB_Controllers._eventsHolder[eventName] = eventFunction; } //...otherwise if we want to keep the old function, we keep it: else { //Stores old function: var eventFunctionOld = CB_Controllers._eventsHolder[eventName]; //Stores old function of eventFunctionHolder. CB_Controllers._eventsHolder[eventName] = function(e) { if (typeof(eventFunctionOld) === \"function\") { eventFunctionOld(e); } eventFunction(e); }; } } //Finds and returns a desired property from one or more gamepads: CB_Controllers._findProperty = function(findFunction, valueIfNotFound, gamepadId, gamepadIdNumeric, caseSensitive, avoidProprietary, extraData) { if (typeof(findFunction) !== \"function\") { findFunction = CB_Controllers._findButtonsDown; } if (typeof(valueIfNotFound) === \"undefined\") { valueIfNotFound = {}; } if (avoidProprietary !== true &amp;&amp; avoidProprietary !== false) { avoidProprietary = CB_Configuration[CB_BASE_NAME].CB_Controllers_avoidProprietary_DEFAULT; } gamepadId = CB_trim(gamepadId); if (gamepadId !== \"\") { if (gamepadIdNumeric || !isNaN(gamepadId) &amp;&amp; (typeof(gamepadIdNumeric) === \"undefined\" || gamepadIdNumeric === null)) { gamepadIdNumeric = true; gamepadId = parseInt(gamepadId); } } var gamepads = CB_Controllers.getGamePads(avoidProprietary); var properties = valueIfNotFound; //If desired, just gets the buttons down from the devices compatible with the HTML5 Gamepad API: if (avoidProprietary) { properties = findFunction(gamepadId, gamepadIdNumeric, caseSensitive, gamepads, extraData); } //...otherwise, also gets from the ones which use a proprietary API: else { //Gets the buttons down from the devices compatible with the HTML5 Gamepad API: properties = findFunction(gamepadId, gamepadIdNumeric, caseSensitive, gamepads.standard.gamepads, extraData); //Adds also the buttons down from the devices which use a proprietary API: var propertiesProprietary; for (var proprietarySystem in gamepads) { if (proprietarySystem === \"standard\") { continue; } //Just checks proprietary systems. for (var devicesType in gamepads[proprietarySystem]) { propertiesProprietary = findFunction(gamepadId, gamepadIdNumeric, caseSensitive, gamepads[proprietarySystem][devicesType], extraData); for (var propertyIndex in propertiesProprietary) { if (!properties[propertyIndex]) { properties[propertyIndex] = propertiesProprietary[propertyIndex]; } } } } } return properties; } //Returns an array with the axes from a given devices object (sub-objects returned by the CB_Controllers.getGamePads function): CB_Controllers._findAxes = function(gamepadId, gamepadIdNumeric, caseSensitive, devicesObject, extraData) { var axes = []; //Gets the pressed buttons from the desired gamepad ID (or from all the gamepads if there is no gamepad ID given): var axesLoopLength, y; for (var x in devicesObject) { if (devicesObject[x].usingPrototype) { continue; } //Skips non-real status objects. if ( gamepadId === \"\" || gamepadIdNumeric &amp;&amp; gamepadId === parseInt(x) || !gamepadIdNumeric &amp;&amp; (caseSensitive &amp;&amp; CB_trim(devicesObject[x].id) === gamepadId || !caseSensitive &amp;&amp; CB_trim(devicesObject[x].id).toLowerCase() === gamepadId.toLowerCase()) ) { if (CB_isArray(devicesObject[x].axes)) { axesLoopLength = devicesObject[x].axes.length; for (y = 0; y &lt; axesLoopLength; y++) { if (!axes[y]) { axes[y] = devicesObject[x].axes[y]; } } } } } return axes; } /** * Gets an array with information about the status of the axes of a given gamepad (or from all if none is given). * @function * @param {integer|string} [gamepadId=\"\"] - If an empty string is given, all gamepads available will be checked. Otherwise, it will only check the gamepad with the given ID or index (if any). When more than one gamepad is checked, the first axes values found which are not zero (0) will have priority. * @param {boolean} [gamepadIdNumeric=false|true] - If the \"gamepadId\" parameter is an empty string, this parameter will be ignored. Otherwise, if the \"gamepadId\" parameter is not empty and this parameter is set to true, the gamepadId parameter will be converted to integer using \"parseInt\" internally. By default, this parameter is false unless the given \"gamepadId\" is numeric. * @param {boolean} [caseSensitive=false] - Defines whether the \"gamepadId\" given should match the ID of the gamepad being case sensitive or not. This parameter will only be considered when the \"gamepadIdNumeric\" parameter is set to false. * @param {boolean} [avoidProprietary={@link CB_Configuration.CrossBase.CB_Controllers_avoidProprietary_DEFAULT}] - If set to true, proprietary gamepads will not be checked (performance will be faster). * @returns {array} Returns an array with information about the status of the axes of a given gamepad (or from all if none is given). */ CB_Controllers.getAxes = function(gamepadId, gamepadIdNumeric, caseSensitive, avoidProprietary) { return CB_Controllers._findProperty(CB_Controllers._findAxes, [], gamepadId, gamepadIdNumeric, caseSensitive, avoidProprietary); } //Returns an object with the the buttons down from a given devices object (sub-objects returned by the CB_Controllers.getGamePads function): CB_Controllers._findAxesDown = function(gamepadId, gamepadIdNumeric, caseSensitive, devicesObject, extraData) { var axes = []; if (isNaN(extraData.minimumValue) || extraData.minimumValue === null) { extraData.minimumValue = 0.5; } if (isNaN(extraData.maximumValue) || extraData.maximumValue === null) { extraData.maximumValue = extraData.minimumValue &lt;= 0 ? -0.5 : 1; } if (extraData.maximumValue &lt; extraData.minimumValue) { extraData._minimumValueBackup = extraData.minimumValue; extraData.minimumValue = extraData.maximumValue; extraData.maximumValue = extraData._minimumValueBackup; } //Gets the pressed buttons from the desired gamepad ID (or from all the gamepads if there is no gamepad ID given): var axesLoopLength, y; for (var x in devicesObject) { if (devicesObject[x].usingPrototype) { continue; } //Skips non-real status objects. if ( gamepadId === \"\" || gamepadIdNumeric &amp;&amp; gamepadId === parseInt(x) || !gamepadIdNumeric &amp;&amp; (caseSensitive &amp;&amp; CB_trim(devicesObject[x].id) === gamepadId || !caseSensitive &amp;&amp; CB_trim(devicesObject[x].id).toLowerCase() === gamepadId.toLowerCase()) ) { if (CB_isArray(devicesObject[x].axes)) { axesLoopLength = devicesObject[x].axes.length; for (y = 0; y &lt; axesLoopLength; y++) { if (!axes[y] &amp;&amp; devicesObject[x].axes[y] !== null &amp;&amp; !isNaN(devicesObject[x].axes[y]) &amp;&amp; devicesObject[x].axes[y] &gt;= extraData.minimumValue &amp;&amp; devicesObject[x].axes[y] &lt;= extraData.maximumValue) { axes[y] = devicesObject[x].axes[y]; } } } } } return axes; } /** * Gets an array with the axes pressed of a given gamepad (or from all if none is given). If more than one gamepad is pressing the same axis, it will return the value of the first one found. * @function * @param {integer|string} [gamepadId=\"\"] - If an empty string is given, all gamepads available will be checked. Otherwise, it will only check the gamepad with the given ID or index (if any). * @param {float} [minimumValue=0.5] - The minimum value (included) that the checked axis or axes must have to consider them to be pressed. * @param {float} [maximumValue=1|-0.5] - The maximum value (included) that the checked axis or axes must have to consider them to be pressed. The default value will be -0.5 if the given \"minimumValue\" is negative or zero (0) or it will be 1 otherwise. * @param {boolean} [gamepadIdNumeric=false|true] - If the \"gamepadId\" parameter is an empty string, this parameter will be ignored. Otherwise, if the \"gamepadId\" parameter is not empty and this parameter is set to true, the gamepadId parameter will be converted to integer using \"parseInt\" internally. By default, this parameter is false unless the given \"gamepadId\" is numeric. * @param {boolean} [caseSensitive=false] - Defines whether the \"gamepadId\" given should match the ID of the gamepad being case sensitive or not. This parameter will only be considered when the \"gamepadIdNumeric\" parameter is set to false. * @param {boolean} [avoidProprietary={@link CB_Configuration.CrossBase.CB_Controllers_avoidProprietary_DEFAULT}] - If set to true, proprietary gamepads will not be checked (performance will be faster). * @returns {Object} Returns an array with the axes pressed of a given gamepad (or from all if none is given). If more than one gamepad is pressing the same axis, it will return the value of the first one found. */ CB_Controllers.getAxesDown = function(gamepadId, minimumValue, maximumValue, gamepadIdNumeric, caseSensitive, avoidProprietary) { return CB_Controllers._findProperty(CB_Controllers._findAxesDown, [], gamepadId, gamepadIdNumeric, caseSensitive, avoidProprietary, { minimumValue: minimumValue, maximumValue: maximumValue }); } /** * Returns whether a given axis or axes are being pressed or not (accepts one index or more than one with an array). * @function * @param {integer|array} axesNumbers - Number with the index of the axis or array of numbers with the indexes of the axes that we want to check. * @param {integer|string} [gamepadId=\"\"] - If an empty string is given, all gamepads available will be checked. Otherwise, it will only check the gamepad with the given ID or index (if any). * @param {float} [minimumValue=0.5] - The minimum value (included) that the checked axis or axes must have to consider them to be pressed. * @param {float} [maximumValue=1|-0.5] - The maximum value (included) that the checked axis or axes must have to consider them to be pressed. The default value will be -0.5 if the given \"minimumValue\" is negative or zero (0) or it will be 1 otherwise. * @param {boolean} [allPressed=false] - If set to true, the function will return true only in the case that all given axes are being pressed. In the case that this parameter is set to true and the \"gamepadId\" parameter is set to an empty string, it will not have in mind whether the axes are pressed by a unique gamepad or by different ones as long as all axes are pressed. * @param {boolean} [gamepadIdNumeric=false|true] - If the \"gamepadId\" parameter is an empty string, this parameter will be ignored. Otherwise, if the \"gamepadId\" parameter is not empty and this parameter is set to true, the gamepadId parameter will be converted to integer using \"parseInt\" internally. By default, this parameter is false unless the given \"gamepadId\" is numeric. * @param {boolean} [caseSensitive=false] - Defines whether the \"gamepadId\" given should match the ID of the gamepad being case sensitive or not. This parameter will only be considered when the \"gamepadIdNumeric\" parameter is set to false. * @param {boolean} [avoidProprietary={@link CB_Configuration.CrossBase.CB_Controllers_avoidProprietary_DEFAULT}] - If set to true, proprietary gamepads will not be checked (performance will be faster). * @returns {boolean} If the \"allPressed\" parameter is false, returns true if the given code or any of the given codes is pressed. If the \"allPressed\" parameter is set to true, it will return true only in the case that all given axes are being pressed. In the case that the \"allPressed\" parameter is set to true and the gamepadId parameter is set to an empty string, it will not have in mind whether the axes are pressed by a unique gamepad or by different ones as long as all axes are pressed. * @todo Make it compatible with proprietary gamepads (if possible). */ CB_Controllers.isAxisDown = function(axesNumbers, gamepadId, minimumValue, maximumValue, allPressed, gamepadIdNumeric, caseSensitive, avoidProprietary) { //TODO: make it compatible with proprietary gamepads (if possible). //TODO: consider to have in mind the axis. var isDown = false; //If the parameter given is not an array, we force it to be an array: if (!CB_isArray(axesNumbers)) { axesNumbers = [axesNumbers]; } //Gets the pressed buttons from the desired gamepad ID (or from all the gamepads if there is no gamepad ID given): var axesAll = CB_Controllers.getAxesDown(gamepadId, minimumValue, maximumValue, gamepadIdNumeric, caseSensitive, avoidProprietary); //Checks whether the buttons given are being pressed or not (checking whether all are pressed, if desired): var axesNumbersLength = axesNumbers.length; for (var x = 0; x &lt; axesNumbersLength; x++) { //If the code given is a number, it exists in the axesAll array and it is being pressed: if (typeof(axesNumbers[x]) !== \"undefined\" &amp;&amp; axesNumbers[x] !== null &amp;&amp; !isNaN(axesNumbers[x]) &amp;&amp; typeof(axesAll[axesNumbers[x]]) !== \"undefined\") { isDown = true; if (!allPressed) { break; } //If the user does not want to know whether all are keys given are pressed, with one is enough so it exits. } //...otherwise, if the user wanted to know whether all given keys were pressed: else if (allPressed) { //Not all given keys are pressed so it exits: isDown = false; break; } } return isDown; } //Returns an object with the the buttons down from a given devices object (sub-objects returned by the CB_Controllers.getGamePads function): CB_Controllers._findButtons = function(gamepadId, gamepadIdNumeric, caseSensitive, devicesObject, extraData) { var buttons = {}; //Gets the pressed buttons from the desired gamepad ID (or from all the gamepads if there is no gamepad ID given): for (var x in devicesObject) { if (devicesObject[x].usingPrototype) { continue; } //Skips non-real status objects. if ( gamepadId === \"\" || gamepadIdNumeric &amp;&amp; gamepadId === parseInt(x) || !gamepadIdNumeric &amp;&amp; (caseSensitive &amp;&amp; CB_trim(devicesObject[x].id) === gamepadId || !caseSensitive &amp;&amp; CB_trim(devicesObject[x].id).toLowerCase() === gamepadId.toLowerCase()) ) { for (var buttonCode in devicesObject[x].buttons) { if (typeof(devicesObject[x].buttons[buttonCode].pressed) === \"undefined\") { continue; } //Skips properties which do not contain button objects. buttons[buttonCode] = { \"pressed\" : devicesObject[x].buttons[buttonCode].pressed, \"touched\" : devicesObject[x].buttons[buttonCode].touched, \"value\" : devicesObject[x].buttons[buttonCode].value }; } } } return buttons; } /** * Gets an object with all the buttons of a given gamepad (or from all if none is given). * @function * @param {integer|string} [gamepadId=\"\"] - If an empty string is given, all gamepads available will be checked. Otherwise, it will only check the gamepad with the given ID or index (if any). * @param {boolean} [gamepadIdNumeric=false|true] - If the \"gamepadId\" parameter is an empty string, this parameter will be ignored. Otherwise, if the \"gamepadId\" parameter is not empty and this parameter is set to true, the gamepadId parameter will be converted to integer using \"parseInt\" internally. By default, this parameter is false unless the given \"gamepadId\" is numeric. * @param {boolean} [caseSensitive=false] - Defines whether the \"gamepadId\" given should match the ID of the gamepad being case sensitive or not. This parameter will only be considered when the \"gamepadIdNumeric\" parameter is set to false. * @param {boolean} [avoidProprietary={@link CB_Configuration.CrossBase.CB_Controllers_avoidProprietary_DEFAULT}] - If set to true, proprietary gamepads will not be checked (performance will be faster). * @returns {Object} Returns an object with all the buttons of a given gamepad (or from all if none is given). The indexes will be the button code and the values will be an object with information about the button (with properties such as \"pressed\", \"value\", etc.). */ CB_Controllers.getButtons = function(gamepadId, gamepadIdNumeric, caseSensitive, avoidProprietary) { return CB_Controllers._findProperty(CB_Controllers._findButtons, {}, gamepadId, gamepadIdNumeric, caseSensitive, avoidProprietary); } //Returns an object with the the buttons down from a given devices object (sub-objects returned by the CB_Controllers.getGamePads function): CB_Controllers._findButtonsDown = function(gamepadId, gamepadIdNumeric, caseSensitive, devicesObject, extraData) { var buttonsDown = {}; //Gets the pressed buttons from the desired gamepad ID (or from all the gamepads if there is no gamepad ID given): for (var x in devicesObject) { if (devicesObject[x].usingPrototype) { continue; } //Skips non-real status objects. if ( gamepadId === \"\" || gamepadIdNumeric &amp;&amp; gamepadId === parseInt(x) || !gamepadIdNumeric &amp;&amp; (caseSensitive &amp;&amp; CB_trim(devicesObject[x].id) === gamepadId || !caseSensitive &amp;&amp; CB_trim(devicesObject[x].id).toLowerCase() === gamepadId.toLowerCase()) ) { for (var buttonCode in devicesObject[x].buttons) { if (devicesObject[x].buttons[buttonCode].pressed) { buttonsDown[buttonCode] = true; } } } } return buttonsDown; } /** * Gets an object with the buttons pressed of a given gamepad (or from all if none is given). * @function * @param {integer|string} [gamepadId=\"\"] - If an empty string is given, all gamepads available will be checked. Otherwise, it will only check the gamepad with the given ID or index (if any). * @param {boolean} [gamepadIdNumeric=false|true] - If the \"gamepadId\" parameter is an empty string, this parameter will be ignored. Otherwise, if the \"gamepadId\" parameter is not empty and this parameter is set to true, the gamepadId parameter will be converted to integer using \"parseInt\" internally. By default, this parameter is false unless the given \"gamepadId\" is numeric. * @param {boolean} [caseSensitive=false] - Defines whether the \"gamepadId\" given should match the ID of the gamepad being case sensitive or not. This parameter will only be considered when the \"gamepadIdNumeric\" parameter is set to false. * @param {boolean} [avoidProprietary={@link CB_Configuration.CrossBase.CB_Controllers_avoidProprietary_DEFAULT}] - If set to true, proprietary gamepads will not be checked (performance will be faster). * @returns {Object} Returns an object with the buttons pressed of a given gamepad (or from all if none is given). */ CB_Controllers.getButtonsDown = function(gamepadId, gamepadIdNumeric, caseSensitive, avoidProprietary) { return CB_Controllers._findProperty(CB_Controllers._findButtonsDown, {}, gamepadId, gamepadIdNumeric, caseSensitive, avoidProprietary); } /** * Returns whether a given button or buttons are being pressed or not (accepts one key code or more than one with an array). * @function * @param {integer|array} buttonCodes - Number with the button code or array of numbers with the button codes that we want to check. * @param {integer|string} [gamepadId=\"\"] - If an empty string is given, all gamepads available will be checked. Otherwise, it will only check the gamepad with the given ID or index (if any). * @param {boolean} [allPressed=false] - If set to true, the function will return true only in the case that all given buttons are being pressed. In the case that this parameter is set to true and the \"gamepadId\" parameter is set to an empty string, it will not have in mind whether the buttons are pressed by a unique gamepad or by different ones as long as all buttons are pressed. * @param {boolean} [gamepadIdNumeric=false|true] - If the \"gamepadId\" parameter is an empty string, this parameter will be ignored. Otherwise, if the \"gamepadId\" parameter is not empty and this parameter is set to true, the gamepadId parameter will be converted to integer using \"parseInt\" internally. By default, this parameter is false unless the given \"gamepadId\" is numeric. * @param {boolean} [caseSensitive=false] - Defines whether the \"gamepadId\" given should match the ID of the gamepad being case sensitive or not. This parameter will only be considered when the \"gamepadIdNumeric\" parameter is set to false. * @param {boolean} [avoidProprietary={@link CB_Configuration.CrossBase.CB_Controllers_avoidProprietary_DEFAULT}] - If set to true, proprietary gamepads will not be checked (performance will be faster). * @returns {boolean} If the \"allPressed\" parameter is false, returns true if the given code or any of the given codes is pressed. If the \"allPressed\" parameter is set to true, it will return true only in the case that all given buttons are being pressed. In the case that the \"allPressed\" parameter is set to true and the gamepadId parameter is set to an empty string, it will not have in mind whether the buttons are pressed by a unique gamepad or by different ones as long as all buttons are pressed. * @todo Make it compatible with proprietary gamepads (if possible). */ CB_Controllers.isButtonDown = function(buttonCodes, gamepadId, allPressed, gamepadIdNumeric, caseSensitive, avoidProprietary) { //TODO: make it compatible with proprietary gamepads (if possible). //TODO: consider to have in mind the axis. var isDown = false; //If the parameter given is not an array, we force it to be an array: if (!CB_isArray(buttonCodes)) { buttonCodes = [buttonCodes]; } //Gets the pressed buttons from the desired gamepad ID (or from all the gamepads if there is no gamepad ID given): var buttonsDown = CB_Controllers.getButtonsDown(gamepadId, gamepadIdNumeric, caseSensitive, avoidProprietary); //Checks whether the buttons given are being pressed or not (checking whether all are pressed, if desired): var buttonCodesLength = buttonCodes.length; for (var x = 0; x &lt; buttonCodesLength; x++) { //If the code given is a number, it exists in the buttonsDown array and it is being pressed: if (typeof(buttonCodes[x]) !== \"undefined\" &amp;&amp; buttonCodes[x] !== null &amp;&amp; !isNaN(buttonCodes[x]) &amp;&amp; typeof(buttonsDown[buttonCodes[x]]) !== \"undefined\" &amp;&amp; buttonsDown[buttonCodes[x]]) { isDown = true; if (!allPressed) { break; } //If the user does not want to know whether all are keys given are pressed, with one is enough so it exits. } //...otherwise, if the user wanted to know whether all given keys were pressed: else if (allPressed) { //Not all given keys are pressed so it exits: isDown = false; break; } } return isDown; } /** * Returns an object with the current gamepad objects, if any (using the [GamePad API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API} for non-proprietary gamepads). * @function * @param {boolean} [avoidProprietary={@link CB_Configuration.CrossBase.CB_Controllers_avoidProprietary_DEFAULT}] - If set to true, proprietary gamepads which do not use the [GamePad API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API} (as WII, WI U gamepads, etc.) will not be included in the returning object and it will only include the ones detected by the [GamePad API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API}. Otherwise, if set to true, the returning object will contain one property called \"standard\" which will contain an object with the \"gamepads\" property with the gamepad objects that use the [GamePad API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API} and possibly different properties (one per each proprietary system) and inside of them an object with the \"gamepads\" property and maybe also other properties for other kind of devices which will include the status objects of those devices for each proprietary system. For gamepads that support the [GamePad API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API}, the indexes will be the identifier for each gamepad and the value its gamepad object. For proprietary gamepads, it will contain the returning value of the \"getGamePads\" function of each proprietary API. * @returns {Object} Returns an object with the current gamepad objects, if any (using the [GamePad API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API} for non-proprietary gamepads). * @todo The proprietary ones should return better-normalized values to simulate the [GamePad API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API}. */ CB_Controllers.getGamePads = function(avoidProprietary) { if (avoidProprietary !== true &amp;&amp; avoidProprietary !== false) { avoidProprietary = CB_Configuration[CB_BASE_NAME].CB_Controllers_avoidProprietary_DEFAULT; } CB_Controllers._gamePadUpdateAll(); //Updates and normalizes all. if (!avoidProprietary) { //TODO: the proprietary ones should return normalize values to simulate the GamePad API. return { standard: { \"gamepads\" : CB_Controllers._gamepads }, WII_U : CB_Controllers_Proprietary[\"WII_U\"].getGamePads(), WII : CB_Controllers_Proprietary[\"WII\"].getGamePads() }; } return CB_Controllers._gamepads; } //TODO: find a way to do button mapping (so we could use names as LEFT, RIGHT, etc.) and normalization for most web clients and gamepads (without forgetting proprietary ones as WII U, etc.). } × Search results Close "},"CrossBase_input_controllers_CB_Controllers_Proprietary_WII.js.html":{"id":"CrossBase_input_controllers_CB_Controllers_Proprietary_WII.js.html","title":"Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII.js /** * @file Nintendo Wii remotes (Wiimotes) management. Contains the {@link CB_Controllers_Proprietary.WII} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage proprietary controller APIs. * @namespace CB_Controllers_Proprietary */ /** * Static class to manage the Nintendo Wii remotes (Wiimotes). It will return itself if it is tried to be instantiated. It uses [wii-js]{@link https://github.com/ryanmcgrath/wii-js}. NOTE: This class is still under development. * @namespace CB_Controllers_Proprietary.WII * @todo Find a way to know how to check when a button is released. * @todo Update values of CB_Controllers_Proprietary.WII._wiimotes[x].UP, etc. * @todo Do not forget x and y properties (?). */ //* Source: https://github.com/ryanmcgrath/wii-js if (typeof(CB_Controllers_Proprietary) === \"undefined\") { var CB_Controllers_Proprietary = {}; } CB_Controllers_Proprietary.WII = function() { return CB_Controllers_Proprietary.WII; }; { CB_Controllers_Proprietary.WII.initialized = false; //It will tells whether the object has been initialized or not. //Generic template object that represents the status of a Wiimote: CB_Controllers_Proprietary.WII._wiimoteInfoTemplate = //For buttons: true = pressed, false = released, undefined = unknown. { usingPrototype: true, //This property will not exist in the case it is using the real API. connected: false, realObject: undefined, id: undefined, index: undefined, buttons: { UP: { pressed: false, touched: false, value: 0 }, DOWN: { pressed: false, touched: false, value: 0 }, LEFT: { pressed: false, touched: false, value: 0 }, RIGHT: { pressed: false, touched: false, value: 0 }, A: { pressed: false, touched: false, value: 0 }, B: { pressed: undefined, touched: false, value: 0 }, C: { pressed: undefined, touched: false, value: 0 }, Z: { pressed: undefined, touched: false, value: 0 }, _1: { pressed: false, touched: false, value: 0 }, _2: { pressed: false, touched: false, value: 0 }, PLUS: { pressed: false, touched: false, value: 0 }, MINUS: { pressed: false, touched: false, value: 0 } }, axes: [0, 0], horizontal: true, roll: undefined, distance: undefined, x: undefined, y: undefined, mapping: \"\", timestamp: window.performance.now(), vibrationActuator: null //... maybe more properties will be added. }; CB_Controllers_Proprietary.WII._wiimoteInfoTemplate.buttons[\"ONE\"] = CB_Controllers_Proprietary.WII._wiimoteInfoTemplate.buttons[\"1\"] = CB_Controllers_Proprietary.WII._wiimoteInfoTemplate.buttons._1; CB_Controllers_Proprietary.WII._wiimoteInfoTemplate.buttons[\"TWO\"] = CB_Controllers_Proprietary.WII._wiimoteInfoTemplate.buttons[\"2\"] = CB_Controllers_Proprietary.WII._wiimoteInfoTemplate.buttons._2; //It will store the objects that represent the possible four Wiimotes (if any): CB_Controllers_Proprietary.WII._wiimotes = //NOTE: Using object instead of array to respect the CB_Controllers standard. { \"0\" : CB_Controllers_Proprietary.WII._wiimoteInfoTemplate, \"1\" : CB_Controllers_Proprietary.WII._wiimoteInfoTemplate, \"2\" : CB_Controllers_Proprietary.WII._wiimoteInfoTemplate, \"3\" : CB_Controllers_Proprietary.WII._wiimoteInfoTemplate }; CB_Controllers_Proprietary.WII._wiimotes[\"0\"].index = 0; CB_Controllers_Proprietary.WII._wiimotes[\"1\"].index = 1; CB_Controllers_Proprietary.WII._wiimotes[\"2\"].index = 2; CB_Controllers_Proprietary.WII._wiimotes[\"3\"].index = 3; CB_Controllers_Proprietary.WII._wiimotes[\"0\"].id = \"WII_REMOTE_0\"; CB_Controllers_Proprietary.WII._wiimotes[\"1\"].id = \"WII_REMOTE_1\"; CB_Controllers_Proprietary.WII._wiimotes[\"2\"].id = \"WII_REMOTE_2\"; CB_Controllers_Proprietary.WII._wiimotes[\"3\"].id = \"WII_REMOTE_3\"; //Initializes all values: CB_Controllers_Proprietary.WII.init = function() { if (CB_Controllers_Proprietary.WII.initialized) { return CB_Controllers_Proprietary.WII; } //The object has been initialized: CB_Controllers_Proprietary.WII.initialized = true; if (typeof(Wii) !== \"undefined\" &amp;&amp; Wii.Remote) { //Sets the events that work for all controllers: //TODO: find a way to know how to check when a button is released. //TODO: update values of CB_Controllers_Proprietary.WII._wiimotes[x].UP, etc. for (var x = 0; x &lt; 4; x++) { //NOTE: orientation scheme can be changed setting CB_Controllers_Proprietary.WII._wiimotes[index] to false. CB_Controllers_Proprietary.WII._wiimotes[x].realObject = new Wii.Remote(x + 1, {horizontal: true}); //TODO: Update \"timestamp\" property. CB_Controllers_Proprietary.WII._wiimotes[x].realObject.when(\"pressed_up\", function() { }); //\"UP\" pressed. CB_Controllers_Proprietary.WII._wiimotes[x].realObject.when(\"pressed_down\", function() { }); //\"DOWN\" pressed. CB_Controllers_Proprietary.WII._wiimotes[x].realObject.when(\"pressed_left\", function() { }); //\"LEFT\" pressed. CB_Controllers_Proprietary.WII._wiimotes[x].realObject.when(\"pressed_right\", function() { }); //\"RIGHT\" pressed. CB_Controllers_Proprietary.WII._wiimotes[x].realObject.when(\"pressed_a\", function() { }); //\"A\" pressed. CB_Controllers_Proprietary.WII._wiimotes[x].realObject.when(\"pressed_1\", function() { /* Remember ._1 and [\"1\"] */ }); //\"1\" pressed. Note: On controller 1, this triggers a menu (read https://github.com/ryanmcgrath/wii-js). CB_Controllers_Proprietary.WII._wiimotes[x].realObject.when(\"pressed_2\", function() { /* Remember ._2 and [\"2\"] */ }); //\"2\" pressed. CB_Controllers_Proprietary.WII._wiimotes[x].realObject.when(\"pressed_plus\", function() { }); //\"PLUS\" (\"+\") pressed. CB_Controllers_Proprietary.WII._wiimotes[x].realObject.when(\"pressed_minus\", function() { }); //\"MINUS\" (\"-\") pressed. CB_Controllers_Proprietary.WII._wiimotes[x].realObject.when(\"roll_change\", function() { }); //The roll of the controller (balance) changed. You can get the current roll in radians with \"this.roll\"; positive is upright, negative is the other. CB_Controllers_Proprietary.WII._wiimotes[x].realObject.when(\"distance_change\", function() { }); //The distance of the wiimote (in meters) from the TV/sensor bar has changed. This event isn't totally reliable, but should work for most cases. //Events for extra controllers that do not work on the primary controller: CB_Controllers_Proprietary.WII._wiimotes[x].realObject.when(\"pressed_b\", function() { }); //\"B\" pressed. CB_Controllers_Proprietary.WII._wiimotes[x].realObject.when(\"pressed_c\", function() { }); //\"C\" pressed (on the Nunchuk). CB_Controllers_Proprietary.WII._wiimotes[x].realObject.when(\"pressed_z\", function() { }); //\"Z\" pressed (on the Nunchuk). //TODO: do not forget x and y properties (?). } //Starts the main listener: Wii.listen(); } return CB_Controllers_Proprietary.WII; } /** * Returns an object with all gamepads simulating the [GamePad API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API}. * @function * @returns {Object} Returns an object with the \"remotes\" property which contains another object whose properties are the index of each device and the value an object with the status of that device. The number of remotes is 4 (index from \"0\" to \"3\"). Simulating the [GamePad API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API}. Those status objects which are not using the real API will have a property called \"usingPrototype\" set to true. */ CB_Controllers_Proprietary.WII.getGamePads = function() { //TODO: normalize all to simulate GamePad API. return { \"remotes\" : CB_Controllers_Proprietary.WII._wiimotes }; } } × Search results Close "},"CrossBase_input_controllers_CB_Controllers_Proprietary_WII_U.js.html":{"id":"CrossBase_input_controllers_CB_Controllers_Proprietary_WII_U.js.html","title":"Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js /** * @file Nintendo Wii U gamepad and remotes (Wiimotes) management. Contains the {@link CB_Controllers_Proprietary.WII_U} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage the Nintendo Wii U gamepad and remotes. It will return itself if it is tried to be instantiated. NOTE: This class is still under development. * @namespace CB_Controllers_Proprietary.WII_U * @todo Function or option that returns an array with the pressed buttons (LEFT: true, L: true, R: false, etc.). Use the bitmasks of CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS and CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS. */ //* Source: http://wiiubrew.org/wiki/Internet_Browser and https://www.nintendo.com/wiiu/built-in-software/browser-specs/extended-functionality/ if (typeof(CB_Controllers_Proprietary) === \"undefined\") { var CB_Controllers_Proprietary = {}; } CB_Controllers_Proprietary.WII_U = function() { return CB_Controllers_Proprietary.WII_U; }; { CB_Controllers_Proprietary.WII_U.initialized = false; //It will tells whether the object has been initialized or not. /** * Keeps the \"wiiu\" object (if any). * @var * @readonly * @type {Object} * @default */ CB_Controllers_Proprietary.WII_U.wiiuObject = null; /** * Keeps the last return value of the {@link CB_Controllers_Proprietary.WII_U.getGamePadStatus} function (if any). The value should be the last status object returned. * @var * @readonly * @type {Object} * @default */ CB_Controllers_Proprietary.WII_U.gamepadLastStatus = null; //Last read status for the gamepad. /** * Keeps an array with numeric indexes (should be from 0 to 7 maximum) that belong to each remote number and whose values contain the last return value of the {@link CB_Controllers_Proprietary.WII_U.getRemoteStatus} function (if any). Each value should be the last status object returned. * @var * @readonly * @type {array} * @default */ CB_Controllers_Proprietary.WII_U.remoteLastStatus = []; //Last read status for the remote. /** * Object which keeps the values for the Nintendo Wii U gamepad's buttons (bitmasks). * @memberof CB_Controllers_Proprietary.WII_U * @name GAMEPAD_BUTTONS * @constant * @type {Object} * @default * @property {number} LEFT_STICK_LEFT - LEFT on the LEFT STICK. Default action: Scroll/Pan. * @property {number} LEFT_STICK_RIGHT - RIGHT on the LEFT STICK. Default action: Scroll/Pan. * @property {number} LEFT_STICK_UP - UP on the LEFT STICK. Default action: Scroll/Pan. * @property {number} LEFT_STICK_DOWN - DOWN on the LEFT STICK. Default action: Scroll/Pan. * @property {number} LEFT_STICK_CLICK - CLICK on the LEFT STICK. Default action: Hide/show bottom toolbar. * @property {number} RIGHT_STICK_LEFT - LEFT on the RIGHT STICK. Default action: Zoom. * @property {number} RIGHT_STICK_RIGHT - RIGHT on the RIGHT STICK. Default action: Zoom. * @property {number} RIGHT_STICK_UP - UP on the RIGHT STICK. Default action: Zoom. * @property {number} RIGHT_STICK_DOWN - DOWN on the RIGHT STICK. Default action: Zoom. * @property {number} RIGHT_STICK_CLICK - CLICK on the RIGHT STICK. Default actionn: Toggle zoom in/out on center of screen. * @property {number} TV - \"TV\" button. * @property {number} A - \"A\" button. Send the \"Enter\" key (keyCode 13). * @property {number} B - \"B\" button. Default action: Back to previous page (hold B: Close current tab). * @property {number} X - \"X\" button. Default action: Toggle curtain mode. * @property {number} Y - \"Y\" button. Default action: View bookmarks. * @property {number} LEFT - LEFT button on the control pad. Default action: Select links / form fields. * @property {number} RIGHT - RIGHT button on the control pad. Default action: Select links / form fields. * @property {number} UP - UP button on the control pad. Default action: Select links / form fields. * @property {number} DOWN - DOWN button on the control pad. Default action: Select links / form fields. * @property {number} ZL - \"ZL\" button. Default action: Switch to previous tab (hold ZL+ZR: Tilt scrolling). * @property {number} ZR - \"ZR\" button. Default action: Switch to next tab (hold ZL+ZR: Tilt scrolling). * @property {number} L - \"L\" button. Default action: Back to previous page. * @property {number} R - \"R\" button. Default action: Forward to next page. * @property {number} START - \"START\" button. * @property {number} PLUS - Alias for {@link CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.START}. * @property {number} SELECT - \"SELECT\" button. * @property {number} MINUS - Alias for {@link CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.SELECT}. * @property {number} HOME - HOME button. Default action: Quit browser. */ CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS = {}; CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.LEFT_STICK_LEFT = 0x40000000; //1073741824. Default action: Scroll/Pan. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.LEFT_STICK_RIGHT = 0x20000000; //536870912. Default action: Scroll/Pan. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.LEFT_STICK_UP = 0x10000000; //268435456. Default action: Scroll/Pan. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.LEFT_STICK_DOWN = 0x08000000; //134217728. Default action: Scroll/Pan. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.LEFT_STICK_CLICK = 0x00040000; //262144. Default action: Hide/show bottom toolbar. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.RIGHT_STICK_LEFT = 0x04000000; //67108864. Default action: Zoom. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.RIGHT_STICK_RIGHT = 0x02000000; //33554432. Default action: Zoom. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.RIGHT_STICK_UP = 0x01000000; //16777216. Default action: Zoom. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.RIGHT_STICK_DOWN = 0x00800000; //8388608. Default action: Zoom. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.RIGHT_STICK_CLICK = 0x00020000; //131072. Default actionn: Toggle zoom in/out on center of screen. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.TV = 0x00010000; //65536. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.A = 0x00008000; //32768. Default action: Send the \"Enter\" key (keyCode 13). CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.B = 0x00004000; //16384. Default action: Back to previous page (hold B: Close current tab). CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.X = 0x00002000; //8192. Default action: Toggle curtain mode. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.Y = 0x00001000; //4096. Default action: View bookmarks. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.LEFT = 0x00000800; //2048. Default action: Select links / form fields. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.RIGHT = 0x00000400; //1024. Default action: Select links / form fields. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.UP = 0x00000200; //512. Default action: Select links / form fields. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.DOWN = 0x00000100; //256. Default action: Select links / form fields. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.ZL = 0x00000080; //128. Default action: Switch to previous tab (hold ZL+ZR: Tilt scrolling). CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.ZR = 0x00000040; //64. Default action: Switch to next tab (hold ZL+ZR: Tilt scrolling). CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.L = 0x00000020; //32. Default action: Back to previous page. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.R = 0x00000010; //16. Default action: Forward to next page. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.START = CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.PLUS = 0x00000008; //8. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.SELECT = CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.MINUS = 0x00000004; //4. CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.HOME = 0x00000002; //2. Default action: Quit browser. /** * Object which keeps the values for the Nintendo Wii U remote's buttons (bitmasks). * @memberof CB_Controllers_Proprietary.WII_U * @name REMOTE_BUTTONS * @constant * @type {Object} * @default * @property {number} UP - UP button. * @property {number} DOWN - DOWN button. * @property {number} LEFT - LEFT button. * @property {number} RIGHT - RIGHT button. * @property {number} A - \"A\" button. * @property {number} B - \"B\" button. * @property {number} ONE - \"1\" button. * @property {number} _1 - Alias for {@link CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.ONE}. * @property {number} 1 - Alias for {@link CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.ONE}. * @property {number} TWO - \"2\" button. * @property {number} _2 - Alias for {@link CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.TWO}. * @property {number} 2 - Alias for {@link CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.TWO}. * @property {number} PLUS - PLUS (\"+\") button. * @property {number} MINUS - MINUS (\"-\") button. * @property {number} HOME - HOME button. */ CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS = {}; CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.UP = 0x00000800; //2048. CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.DOWN = 0x00000400; //1024. CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.LEFT = 0x00000100; //256. CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.RIGHT = 0x00000200; //512. CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.A = 0x00000008; //8. CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.B = 0x00000004; //4. CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.ONE = CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS._1 = CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS[\"1\"] = 0x00000001; //1. CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.TWO = CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS._2 = CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS[\"2\"] = 0x00000002; //2. CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.PLUS = 0x00001000; //4096. CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.MINUS = 0x00000010; //16. CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.HOME = 0x00000080; //128. //Initializes all values: CB_Controllers_Proprietary.WII_U.init = function() { if (CB_Controllers_Proprietary.WII_U.initialized) { return CB_Controllers_Proprietary.WII_U; } //The object has been initialized: CB_Controllers_Proprietary.WII_U.initialized = true; //If it does not exist any property, creates it (empty object): if (typeof(wiiu) === \"undefined\" || wiiu === null) { var wiiu = {}; } if (typeof(wiiu.gamepad) === \"undefined\" || wiiu.gamepad === null) { wiiu.gamepad = { usingPrototype: true, //This property will not exist in the case it is using the real API. //General: isDataValid: 0, //After a successful update, wiiu.gamepad.isDataValid will be set to 1. If no update has happened yet, or if the GamePad is not connected, it will be set to 0. isEnabled: 0, //If the GamePad is connected wiiu.gamepad.isEnabled will be set to 1, else it will be set to 0. //Touch screen: tpTouch: 0, //1 if touch is present. tpValidity: 3, //0 = X and Y coordinates valid, 1 = X coordinate invalid, 2 = Y coordinate invalid, 3 = X and Y coordinates invalid. tpX: undefined, //X position in screen coordinates. tpY: undefined, //Y position in screen coordinates. contentX: undefined, //X position in page coordinates. contentY: undefined, //Y position in page coordinates. //Analog sticks (from -1.0 to 1.0): lStickX: 0, //GamePad Left Control Stick X deflection. lStickY: 0, //GamePad Left Control Stick Y deflection. rStickX: 0, //GamePad Right Control Stick X deflection. rStickY: 0, //GamePad Right Control Stick Y deflection. //Buttons: hold: 0, //Bitmask (to use with properties of CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS). //Accelerometer (acceleration forces in Gs. When held level and motionless, the force of gravity will cause these variables to contain the vector (0.0, -1.0, 0.0)): accX: undefined, //Force on X (horizontal) axis. accY: undefined, //Force on Y (depth) axis. accZ: undefined, //Force on Z (vertical) axis. //Gyroscope (when the GamePad is motionless these values hover around 0.0): gyroX: undefined, //Rotation speed around X (horizontal) axis. gyroY: undefined, //Rotation speed around Y (depth) axis. gyroZ: undefined, //Rotation speed around Z (vertical) axis. //Angle (if properly calibrated, angleX and angleZ should hover around 0.0 when the GamePad is held level, but as the gyroscopes have limited range and resolution the alignment will drift with use): //Note: A change of 1.0 in these values represents a complete revolution around the specified axis. Multiple revolutions around the same axis will cause the value to continuously increase or decrease. angleX: undefined, //Rotation around X (horizontal) axis. angleY: undefined, //Rotation around Y (depth) axis. angleZ: undefined, //Rotation around Z (vertical) axis. //Orientation: //Note: This is a basis of 3 perpendicular unit vectors; each vector has length 1.0 and points along the relevant axis of the GamePad relative to an arbitrary starting orientation in three-dimensional space. //X (horizontal) axis: dirXx: undefined, dirXy: undefined, dirXz: undefined, //Y (depth) axis: dirYx: undefined, dirYy: undefined, dirYz: undefined, //Z (vertical) axis: dirZx: undefined, dirZy: undefined, dirZz: undefined }; } if (typeof(wiiu.gamepad.update) !== \"function\") { wiiu.gamepad.update = function() { return wiiu.gamepad; }; } if (typeof(wiiu.remote) === \"undefined\" || wiiu.remote === null) { var remoteFakeObject = { usingPrototype: true, //This property will not exist in the case it is using the real API. //General: isDataValid: 0, //If the specified Wii Remote returns valid data, wiiu.remote.isDataValid will be set to 1. If no update has happened yet, or if the selected Wii Remote is not connected, it will be set to 0. //Buttons: held: 0, //Bitmask (to use with properties of CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS). //Accelerometer (acceleration forces in Gs. When held level and motionless, the force of gravity will cause these variables to contain the vector (0.0, -1.0, 0.0)): accX: undefined, //Force on X (horizontal) axis accY: undefined, //Force on Y (depth) axis accZ: undefined, //Force on Z (vertical) axis //Pointer (track the Wii Remote's cursor on the screen): setCursorViewable: function(n, enable) { return null; }, //Enable or disable the display of a Wii Remote's cursor. dpdX: undefined, //X position in screen coordinates dpdY: undefined, //Y position in screen coordinates dpdDistance: undefined, //Distance between Wii Remote and Sensor Bar contentX: undefined, //X position in page coordinates contentY: undefined, //Y position in page coordinates isCursorViewable: 0, //1 if cursor display is enabled dpdValidity: 3, //0 = X and Y coordinates valid, 1 = X coordinate invalid, 2 = Y coordinate invalid, 3 = X and Y coordinates invalid. //Motion Plus: //Note: Basis of 3 perpendicular unit vectors; Each vector has length 1.0 and points along the relevant axis of the GamePad relative to an arbitrary starting orientation in three-dimensional space. //X (horizontal) axis mplsDirXx: undefined, mplsDirXy: undefined, mplsDirXz: undefined, //Y (depth) axis mplsDirYx: undefined, mplsDirYy: undefined, mplsDirYz: undefined, //Z (vertical) axis mplsDirZx: undefined, mplsDirZy: undefined, mplsDirZz: undefined, //The following variables are also available to track the motion of the Wii Remote: mplsAngX: undefined, //Rotation around X (horizontal) axis. mplsAngY: undefined, //Rotation around Y (depth) axis. mplsAngZ: undefined, //Rotation around Z (vertical) axis. mplsVelX: undefined, //Movement speed along X (horizontal) axis. mplsVelY: undefined, //Movement speed along Y (depth) axis. mplsVelZ: undefined, //Movement speed along Z (vertical) axis. mplsRollX: undefined, //TODO: ? (Source: http://wiiubrew.org/wiki/Internet_Browser). mplsRollY: undefined //TODO: ?. }; wiiu.remote = { _devices: [remoteFakeObject] }; } if (typeof(wiiu.remote.update) !== \"function\") { wiiu.remote.update = function(n) { return typeof(wiiu.remote._devices[n]) === \"undefined\" ? remoteFakeObject : wiiu.remote._devices[n]; }; } //Stores the object (maybe fake one): CB_Controllers_Proprietary.WII_U.wiiuObject = wiiu; //Gets the status for the first time: CB_Controllers_Proprietary.WII_U.getGamePadStatus(); return CB_Controllers_Proprietary.WII_U; } /** * Normalizes the given gamepad status object, adding missing properties. * @function * @param {object} gamepadStatusObject - The gamepad status object that we want to normalize. * @returns {Object} Returns the given gamepad status object but normalized, adding missing properties. */ CB_Controllers_Proprietary.WII_U.normalizeGamepad = function(statusObject) { if (typeof(statusObject) === \"undefined\" || statusObject === null) { statusObject = {}; } //Sets the \"id\" and \"index\" properties: statusObject.index = 0; statusObject.id = \"WII_U_GAMEPAD_0\"; //Sets its \"connected\" property: statusObject.connected = !!statusObject.isEnabled; //Updates the \"timestamp\" property if the data has been updated: if (statusObject.isDataValid) { statusObject.timestamp = window.performance.now(); } //Sets the \"buttons\" property: if (typeof(statusObject.buttons) === \"undefined\" || statusObject.buttons === null) { statusObject.buttons = {}; } for (var buttonName in CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS) { if (typeof(statusObject.buttons[buttonName]) === \"undefined\" || statusObject.buttons[buttonName] === null) { statusObject.buttons[buttonName] = {}; } statusObject.buttons[buttonName].pressed = statusObject.buttons[buttonName].touched = !!(statusObject.hold &amp; CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS[buttonName]); //statusObject.hold is a bitmask with the buttons pressed. statusObject.buttons[buttonName].value = statusObject.buttons[buttonName].pressed ? 1 : 0; } //Sets the \"axes\" property: if (typeof(statusObject.axes) === \"undefined\" || statusObject.axes === null) { statusObject.axes = [0, 0, 0, 0, 0, 0]; } //Axes for LEFT, RIGHT, UP and DOWN: statusObject.axes[0] = 0; if (statusObject.buttons.LEFT.pressed) { statusObject.axes[0] += -1; } if (statusObject.buttons.RIGHT.pressed) { statusObject.axes[0] += 1; } statusObject.axes[1] = 0; if (statusObject.buttons.UP.pressed) { statusObject.axes[1] += -1; } if (statusObject.buttons.DOWN.pressed) { statusObject.axes[1] += 1; } //Axes for LEFT, RIGHT, UP and DOWN of the LEFT STICK and their value: statusObject.axes[2] = statusObject.lStickX || 0; statusObject.buttons.LEFT_STICK_LEFT.value = 0; statusObject.buttons.LEFT_STICK_RIGHT.value = 0; if (statusObject.axes[2] &lt; 0) { statusObject.buttons.LEFT_STICK_LEFT.value = statusObject.axes[2] * -1; } else if (statusObject.axes[2] &gt; 0) { statusObject.buttons.LEFT_STICK_RIGHT.value = statusObject.axes[2]; } statusObject.axes[3] = statusObject.lStickY || 0; statusObject.buttons.LEFT_STICK_UP.value = 0; statusObject.buttons.LEFT_STICK_DOWN.value = 0; if (statusObject.axes[3] &lt; 0) { statusObject.buttons.LEFT_STICK_UP.value = statusObject.axes[3] * -1; } else if (statusObject.axes[3] &gt; 0) { statusObject.buttons.LEFT_STICK_DOWN.value = statusObject.axes[3]; } //Axes for LEFT, RIGHT, UP and DOWN of the RIGHT STICK and their value: statusObject.axes[4] = statusObject.rStickX || 0; statusObject.buttons.RIGHT_STICK_LEFT.value = 0; statusObject.buttons.RIGHT_STICK_RIGHT.value = 0; if (statusObject.axes[4] &lt; 0) { statusObject.buttons.RIGHT_STICK_LEFT.value = statusObject.axes[4] * -1; } else if (statusObject.axes[4] &gt; 0) { statusObject.buttons.RIGHT_STICK_RIGHT.value = statusObject.axes[4]; } statusObject.axes[5] = statusObject.rStickY || 0; statusObject.buttons.RIGHT_STICK_UP.value = 0; statusObject.buttons.RIGHT_STICK_DOWN.value = 0; if (statusObject.axes[5] &lt; 0) { statusObject.buttons.RIGHT_STICK_UP.value = statusObject.axes[5] * -1; } else if (statusObject.axes[5] &gt; 0) { statusObject.buttons.RIGHT_STICK_DOWN.value = statusObject.axes[5]; } //Updates the rest of the properties: statusObject.mapping = \"\"; statusObject.vibrationActuator = null; return statusObject; } /** * Normalizes the given remote status object, adding missing properties. * @function * @param {object} gamepadStatusObject - The remote status object that we want to normalize. * @param {integer} [n=0] - Number of the remote whose status we want to get, from 0 to 7 (both numbers included, 8 in total). It will be used as its identifier. * @returns {Object} Returns the given remote status object but normalized, adding missing properties. */ CB_Controllers_Proprietary.WII_U.normalizeRemote = function(statusObject, n) { if (typeof(statusObject) === \"undefined\" || statusObject === null) { statusObject = {}; } //Sets the \"id\" and \"index\" properties: statusObject.index = n ? n : 0; statusObject.id = \"WII_U_REMOTE_\" + statusObject.index; //Sets its \"connected\" property: if (!statusObject.connected) { statusObject.connected = !!statusObject.isDataValid; } //Updates the \"timestamp\" property if the data has been updated: if (statusObject.isDataValid) { statusObject.timestamp = window.performance.now(); } //Sets the \"buttons\" property: if (typeof(statusObject.buttons) === \"undefined\" || statusObject.buttons === null) { statusObject.buttons = {}; } for (var buttonName in CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS) { if (typeof(statusObject.buttons[buttonName]) === \"undefined\" || statusObject.buttons[buttonName] === null) { statusObject.buttons[buttonName] = {}; } statusObject.buttons[buttonName].pressed = statusObject.buttons[buttonName].touched = !!(statusObject.held &amp; CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS[buttonName]); //statusObject.held is a bitmask with the buttons pressed. statusObject.buttons[buttonName].value = statusObject.buttons[buttonName].pressed ? 1 : 0; } //Sets the \"axes\" property: if (typeof(statusObject.axes) === \"undefined\" || statusObject.axes === null) { statusObject.axes = [0, 0]; } //Axes for LEFT, RIGHT, UP and DOWN: statusObject.axes[0] = 0; if (statusObject.buttons.LEFT.pressed) { statusObject.axes[0] += -1; } if (statusObject.buttons.RIGHT.pressed) { statusObject.axes[0] += 1; } statusObject.axes[1] = 0; if (statusObject.buttons.UP.pressed) { statusObject.axes[1] += -1; } if (statusObject.buttons.DOWN.pressed) { statusObject.axes[1] += 1; } //Updates the rest of the properties: statusObject.mapping = \"\"; statusObject.vibrationActuator = null; return statusObject; } /** * Returns an object with the current status of each button of the gamepad. Already calls {@link CB_Controllers_Proprietary.WII_U.normalizeGamepad} automatically. * @function * @returns {Object} Returns an object with the current status of each button of the gamepad. */ CB_Controllers_Proprietary.WII_U.getGamePadStatus = function() { return CB_Controllers_Proprietary.WII_U.gamepadLastStatus = CB_Controllers_Proprietary.WII_U.normalizeGamepad(CB_Controllers_Proprietary.WII_U.wiiuObject.gamepad.update()); } /** * Returns an object with the current status of each button of the desired remote. Already calls {@link CB_Controllers_Proprietary.WII_U.normalizeRemote} automatically. * @function * @param {integer} [n=0] - Number of the remote whose status we want to get, from 0 to 7 (both numbers included, 8 in total). * @returns {Object} Returns an object with the current status of each button of the desired remote. * @todo Check documentation to see whether the first index should be 0 or 1 and maximum 7 or 8. */ CB_Controllers_Proprietary.WII_U.getRemoteStatus = function(n) { if (typeof(n) === \"undefined\" || n === null || !isNaN(n) || n &lt; 0) { n = 0; } //TODO: check documentation to see whether the minimum should be 0 or 1 and maximum 7 or 8. else if (n &gt; 8) { n = 7; } return CB_Controllers_Proprietary.WII_U.remoteLastStatus[n] = CB_Controllers_Proprietary.WII_U.normalizeRemote(CB_Controllers_Proprietary.WII_U.wiiuObject.remote.update(n), n); } /** * Returns an object with the gamepad and all remotes simulating the [GamePad API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API}. Uses the {@link CB_Controllers_Proprietary.WII_U.getRemoteStatus} and {@link CB_Controllers_Proprietary.WII_U.getRemoteStatus} internally so the objects will be normalized already. * @function * @returns {Object} Returns an object with two properties: \"gamepads\" and \"remotes\". Each of those two properties will have an object as value whose names will be the index of the device and the value an object with the status of that device. In the case of the gamepad (which is unique), there will only be one index (\"0\", zero). In the case of the remotes, it will contain the status objects of all the remotes. The number of remotes is 8 (index from \"0\" to \"7\"). Simulating the [GamePad API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API}. Those status objects which are not using the real API will have a property called \"usingPrototype\" set to true. * @todo Check the documentation to find out the maximum number of remotes allowed and find out whether the first index should be 0 or 1 and last one 7 or 8. */ CB_Controllers_Proprietary.WII_U.getGamePads = function() { //TODO: normalize all to simulate GamePad API. return { \"gamepads\" : { \"0\" : CB_Controllers_Proprietary.WII_U.getGamePadStatus() }, \"remotes\" : { //TODO: check the documentation to find out the maximum number of remotes allowed. \"0\" : CB_Controllers_Proprietary.WII_U.getRemoteStatus(0), \"1\" : CB_Controllers_Proprietary.WII_U.getRemoteStatus(1), \"2\" : CB_Controllers_Proprietary.WII_U.getRemoteStatus(2), \"3\" : CB_Controllers_Proprietary.WII_U.getRemoteStatus(3), \"4\" : CB_Controllers_Proprietary.WII_U.getRemoteStatus(4), \"5\" : CB_Controllers_Proprietary.WII_U.getRemoteStatus(5), \"6\" : CB_Controllers_Proprietary.WII_U.getRemoteStatus(6), \"7\" : CB_Controllers_Proprietary.WII_U.getRemoteStatus(7) } }; } //TODO: function or option that returns an array with the pressed buttons (LEFT: true, L: true, R: false, etc.). Use the bitmasks of CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS and CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS. } × Search results Close "},"CrossBase_device_CB_Device.js.html":{"id":"CrossBase_device_CB_Device.js.html","title":"Source: CrossBase/device/CB_Device.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/device/CB_Device.js /** * @file Device management. Contains the {@link CB_Device} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage the device. It will return itself if it is tried to be instantiated. * @namespace * @todo Think about defining a parameter on many of the events to disable automatic normalization of the event object. */ var CB_Device = function() { return CB_Device; }; { CB_Device.initialized = false; //It will tells whether the object has been initialized or not. //Initializes all values: CB_Device.init = function() { if (CB_Device.initialized) { return CB_Device; } //The object has been initialized: CB_Device.initialized = true; //If now() static function not available, uses getTime() method: if (!Date.now) { Date.now = function() { return new Date().getTime(); }; } //If desired and it is possible, changes the CB_Device.getTime method to use high precission: 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). { CB_Device.getTime = function() { return window.performance.timing.navigationStart + window.performance.now() || Date.now(); }; } //Initializes sub-classes: CB_Device.Battery.init(); return CB_Device; } /** * 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). * @function * @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. */ CB_Device.getTime = function() //Can be replaced in CB_Device.init to use high precision. { return Date.now(); }; /** * 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). * @function * @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). */ CB_Device.getTiming = function() //Can be replaced in CB_Device.init to use high precision. { return window.performance.now(); }; //Sets a function to execute when a desired event is fired: CB_Device._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture, target) { //If they are not set, use default values for optional parameters: if (typeof(keepOldFunction) === \"undefined\" || keepOldFunction === null) { keepOldFunction = true; } //If not set, it keeps old function by default. if (typeof(target) === \"undefined\" || target === null) { target = window; } //If a function has been sent: if (typeof(eventFunction) === \"function\") { //If able, adds the function given to the event: CB_Events.add(target, eventName, eventFunction, useCapture, keepOldFunction, true); } //...but if the function given is null, it will cancel the event: else if (eventFunction === null) { CB_Events.removeByName(target, eventName); } } } //End of the static class CB_Device. /** * Static class to manage the device's location. It will return itself if it is tried to be instantiated. * @namespace * @todo Normalize more differences between web clients. */ CB_Device.Location = function() { return CB_Device.Location; }; { /** * Keeps the last watch ID that gets the location constantly. Used by the {@link CB_Device.Location.getConstantly} function. * @var * @readonly * @type {integer|null} * @default */ CB_Device.Location.getConstantly_lastId = null; /** * 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. * @var * @readonly * @type {Object|null} * @default */ CB_Device.Location.keepAwake_locationLockGPS = null; /** * Keeps the callback function used when location can be gotten successfully for the {@link CB_Device.Location.get} function. * @var * @readonly * @type {function|null} * @default */ CB_Device.Location.get_callbackOk = null; /** * Keeps the callback function used when there is an error getting the location for the {@link CB_Device.Location.get} function. * @var * @readonly * @type {function|null} * @default */ CB_Device.Location.get_callbackError = null; /** * Keeps the last options used by the {@link CB_Device.Location.get} function. * @var * @readonly * @type {Object|undefined} * @default */ CB_Device.Location.get_options = undefined; /** * Keeps the callback function used when location can be gotten successfully for the {@link CB_Device.Location.getConstantly} function. * @var * @readonly * @type {function|null} * @default */ CB_Device.Location.getConstantly_callbackOk = null; /** * Keeps the callback function used when there is an error getting the location for the {@link CB_Device.Location.getConstantly} function. * @var * @readonly * @type {function|null} * @default */ CB_Device.Location.getConstantly_callbackError = null; /** * Keeps the last options used by the {@link CB_Device.Location.getConstantly} function. * @var * @readonly * @type {Object|undefined} * @default */ CB_Device.Location.getConstantly_options = undefined; /** * 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. * @function * @returns {boolean} */ CB_Device.Location.isSupported = function() { return (window.navigator &amp;&amp; \"geolocation\" in navigator &amp;&amp; typeof(navigator.geolocation.getCurrentPosition) !== \"undefined\"); } CB_Device.Location._getFirstTime = false; /** * 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}). * @function * @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. * @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. * @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. * @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. * @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. * @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. * @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. */ CB_Device.Location.get = function(callbackOk, callbackError, options, keepOldCallbackOk, keepOldCallbackError, keepOldOptions) { if (typeof(keepOldCallbackOk) === \"undefined\" || keepOldCallbackOk === null) { keepOldCallbackOk = true; } //If not set, it keeps old ok function by default. if (typeof(keepOldCallbackError) === \"undefined\" || keepOldCallbackError === null) { keepOldCallbackError = true; } //If not set, it keeps old error function by default. if (CB_Device.Location.isSupported() &amp;&amp; typeof(callbackOk) === \"function\") { if (!keepOldCallbackOk) { CB_Device.Location.get_callbackOk = callbackOk; } else { var callbackOkOld = CB_Device.Location.get_callbackOk; CB_Device.Location.get_callbackOk = function(locationObject) { if (typeof(callbackOkOld) === \"function\") { callbackOkOld(locationObject); } if (typeof(callbackOk) === \"function\") { callbackOk(locationObject); } }; } if (!keepOldCallbackError) { CB_Device.Location.get_callbackError = callbackError; } else { var callbackErrorOld = CB_Device.Location.get_callbackError; CB_Device.Location.get_callbackError = function(error) { if (typeof(callbackErrorOld) === \"function\") { callbackErrorOld(error); } if (typeof(callbackError) === \"function\") { callbackError(error); } }; } if (!keepOldOptions) { CB_Device.Location.get_options = options; } if (CB_Device.Location._getFirstTime === true) { CB_Device.Location._getFirstTime = false; navigator.geolocation.getCurrentPosition(function(){}, function(){}, {}); //Hack. Source: Niels Steenbeek @ http://stackoverflow.com/questions/3397585/navigator-geolocation-getcurrentposition-sometimes-works-sometimes-doesnt } return navigator.geolocation.getCurrentPosition(CB_Device.Location.get_callbackOk, CB_Device.Location.get_callbackError, CB_Device.Location.get_options); } return false; } CB_Device.Location._getConstantlyFirstTime = true; /** * 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}). * @function * @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). * @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. * @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. * @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). * @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). * @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). * @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. */ CB_Device.Location.getConstantly = function(callbackOkOrId, callbackError, options, keepOldCallbackOk, keepOldCallbackError, keepOldOptions) { //If either callback function has been given, starts getting the position constantly: if (typeof(callbackOkOrId) === \"function\") { if (typeof(keepOldCallbackOk) === \"undefined\" || keepOldCallbackOk === null) { keepOldCallbackOk = true; } //If not set, it keeps old ok function by default. if (typeof(keepOldCallbackError) === \"undefined\" || keepOldCallbackError === null) { keepOldCallbackError = true; } //If not set, it keeps old error function by default. if (CB_Device.Location.isSupported() &amp;&amp; typeof(navigator.geolocation.watchPosition) !== \"undefined\") { if (!keepOldCallbackOk) { CB_Device.Location.getConstantly_callbackOk = callbackOkOrId; } else { var callbackOkOld = CB_Device.Location.getConstantly_callbackOk; CB_Device.Location.getConstantly_callbackOk = function(locationObject) { if (typeof(callbackOkOld) === \"function\") { callbackOkOld(locationObject); } if (typeof(callbackOkOrId) === \"function\") { callbackOkOrId(locationObject); } }; } if (!keepOldCallbackError) { CB_Device.Location.getConstantly_callbackError = callbackError; } else { var callbackErrorOld = CB_Device.Location.getConstantly_callbackError; CB_Device.Location.getConstantly_callbackError = function(error) { if (typeof(callbackErrorOld) === \"function\") { callbackErrorOld(error); } if (typeof(callbackError) === \"function\") { callbackError(error); } }; } if (!keepOldOptions) { CB_Device.Location.getConstantly_options = options; } if (CB_Device.Location._getConstantlyFirstTime === true) { CB_Device.Location._getConstantlyFirstTime = false; navigator.geolocation.watchPosition(function(){}, function(){}, {}); //Hack. Source: Niels Steenbeek @ http://stackoverflow.com/questions/3397585/navigator-geolocation-getcurrentposition-sometimes-works-sometimes-doesnt } CB_Device.Location.getConstantly_lastId = navigator.geolocation.watchPosition(CB_Device.Location.getConstantly_callbackOk, CB_Device.Location.getConstantly_callbackError, CB_Device.Location.getConstantly_options); return CB_Device.Location.getConstantly_lastId; } } //...otherwise, stops getting the position constantly: else { if (window.navigator &amp;&amp; \"geolocation\" in navigator &amp;&amp; typeof(navigator.geolocation.clearWatch) !== \"undefined\") { //if (typeof(callbackOkOrId) === \"undefined\" || callbackOkOrId === null) { callbackOkOrId = CB_Device.Location.getConstantly_lastId; } if (isNaN(callbackOkOrId) || CB_trim(callbackOkOrId) === \"\") { callbackOkOrId = CB_Device.Location.getConstantly_lastId; } return navigator.geolocation.clearWatch(callbackOkOrId); } } return false; } /** * 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}). * @function * @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. * @param {boolean} [keepOldCallbackOk=false] - If it is set to false, it will not remove the current \"callbackOk\" (if any) which was/were set previously. * @param {boolean} [keepOldCallbackError=false] - If it is set to false, it will remove the current \"callbackError\" (if any) which was/were set previously. * @param {boolean} [keepOldOptions=false] - If it is set to false, it will remove the current \"options\" (if any) which were set previously. * @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. */ CB_Device.Location.getConstantlyDisable = function(id, keepOldCallbackOk, keepOldCallbackError, keepOldOptions) { //if (typeof(id) === \"function\") { id = undefined; } //Prevents calling CB_Device.Location.getConstantly with a function as parameter since that is for starting the watcher. if (isNaN(id) || !id) { id = undefined; } //Prevents calling CB_Device.Location.getConstantly with a function as parameter since that is for starting the watcher. if (!keepOldCallbackOk) { CB_Device.Location.getConstantly_callbackOk = null; } if (!keepOldCallbackError) { CB_Device.Location.getConstantly_callbackError = null; } if (!keepOldOptions) { CB_Device.Location.getConstantly_options = undefined; } return CB_Device.Location.getConstantly(id); } /** * 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). * @function * @param {boolean} [keepAwake=true] - Defines whether we want to keep it awake or stop doing it. * @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. * @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). */ CB_Device.Location.keepAwake = function(keepAwake, lock) { if (typeof(keepAwake) === \"undefined\" || keepAwake === null) { keepAwake = true; } //If we want to lock the device to keep it awake: if (keepAwake) { if (window.navigator &amp;&amp; typeof(window.navigator.requestWakeLock) !== \"undefined\") { CB_Device.Location.keepAwake_locationLockGPS = window.navigator.requestWakeLock(\"gps\"); //So far, only works in Firefox/Firefox OS. return CB_Device.Location.keepAwake_locationLockGPS; } } //...otherwise, if we want to release the lock that keeps the device awake: else { if (typeof(lock) === \"undefined\" || lock === null) { if (typeof(CB_Device.Location.keepAwake_locationLockGPS) !== \"undefined\" &amp;&amp; CB_Device.Location.keepAwake_locationLockGPS !== null) { lock = CB_Device.Location.keepAwake_locationLockGPS; } else { return false; } } if (typeof(lock.unlock) !== \"undefined\") { return lock.unlock(); } //So far, only works in Firefox/Firefox OS. } return false; } } //End of the static class CB_Device.Location. /** * Static class to manage the device's orientation. It will return itself if it is tried to be instantiated. * @namespace * @todo Normalize more differences between web clients. */ CB_Device.Orientation = function() { return CB_Device.Orientation; }; { /** * 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. * @var * @readonly * @type {integer|null} * @default */ CB_Device.Orientation.cordova_getCompassConstantly_lastId = null; /** * 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. * @function * @returns {boolean} * @todo Think about using the \"ondeviceorientationabsolute\" event. */ CB_Device.Orientation.isSupported = function() { return (\"DeviceOrientationEvent\" in window || \"ondeviceorientation\" in window); } /** * Tells whether the [MozOrientation API]{@link https://developer.mozilla.org/docs/Web/Events/MozOrientation} is supported or not. * @function * @returns {boolean} */ CB_Device.Orientation.isMozOrientationSupported = function() { return (\"MozOrientation\" in window); } /** * 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. * @function * @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. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @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. * @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. * @todo Think about using the \"deviceorientationabsolute\" event. */ CB_Device.Orientation.onChange = function(eventFunction, keepOldFunction, useCapture) { if (CB_Device.Orientation.isSupported()) { return CB_Device.Orientation._setEvent(\"deviceorientation\", eventFunction, keepOldFunction, useCapture, window); } else if (CB_Device.Orientation.isMozOrientationSupported()) { return CB_Device.Orientation._setEvent(\"MozOrientation\", eventFunction, keepOldFunction, useCapture, window); } else { return false; } } //Sets a function to execute when a desired event is fired: CB_Device.Orientation._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture, target) { var wrapperFunction = eventFunction; if (typeof(eventFunction) === \"function\") { wrapperFunction = function(e) { e = CB_Device.Orientation.normalizeEvent(e, eventName); return eventFunction(e); }; } CB_Device._setEvent(eventName, wrapperFunction, keepOldFunction, useCapture, target); } /** * 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. * @function * @param {Event} e - The event object that we want to normalize. * @param {('deviceorientation'|'MozOrientation')} eventName - The name of the event that we want to normalize. Case sensitive. * @returns {Event} Returns the given event object again but normalized (if possible). * @todo Think about using the \"deviceorientationabsolute\" event. * @todo Normalize more differences between web clients. */ CB_Device.Orientation.normalizeEvent = function(e, eventName) { e = CB_Events.normalize(e); if (typeof(e) !== \"undefined\" &amp;&amp; e !== null) { if (eventName === \"deviceorientation\") { 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/ } else if (eventName === \"MozOrientation\") { if (!e.gamma &amp;&amp; !e.beta) //For FF3.6+ (Source: https://developer.mozilla.org/en-US/docs/Web/Events/MozOrientation) { e.gamma = -(e.x * (180 / Math.PI)); e.beta = -(e.y * (180 / Math.PI)); } } //TODO: there are still more differences between web clients! } return e; } /** * 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. * @function * @returns {boolean} */ CB_Device.Orientation.isCompassNeedsCalibrationSupported = function() { return (\"CompassNeedsCalibration\" in window || \"oncompassneedscalibration\" in window); //return (\"DeviceMotionEvent\" in window || \"ondevicemotion\" in window); } /** * 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. * @function * @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. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @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. * @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. */ CB_Device.Orientation.onCompassNeedsCalibration = function(eventFunction, keepOldFunction, useCapture) { if (!CB_Device.Orientation.isCompassNeedsCalibrationSupported()) { return false; } return CB_Device._setEvent(\"compassneedscalibration\", eventFunction, keepOldFunction, useCapture, window); } /** * Tells whether the [Apache Cordova's Device Orientation plugin]{@link https://github.com/apache/cordova-plugin-device-orientation} is available or not. * @function * @returns {boolean} */ CB_Device.Orientation.cordova_isCompassSupported = function() { 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); } /** * 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. * @function * @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). * @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). * @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. * @todo Add a function to normalize the event and call it automatically. */ CB_Device.Orientation.cordova_getCompass = function(callbackOk, callbackError) { if (!CB_Device.Orientation.cordova_isCompassSupported()) { return false; } navigator.compass.getCurrentHeading(callbackOk, callbackError); } /** * 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). * @function * @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}. * @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}. * @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}. * @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. * @todo Add a function to normalize the event and call it automatically. * @todo Add parameters to keep old callbacks and options. */ CB_Device.Orientation.cordova_getCompassConstantly = function(callbackOkOrId, callbackError, options) //Note: options can be an object with two optional properties (\"frequency\" and \"filter\"). { if (!CB_Device.Orientation.cordova_isCompassSupported()) { return false; } //If either callback function has been given, starts getting the compass heading constantly: if (typeof(callbackOkOrId) === \"function\") { CB_Device.Orientation.cordova_getCompassConstantly_lastId = navigator.compass.watchHeading(callbackOkOrId, callbackError, options); return CB_Device.Orientation.cordova_getCompassConstantly_lastId; } //...otherwise, stops getting the compass heading constantly: else { //if (typeof(callbackOkOrId) === \"undefined\" || callbackOkOrId === null) { callbackOkOrId = CB_Device.Orientation.cordova_getCompassConstantly_lastId; } if (isNaN(callbackOkOrId) || CB_trim(callbackOkOrId) === \"\") { callbackOkOrId = CB_Device.Orientation.cordova_getCompassConstantly_lastId; } navigator.compass.clearWatch(callbackOkOrId); return; } return false; } /** * 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). * @function * @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}. * @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. * @todo Add parameters to keep old callbacks and options. */ CB_Device.Orientation.cordova_getCompassConstantlyDisable = function(id) { 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. return CB_Device.Orientation.cordova_getCompassConstantly(id); } } //End of the static class CB_Device.Orientation. /** * Static class to manage the device's motion. It will return itself if it is tried to be instantiated. * @namespace * @todo Normalize more differences between web clients. */ CB_Device.Motion = function() { return CB_Device.Motion; }; { /** * 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. * @var * @readonly * @type {integer|null} * @default */ CB_Device.Motion.cordova_getAccelerationConstantly_lastId = null; /** * 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. * @function * @returns {boolean} */ CB_Device.Motion.isSupported = function() { return (\"DeviceMotionEvent\" in window || \"ondevicemotion\" in window); } /** * 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. * @function * @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. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @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. * @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. */ CB_Device.Motion.onChange = function(eventFunction, keepOldFunction, useCapture) { if (!CB_Device.Motion.isSupported()) { return false; } return CB_Device._setEvent(\"devicemotion\", eventFunction, keepOldFunction, useCapture, window); } /** * Tells whether the [Apache Cordova's Device Motion plugin]{@link https://github.com/apache/cordova-plugin-device-motion} is available or not. * @function * @returns {boolean} */ CB_Device.Motion.cordova_isAccelerationSupported = function() { 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); } /** * 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. * @function * @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). * @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). * @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. */ CB_Device.Motion.cordova_getAcceleration = function(callbackOk, callbackError) { if (!CB_Device.Motion.cordova_isAccelerationSupported()) { return false; } var callbackOkWrapper = function(e) { e = CB_Device.Motion.cordova_getAccelerationNormalized(e); if (typeof(callbackOk) === \"function\") { callbackOk(e); } } //Normalizes the event. navigator.accelerometer.getCurrentAcceleration(callbackOkWrapper, callbackError); } /** * 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). * @function * @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}. * @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}. * @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}. * @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. * @todo Add parameters to keep old callbacks and options. */ CB_Device.Motion.cordova_getAccelerationConstantly = function(callbackOkOrId, callbackError, options) //Note: options can be an object with an optional property (\"frequency\"). { if (!CB_Device.Motion.cordova_isAccelerationSupported()) { return false; } //If either callback function has been given, starts getting the acceleration constantly: if (typeof(callbackOkOrId) === \"function\") { var callbackOkOrIdWrapper = function(e) { e = CB_Device.Motion.cordova_getAccelerationNormalized(e); if (typeof(callbackOkOrId) === \"function\") { callbackOkOrId(e); } } //Normalizes the event. CB_Device.Motion.cordova_getAccelerationConstantly_lastId = navigator.accelerometer.watchAcceleration(callbackOkOrIdWrapper, callbackError, options); return CB_Device.Motion.cordova_getAccelerationConstantly_lastId; } //...otherwise, stops getting the acceleration constantly: else { //if (typeof(callbackOkOrId) === \"undefined\" || callbackOkOrId === null) { callbackOkOrId = CB_Device.Motion.cordova_getAccelerationConstantly_lastId; } if (isNaN(callbackOkOrId) || CB_trim(callbackOkOrId) === \"\") { callbackOkOrId = CB_Device.Motion.cordova_getAccelerationConstantly_lastId; } navigator.accelerometer.clearWatch(callbackOkOrId); return; } return false; } /** * 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). * @function * @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}. * @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. * @todo Add parameters to keep old callbacks and options. */ CB_Device.Motion.cordova_getAccelerationConstantlyDisable = function(id) { 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. return CB_Device.Motion.cordova_getAccelerationConstantly(id); } /** * 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. * @function * @param {Object} accelerometerData - The acceleration object that we want to normalize. * @returns {Event} Returns the given acceleration object again but normalized (if possible). * @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. */ CB_Device.Motion.cordova_getAccelerationNormalized = function(accelerometerData) { if (typeof(accelerometerData) !== \"undefined\" &amp;&amp; accelerometerData !== null) { if (typeof(accelerometerData.accelerationIncludingGravity) === \"undefined\" || accelerometerData.accelerationIncludingGravity === null) { accelerometerData.accelerationIncludingGravity = {}; if (typeof(accelerometerData.x) !== \"undefined\") { accelerometerData.accelerationIncludingGravity.x = accelerometerData.x; } if (typeof(accelerometerData.y) !== \"undefined\") { accelerometerData.accelerationIncludingGravity.y = accelerometerData.y; } if (typeof(accelerometerData.z) !== \"undefined\") { accelerometerData.accelerationIncludingGravity.z = accelerometerData.z; } } //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. } return accelerometerData; } } //End of the static class CB_Device.Motion. /** * Static class to manage the device's battery. It will return itself if it is tried to be instantiated. * @namespace * @todo Normalize more differences between web clients. */ CB_Device.Battery = function() { return CB_Device.Battery; }; { CB_Device.Battery._cordova_level = null; //Keeps the battery level for Apache Cordova. CB_Device.Battery._cordova_isPlugged = null; //Keeps whether the device is plugged in or not for Apache Cordova. //Initializes all values: CB_Device.Battery.init = function() { //Adds the event listener to let Apache Cordova get the battery level: CB_Events.add(window, \"batterystatus\", function(batteryStatus) { CB_Device.Battery._cordova_level = batteryStatus.level; CB_Device.Battery._cordova_isPlugged = batteryStatus.isPlugged; }, true, true, false); } /** * Tells whether the [Battery Status API]{@link https://developer.mozilla.org/docs/Web/API/Battery_Status_API} (or compatible one) is available or not. * @function * @returns {boolean} */ CB_Device.Battery.isSupported = function() { return !!(window.navigator &amp;&amp; (typeof(navigator.getBattery) === \"function\" || navigator.battery || navigator.webkitBattery || navigator.mozBattery || navigator.msBattery)); } /** * 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. &lt;br /&gt; 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. &lt;br /&gt; 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). * @function * @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). * @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. * @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. * @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. * @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. * @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. */ CB_Device.Battery.get = function(callbackOk, chargingOnFail, levelOnFail, chargingTimeOnFail, dischargingTimeOnFail) { var batteryObject = null; if (window.navigator) { if (typeof(navigator.getBattery) === \"function\") { return navigator.getBattery().then(callbackOk); } else if (typeof(navigator.battery) !== \"undefined\") { batteryObject = navigator.battery; } else if (typeof(navigator.webkitBattery) !== \"undefined\") { batteryObject = navigator.webkitBattery; } else if (typeof(navigator.mozBattery) !== \"undefined\") { batteryObject = navigator.mozBattery; } else if (typeof(navigator.msBattery) !== \"undefined\") { batteryObject = navigator.msBattery; } } if (typeof(batteryObject) === \"undefined\" || batteryObject === null) { batteryObject = { \"charging\" : typeof(CB_Device.Battery._cordova_isPlugged) !== \"undefined\" &amp;&amp; CB_Device.Battery._cordova_isPlugged !== null ? CB_Device.Battery._cordova_isPlugged : chargingOnFail, \"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, \"chargingTime\" : chargingTimeOnFail, \"dischargingTime\" : dischargingTimeOnFail, \"onchargingchange\" : null, \"onchargingtimechage\" : null, \"ondischargingtimechange\" : null, \"onlevelchange\" : null }; } if (typeof(callbackOk) === \"function\") { callbackOk(batteryObject); } return batteryObject; } /** * 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. &lt;br /&gt; 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). * @function * @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). * @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. * @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. */ CB_Device.Battery.isCharging = function(callbackOk, valueOnFail) { var objectOrPromise = CB_Device.Battery.get(function(batteryObject) { if (typeof(callbackOk) === \"function\") { callbackOk(batteryObject.charging); } }, valueOnFail); if (typeof(objectOrPromise) !== \"undefined\" &amp;&amp; objectOrPromise !== null &amp;&amp; typeof(objectOrPromise.charging) !== \"undefined\") { return objectOrPromise.charging; } return objectOrPromise; } /** * 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. &lt;br /&gt; 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). * @function * @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). * @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. * @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. */ CB_Device.Battery.getLevel = function(callbackOk, valueOnFail) { var objectOrPromise = CB_Device.Battery.get(function(batteryObject) { if (typeof(callbackOk) === \"function\") { callbackOk(batteryObject.level); } }, undefined, valueOnFail).level; if (typeof(objectOrPromise) !== \"undefined\" &amp;&amp; objectOrPromise !== null &amp;&amp; typeof(objectOrPromise.level) !== \"undefined\") { return objectOrPromise.level; } return objectOrPromise; } /** * 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. &lt;br /&gt; 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). * @function * @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). * @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. * @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. */ CB_Device.Battery.getChargingTime = function(callbackOk, valueOnFail) { var objectOrPromise = CB_Device.Battery.get(function(batteryObject) { if (typeof(callbackOk) === \"function\") { callbackOk(batteryObject.chargingTime); } }, undefined, undefined, valueOnFail).chargingTime; if (typeof(objectOrPromise) !== \"undefined\" &amp;&amp; objectOrPromise !== null &amp;&amp; typeof(objectOrPromise.chargingTime) !== \"undefined\") { return objectOrPromise.chargingTime; } return objectOrPromise; } /** * 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. &lt;br /&gt; 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). * @function * @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). * @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. * @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. */ CB_Device.Battery.getDischargingTime = function(callbackOk, valueOnFail) { var objectOrPromise = CB_Device.Battery.get(function(batteryObject) { if (typeof(callbackOk) === \"function\") { callbackOk(batteryObject.dischargingTime); } }, undefined, undefined, undefined, valueOnFail).dischargingTime; if (typeof(objectOrPromise) !== \"undefined\" &amp;&amp; objectOrPromise !== null &amp;&amp; typeof(objectOrPromise.dischargingTime) !== \"undefined\") { return objectOrPromise.dischargingTime; } return objectOrPromise; } /** * 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). * @function * @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. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @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. * @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. */ CB_Device.Battery.onChargingChange = function(eventFunction, keepOldFunction, useCapture) { return CB_Device.Battery._setEvent(\"chargingchange\", eventFunction, keepOldFunction, useCapture) } /** * 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). * @function * @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. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @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. * @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. */ CB_Device.Battery.onChargingTimeChange = function(eventFunction, keepOldFunction, useCapture) { return CB_Device.Battery._setEvent(\"chargingtimechage\", eventFunction, keepOldFunction, useCapture) } /** * 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). * @function * @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. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @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. * @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. */ CB_Device.Battery.onDischargingTimeChange = function(eventFunction, keepOldFunction, useCapture) { return CB_Device.Battery._setEvent(\"dischargingtimechange\", eventFunction, keepOldFunction, useCapture) } /** * 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). * @function * @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. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @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. * @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. */ CB_Device.Battery.onLevelChange = function(eventFunction, keepOldFunction, useCapture) { return CB_Device.Battery._setEvent(\"levelchange\", eventFunction, keepOldFunction, useCapture) } //Sets an event for the Battery Status API (Battery API): CB_Device.Battery._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture) { if (!CB_Device.Battery.isSupported()) { return false; } if (window.navigator &amp;&amp; typeof(navigator.getBattery) === \"function\") { return navigator.getBattery().then ( function(batteryObject) { CB_Device._setEvent ( eventName, function(e) { if (typeof(eventFunction) === \"function\") { eventFunction(batteryObject, eventName, e); } }, keepOldFunction, useCapture, batteryObject ); } ); } var eventFunctionWrapper = eventFunction; if (typeof(eventFunction) === \"function\") { eventFunctionWrapper = function(e) { eventFunction(CB_Device.Battery.get(), eventName, e); }; } return CB_Device._setEvent(eventName, eventFunctionWrapper, keepOldFunction, useCapture, navigator.battery || navigator.webkitBattery || navigator.mozBattery || navigator.msBattery); } /** * 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}. * @function * @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. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @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. */ CB_Device.Battery.cordova_onChange = function(eventFunction, keepOldFunction, useCapture) { return CB_Device._setEvent(\"batterystatus\", eventFunction, keepOldFunction, useCapture, window); } /** * 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}. * @function * @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. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @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. */ CB_Device.Battery.cordova_onLow = function(eventFunction, keepOldFunction, useCapture) { return CB_Device._setEvent(\"batterylow\", eventFunction, keepOldFunction, useCapture, window); } /** * 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}. * @function * @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. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @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. */ CB_Device.Battery.cordova_onCritical = function(eventFunction, keepOldFunction, useCapture) { return CB_Device._setEvent(\"batterycritical\", eventFunction, keepOldFunction, useCapture, window); } } //End of the static class CB_Device.Battery. /** * Static class to manage the device's vibration. It will return itself if it is tried to be instantiated. * @namespace */ CB_Device.Vibration = function() { return CB_Device.Vibration; }; { /** * 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. * @function * @returns {boolean} */ CB_Device.Vibration.isSupported = function() { return (window.navigator &amp;&amp; \"vibrate\" in navigator &amp;&amp; typeof(navigator.vibrate) === \"function\"); } /** * 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}). * @function * @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. * @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. */ CB_Device.Vibration.start = function(vibration) { navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; if (navigator.vibrate) { return navigator.vibrate(vibration); } return false; } /** * 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}). * @function * @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. */ CB_Device.Vibration.stop = function() { return CB_Device.Vibration.start(0); } } //End of the static class CB_Device.Vibration. /** * Static class to manage the device's ambient light sensor. It will return itself if it is tried to be instantiated. * @namespace * @todo Normalize more differences between web clients. */ CB_Device.AmbientLight = function() { return CB_Device.AmbientLight; }; { /** * 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. * @function * @returns {boolean} */ CB_Device.AmbientLight.isSupported = function() { return (typeof(AmbientLightSensor) !== \"undefined\" || \"ondevicelight\" in window || \"onlightlevel\" in window); } /** * 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/}. &lt;br/&gt; 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): &lt;br /&gt; 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. &lt;br /&gt; 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. &lt;br /&gt; 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. * @function * @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. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @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. * @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). * @returns {undefined|false} Returns false in the case that no way to get the ambient light is available or undefined otherwise. */ CB_Device.AmbientLight.onChange = function(eventFunction, keepOldFunction, useCapture, callbackError) { if (typeof(AmbientLightSensor) !== \"undefined\") { var sensor = new AmbientLightSensor(); sensor.start(); sensor.onerror = callbackError; //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. //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. if (\"onchange\" in sensor) { return CB_Device.AmbientLight._setEvent(\"change\", eventFunction, keepOldFunction, useCapture, sensor, sensor); } //event.reading.illuminance will contain the units in lux. else { return CB_Device.AmbientLight._setEvent(\"reading\", eventFunction, keepOldFunction, useCapture, sensor, sensor); } //sensor.illuminance will contain the units in lux. } else if (\"ondevicelight\" in window) { return CB_Device.AmbientLight._setEvent(\"devicelight\", eventFunction, keepOldFunction, useCapture, window); //event.value will contain the units in lux. } else if (\"onlightlevel\" in window) { 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! } //if (typeof(callbackError) === \"function\") { callbackError(); } return false; } //Sets a function to execute when a desired event is fired: CB_Device.AmbientLight._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture, target, sensor) { var wrapperFunction = eventFunction; if (typeof(eventFunction) === \"function\") { wrapperFunction = function(e) { e = CB_Device.AmbientLight.normalizeEvent(e, eventName, sensor); return eventFunction(e); }; } CB_Device._setEvent(eventName, wrapperFunction, keepOldFunction, useCapture, target); } /** * 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. * @function * @param {Event} e - The event object that we want to normalize. * @param {('change'|'reading'|'devicelight'|'lightlevel')} eventName - The name of the event that we want to normalize. Case sensitive. * @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/}. * @returns {Event} Returns the given event object again but normalized (if possible). * @todo Normalize more differences between web clients. */ CB_Device.AmbientLight.normalizeEvent = function(e, eventName, sensor) { e = CB_Events.normalize(e); //Normalizes ambient light sensor data: /* if (typeof(AmbientLightSensor) !== \"undefined\" &amp;&amp; e &amp;&amp; e.reading &amp;&amp; typeof(e.reading.illuminance) !== \"undefined\") { if (typeof(e.value) === \"undefined\" || e.value === null) { e.value = e.reading.illuminance; } } */ if (typeof(AmbientLightSensor) !== \"undefined\" &amp;&amp; typeof(sensor) !== \"undefined\" &amp;&amp; sensor !== null) { if (eventName === \"change\") { //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. 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. } else if (eventName === \"reading\") { e.value = sensor ? sensor.illuminance : e.value; //sensor.illuminance will contain the units in lux. } } return e; } } //End of the static class CB_Device.AmbientLight. /** * Static class to manage the device's proximity sensor. It will return itself if it is tried to be instantiated. * @namespace * @todo Normalize more differences between web clients. */ CB_Device.Proximity = function() { return CB_Device.Proximity; }; { /** * 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. * @function * @returns {boolean} */ CB_Device.Proximity.isSupported = function() { return (typeof(ProximitySensor) !== \"undefined\" || \"ondeviceproximity\" in window || \"onuserproximity\" in window); } /** * 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}. &lt;br/&gt; 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: &lt;br /&gt; 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). &lt;br /&gt; 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. &lt;br /&gt; 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. * @function * @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. * @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}. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener or not. * @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. * @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). * @returns {undefined|false} Returns false in the case that no way to get the proximity is available or undefined otherwise. */ CB_Device.Proximity.onChange = function(eventFunction, detectNear, keepOldFunction, useCapture, callbackError) { if (!detectNear) { if (typeof(ProximitySensor) !== \"undefined\") { var sensor = new ProximitySensor(); sensor.start(); sensor.onerror = callbackError; //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. //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. if (\"onchange\" in sensor) { return CB_Device.Proximity._setEvent(\"change\", eventFunction, keepOldFunction, useCapture, sensor, sensor); } //event.reading.distance will contain the units in centimeters. 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. } else if (\"ondeviceproximity\" in window) { return CB_Device.Proximity._setEvent(\"deviceproximity\", eventFunction, keepOldFunction, useCapture, window); //event.value will contain the units in centimeters. } } else { if (\"onuserproximity\" in window) { return CB_Device.Proximity._setEvent(\"userproximity\", eventFunction, keepOldFunction, useCapture, window); //event.near will be received (boolean). } } //if (typeof(callbackError) === \"function\") { callbackError(); } return false; } //Sets a function to execute when a desired event is fired: CB_Device.Proximity._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture, target, sensor) { var wrapperFunction = eventFunction; if (typeof(eventFunction) === \"function\") { wrapperFunction = function(e) { e = CB_Device.Proximity.normalizeEvent(e, eventName, sensor); return eventFunction(e); }; } CB_Device._setEvent(eventName, wrapperFunction, keepOldFunction, useCapture, target); } /** * 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. * @function * @param {Event} e - The event object that we want to normalize. * @param {('change'|'reading'|'deviceproximity'|'userproximity')} eventName - The name of the event that we want to normalize. Case sensitive. * @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/}. * @returns {Event} Returns the given event object again but normalized (if possible). * @todo Normalize more differences between web clients. */ CB_Device.Proximity.normalizeEvent = function(e, eventName, sensor) { e = CB_Events.normalize(e); /* //Normalizes proximity sensor data: if (typeof(ProximitySensor) !== \"undefined\" &amp;&amp; e &amp;&amp; event.reading &amp;&amp; typeof(event.reading.distance) !== \"undefined\") { if (typeof(e.value) === \"undefined\" || e.value === null) { e.value = event.reading.distance; } } */ if (typeof(ProximitySensor) !== \"undefined\" &amp;&amp; typeof(sensor) !== \"undefined\" &amp;&amp; sensor !== null) { if (eventName === \"change\") { //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. 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. } else if (eventName === \"reading\") { e.value = sensor ? sensor.distance : e.value; //sensor.distance will contain the units in centimeters. e.near = sensor ? sensor.near : e.near; //sensor.near will be a boolean telling whether an object is near or not. } } return e; } } //End of the static class CB_Device.Proximity. × Search results Close "},"CrossBase_general_CB_Elements.js.html":{"id":"CrossBase_general_CB_Elements.js.html","title":"Source: CrossBase/general/CB_Elements.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/general/CB_Elements.js /** * @file DOM elements management. Contains the {@link CB_Elements} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage DOM elements. It will return itself if it is tried to be instantiated. * @namespace * @todo Think about creating a function called \"add\" or \"create\" to create a new element (it could accept \"tagName\", \"id\" and \"content\" parameters). * @todo Think about creating \"setStyle\" and \"setStyleById\" methods to add a given style attribute and also supporting a boolean parameter to also add the style attribute with vendor prefixes (webkit, moz, ms, o, khtml) if we want to. */ var CB_Elements = function() { return CB_Elements; }; { CB_Elements.initialized = false; //It will tells whether the object has been initialized or not. //Initializes all values: CB_Elements.init = function() { //If this is the fist time: if (CB_Elements.initialized) { return CB_Elements; } //The object has been initialized: CB_Elements.initialized = true; //TODO. if (!document.body) { var tagBody = CB_Elements.tag(\"body\", document); if (typeof(tagBody) !== \"undefined\" &amp;&amp; tagBody !== null &amp;&amp; typeof(tagBody[0]) !== \"undefined\" &amp;&amp; tagBody[0] !== null) { document.body = tagBody[0]; } } return CB_Elements; } CB_Elements._tagCache = {}; /** * Returns elements by their tag name. * @function * @param {string} [tagName='*'] - The name of the tag whose elements we want to find. Use asterisk (\"*\") in the case that we want all the elements. * @param {Node} [baseElement=document] - The node element parent where we want to focus our search. * @param {boolean} [useCache={@link CB_Configuration.CrossBase.CB_Elements_tag_USE_CACHE}] - Defines whether to try to get the result from an internal cache (it will exist if we previously called the function with the same parameters) or not. The internal cache will be updated when this parameter is set to false or it will be created automatically when it did not exist before. * @returns {NodeList|array} Returns the elements (NodeList or array, depending on the web client). */ CB_Elements.tag = function(tagName, baseElement, useCache) { if (typeof(baseElement) === \"undefined\" || baseElement === null) { baseElement = document; } //Uses document as default base element. if (typeof(useCache) === \"undefined\" || useCache === null) { useCache = CB_Configuration[CB_BASE_NAME].CB_Elements_tag_USE_CACHE; } //If no tag name is sent, uses \"*\" (all) by default: tagName = CB_trim(tagName).toLowerCase(); if (tagName === \"\") { tagName = \"*\"; } if (!useCache || typeof(CB_Elements._tagCache[baseElement]) === \"undefined\" || CB_Elements._tagCache[baseElement] === null || typeof(CB_Elements._tagCache[baseElement][tagName]) === \"undefined\" || CB_Elements._tagCache[baseElement][tagName] === null) { if (typeof(CB_Elements._tagCache[baseElement]) === \"undefined\" || CB_Elements._tagCache[baseElement] === null) { CB_Elements._tagCache[baseElement] = {}; } if (typeof(baseElement.getElementsByTagName) !== \"undefined\" &amp;&amp; baseElement.getElementsByTagName !== null) { CB_Elements._tagCache[baseElement][tagName] = baseElement.getElementsByTagName(tagName); if (tagName === \"*\" &amp;&amp; CB_Elements._tagCache[baseElement][tagName].length === 0 &amp;&amp; typeof(document.all) !== \"undefined\" &amp;&amp; document.all !== null) { CB_Elements._tagCache[baseElement][tagName] = document.all; } } else if (baseElement.querySelectorAll) { CB_Elements._tagCache[baseElement][tagName] = baseElement.querySelectorAll(tagName); } else if (document.querySelectorAll) { CB_Elements._tagCache[baseElement][tagName] = document.querySelectorAll(tagName); } else if (typeof(baseElement.all) !== \"undefined\" &amp;&amp; baseElement.all !== null) { if (tagName === \"*\") { CB_Elements._tagCache[baseElement][tagName] = baseElement.all; } else { CB_Elements._tagCache[baseElement][tagName] = baseElement.all.tags(tagName); } } else if (typeof(document.all) !== \"undefined\" &amp;&amp; document.all !== null) { if (tagName === \"*\") { CB_Elements._tagCache[baseElement][tagName] = document.all; } else { CB_Elements._tagCache[baseElement][tagName] = document.all.tags(tagName); } } else if (baseElement.layers || document.layers) { if (typeof(CB_Elements._tagCache[baseElement][tagName]) === \"undefined\" || CB_Elements._tagCache[baseElement][tagName] === null) { CB_Elements._tagCache[baseElement][tagName] = []; } var allElements = baseElement.layers || document.layers; //If we want all elements, then we get all of them: if (tagName === \"*\") { CB_Elements._tagCache[baseElement][tagName] = allElements; } //...otherwise, obtains all elements with the given tag name: else { //If any elements were obtained, we select just the ones with the desired tag name: var allElementsLength = allElements.length; var elementCurrent; for (var x = 0; x &lt; allElementsLength; x++) { elementCurrent = allElements[x]; if (elementCurrent !== null &amp;&amp; typeof(elementCurrent.tagName) !== \"undefined\") { if (CB_trim(elementCurrent.tagName).toLowerCase() === tagName) { CB_Elements._tagCache[baseElement][tagName].push(elementCurrent); } } } //CB_Elements._tagCache[baseElement][tagName] = baseElement.layers[tagName]; } } else if (typeof(CB_Elements._tagCache[baseElement][tagName]) === \"undefined\" || CB_Elements._tagCache[baseElement][tagName] === null) { CB_Elements._tagCache[baseElement][tagName] = []; } /* else if (baseElement.layers) { CB_Elements._tagCache[baseElement][tagName] = baseElement.layers[tagName]; } else if (document.layers) { CB_Elements._tagCache[baseElement][tagName] = document.layers[tagName]; }*/ //If we used \"*\" and there is no elements, we try to use document.all instead (for old web clients): //if (tagName === \"*\" &amp;&amp; CB_Elements._tagCache[baseElement][tagName].length === 0) //{ //if (all in document) { CB_Elements._tagCache[baseElement][tagName] = document.all; } //} CB_Elements._tagCache[baseElement][tagName] = CB_Elements._tagCache[baseElement][tagName] || []; } return CB_Elements._tagCache[baseElement][tagName]; } /** * Returns elements by their tag name, updating (or creating) the internal cache. Calls the {@link CB_Elements.tag} function internally, with the \"useCache\" parameter set to false. * @function * @param {string} [tagName='*'] - The name of the tag whose elements we want to find. Use asterisk (\"*\") in the case that we want all the elements. * @param {Node} [baseElement=document] - The node element parent where we want to focus our search. * @returns {NodeList|array} Returns the elements (NodeList or array, depending on the web client). */ CB_Elements.tagCacheUpdate = function(tagName, baseElement) { return CB_Elements.tag(tagName, baseElement, false); } /** * Clears the internal cache user by {@link CB_Elements.tag} and others. If no parameter is given, whole internal cache will be cleared. * @function * @param {string} [tagName] - The name of the tag whose internal cache we want to clear. Use asterisk (\"*\") in the case that we want to clear the internal cache for {@link CB_Elements.tag} which is used when it is called with this exact parameter. If not provided, it will clear the whole internal cache or the internal cache that belongs to the \"baseElement\" given (if provided). * @param {Node} [baseElement] - The node element parent whose internal cache we want to clear. If not provided but \"tagName\" is provided, it will clear the internal cache which matches the given \"tagName\" for any nodes. If it is provided but \"tagName\" is not, it will clear all the internal cache that belongs to this node element. * @returns {Object} Returns the current internal cache after clearing it (if it is has been possible), which is an associative array of two dimensions (JavaScript object) whose first index belongs to the nodes, the second and last index belongs to the tag name and the value belongs to the returning value of the {@link CB_Elements.tag} function when it was called for those parameters. */ CB_Elements.tagCacheClear = function(tagName, baseElement) { tagName = CB_trim(tagName).toLowerCase(); //If no base element and no tag name are defined, we clean all the array: if (typeof(baseElement) === \"undefined\" &amp;&amp; tagName === \"\" || baseElement === null &amp;&amp; (typeof(tagName) === \"undefined\" || tagName === null)) { CB_Elements._tagCache = {}; } //...otherwise, if both base element and tag name are defined, we clear the elements of that base element: else if (typeof(baseElement) !== \"undefined\" &amp;&amp; baseElement !== null &amp;&amp; tagName !== \"\") { if (typeof(CB_Elements._tagCache[baseElement]) !== \"undefined\" &amp;&amp; CB_Elements._tagCache[baseElement] !== null) { if (typeof(CB_Elements._tagCache[baseElement][tagName]) !== \"undefined\" &amp;&amp; CB_Elements._tagCache[baseElement][tagName] !== null) { CB_Elements._tagCache[baseElement][tagName] = null; } } } //...otherwise, if a base element is defined (but not a tagName), we clear all elements of that base element: else if (typeof(baseElement) !== \"undefined\" &amp;&amp; baseElement !== null) { if (typeof(CB_Elements._tagCache[baseElement]) !== \"undefined\" &amp;&amp; CB_Elements._tagCache[baseElement] !== null) { CB_Elements._tagCache[baseElement] = {}; } } //...otherwise, if a tag name is defined (but not a base element), we clear all the elements of that tag name from all the element bases: else if (tagName !== \"\") { for (var currentBaseElement in CB_Elements._tagCache) { if (typeof(CB_Elements._tagCache[currentBaseElement][tagName]) !== \"undefined\" &amp;&amp; CB_Elements._tagCache[currentBaseElement][tagName] !== null) { CB_Elements._tagCache[currentBaseElement][tagName] = null; } } } return CB_Elements._tagCache; } /** * Alias for {@link CB_Elements.tagRemove}. * @function CB_Elements.removeByTagName * @see {@link CB_Elements.tagRemove} */ /** * Removes elements by their tag name. * @function * @param {string} [tagName='*'] - The name of the tag whose elements we want to delete. Use asterisk (\"*\") in the case that we want all the elements. * @param {Node} [baseElement=document] - The node element parent where we want to focus our search. * @param {boolean} [useCache={@link CB_Configuration.CrossBase.CB_Elements_tag_USE_CACHE}] - Defines whether to try to get the result from an internal cache (it will exist if we previously called the function with the same parameters) or not. The internal cache will be updated when this parameter is set to false or it will be created automatically when it did not exist before. */ CB_Elements.tagRemove = CB_Elements.removeByTagName = function(tagName, baseElement, useCache) { if (typeof(baseElement) === \"undefined\" || baseElement === null) { baseElement = document; } //Uses document as default base element. tagName = CB_trim(tagName); if (tagName === \"\") { tagName = \"*\"; } var elementsOriginal = CB_Elements.tag(tagName, baseElement, useCache); if (typeof(elementsOriginal) !== \"undefined\" &amp;&amp; elementsOriginal !== null &amp;&amp; typeof(elementsOriginal.length) !== \"undefined\" &amp;&amp; elementsOriginal.length !== null &amp;&amp; elementsOriginal.length &gt; 0) { var elements = []; var elementsLength = elementsOriginal.length; for (var x = 0; x &lt; elementsLength; x++) { elements[x] = elementsOriginal[x]; } elementsLength = elements.length; for (var x = 0; x &lt; elementsLength; x++) { //elements[x].parentNode.removeChild(elements[x]); CB_Elements.remove(elements[x]); } CB_Elements._tagCache[baseElement][tagName] = null; } } CB_Elements._classesCache = {}; /** * Returns elements by their class or classes name. * @function * @param {string} classNames - The name of the class or classes (separated by a blank space) whose elements we want to find. The order of the classes is just important for the internal cache. * @param {Node} [baseElement=document] - The node element parent where we want to focus our search. * @param {boolean} [useCache={@link CB_Configuration.CrossBase.CB_Elements_classes_USE_CACHE}] - Defines whether to try to get the result from an internal cache (it will exist if we previously called the function with the same parameters) or not. The internal cache will be updated when this parameter is set to false or it will be created automatically when it did not exist before. * @returns {NodeList|array} Returns the elements (NodeList or array, depending on the web client). */ CB_Elements.classes = function(classNames, baseElement, useCache) { if (typeof(useCache) === \"undefined\" || useCache === null) { useCache = CB_Configuration[CB_BASE_NAME].CB_Elements_classes_USE_CACHE; } if (typeof(baseElement) === \"undefined\" || baseElement === null) { baseElement = document; } //If no class name is sent, returns am empty array: classNames = CB_trim(classNames);//.toLowerCase(); if (classNames === \"\") { return []; } if (!useCache || typeof(CB_Elements._classesCache[baseElement]) === \"undefined\" || CB_Elements._classesCache[baseElement] === null || typeof(CB_Elements._classesCache[baseElement][classNames]) === \"undefined\" || CB_Elements._classesCache[baseElement][classNames] === null) { if (typeof(CB_Elements._classesCache[baseElement]) === \"undefined\" || CB_Elements._classesCache[baseElement] === null) { CB_Elements._classesCache[baseElement] = {}; } //CB_Elements._classesCache[baseElement][classNames] = baseElement.getElementsByClassName(classNames); if (typeof(baseElement.getElementsByClassName) !== \"undefined\" &amp;&amp; baseElement.getElementsByClassName !== null) { CB_Elements._classesCache[baseElement][classNames] = baseElement.getElementsByClassName(classNames); } else if (baseElement.querySelectorAll) { CB_Elements._classesCache[baseElement][classNames] = baseElement.querySelectorAll(\".\" + classNames.replace(/ /g, \".\")); } else if (document.querySelectorAll) { CB_Elements._classesCache[baseElement][classNames] = document.querySelectorAll(\".\" + classNames.replace(/ /g, \".\")); } else { //Obtains all elements: var allElements = CB_Elements.tag(\"*\", baseElement, useCache); //If any elements were obtained, we select just the ones with the desired class name: var allElementsLength = allElements.length; if (allElementsLength &gt; 0) { if (typeof(CB_Elements._classesCache[baseElement][classNames]) === \"undefined\" || CB_Elements._classesCache[baseElement][classNames] === null) { CB_Elements._classesCache[baseElement][classNames] = []; } /* //classNames = classNames.toLowerCase(); var elementCurrent; var classes; var classesLength; for (var x = 0; x &lt; allElementsLength; x++) { elementCurrent = allElements[x]; if (elementCurrent !== null) { classes = elementCurrent.className.split(\" \"); classesLength = classes.length; for (var y = 0; y &lt; classesLength; y++) { classes[y] = CB_trim(classes[y]).toLowerCase(); //TODO: make it compatible with regular expressions (be careful with web clients not compatible with RegExp!). if (classes[y] === classNames) { CB_Elements._classesCache[baseElement][classNames].push(elementCurrent); break; } } } } */ //TODO: make it compatible with regular expressions (be careful with web clients not compatible with RegExp!). var classesDesired = classNames.split(\" \"); var classesDesiredLength = classesDesired.length; for (var x = 0; x &lt; classesDesiredLength; x++) { classesDesired[x] = CB_trim(classesDesired[x]);//.toLowerCase(); } var elementCurrent; var elementCurrentClass; var classes; var classesLength; var y, z; var allClassesFound; for (x = 0; x &lt; allElementsLength; x++) { elementCurrent = allElements[x]; if (elementCurrent !== null) { elementCurrentClass = CB_trim(elementCurrent.className); if (elementCurrentClass === \"\") { continue; } classes = elementCurrentClass.split(\" \"); classesLength = classes.length; for (y = 0; y &lt; classesLength; y++) { classes[y] = CB_trim(classes[y]);//.toLowerCase(); } allClassesFound = true; for (z = 0; z &lt; classesDesiredLength; z++) { if (CB_indexOf(classes, classesDesired[z]) === -1) { allClassesFound = false; break; } } if (allClassesFound) { CB_Elements._classesCache[baseElement][classNames].push(elementCurrent); //elements[elements.length] = elementCurrent; } } } } } /* else if (typeof(baseElement.all) !== \"undefined\" &amp;&amp; baseElement.all !== null) { //allElements = baseElement.all; allElements = CB_Elements.tag(\"*\", baseElement, useCache); } else if (typeof(document.all) !== \"undefined\" &amp;&amp; document.all !== null) { //allElements = document.all; allElements = CB_Elements.tag(\"*\", document, useCache); } */ /* else if (baseElement.layers) { CB_Elements._classesCache[baseElement][classNames] = baseElement.layers[classNames]; } else if (document.layers) { CB_Elements._classesCache[baseElement][classNames] = document.layers[classNames]; }*/ CB_Elements._classesCache[baseElement][classNames] = CB_Elements._classesCache[baseElement][classNames] || []; } return CB_Elements._classesCache[baseElement][classNames]; } /** * Returns elements by their class or classes name, updating (or creating) the internal cache. Calls the {@link CB_Elements.classes} function internally, with the \"useCache\" parameter set to false. * @function * @param {string} classNames - The name of the class or classes (separated by a blank space) whose elements we want to find. The order of the classes is just important for the internal cache. * @param {Node} [baseElement=document] - The node element parent where we want to focus our search. * @returns {NodeList|array} Returns the elements (NodeList or array, depending on the web client). */ CB_Elements.classesCacheUpdate = function(classNames, baseElement) { return CB_Elements.classes(classNames, baseElement, false); } /** * Clears the internal cache used by {@link CB_Elements.classes} and others. If no parameter is given, whole internal cache will be cleared. * @function * @param {string} [classNames] - The name of the class or classes (separated by a blank space) whose internal cache we want to clear. The order of the classes is important for the internal cache. If not provided, it will clear the whole internal cache or the internal cache that belongs to the \"baseElement\" given (if provided). * @param {Node} [baseElement] - The node element parent whose internal cache we want to clear. If not provided but \"classNames\" is provided, it will clear the internal cache which matches the given \"classNames\" for any nodes. If it is provided but \"classNames\" is not, it will clear all the internal cache that belongs to this node element. * @returns {Object} Returns the current internal cache after cleaning it (if it is has been possible), which is an associative array of two dimensions (JavaScript object) whose first index belongs to the nodes, the second and last index belongs to the class name or class names and the value belongs to the returning value of the {@link CB_Elements.classes} function when it was called for those parameters. */ CB_Elements.classesCacheClear = function(classNames, baseElement) { classNames = CB_trim(classNames);//.toLowerCase(); //If no base element and no class name are defined, we clean all the array: if (typeof(baseElement) === \"undefined\" &amp;&amp; classNames === \"\" || baseElement === null &amp;&amp; (typeof(classNames) === \"undefined\" || classNames === null)) { CB_Elements._classesCache = {}; } //...otherwise, if both base element and class name are defined, we clear the elements of that base element: else if (typeof(baseElement) !== \"undefined\" &amp;&amp; baseElement !== null &amp;&amp; classNames !== \"\") { if (typeof(CB_Elements._classesCache[baseElement]) !== \"undefined\" &amp;&amp; CB_Elements._classesCache[baseElement] !== null) { if (typeof(CB_Elements._classesCache[baseElement][classNames]) !== \"undefined\" &amp;&amp; CB_Elements._classesCache[baseElement][classNames] !== null) { CB_Elements._classesCache[baseElement][classNames] = null; } } } //...otherwise, if a base element is defined (but not a classNames), we clear all elements of that base element: else if (typeof(baseElement) !== \"undefined\" &amp;&amp; baseElement !== null) { if (typeof(CB_Elements._classesCache[baseElement]) !== \"undefined\" &amp;&amp; CB_Elements._classesCache[baseElement] !== null) { CB_Elements._classesCache[baseElement] = {}; } } //...otherwise, if a class name is defined (but not a base element), we clear all the elements of that class name from all the element bases: else if (classNames !== \"\") { for (var currentBaseElement in CB_Elements._classesCache) { if (typeof(CB_Elements._classesCache[currentBaseElement][classNames]) !== \"undefined\" &amp;&amp; CB_Elements._classesCache[currentBaseElement][classNames] !== null) { CB_Elements._classesCache[currentBaseElement][classNames] = null; } } } return CB_Elements._classesCache; } /** * Alias for {@link CB_Elements.classesRemove}. * @function CB_Elements.removeByClasses * @see {@link CB_Elements.classesRemove} */ /** * Removes elements by their class or classes name. * @function * @param {string} classNames - The name of the class or classes (separated by a blank space) whose elements we want to delete. The order of the classes is just important for the internal cache. * @param {Node} [baseElement=document] - The node element parent where we want to focus our search. * @param {boolean} [useCache={@link CB_Configuration.CrossBase.CB_Elements_classes_USE_CACHE}] - Defines whether to try to get the result from an internal cache (it will exist if we previously called the function with the same parameters) or not. The internal cache will be updated when this parameter is set to false or it will be created automatically when it did not exist before. */ CB_Elements.classesRemove = CB_Elements.removeByClasses = function(classNames, baseElement, useCache) { if (typeof(baseElement) === \"undefined\" || baseElement === null) { baseElement = document; } classNames = CB_trim(classNames);//.toLowerCase(); if (classNames === \"\") { return; } var elementsOriginal = CB_Elements.classes(classNames, baseElement, useCache); if (typeof(elementsOriginal) !== \"undefined\" &amp;&amp; elementsOriginal !== null &amp;&amp; typeof(elementsOriginal.length) !== \"undefined\" &amp;&amp; elementsOriginal.length !== null &amp;&amp; elementsOriginal.length &gt; 0) { var elements = []; var elementsLength = elementsOriginal.length; for (var x = 0; x &lt; elementsLength; x++) { elements[x] = elementsOriginal[x]; } var elementsLength = elements.length; for (var x = 0; x &lt; elementsLength; x++) { //elements[x].parentNode.removeChild(elements[x]); CB_Elements.remove(elements[x]); } CB_Elements._classesCache[baseElement][classNames] = null; } } CB_Elements._idCache = {}; /** * Alias for {@link CB_Elements.id}. * @function CB_Elements.byId * @see {@link CB_Elements.id} */ /** * Alias for {@link CB_Elements.id}. * @function CB_Elements.get * @see {@link CB_Elements.id} */ /** * Alias for {@link CB_Elements.id}. * @function CB_Elements.getById * @see {@link CB_Elements.id} */ /** * Returns an element by its ID. * @function * @param {string} id - The identifier of the element that we want to find. * @param {boolean} [useCache={@link CB_Configuration.CrossBase.CB_Elements_id_USE_CACHE}] - Defines whether to try to get the result from an internal cache (it will exist if we previously called the function with the same parameters) or not. The internal cache will be updated when this parameter is set to false or it will be created automatically when it did not exist before. * @returns {Node|Object|null} Returns the elements (Node or object, depending on the web client). It will return null when not found. */ CB_Elements.id = CB_Elements.byId = CB_Elements.get = CB_Elements.getById = function(id, useCache) { if (typeof(useCache) === \"undefined\" || useCache === null) { useCache = CB_Configuration[CB_BASE_NAME].CB_Elements_id_USE_CACHE; } id = CB_trim(id);//.toLowerCase(); //If no id is sent, returns null: if (id === \"\") { return null; } if (!useCache || typeof(CB_Elements._idCache[id]) === \"undefined\" || CB_Elements._idCache[id] === null) { if (document.getElementById) { CB_Elements._idCache[id] = document.getElementById(id); } else if (document.querySelector) { CB_Elements._idCache[id] = document.querySelector(\"#\" + id); } else if (document.all) { if (typeof(document.all) !== \"function\") { CB_Elements._idCache[id] = document.all[id]; } else { CB_Elements._idCache[id] = document.all(id); } } else if (document.layers) { CB_Elements._idCache[id] = document.layers[id]; } else { CB_Elements._idCache[id] = null; } CB_Elements._idCache[id] = CB_Elements._idCache[id] || null; } return CB_Elements._idCache[id]; } /** * Returns an element by its ID, updating (or creating) the internal cache. Calls the {@link CB_Elements.id} function internally, with the \"useCache\" parameter set to false. * @function * @param {string} id - The identifier of the element that we want to find. * @returns {node|Object|null} Returns the elements (Node or object, depending on the web client). It will return null when not found. */ CB_Elements.idCacheUpdate = function(id) { return CB_Elements.id(id, false); } /** * Clears the internal cache used by {@link CB_Elements.id} and others. If no parameter is given, whole internal cache will be cleared. * @function * @param {string} [id] - The identifier of the element whose internal cache we want to clear. If not provided, it will clear the whole internal cache. * @returns {Object} Returns the current internal cache after cleaning it (if it is has been possible), which is an associative array of one dimension (JavaScript object) whose first and unique index belongs to the identifier and the value belongs to each element. */ CB_Elements.idCacheClear = function(id) { id = CB_trim(id); if (id === \"\") { CB_Elements._idCache = {}; } else { CB_Elements._idCache[id] = null; } return CB_Elements._idCache; } /** * Alias for {@link CB_Elements.idRemove}. * @function CB_Elements.removeById * @see {@link CB_Elements.idRemove} */ /** * Removes an element by its ID. * @function * @param {string} id - The identifier of the element that we want to delete. * @param {boolean} [useCache={@link CB_Configuration.CrossBase.CB_Elements_id_USE_CACHE}] - Defines whether to try to get the result from an internal cache (it will exist if we previously called the function with the same parameters) or not. The internal cache will be updated when this parameter is set to false or it will be created automatically when it did not exist before. */ CB_Elements.idRemove = CB_Elements.removeById = function(id, useCache) { id = CB_trim(id); if (id === \"\") { return; } var element = CB_Elements.id(id, useCache); //if (typeof(CB_Elements._idCache[id]) !== \"undefined\" &amp;&amp; CB_Elements._idCache[id] !== null) //{ CB_Elements._idCache[id] = null; //} return CB_Elements.remove(element); } /** * Removes an element given. * @function * @param {Node} element - The element that we want to delete. */ CB_Elements.remove = function(element) { if (typeof(element) !== \"undefined\" &amp;&amp; element !== null) { var elementParent = CB_Elements.getParent(element); if (typeof(elementParent) !== \"undefined\" &amp;&amp; elementParent !== null &amp;&amp; typeof(elementParent.removeChild) !== \"undefined\" &amp;&amp; elementParent.removeChild !== null) { ///////return elementParent.removeChild(element); elementParent.removeChild(element); } else if (typeof(element.removeNode) !== \"undefined\" &amp;&amp; element.removeNode !== null) { ///////return element.removeNode(true); element.removeNode(true); } else if (document.all) { if (typeof(document.all) !== \"function\" &amp;&amp; element.id &amp;&amp; typeof(document.all[element.id]) !== \"undefined\" &amp;&amp; document.all[element.id] !== null) { document.all[element.id].innerHTML = document.all[element.id].outerHTML = \"\"; } else if (element.id) { //Uses try-catch because otherwise it fails on IE 8: try { document.all(element.id).innerHTML = document.all(element.id).outerHTML = \"\"; } catch(E) {} } } else if (document.layers &amp;&amp; element.id) { document.layers[element.id].visibility = \"hide\"; delete document.layers[element.id]; } if (typeof(element.remove) !== \"undefined\") { element.remove(); } ///////////////delete(element); //Just in case (for some strange web clients). NOTE: commented since it gives problems with JSDoc (\"ERROR: Unable to parse CB_Elements.js: Deleting local variable in strict mode\"). element = null; element = undefined; } } /** * Returns an array with the parents of a given element, with the topmost parent in the highest index: * @function * @param {Node} element - The element whose parents we want to get. * @returns {array} */ CB_Elements.getParents = function(element) { var elementParents = []; var x = 0; var currentParent; while (currentParent = CB_Elements.getParent(element)) { elementParents[x++] = currentParent; element = currentParent; } return elementParents; } /** * Returns an array with the parents of a given element (by its identifier), with the topmost parent in the highest index: * @function * @param {string} elementId - The identifier of the element whose parents we want to get. * @returns {array} */ CB_Elements.getParentsById = function(elementId) { return CB_Elements.getParents(CB_Elements.id(elementId)); } /** * Returns the first parent of a given element: * @function * @param {Node} element - The element whose parent we want to get. * @returns {Node|null} Returns null if the parent cannot be found. */ CB_Elements.getParent = function(element) { if (typeof(element) === \"undefined\" || element === null) { return null; } var elementParent = null; if (typeof(element.parentNode) !== \"undefined\" &amp;&amp; element.parentNode !== null) { elementParent = element.parentNode; } else if (typeof(element.parentElement) !== \"undefined\" &amp;&amp; element.parentElement !== null) { elementParent = element.parentElement; } return elementParent; } /** * Returns the first parent of a given element (by its identifier): * @function * @param {string} elementId - The identifier of the element whose parent we want to get. * @returns {Node|null} Returns null if the parent cannot be found. */ CB_Elements.getParentById = function(elementId) { return CB_Elements.getParent(CB_Elements.id(elementId)); } /** * Changes a desired element property with the given value. * @function * @param {Node} element - The element whose property we want to modify. * @param {string} property - The name of the property that we want to modify. * @param {*} propertyValue - The value desired for the property. * @param {boolean} [checkValues=false] - If set to true, it will only modify the property if the current value is different from the given one. * @param {function} [onSetProperty] - Callback function that will be called if the property of the element has been set, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. * @returns {Node|null} Returns the given element again or null. */ CB_Elements.setProperty = function(element, property, propertyValue, checkValues, onSetProperty) { if (typeof(element) === \"undefined\" || element === null) { return null; } if (!checkValues || element[property] !== propertyValue) { element[property] = propertyValue; if (typeof(onSetProperty) === \"function\") { onSetProperty(element); } } return element; } /** * Changes a desired element property with the given value (by its identifier). * @function * @param {string} elementId - The identifier of the element whose property we want to modify. * @param {string} property - The name of the property that we want to modify. * @param {*} propertyValue - The value desired for the property. * @param {boolean} [checkValues=false] - If set to true, it will only modify the property if the current value is different from the given one. * @param {function} [onSetProperty] - Callback function that will be called if the property of the element has been set, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. * @returns {Node|null} Returns the affected element (if any) or null otherwise. */ CB_Elements.setPropertyById = function(elementId, property, propertyValue, checkValues, onSetProperty) { return CB_Elements.setProperty(CB_Elements.id(elementId), property, propertyValue, checkValues, onSetProperty); } /** * Inserts the desired content inside a given element (using [innerHTML]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML}). * @function * @param {Node} container - The element whose content we want to modify. * @param {string} content - The content that we want to add. * @param {string} [displayValue] - If provided, it will call {@link CB_Elements.show} internally after inserting the content to set the given [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property to the element. * @param {boolean} [checkValues=false] - If it is set to true, it will only change the content if the current one is different from the given one and it will pass the same parameter to {@link CB_Elements.show} if it is called internally (when \"displayValue\" is given). * @param {boolean} [computed=false] - If \"displayValue\" is given, it will pass this parameter to {@link CB_Elements.show} if it is called internally (when \"displayValue\" is given). * @param {function} [onContentWritten] - Callback function that will be called if the content has been written, after doing it (this will happens always if \"checkValues\" is false). The unique parameter passed will be the container itself. * @param {function} [onShow] - If \"displayValue\" is given, it will pass this parameter to {@link CB_Elements.show} when it is called internally. * @param {boolean} [append=false] - If set to true, it will append the given content to the existing one instead of overwritten it. By default, it appends it at the end unless that the \"appendAtBeginning\" is set to true. * @param {boolean} [appendAtBeginning=false] - If set to true, it will append the given content to the existing one instead of overwritten it. * @returns {Node} Returns the given container again. */ CB_Elements.insertContent = function(container, content, displayValue, checkValues, computed, onContentWritten, onShow, append, appendAtBeginning) { if (container !== null) { if (!checkValues || append || container.innerHTML !== content) { if (append) { container.innerHTML = appendAtBeginning ? content + container.innerHTML : container.innerHTML + content; } else { container.innerHTML = content; } if (typeof(onContentWritten) === \"function\") { onContentWritten(container); } } if (displayValue) { CB_Elements.show(container, displayValue, checkValues, computed, onShow); } } return container; } /** * Appends the desired content inside a given element, keeping the existing one (using [innerHTML]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML}). Calls the {@link CB_Elements.insertContent} internally. * @function * @param {Node} container - The element whose content we want to modify. * @param {string} content - The content that we want to add. * @param {string} [displayValue] - If provided, it will call {@link CB_Elements.show} internally after inserting the content to set the given [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property to the element. * @param {boolean} [checkValues=false] - If it is set to true, it will only change the content if the current one is different from the given one and it will pass the same parameter to {@link CB_Elements.show} if it is called internally (when \"displayValue\" is given). * @param {boolean} [computed=false] - If \"displayValue\" is given, it will pass this parameter to {@link CB_Elements.show} if it is called internally (when \"displayValue\" is given). * @param {function} [onContentWritten] - Callback function that will be called if the content has been written, after doing it (this will happens always if \"checkValues\" is false). The unique parameter passed will be the container itself. * @param {function} [onShow] - If \"displayValue\" is given, it will pass this parameter to {@link CB_Elements.show} when it is called internally. * @param {boolean} [appendAtBeginning=false] - If set to true, it will append the given content to the existing one instead of overwritten it. * @returns {Node} Returns the given container again. */ CB_Elements.appendContent = function(container, content, displayValue, checkValues, computed, onContentWritten, onShow, appendAtBeginning) { return CB_Elements.insertContent(container, content, displayValue, checkValues, computed, onContentWritten, onShow, true, appendAtBeginning); } /** * Appends the desired content inside a given element at the beginning, keeping the existing one (using [innerHTML]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML}). Calls the {@link CB_Elements.insertContent} internally. * @function * @param {Node} container - The element whose content we want to modify. * @param {string} content - The content that we want to add. * @param {string} [displayValue] - If provided, it will call {@link CB_Elements.show} internally after inserting the content to set the given [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property to the element. * @param {boolean} [checkValues=false] - If it is set to true, it will only change the content if the current one is different from the given one and it will pass the same parameter to {@link CB_Elements.show} if it is called internally (when \"displayValue\" is given). * @param {boolean} [computed=false] - If \"displayValue\" is given, it will pass this parameter to {@link CB_Elements.show} if it is called internally (when \"displayValue\" is given). * @param {function} [onContentWritten] - Callback function that will be called if the content has been written, after doing it (this will happens always if \"checkValues\" is false). The unique parameter passed will be the container itself. * @param {function} [onShow] - If \"displayValue\" is given, it will pass this parameter to {@link CB_Elements.show} when it is called internally. * @returns {Node} Returns the given container again. */ CB_Elements.appendContentBeginning = function(container, content, displayValue, checkValues, computed, onContentWritten, onShow) { return CB_Elements.insertContent(container, content, displayValue, checkValues, computed, onContentWritten, onShow, true, true); } /** * Inserts the desired content inside a given element (using [innerHTML]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML}), by its identifier. * @function * @param {string} containerId - The identifier of the element whose content we want to modify. * @param {string} content - The content that we want to add. * @param {string} [displayValue] - If provided, it will call {@link CB_Elements.show} internally after inserting the content to set the given [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property to the element. * @param {boolean} [checkValues=false] - If it is set to true, it will only change the content if the current one is different from the given one and it will pass the same parameter to {@link CB_Elements.show} if it is called internally (when \"displayValue\" is given). * @param {boolean} [computed=false] - If \"displayValue\" is given, it will pass this parameter to {@link CB_Elements.show} if it is called internally (when \"displayValue\" is given). * @param {function} [onContentWritten] - Callback function that will be called if the content has been written, after doing it (this will happens always if \"checkValues\" is false). The unique parameter passed will be the affected container itself. * @param {function} [onShow] - If \"displayValue\" is given, it will pass this parameter to {@link CB_Elements.show} when it is called internally. * @param {boolean} [append=false] - If set to true, it will append the given content to the existing one instead of overwritten it. By default, it appends it at the end unless that the \"appendAtBeginning\" is set to true. * @param {boolean} [appendAtBeginning=false] - If set to true, it will append the given content to the existing one instead of overwritten it. * @returns {Node|null} Returns the affected container (if any) or null otherwise. */ CB_Elements.insertContentById = function(containerId, content, displayValue, checkValues, computed, onContentWritten, onShow, append, appendAtBeginning) { return CB_Elements.insertContent(CB_Elements.id(containerId), content, displayValue, checkValues, computed, onContentWritten, onShow, append, appendAtBeginning); } /** * Appends the desired content inside a given element, keeping the existing one (using [innerHTML]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML}), by its identifier. Calls the {@link CB_Elements.insertContent} internally. * @function * @param {string} containerId - The identifier of the element whose content we want to modify. * @param {string} content - The content that we want to add. * @param {string} [displayValue] - If provided, it will call {@link CB_Elements.show} internally after inserting the content to set the given [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property to the element. * @param {boolean} [checkValues=false] - If it is set to true, it will only change the content if the current one is different from the given one and it will pass the same parameter to {@link CB_Elements.show} if it is called internally (when \"displayValue\" is given). * @param {boolean} [computed=false] - If \"displayValue\" is given, it will pass this parameter to {@link CB_Elements.show} if it is called internally (when \"displayValue\" is given). * @param {function} [onContentWritten] - Callback function that will be called if the content has been written, after doing it (this will happens always if \"checkValues\" is false). The unique parameter passed will be the affected container itself. * @param {function} [onShow] - If \"displayValue\" is given, it will pass this parameter to {@link CB_Elements.show} when it is called internally. * @param {boolean} [append=false] - If set to true, it will append the given content to the existing one instead of overwritten it. By default, it appends it at the end unless that the \"appendAtBeginning\" is set to true. * @param {boolean} [appendAtBeginning=false] - If set to true, it will append the given content to the existing one instead of overwritten it. * @returns {Node|null} Returns the affected container (if any) or null otherwise. */ CB_Elements.appendContentById = function(containerId, content, displayValue, checkValues, computed, onContentWritten, onShow, appendAtBeginning) { return CB_Elements.insertContent(CB_Elements.id(containerId), content, displayValue, checkValues, computed, onContentWritten, onShow, true, appendAtBeginning); } /** * Appends the desired content inside a given element at the beginning, keeping the existing one (using [innerHTML]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML}), by its identifier. Calls the {@link CB_Elements.insertContent} internally. * @function * @param {string} containerId - The identifier of the element whose content we want to modify. * @param {string} content - The content that we want to add. * @param {string} [displayValue] - If provided, it will call {@link CB_Elements.show} internally after inserting the content to set the given [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property to the element. * @param {boolean} [checkValues=false] - If it is set to true, it will only change the content if the current one is different from the given one and it will pass the same parameter to {@link CB_Elements.show} if it is called internally (when \"displayValue\" is given). * @param {boolean} [computed=false] - If \"displayValue\" is given, it will pass this parameter to {@link CB_Elements.show} if it is called internally (when \"displayValue\" is given). * @param {function} [onContentWritten] - Callback function that will be called if the content has been written, after doing it (this will happens always if \"checkValues\" is false). The unique parameter passed will be the affected container itself. * @param {function} [onShow] - If \"displayValue\" is given, it will pass this parameter to {@link CB_Elements.show} when it is called internally. * @param {boolean} [append=false] - If set to true, it will append the given content to the existing one instead of overwritten it. By default, it appends it at the end unless that the \"appendAtBeginning\" is set to true. * @returns {Node|null} Returns the affected container (if any) or null otherwise. */ CB_Elements.appendContentByIdBeginning = function(containerId, content, displayValue, checkValues, computed, onContentWritten, onShow) { return CB_Elements.insertContent(CB_Elements.id(containerId), content, displayValue, checkValues, computed, onContentWritten, onShow, true, true); } /** * Returns the style of an element, computed or static: * @function * @param {Node} element - The element whose style property we want to get. * @param {boolean} [computed=false] - If it is set to true, it will try to use the native function [window.getComputedStyle]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle} (if available). * @returns {Object|null} Returns an associative array (JavaScript object) with all the styles retrieved or null if nothing can be retrieved. */ CB_Elements.getStyle = function(element, computed) { if (typeof(element) === \"undefined\" || element === null) { return null; } if (computed) { if (\"getComputedStyle\" in window &amp;&amp; window.getComputedStyle) { return window.getComputedStyle(element, null); } else if (element.currentStyle) { return element.currentStyle; } } if (element.style) { return element.style; } return null; } /** * Returns the style of an element, computed or static (by its identifier): * @function * @param {string} elementId - The identifier of the element whose style property we want to get. * @param {boolean} [computed=false] - If it is set to true, it will try to use the native function [window.getComputedStyle]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle} (if available). * @returns {Object|null} Returns an associative array (JavaScript object) with all the styles retrieved or null if nothing can be retrieved. */ CB_Elements.getStyleById = function(elementId, computed) { return CB_Elements.getStyle(CB_Elements.id(elementId), computed); } /** * Returns the desired attribute value from the style of an element, computed or static: * @function * @param {Node} element - The element whose attribute value from its style we want to get. * @param {string} attribute - The name of the attribute whose value we want to get from the style. * @param {boolean} [computed=false] - If it is set to true, it will try to use the native function [window.getComputedStyle]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle} (if available). * @returns {*} Returns null if nothing can be retrieved. * @todo Think about supporting a boolean parameter to try to find the attribute having into account vendor prefixes (webkit, moz, ms, o, khtml). */ CB_Elements.getStyleProperty = function(element, attribute, computed) { //If we have received a string instead of an element, we try to get an element with that string as id: //if (CB_isString(element)) { element = CB_Elements.id(element); } var elementStyle = CB_Elements.getStyle(element, computed); if (elementStyle !== null &amp;&amp; typeof(elementStyle[attribute]) !== \"undefined\") { return elementStyle[attribute]; } return null; } /** * Returns the desired attribute value from the style of an element, computed or static (by its identifier): * @function * @param {string} elementId - The identifier of the element whose attribute value from its style we want to get. * @param {string} attribute - The name of the attribute whose value we want to get from the style. * @param {boolean} [computed=false] - If it is set to true, it will try to use the native function [window.getComputedStyle]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle} (if available). * @returns {*} Returns null if nothing can be retrieved. * @todo Think about supporting a boolean parameter to try to find the attribute having into account vendor prefixes (webkit, moz, ms, o, khtml). */ CB_Elements.getStylePropertyById = function(elementId, attribute, computed) { return CB_Elements.getStyleProperty(CB_Elements.id(elementId), attribute, computed); } /** * Returns the integer value or values (base decimal) of a desired attribute from the style of an element, computed or static: * @function * @param {Node} element - The element whose attribute value from its style we want to get. * @param {string} attribute - The name of the attribute whose value we want to get from the style. * @param {boolean} [computed=false] - If it is set to true, it will try to use the native function [window.getComputedStyle]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle} (if available). * @returns {array} Returns a numeric array with the values retrieved. If nothing could be retrieved, the first and unique index of the array will contain the value of zero (0). * @todo Think about supporting a boolean parameter to try to find the attribute having into account vendor prefixes (webkit, moz, ms, o, khtml). */ CB_Elements.getStylePropertyInteger = function(element, attribute, computed) { return CB_Elements.getStylePropertyNumeric(element, attribute, computed, true); } /** * Returns the integer value or values (base decimal) of a desired attribute from the style of an element, computed or static (by its identifier): * @function * @param {string} elementId - The identifier of the element whose attribute value from its style we want to get. * @param {string} attribute - The name of the attribute whose value we want to get from the style. * @param {boolean} [computed=false] - If it is set to true, it will try to use the native function [window.getComputedStyle]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle} (if available). * @returns {array} Returns a numeric array with the values retrieved. If nothing could be retrieved, the first and unique index of the array will contain the value of zero (0). * @todo Think about supporting a boolean parameter to try to find the attribute having into account vendor prefixes (webkit, moz, ms, o, khtml). */ CB_Elements.getStylePropertyIntegerById = function(elementId, attribute, computed) { return CB_Elements.getStylePropertyInteger(CB_Elements.id(elementId), attribute, computed); } /** * Returns the numeric value or values (base decimal) of a desired attribute from the style of an element, computed or static: * @function * @param {Node} element - The element whose attribute value from its style we want to get. * @param {string} attribute - The name of the attribute whose value we want to get from the style. * @param {boolean} [computed=false] - If it is set to true, it will try to use the native function [window.getComputedStyle]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle} (if available). * @param {boolean} [parseToInteger=false] - If it is set to true, the value or values will be parsed to integer. * @returns {array} Returns a numeric array with the values retrieved. If nothing could be retrieved, the first and unique index of the array will contain the value of zero (0). * @todo Think about supporting a boolean parameter to try to find the attribute having into account vendor prefixes (webkit, moz, ms, o, khtml). */ CB_Elements.getStylePropertyNumeric = function(element, attribute, computed, parseToInteger)//, parseToFloat) { var propertyValue = CB_Elements.getStyleProperty(element, attribute, computed); var propertyValuesNumeric = []; if (typeof(propertyValue) !== \"undefined\" &amp;&amp; propertyValue !== null) { var propertyValues = propertyValue.split(\" \"); var propertyValuesLength = propertyValues.length; var y = 0; for (x = 0; x &lt; propertyValues.length; x++) { propertyValue = parseFloat(propertyValues[x]); if (typeof(propertyValue) !== \"undefined\" &amp;&amp; propertyValue !== null &amp;&amp; !isNaN(propertyValue)) { if (parseToInteger) { propertyValue = parseInt(propertyValue, 10); } //if (parseToFloat) { propertyValue = parseFloat(propertyValue); } //else { propertyValue = parseFloat(propertyValue); } propertyValuesNumeric[y++] = propertyValue; //break; } } } //if (propertyValue === null || CB_trim(propertyValue) === \"\") { propertyValue = 0; } if (propertyValuesNumeric.length === 0) { propertyValuesNumeric[0] = 0; } //If there are no values, it will returns 0 as the unique one. //if (isNaN(propertyValue)) { propertyValue = 0; } //if (isNaN(propertyValue)) { propertyValue = 0; } //return propertyValue; return propertyValuesNumeric; } /** * Returns the numeric value or values (base decimal) of a desired attribute from the style of an element, computed or static (by its identifier): * @function * @param {string} elementId - The identifier of the element whose attribute value from its style we want to get. * @param {string} attribute - The name of the attribute whose value we want to get from the style. * @param {boolean} [computed=false] - If it is set to true, it will try to use the native function [window.getComputedStyle]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle} (if available). * @param {boolean} [parseToInteger=false] - If it is set to true, the value or values will be parsed to integer. * @returns {array} Returns a numeric array with the values retrieved. If nothing could be retrieved, the first and unique index of the array will contain the value of zero (0). * @todo Think about supporting a boolean parameter to try to find the attribute having into account vendor prefixes (webkit, moz, ms, o, khtml). */ CB_Elements.getStylePropertyNumericById = function(elementId, attribute, computed, parseToInteger, parseToFloat) { return CB_Elements.getStylePropertyNumeric(CB_Elements.id(elementId), attribute, computed, parseToInteger, parseToFloat); } /** * Toggles the [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property (from \"none\" to the desired value or vice versa) of a given element, to show or hide it. * If the element is hidden (its [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} is \"none\"), it will call {@link CB_Elements.show} internally to show it. Otherwise, it will call {@link CB_Elements.hide} internally. Note that these two functions will also change the [visibility]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/visibility} property (setting it to either \"visible\" or \"hidden\", respectively) of the element. * @function * @param {Node} element - The element whose [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property we want to toggle. * @param {string} [displayValue='block'] - The [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} value when we want to show the element (it will be used only if the element is currently hidden, when it calls {@link CB_Elements.show} internally). The [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} value to hide the element is always \"none\". * @param {boolean} [checkValues=false] - This parameter will be used when it calls either {@link CB_Elements.show} or {@link CB_Elements.hide} internally. * @param {boolean} [computed=false] - This parameter will be used to get the current style and also when it calls either {@link CB_Elements.show} or {@link CB_Elements.hide} internally. * @param {function} [onToggleDisplay] - This parameter will be used when it calls either {@link CB_Elements.show} if \"onShow\" is not provided or {@link CB_Elements.hide} if \"onHide\" is not provided, internally. * @param {function} [onShow] - This parameter will be used when it calls {@link CB_Elements.show} internally. If not provided but \"onToggleDisplay\" is provided, it will use the latter instead. * @param {function} [onHide] - This parameter will be used when it calls {@link CB_Elements.hide} internally. If not provided but \"onToggleDisplay\" is provided, it will use the latter instead. * @returns {Node} Returns the given element again. */ CB_Elements.showHide = function(element, displayValue, checkValues, computed, onToggleDisplay, onShow, onHide) { var style = CB_Elements.getStyle(element, computed); if (style !== null) { if (style.display === \"none\") { CB_Elements.show(element, displayValue, checkValues, computed, typeof(onToggleDisplay) === \"function\" ? onToggleDisplay : onShow); } else { CB_Elements.hide(element, checkValues, computed, typeof(onToggleDisplay) === \"function\" ? onToggleDisplay : onHide); } } return element; } /** * Toggles the [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property (from \"none\" to the desired value or vice versa) of a given element, to show or hide it (by its identifier). * If the element is hidden (its [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} is \"none\"), it will call {@link CB_Elements.show} internally to show it. Otherwise, it will call {@link CB_Elements.hide} internally. Note that these two functions will also change the [visibility]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/visibility} property (setting it to either \"visible\" or \"hidden\", respectively) of the element. * @function * @param {string} elementId - The identifier of the element whose [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property we want to toggle. * @param {string} [displayValue='block'] - The [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} value when we want to show the element (it will be used only if the element is currently hidden, when it calls {@link CB_Elements.show} internally). The [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} value to hide the element is always \"none\". * @param {boolean} [checkValues=false] - This parameter will be used when it calls either {@link CB_Elements.show} or {@link CB_Elements.hide} internally. * @param {boolean} [computed=false] - This parameter will be used to get the current style and also when it calls either {@link CB_Elements.show} or {@link CB_Elements.hide} internally. * @param {function} [onToggleDisplay] - This parameter will be used when it calls either {@link CB_Elements.show} if \"onShow\" is not provided or {@link CB_Elements.hide} if \"onHide\" is not provided, internally. * @param {function} [onShow] - This parameter will be used when it calls {@link CB_Elements.show} internally. If not provided but \"onToggleDisplay\" is provided, it will use the latter instead. * @param {function} [onHide] - This parameter will be used when it calls {@link CB_Elements.hide} internally. If not provided but \"onToggleDisplay\" is provided, it will use the latter instead. * @returns {Node|null} Returns the affected element (if any) or null otherwise. */ CB_Elements.showHideById = function(elementId, displayValue, checkValues, computed, onToggleDisplay, onShow, onHide) { return CB_Elements.showHide(CB_Elements.id(elementId), displayValue, checkValues, computed, onToggleDisplay, onShow, onHide); } /** * Changes the [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property to the desired value of a given element, to show it. Its [visibility]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/visibility} property will be set to \"visible\". * @function * @param {Node} element - The element whose [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property we want to change. * @param {string} [displayValue='block'] - The [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} value we want to set. If not provided or \"none\" is provided, it will use \"block\" instead. * @param {boolean} [checkValues=false] - If it is set to true, it will only perform the change if either the current [visibility]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/visibility} property is not \"visible\" or the current [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property is different from the given one. * @param {boolean} [computed=false] - This parameter will be used when it calls {@link CB_Elements.getStyle} internally. * @param {function} [onShow] - Callback function that will be called if the change has been performed, after doing it (this will happens always if \"checkValues\" is false). The first parameter passed will be the affected element itself and the second and last parameter will be the new value of the [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property (not computed). * @returns {Node} Returns the given element again. */ CB_Elements.show = function(element, displayValue, checkValues, computed, onShow) { var style = CB_Elements.getStyle(element, computed); if (style !== null) { displayValue = CB_trim(displayValue); if (displayValue === \"\" || displayValue.toLowerCase() === \"none\") { displayValue = \"block\"; } if (!checkValues || style.visibility !== \"visible\" || style.display !== displayValue) { element.style.visibility = \"visible\"; element.style.display = displayValue; if (typeof(onShow) === \"function\") { onShow(element, element.style.display); } } } return element; } /** * Changes the [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property to the desired value of a given element, to show it (by its identifier). Its [visibility]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/visibility} property will be set to \"visible\". * @function * @param {string} elementId - The identifier of the element whose [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property we want to change. * @param {string} [displayValue='block'] - The [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} value we want to set. If not provided or \"none\" is provided, it will use \"block\" instead. * @param {boolean} [checkValues=false] - If it is set to true, it will only perform the change if either the current [visibility]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/visibility} property is not \"visible\" or the current [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property is different from the given one. * @param {boolean} [computed=false] - This parameter will be used when it calls {@link CB_Elements.getStyle} internally. * @param {function} [onShow] - Callback function that will be called if the change has been performed, after doing it (this will happens always if \"checkValues\" is false). The first parameter passed will be the affected element itself and the second and last parameter will be the new value of the [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property (not computed). * @returns {Node|null} Returns the affected element (if any) or null otherwise. */ CB_Elements.showById = function(elementId, displayValue, checkValues, computed, onShow) { return CB_Elements.show(CB_Elements.id(elementId), displayValue, checkValues, computed, onShow); } /** * Hides a given element by changing its [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property to \"none\" and its [visibility]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/visibility} to \"hidden\". * @function * @param {Node} element - The element that we want to hide. * @param {boolean} [checkValues=false] - If it is set to true, it will only perform the change if either the current [visibility]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/visibility} property is not \"hidden\" or the current [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property is not \"none\". * @param {boolean} [computed=false] - This parameter will be used when it calls {@link CB_Elements.getStyle} internally. * @param {function} [onHide] - Callback function that will be called if the element has been hidden, after doing it (this will happens always if \"checkValues\" is false). The first parameter passed will be the affected element itself and the second and last parameter will be the new value of the [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property (not computed) which should be \"none\". * @returns {Node} Returns the given element again. */ CB_Elements.hide = function(element, checkValues, computed, onHide) { var style = CB_Elements.getStyle(element, computed); if (style !== null) { if (!checkValues || style.visibility !== \"hidden\" || style.display !== \"none\") { element.style.visibility = \"hidden\"; element.style.display = \"none\"; if (typeof(onHide) === \"function\") { onHide(element, element.style.display); } } } return element; } /** * Hides a given element by changing its [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property to \"none\" and its [visibility]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/visibility} to \"hidden\" (by its identifier). * @function * @param {string} elementId - The identifier of the element that we want to hide. * @param {boolean} [checkValues=false] - If it is set to true, it will only perform the change if either the current [visibility]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/visibility} property is not \"hidden\" or the current [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property is not \"none\". * @param {boolean} [computed=false] - This parameter will be used when it calls {@link CB_Elements.getStyle} internally. * @param {function} [onHide] - Callback function that will be called if the element has been hidden, after doing it (this will happens always if \"checkValues\" is false). The first parameter passed will be the affected element itself and the second and last parameter will be the new value of the [display]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/display} property (not computed) which should be \"none\". * @returns {Node|null} Returns the affected element (if any) or null otherwise. */ CB_Elements.hideById = function(elementId, checkValues, computed, onHide) { return CB_Elements.hide(CB_Elements.id(elementId), checkValues, computed, onHide); } /** * Toggles the class of a given element between two given classes or adds/removes the given class. The element can contain other classes and they will be kept. * @function * @param {Node} element - The element whose class we want to toggle. * @param {string} classA - The class that will be used in the case that the element is not using it already. * @param {string} [classB=''] - The class that will be used in the case that the given \"classA\" is being used by the element. If not given or an empty string is given, it will just remove the \"classA\" in the case it is being used by the element. * @param {function} [onToggleClass] - Callback function that will be called if the class of the element has been toggled or removed, after doing it. The first parameter passed will be the affected element itself and the second and last parameter will be the class used this time (or an empty string). * @returns {Node} Returns the given element again. */ CB_Elements.toggleClass = function(element, classA, classB, onToggleClass) { if (typeof(element) !== \"undefined\" &amp;&amp; element !== null) { classA = CB_trim(classA).toLowerCase(); classB = CB_trim(classB).toLowerCase(); if (classA === \"\" &amp;&amp; classB === \"\") { return element; } else if (classA === \"\") { classA = classB; classB = \"\"; } var classesUsed = \" \" + CB_trim(element.className).toLowerCase() + \" \"; if (classesUsed.indexOf(\" \" + classA + \" \") === -1) { if (classB !== \"\" &amp;&amp; classesUsed.indexOf(\" \" + classB + \" \") !== -1) { classesUsed = classesUsed.replace(CB_regularExpressionString(\" \" + classB + \" \", true, true), \" \" + classA + \" \"); } else { classesUsed += \" \" + classA; } element.className = CB_trim(classesUsed); if (typeof(onToggleClass) === \"function\") { onToggleClass(element, classA); } } else { classesUsed = classesUsed.replace(CB_regularExpressionString(\" \" + classA + \" \", true, true), \" \"); if (classB !== \"\" &amp;&amp; classesUsed.indexOf(\" \" + classB + \" \") === -1) { classesUsed += \" \" + classB; } element.className = CB_trim(classesUsed); if (typeof(onToggleClass) === \"function\") { onToggleClass(element, classB); } } } return element; } /** * Toggles the class of a given element between two given classes (by its identifier). The element can contain other classes and they will be kept. * @function * @param {string} elementId - The identifier of the element whose class we want to toggle. * @param {string} classA - The class that will be used in the case that the element is not using it already. * @param {string} [classB=''] - The class that will be used in the case that the given \"classA\" is being used by the element. If not given or an empty string is given, it will just remove the \"classA\" in the case it is being used by the element. * @param {function} [onToggleClass] - Callback function that will be called if the class of the element has been toggled or removed, after doing it. The first parameter passed will be the affected element itself and the second and last parameter will be the class used this time (or an empty string). * @returns {Node|null} Returns the affected element (if any) or null otherwise. */ CB_Elements.toggleClassById = function(elementId, classA, classB, onToggleClass) { return CB_Elements.toggleClass(CB_Elements.id(elementId), classA, classB, onToggleClass); } /** * Removes a desired class from a given element. The element can contain other classes and they will be kept. * @function * @param {Node} element - The element whose class we want to remove. * @param {string} className - The class that will be removed if the element is using it. * @param {boolean} [checkValues=false] - If it is set to true, it will only try to perform the action if the given \"className\" is being used. The result will be the same with either true or false, but depending on the client used it could gain or lose performance. * @param {function} [onRemoveClass] - Callback function that will be called if the class of the element has been tried to be removed, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. * @returns {Node} Returns the given element again. * @todo Think about allowing to remove more than once class at the same time, regardless of the order given and order set. */ CB_Elements.removeClass = function(element, className, checkValues, onRemoveClass) { if (typeof(element) !== \"undefined\" &amp;&amp; element !== null) { className = CB_trim(className).toLowerCase(); if (className === \"\") { return element; } var classesUsed = \" \" + CB_trim(element.className).toLowerCase() + \" \"; if (!checkValues || classesUsed.indexOf(\" \" + className + \" \") !== -1) { element.className = CB_trim(classesUsed.replace(CB_regularExpressionString(\" \" + className + \" \", true, true), \" \")); if (typeof(onRemoveClass) === \"function\") { onRemoveClass(element); } } } return element; } /** * Removes a desired class from a given element (by its identifier). The element can contain other classes and they will be kept. * @function * @param {string} elementId - The identifier of the element whose class we want to remove. * @param {string} className - The class that will be removed if the element is using it. * @param {boolean} [checkValues=false] - If it is set to true, it will only try to perform the action if the given \"className\" is being used. The result will be the same with either true or false, but depending on the client used it could gain or lose performance. * @param {function} [onRemoveClass] - Callback function that will be called if the class of the element has been tried to be removed, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. * @returns {Node|null} Returns the affected element (if any) or null otherwise. * @todo Think about allowing to remove more than once class at the same time, regardless of the order given and order set. */ CB_Elements.removeClassById = function(elementId, className, checkValues, onRemoveClass) { return CB_Elements.removeClass(CB_Elements.id(elementId), className, checkValues, onRemoveClass); } /** * Adds a desired class to a given element. The element can contain other classes and they will be kept. * @function * @param {Node} element - The element that will get the new given class. * @param {string} className - The class that will be added. * @param {boolean} [checkValues=false] - If it is set to true, it will only try to add the given class if it is not being used already. It is recommended to use true to prevent some old clients from adding the same class multiple times. * @param {function} [onAddClass] - Callback function that will be called if the class of the element has been added, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. * @returns {Node} Returns the given element again. * @todo Think about allowing to use more than once class (and think how many times the \"onAddClass\" function should be called). */ CB_Elements.addClass = function(element, className, checkValues, onAddClass) { if (typeof(element) !== \"undefined\" &amp;&amp; element !== null) { className = CB_trim(className).toLowerCase(); if (className === \"\") { return element; } var classesUsed = \" \" + CB_trim(element.className).toLowerCase() + \" \"; if (!checkValues || classesUsed.indexOf(\" \" + className + \" \") === -1) { element.className = CB_trim(CB_trim(classesUsed) + \" \" + className); if (typeof(onAddClass) === \"function\") { onAddClass(element); } } } return element; } /** * Adds a desired class to a given element (by its identifier). The element can contain other classes and they will be kept. * @function * @param {string} elementId - The identifier of the element that will get the new given class. * @param {string} className - The class that will be added. * @param {boolean} [checkValues=false] - If it is set to true, it will only try to add the given class if it is not being used already. It is recommended to use true to prevent some old clients from adding the same class multiple times. * @param {function} [onAddClass] - Callback function that will be called if the class of the element has been added, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. * @returns {Node|null} Returns the affected element (if any) or null otherwise. * @todo Think about allowing to use more than once class (and think how many times the \"onAddClass\" function should be called). */ CB_Elements.addClassById = function(elementId, className, checkValues, onAddClass) { return CB_Elements.addClass(CB_Elements.id(elementId), className, checkValues, onAddClass); } /** * Sets a desired class or classes to a given element. All previous classes (if any) will be replaced by the new one or new ones. * @function * @param {Node} element - The element that will get the new given class or classes. * @param {string} classNames - The class or classes that will be set. More than one class can be given (separated by blank spaces). * @param {boolean} [checkValues=false] - If it is set to true, it will only try to set the given class or classes if they are not being used already. * @param {function} [onSetClass] - Callback function that will be called if the class or classes of the element have been set, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. * @returns {Node} Returns the given element again. */ CB_Elements.setClass = function(element, classNames, checkValues, onSetClass) { if (typeof(element) !== \"undefined\" &amp;&amp; element !== null) { if (!checkValues || element.className !== classNames) { element.className = classNames; if (typeof(onSetClass) === \"function\") { onSetClass(element); } } } return element; } /** * Sets a desired class or classes to a given element (by its identifier). All previous classes (if any) will be replaced by the new one or new ones. * @function * @param {string} elementId - The identifier of the element that will get the new given class or classes. * @param {string} classNames - The class or classes that will be set. More than one class can be given (separated by blank spaces). * @param {boolean} [checkValues=false] - If it is set to true, it will only try to set the given class or classes if they are not being used already. * @param {function} [onSetClass] - Callback function that will be called if the class or classes of the element have been set, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. * @returns {Node|null} Returns the affected element (if any) or null otherwise. */ CB_Elements.setClassById = function(elementId, classNames, checkValues, onSetClass) { return CB_Elements.setClass(CB_Elements.id(elementId), classNames, checkValues, onSetClass); } /** * Returns the left position of an element (having in mind [getBoundingClientRect]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect} if available, its parents, etc.). * @function * @param {Node} element - The element whose data we are interested in. * @param {boolean} [ignoreScroll=true] - If it is set to false, it will have in mind the current scroll position to calculate the result. * @param {function} [returnNullOnFail=false] - If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. * @param {boolean} [computed=false] - This parameter will be used when it calls {@link CB_Elements.getStyleProperty} and {@link CB_Elements.getStylePropertyInteger} internally. * @returns {*} It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). */ CB_Elements.getLeft = function(element, ignoreScroll, returnNullOnFail, computed) { if (typeof(element) === \"undefined\" || element === null) { return returnNullOnFail ? null : 0; } //If it's not set, we mind scroll as default: if (typeof(ignoreScroll) === \"undefined\" || ignoreScroll === null) { ignoreScroll = true; } var elementLeft = 0; var originalElement = true; if (typeof(element.getBoundingClientRect) !== \"undefined\" &amp;&amp; element.getBoundingClientRect !== null) { var rect = element.getBoundingClientRect(); if (typeof(rect.left) !== \"undefined\" &amp;&amp; rect.left !== null &amp;&amp; !isNaN(rect.left)) { elementLeft = rect.left; elementLeft -= CB_Client.getBoundingClientRectMargin(\"left\"); if (ignoreScroll) { elementLeft += CB_Screen.getScrollLeft(); } return elementLeft; } } //Gets the left position having in mind its parents (if any) and adds them: do { if (typeof(element) !== \"undefined\" &amp;&amp; element !== null) { var elementPosition = CB_Elements.getStyleProperty(element, \"position\", computed); if (elementPosition === \"absolute\") { if (typeof(getComputedStyle) !== \"undefined\" &amp;&amp; getComputedStyle !== null) { if (element !== document &amp;&amp; !isNaN(parseInt(getComputedStyle(element, \"\").getPropertyValue(\"left\")))) { elementLeft += parseInt(getComputedStyle(element, \"\").getPropertyValue(\"left\")); } else if (!isNaN(parseInt(getComputedStyle(document.body, \"\").getPropertyValue(\"left\")))) { elementLeft += parseInt(getComputedStyle(document.body, \"\").getPropertyValue(\"left\")); } ////////elementLeft += CB_Elements.getStylePropertyInteger(element, \"borderLeftWidth\")[0]; ////////elementLeft += CB_Elements.getStylePropertyInteger(element, \"paddingLeft\")[0]; elementLeft += CB_Elements.getStylePropertyInteger(element, \"borderLeftWidth\", computed)[0]; elementLeft += CB_Elements.getStylePropertyInteger(element, \"paddingLeft\", computed)[0]; if (originalElement) { ///////elementLeft -= CB_Elements.getStylePropertyInteger(element, \"border\")[0]; elementLeft -= CB_Elements.getStylePropertyInteger(element, \"border\", computed)[0]; originalElement = false; } } else if (typeof(element.offsetLeft) !== \"undefined\" &amp;&amp; element.offsetLeft !== null &amp;&amp; !isNaN(parseInt(element.offsetLeft))) { elementLeft += parseInt(element.offsetLeft, 10); } } else { if (typeof(element.offsetLeft) !== \"undefined\" &amp;&amp; element.offsetLeft !== null &amp;&amp; !isNaN(parseInt(element.offsetLeft))) { elementLeft += parseInt(element.offsetLeft, 10); } } } if (typeof(element.offsetParent) !== \"undefined\" &amp;&amp; element.offsetParent !== null) { element = element.offsetParent; } /* else if (typeof(element.parentNode) !== \"undefined\" &amp;&amp; element.parentNode !== null) { element = element.parentNode; } else if (typeof(element.parentElement) !== \"undefined\" &amp;&amp; element.parentElement !== null) { element = element.parentElement; } */ else { var elementParent = CB_Elements.getParent(element); if (typeof(elementParent) !== \"undefined\" &amp;&amp; elementParent !== null) { element = elementParent; } else { element = null; } } } while (element) if (!ignoreScroll) { elementLeft -= CB_Screen.getScrollLeft(); } return isNaN(elementLeft) &amp;&amp; returnNullOnFail ? null : elementLeft; } /** * Returns the left position of an element (having in mind [getBoundingClientRect]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect} if available, its parents, etc.), by its identifier. * @function * @param {string} elementId - The identifier of the element whose data we are interested in. * @param {boolean} [ignoreScroll=true] - If it is set to false, it will have in mind the current scroll position to calculate the result. * @param {function} [returnNullOnFail=false] - If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. * @param {boolean} [computed=false] - This parameter will be used when it calls {@link CB_Elements.getStyleProperty} and {@link CB_Elements.getStylePropertyInteger} internally. * @returns {*} It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). */ CB_Elements.getLeftById = function(elementId, ignoreScroll, returnNullOnFail, computed) { return CB_Elements.getLeft(CB_Elements.id(elementId), ignoreScroll, returnNullOnFail, computed); } /** * Returns the top position of an element (having in mind [getBoundingClientRect]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect} if available, its parents, etc.). * @function * @param {Node} element - The element whose data we are interested in. * @param {boolean} [ignoreScroll=true] - If it is set to false, it will have in mind the current scroll position to calculate the result. * @param {function} [returnNullOnFail=false] - If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. * @param {boolean} [computed=false] - This parameter will be used when it calls {@link CB_Elements.getStyleProperty} and {@link CB_Elements.getStylePropertyInteger} internally. * @returns {*} It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). */ CB_Elements.getTop = function(element, ignoreScroll, returnNullOnFail, computed) { if (typeof(element) === \"undefined\" || element === null) { return returnNullOnFail ? null : 0; } //If it's not set, we mind scroll as default: if (typeof(ignoreScroll) === \"undefined\" || ignoreScroll === null) { ignoreScroll = true; } var elementTop = 0; var originalElement = true; if (typeof(element.getBoundingClientRect) !== \"undefined\" &amp;&amp; element.getBoundingClientRect !== null) { var rect = element.getBoundingClientRect(); if (typeof(rect.top) !== \"undefined\" &amp;&amp; rect.top !== null &amp;&amp; !isNaN(rect.top)) { elementTop = rect.top; elementTop -= CB_Client.getBoundingClientRectMargin(\"top\"); if (ignoreScroll) { elementTop += CB_Screen.getScrollTop(); } return elementTop; } } //Gets the top position having in mind its parents (if any) and adds them: do { if (typeof(element) !== \"undefined\" &amp;&amp; element !== null) { var elementPosition = CB_Elements.getStyleProperty(element, \"position\", computed); if (elementPosition === \"absolute\") { if (typeof(getComputedStyle) !== \"undefined\" &amp;&amp; getComputedStyle !== null) { if (element !== document &amp;&amp; !isNaN(parseInt(getComputedStyle(element, \"\").getPropertyValue(\"top\")))) { elementTop += parseInt(getComputedStyle(element, \"\").getPropertyValue(\"top\")); } else if (!isNaN(parseInt(getComputedStyle(document.body, \"\").getPropertyValue(\"top\")))) { elementTop += parseInt(getComputedStyle(document.body, \"\").getPropertyValue(\"top\")); } ////////elementTop += CB_Elements.getStylePropertyInteger(element, \"borderTopWidth\")[0]; ////////elementTop += CB_Elements.getStylePropertyInteger(element, \"paddingTop\")[0]; elementTop += CB_Elements.getStylePropertyInteger(element, \"borderTopWidth\", computed)[0]; elementTop += CB_Elements.getStylePropertyInteger(element, \"paddingTop\", computed)[0]; if (originalElement) { //////////elementTop -= CB_Elements.getStylePropertyInteger(element, \"border\")[0]; elementTop -= CB_Elements.getStylePropertyInteger(element, \"border\", computed)[0]; originalElement = false; } } else if (typeof(element.offsetTop) !== \"undefined\" &amp;&amp; element.offsetTop !== null &amp;&amp; !isNaN(parseInt(element.offsetTop))) { elementTop += parseInt(element.offsetTop, 10); } } else { if (typeof(element.offsetTop) !== \"undefined\" &amp;&amp; element.offsetTop !== null &amp;&amp; !isNaN(parseInt(element.offsetTop))) { elementTop += parseInt(element.offsetTop, 10); } } } if (typeof(element.offsetParent) !== \"undefined\" &amp;&amp; element.offsetParent !== null) { element = element.offsetParent; } /* else if (typeof(element.parentNode) !== \"undefined\" &amp;&amp; element.parentNode !== null) { element = element.parentNode; } else if (typeof(element.parentElement) !== \"undefined\" &amp;&amp; element.parentElement !== null) { element = element.parentElement; } else { element = null; } */ else { var elementParent = CB_Elements.getParent(element); if (typeof(elementParent) !== \"undefined\" &amp;&amp; elementParent !== null) { element = elementParent; } else { element = null; } } } while (element) if (!ignoreScroll) { elementTop -= CB_Screen.getScrollTop(); } return isNaN(elementTop) &amp;&amp; returnNullOnFail ? null : elementTop; } /** * Returns the top position of an element (having in mind [getBoundingClientRect]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect} if available, its parents, etc.), by its identifier. * @function * @param {string} elementId - The identifier of the element whose data we are interested in. * @param {boolean} [ignoreScroll=true] - If it is set to false, it will have in mind the current scroll position to calculate the result. * @param {function} [returnNullOnFail=false] - If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. * @param {boolean} [computed=false] - This parameter will be used when it calls {@link CB_Elements.getStyleProperty} and {@link CB_Elements.getStylePropertyInteger} internally. * @returns {*} It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). */ CB_Elements.getTopById = function(elementId, ignoreScroll, returnNullOnFail, computed) { return CB_Elements.getTop(CB_Elements.id(elementId), ignoreScroll, returnNullOnFail, computed); } /** * Returns the width of an element (having in mind its border). * @function * @param {Node} element - The element whose data we are interested in. * @param {function} [returnNullOnFail=false] - If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. * @param {boolean} [computed=false] - This parameter will be used when it calls {@link CB_Elements.getStylePropertyInteger} internally. * @returns {*} It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). */ CB_Elements.getWidth = function(element, returnNullOnFail, computed) { if (typeof(element) === \"undefined\" || element === null) { return returnNullOnFail ? null : 0; } var elementWidth = 0; if (typeof(element.getBoundingClientRect) !== \"undefined\" &amp;&amp; element.getBoundingClientRect !== null) { var rect = element.getBoundingClientRect(); if (typeof(rect.width) !== \"undefined\" &amp;&amp; rect.width !== null &amp;&amp; !isNaN(rect.width)) { elementWidth += rect.width; } } if (typeof(elementWidth) === \"undefined\" || elementWidth === null || isNaN(elementWidth) || elementWidth === 0) { if (typeof(element.offsetWidth) !== \"undefined\" &amp;&amp; element.offsetWidth !== null &amp;&amp; !isNaN(parseInt(element.offsetWidth))) { elementWidth += parseInt(element.offsetWidth, 10); } else { /* elementWidth += CB_Elements.getStylePropertyInteger(element, \"width\")[0]; //elementWidth += CB_Elements.getStylePropertyInteger(element, \"border\")[0]; elementHeight += CB_Elements.getStylePropertyInteger(element, \"borderLeftWidth\")[0]; elementHeight += CB_Elements.getStylePropertyInteger(element, \"borderRightWidth\")[0]; elementWidth += CB_Elements.getStylePropertyInteger(element, \"paddingLeft\")[0]; */ elementWidth += CB_Elements.getStylePropertyInteger(element, \"width\", computed)[0]; //elementWidth += CB_Elements.getStylePropertyInteger(element, \"border\", computed)[0]; elementWidth += CB_Elements.getStylePropertyInteger(element, \"borderLeftWidth\", computed)[0]; elementWidth += CB_Elements.getStylePropertyInteger(element, \"borderRightWidth\", computed)[0]; elementWidth += CB_Elements.getStylePropertyInteger(element, \"paddingLeft\", computed)[0]; } } return isNaN(elementWidth) &amp;&amp; returnNullOnFail ? null : elementWidth; } /** * Returns the width of an element (having in mind its border), by its identifier. * @function * @param {string} elementId - The identifier of the element whose data we are interested in. * @param {function} [returnNullOnFail=false] - If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. * @param {boolean} [computed=false] - This parameter will be used when it calls {@link CB_Elements.getStylePropertyInteger} internally. * @returns {*} It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). */ CB_Elements.getWidthById = function(elementId, returnNullOnFail, computed) { return CB_Elements.getWidth(CB_Elements.id(elementId)); } /** * Returns the height of an element (having in mind its border). * @function * @param {Node} element - The element whose data we are interested in. * @param {function} [returnNullOnFail=false] - If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. * @param {boolean} [computed=false] - This parameter will be used when it calls {@link CB_Elements.getStylePropertyInteger} internally. * @returns {*} It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). */ CB_Elements.getHeight = function(element, returnNullOnFail, computed) { if (typeof(element) === \"undefined\" || element === null) { return returnNullOnFail ? null : 0; } var elementHeight = 0; if (typeof(element.getBoundingClientRect) !== \"undefined\" &amp;&amp; element.getBoundingClientRect !== null) { var rect = element.getBoundingClientRect(); if (typeof(rect.height) !== \"undefined\" &amp;&amp; rect.height !== null &amp;&amp; !isNaN(rect.height)) { elementHeight += rect.height; } } if (typeof(elementHeight) === \"undefined\" || elementHeight === null || isNaN(elementHeight) || elementHeight === 0) { if (typeof(element.offsetHeight) !== \"undefined\" &amp;&amp; element.offsetHeight !== null &amp;&amp; !isNaN(parseInt(element.offsetHeight))) { elementHeight += parseInt(element.offsetHeight, 10); } else { /* elementHeight += CB_Elements.getStylePropertyInteger(element, \"height\")[0]; //elementHeight += CB_Elements.getStylePropertyInteger(element, \"border\")[0]; elementWidth += CB_Elements.getStylePropertyInteger(element, \"borderTopWidth\")[0]; elementWidth += CB_Elements.getStylePropertyInteger(element, \"borderBottomWidth\")[0]; elementHeight += CB_Elements.getStylePropertyInteger(element, \"paddingTop\")[0]; */ elementHeight += CB_Elements.getStylePropertyInteger(element, \"height\", computed)[0]; //elementHeight += CB_Elements.getStylePropertyInteger(element, \"border\", computed)[0]; elementHeight += CB_Elements.getStylePropertyInteger(element, \"borderTopWidth\", computed)[0]; elementHeight += CB_Elements.getStylePropertyInteger(element, \"borderBottomWidth\", computed)[0]; elementHeight += CB_Elements.getStylePropertyInteger(element, \"paddingTop\", computed)[0]; } } return isNaN(elementHeight) &amp;&amp; returnNullOnFail ? null : elementHeight; } /** * Returns the height of an element (having in mind its border), by its identifier. * @function * @param {string} elementId - The identifier of the element whose data we are interested in. * @param {function} [returnNullOnFail=false] - If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. * @param {boolean} [computed=false] - This parameter will be used when it calls {@link CB_Elements.getStylePropertyInteger} internally. * @returns {*} It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). */ CB_Elements.getHeightById = function(elementId, returnNullOnFail, computed) { return CB_Elements.getHeight(CB_Elements.id(elementId)); } /** * Prevents or allows the possibility of selecting the content of a given element (makes it unselectable). * @function * @param {Node} element - The element which we want to affect. * @param {boolean} [avoidSelection=true] - If set to false, it will allow selecting the content. Otherwise, it will prevent it to be selected. * @returns {Node|null} Returns the given element again or null. */ CB_Elements.preventSelection = function(element, avoidSelection) { if (typeof(element) === \"undefined\" || element === null) { return null; } if (avoidSelection !== true &amp;&amp; avoidSelection !== false) { avoidSelection = true; } if (avoidSelection) { element.unselectable = \"on\"; element.style.MozUserSelect = \"none\"; element.style.WebkitUserSelect = \"none\"; element.style.userSelect = \"none\"; element.style.KhtmlUserSelect = \"none\"; element.style.MsUserSelect = \"none\"; element.style.MsTouchSelect = \"none\"; element.style.touchSelect = \"none\"; //-webkit-tap-highlight-color:rgba(0, 0, 0, 0); //-webkit-touch-callout:none; //-ms-touch-action:none; //-touch-action:none; element.onselectstart = function() { return false; }; } else { element.unselectable = undefined; element.style.MozUserSelect = undefined; element.style.WebkitUserSelect = undefined; element.style.userSelect = undefined; element.style.KhtmlUserSelect = undefined; element.style.MsUserSelect = undefined; element.style.MsTouchSelect = undefined; element.style.touchSelect = undefined; //-webkit-tap-highlight-color:rgba(0, 0, 0, 0); //-webkit-touch-callout:none; //-ms-touch-action:none; //-touch-action:none; element.onselectstart = undefined; } return element; } /** * Prevents or allows the possibility of selecting the content of a given element (makes it unselectable), by its ID. * @function * @param {string} elementId - The identifier of the element which we want to affect. * @param {boolean} [avoidSelection=true] - If set to false, it will allow selecting the content. Otherwise, it will prevent it to be selected. * @returns {Node|null} Returns the affected element (if any) or null otherwise. */ CB_Elements.preventSelectionById = function(elementId, allowSelection) { return CB_Elements.preventSelection(CB_Elements.id(elementId), allowSelection); } /** * Disables or enables the contextual menu for a given element or in the whole document. * @function * @param {Node} [element=document] - The element whose contextual menu we want to disable or enable. If not given, it will affect the whole document. * @param {boolean} [disableContextMenu=true] - If set to false, it will allow showing the contextual menu. Otherwise, it will prevent it to show. * @returns {Node} Returns the affected element. */ CB_Elements.contextMenuDisable = function(element, disableContextMenu) { if (typeof(element) === \"undefined\" || element === null) { element = document; } if (disableContextMenu !== true &amp;&amp; disableContextMenu !== false) { disableContextMenu = true; } if (disableContextMenu) { CB_Events.add(element, \"contextmenu\", function(e) { e = CB_Events.normalize(e); if (typeof(e.preventDefault) !== \"undefined\") { e.preventDefault(); } return false; }, true, true, false); } else { element.contextmenu = undefined; } return element; } /** * Disables or enables the contextual menu for a given element (by its identifier). * @function * @param {string} elementId - The identifier of the element whose contextual menu we want to disable or enable. * @param {boolean} [disableContextMenu=true] - If set to false, it will allow showing the contextual menu. Otherwise, it will prevent it to show. * @returns {Node|null} Returns the affected element (if any) or null otherwise. */ CB_Elements.contextMenuDisableById = function(elementId, allowContextMenu) { var element = CB_Elements.id(elementId); if (element !== null) { return CB_Elements.contextMenuDisable(element, allowContextMenu); } return null; } /** * Tries to get the body content of an [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe}. Depending on the client and the safety measures, this might fail. * @function * @param {HTMLIFrameElement} frameElement - The [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} element whose body content we want to get. * @returns {string|null} Returns null if something goes wrong. */ //* Source: Jose Basilio and nekno @ http://stackoverflow.com/questions/926916/how-to-get-the-bodys-content-of-an-iframe-in-javascript CB_Elements.getFrameBodyContent = function(frameElement) { if (typeof(frameElement) !== \"undefined\" &amp;&amp; frameElement !== null) { var frameBody = null; if (frameElement.contentDocument &amp;&amp; typeof(frameElement.contentDocument.getElementsByTagName) !== \"undefined\") { frameBody = frameElement.contentDocument.getElementsByTagName(\"body\"); if (frameBody !== null &amp;&amp; typeof(frameBody[0]) !== \"undefined\" &amp;&amp; frameBody[0] !== null) { frameBody = frameBody[0]; } else { frameBody = null; } } if (frameBody === null &amp;&amp; frameElement.contentWindow &amp;&amp; typeof(frameElement.contentWindow.document) !== \"undefined\" &amp;&amp; typeof(frameElement.contentWindow.document.getElementsByTagName) !== \"undefined\") { frameBody = frameElement.contentWindow.document.getElementsByTagName(\"body\"); if (frameBody !== null &amp;&amp; typeof(frameBody[0]) !== \"undefined\" &amp;&amp; frameBody[0] !== null) { frameBody = frameBody[0]; } else { frameBody = null; } } if (frameBody === null &amp;&amp; frameElement !== \"\" &amp;&amp; window.frames &amp;&amp; window.frames[frameElement] &amp;&amp; window.frames[frameElement].document &amp;&amp; window.frames[frameElement].document.body) { frameBody = window.frames[frameElement].document.body; } if (typeof(frameBody) !== \"undefined\" &amp;&amp; frameBody !== null &amp;&amp; frameBody.innerHTML) { return frameBody.innerHTML; } } return null; } /** * Tries to get the body content of an [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} (by its identifier). Depending on the client and the safety measures, this might fail. * @function * @param {string} frameElementId - The identifier of the [iframe]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe} element whose body content we want to get. * @returns {string|null} Returns null if something goes wrong. */ CB_Elements.getFrameBodyContentById = function(frameElementId) { CB_Elements.getFrameBodyContent(CB_Elements.id(frameElementId)); } /** * Callback that is used as the \"onScrollLeftChanges\" parameter for the {@link CB_Elements.getScrollLeftById} function or as the \"onScrollTopChanges\" parameter for the {@link CB_Elements.getScrollTopById} function. All values received should be checked since some could be not numbers. * @memberof CB_Elements * @callback CB_Elements.getScrollLeftById_getScrollTopById_ON_SCROLL_CHANGES * @param {*} scrollLeftOrTop - The scroll left or scroll top position. * @param {*} scrollLeftOrTopPrevious - The previous scroll left or scroll top position. * @param {*} scrollWidthOrHeight - The scroll width or scroll height. * @param {*} clientWidthOrHeight - The client width or client height ([element.clientWidth]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth}/[element.offsetWidth]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth} or [element.clientHeight]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight}/[element.offsetHeight]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight}, depending on the web client). * @param {*} scrollLeftOrTopRelative - The relative scroll left or scroll top position. * @param {*} scrollLeftOrTopRelativePrevious - The previous relative scroll left or scroll top position. */ CB_Elements._getScrollLeftByIdLastValue = {}; CB_Elements._getScrollLeftByIdTimeout = {}; CB_Elements._getScrollLeftByIdScrollRelativePrevious = {}; /** * Returns the horizontal scroll of a given element (by its identifier) and allows running a callback function (becoming recursive if desired). Any previous interval started by a previous call to this function, for the same \"elementId\", will be stopped. * @function * @param {string|window} [elementId=window] - The identifier of the element whose horizontal scroll position we want to get. If a string with the identifier is not given, the unique value allowed is the window object (which is the default value when a non-valid value or no value is given). * @param {CB_Elements.getScrollLeftById_getScrollTopById_ON_SCROLL_CHANGES} [onScrollLeftChanges] - The desired callback function. It will be called as an interval if \"timeoutMs\" is a valid integer value. * @param {boolean} [fireFirstTime=false] - If it is set to true, it will call the callback function (if any) as soon as this function is called. * @param {boolean} [fireAlways=false] - If it is set to true, it will call the callback function (if any) every interval even if the horizontal scroll value has not changed from the last call. * @param {integer} [timeoutMs] - The number of milliseconds between one call to the callback function (if any) and the next one. If not given, it will not perform any interval. * @param {function} [returnNullOnFail=false] - If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. * @returns {number|null} Returns the horizontal scroll of the given element (by its identifier). It could return zero (0) if something fails (use \"returnNullOnFail\" set to true to return null when it fails). */ CB_Elements.getScrollLeftById = function(elementId, onScrollLeftChanges, fireFirstTime, fireAlways, timeoutMs, returnNullOnFail, timeout) { if (typeof(elementId) === \"undefined\" || elementId === null || elementId === window) { elementId === \"_WHOLE_DOCUMENT_\"; } if (typeof(CB_Elements._getScrollLeftByIdLastValue[elementId]) === \"undefined\") { CB_Elements._getScrollLeftByIdLastValue[elementId] = null; } if (typeof(timeout) === \"undefined\" || timeout === null) { if (typeof(CB_Elements._getScrollLeftByIdTimeout[elementId]) === \"undefined\") { CB_Elements._getScrollLeftByIdTimeout[elementId] = null; } timeout = CB_Elements._getScrollLeftByIdTimeout[elementId]; } clearTimeout(timeout); var element = CB_isString(elementId) ? CB_Elements.id(elementId) : elementId; var scrollLeftValue = returnNullOnFail ? null : 0; if (typeof(element) === \"undefined\" || element === null || element === window) { element = CB_Elements.tag(\"body\", document); if (element === null || typeof(element[0]) === \"undefined\" || element[0] === null) { return returnNullOnFail ? null : 0; } element = element[0]; if (typeof(window.pageXOffset) !== \"undefined\") { scrollLeftValue = window.pageXOffset; } else if (typeof(window.scrollX) !== \"undefined\") { scrollLeftValue = window.scrollX; } else if (typeof(document.documentElement.scrollLeft) !== \"undefined\" &amp;&amp; document.documentElement.scrollLeft !== null &amp;&amp; !isNaN(document.documentElement.scrollLeft) &amp;&amp; document.documentElement.scrollLeft &gt; 0) { scrollLeftValue = document.documentElement.scrollLeft; } else if (typeof(document.body.scrollLeft) !== \"undefined\" &amp;&amp; document.body.scrollLeft !== null) { scrollLeftValue = document.body.scrollLeft; } } else { if (typeof(element.scrollLeft) !== \"undefined\" &amp;&amp; element.scrollLeft !== null &amp;&amp; !isNaN(element.scrollLeft) &amp;&amp; element.scrollLeft &gt; 0) { scrollLeftValue = element.scrollLeft; } else if (typeof(element.scrollWidth) !== \"undefined\" &amp;&amp; element.scrollWidth !== null &amp;&amp; !isNaN(element.scrollWidth) &amp;&amp; element.scrollWidth &gt; 0) { scrollLeftValue = element.scrollWidth; } } if (isNaN(scrollLeftValue)) { scrollLeftValue = 0; if (returnNullOnFail) { scrollLeftValue = null; } } //If it's not the first time and scroll has been changed, calls the onScrollLeft function (if any): if (fireAlways || ((fireFirstTime || CB_Elements._getScrollLeftByIdLastValue[elementId] !== null) &amp;&amp; CB_Elements._getScrollLeftByIdLastValue[elementId] !== scrollLeftValue)) { //If there is any defined function: if (typeof(onScrollLeftChanges) === \"function\") { var scrollRelative = (scrollLeftValue + (element.clientWidth || element.offsetWidth)) / element.scrollWidth * 100; if (isNaN(scrollRelative)) { scrollRelative = 0; if (returnNullOnFail) { scrollRelative = null; } } //Sets the new position (to avoid possible infinite recursive loop in the case fireAlways is false): CB_Elements._getScrollLeftByIdLastValue[elementId] = scrollLeftValue; //Executes the function: onScrollLeftChanges(scrollLeftValue, CB_Elements._getScrollLeftByIdLastValue[elementId], element.scrollWidth, element.clientWidth || element.offsetWidth, scrollRelative, CB_Elements._getScrollLeftByIdScrollRelativePrevious[elementId]); CB_Elements._getScrollLeftByIdScrollRelativePrevious[elementId] = scrollRelative; } } //Sets the new position: CB_Elements._getScrollLeftByIdLastValue[elementId] = scrollLeftValue; if (typeof(timeoutMs) !== \"undefined\" &amp;&amp; timeoutMs !== null &amp;&amp; !isNaN(timeoutMs) &amp;&amp; timeoutMs &gt;= 0) { CB_Elements._getScrollLeftByIdTimeout[elementId] = timeout = setTimeout ( function() { CB_Elements.getScrollLeftById(elementId, onScrollLeftChanges, fireFirstTime, timeoutMs, returnNullOnFail, timeout); }, timeoutMs ); } return scrollLeftValue; } CB_Elements._getScrollTopByIdLastValue = {}; CB_Elements._getScrollTopByIdTimeout = {}; CB_Elements._getScrollTopByIdScrollRelativePrevious = {}; /** * Returns the vertical scroll of a given element (by its identifier) and allows running a callback function (becoming recursive if desired). Any previous interval started by a previous call to this function, for the same \"elementId\", will be stopped. * @function * @param {string|window} [elementId=window] - The identifier of the element whose vertical scroll position we want to get. If a string with the identifier is not given, the unique value allowed is the window object (which is the default value when a non-valid value or no value is given). * @param {CB_Elements.getScrollLeftById_getScrollTopById_ON_SCROLL_CHANGES} [onScrollTopChanges] - The desired callback function. It will be called as an interval if \"timeoutMs\" is a valid integer value. * @param {boolean} [fireFirstTime=false] - If it is set to true, it will call the callback function (if any) as soon as this function is called. * @param {boolean} [fireAlways=false] - If it is set to true, it will call the callback function (if any) every interval even if the vertical scroll value has not changed from the last call. * @param {integer} [timeoutMs] - The number of milliseconds between one call to the callback function (if any) and the next one. If not given, it will not perform any interval. * @param {function} [returnNullOnFail=false] - If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. * @returns {number|null} Returns the vertical scroll of the given element (by its identifier). It could return zero (0) if something fails (use \"returnNullOnFail\" set to true to return null when it fails). */ CB_Elements.getScrollTopById = function(elementId, onScrollTopChanges, fireFirstTime, fireAlways, timeoutMs, returnNullOnFail, timeout) { if (typeof(elementId) === \"undefined\" || elementId === null || elementId === window) { elementId === \"_WHOLE_DOCUMENT_\"; } if (typeof(CB_Elements._getScrollTopByIdLastValue[elementId]) === \"undefined\") { CB_Elements._getScrollTopByIdLastValue[elementId] = null; } if (typeof(timeout) === \"undefined\" || timeout === null) { if (typeof(CB_Elements._getScrollTopByIdTimeout[elementId]) === \"undefined\") { CB_Elements._getScrollTopByIdTimeout[elementId] = null; } timeout = CB_Elements._getScrollTopByIdTimeout[elementId]; } clearTimeout(timeout); var element = CB_isString(elementId) ? CB_Elements.id(elementId) : elementId; var scrollTopValue = returnNullOnFail ? null : 0; if (typeof(element) === \"undefined\" || element === null || element === window) { element = CB_Elements.tag(\"body\", document); if (element === null || typeof(element[0]) === \"undefined\" || element[0] === null) { return returnNullOnFail ? null : 0; } element = element[0]; if (typeof(window.pageYOffset) !== \"undefined\") { scrollTopValue = window.pageYOffset; } else if (typeof(window.scrollY) !== \"undefined\") { scrollTopValue = window.scrollY; } else if (typeof(document.documentElement.scrollTop) !== \"undefined\" &amp;&amp; document.documentElement.scrollTop !== null &amp;&amp; !isNaN(document.documentElement.scrollTop) &amp;&amp; document.documentElement.scrollTop &gt; 0) { scrollTopValue = document.documentElement.scrollTop; } else if (typeof(document.body.scrollTop) !== \"undefined\" &amp;&amp; document.body.scrollTop !== null) { scrollTopValue = document.body.scrollTop; } } else { if (typeof(element.scrollTop) !== \"undefined\" &amp;&amp; element.scrollTop !== null &amp;&amp; !isNaN(element.scrollTop) &amp;&amp; element.scrollTop &gt; 0) { scrollTopValue = element.scrollTop; } else if (typeof(element.scrollHeight) !== \"undefined\" &amp;&amp; element.scrollHeight !== null &amp;&amp; !isNaN(element.scrollHeight) &amp;&amp; element.scrollHeight &gt; 0) { scrollTopValue = element.scrollHeight; } } if (isNaN(scrollTopValue)) { scrollTopValue = 0; if (returnNullOnFail) { scrollTopValue = null; } } //If it's not the first time and scroll has been changed, calls the onScrollTop function (if any): if (fireAlways || ((fireFirstTime || CB_Elements._getScrollTopByIdLastValue[elementId] !== null) &amp;&amp; CB_Elements._getScrollTopByIdLastValue[elementId] !== scrollTopValue)) { //If there is any defined function: if (typeof(onScrollTopChanges) === \"function\") { var scrollRelative = (scrollTopValue + (element.clientHeight || element.offsetHeight)) / element.scrollHeight * 100; if (isNaN(scrollRelative)) { scrollRelative = 0; if (returnNullOnFail) { scrollRelative = null; } } //Sets the new position (to avoid possible infinite recursive loop in the case fireAlways is false): CB_Elements._getScrollTopByIdLastValue[elementId] = scrollTopValue; //Executes the function: onScrollTopChanges(scrollTopValue, CB_Elements._getScrollTopByIdLastValue[elementId], element.scrollHeight, element.clientHeight || element.offsetHeight, scrollRelative, CB_Elements._getScrollTopByIdScrollRelativePrevious[elementId]); CB_Elements._getScrollTopByIdScrollRelativePrevious[elementId] = scrollRelative; } } //Sets the new position: CB_Elements._getScrollTopByIdLastValue[elementId] = scrollTopValue; if (typeof(timeoutMs) !== \"undefined\" &amp;&amp; timeoutMs !== null &amp;&amp; !isNaN(timeoutMs) &amp;&amp; timeoutMs &gt;= 0) { CB_Elements._getScrollTopByIdTimeout[elementId] = timeout = setTimeout ( function() { CB_Elements.getScrollTopById(elementId, onScrollTopChanges, fireFirstTime, timeoutMs, returnNullOnFail, timeout); }, timeoutMs ); } return scrollTopValue; } } × Search results Close "},"CrossBase_general_CB_Events.js.html":{"id":"CrossBase_general_CB_Events.js.html","title":"Source: CrossBase/general/CB_Events.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/general/CB_Events.js /** * @file Events management. Contains the {@link CB_Events} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage events. It will return itself if it is tried to be instantiated. * @namespace */ var CB_Events = function() { return CB_Events; }; { CB_Events.initialized = false; //It will tells whether the object has been initialized or not. CB_Events._stored = []; //Array that stores the events (so we could delete all from one type if we wanted). //Initializes all values: CB_Events.init = function() { if (CB_Events.initialized) { return CB_Events; } //The object has been initialized: CB_Events.initialized = true; //TODO. return CB_Events; } /** * Gets the right event object for the current web client and normalizes it attaching to it some methods and properties if they were not present (as preventDefault, stopPropagation, target, etc.). The new attached methods and properties may include polyfills, etc. * @function * @param {Event} e - Event object. If not provided, it will use the value of \"event\", \"window.event\", \"Event\" or an empty object (\"{}\"). * @returns {Event} Returns the event object normalized. */ CB_Events.normalize = function(e) { if (!e) { if (typeof(event) !== \"undefined\") { e = event; } else if (typeof(window.event) !== \"undefined\") { e = window.event; } else if (typeof(Event) !== \"undefined\") { e = Event; } if (!e) { e = {}; } } try { e._writable = true; } catch(E) { e._writable = false; } if (!e._writable) { e = CB_copyObject(e); } //If the event object cannot be written, copies it. //NOTE: Think about using Object.defineProperty with writable: true as option to prevent some web client problems that have readonly properties. //If not supported, adds preventDefault compatibility to the event object: if (typeof(e.preventDefault) === \"undefined\" || e.preventDefault === null) { if (\"returnValue\" in e) { e.preventDefault = function() { e.returnValue = false; return false; }; } else if (typeof(window.event) !== \"undefined\" &amp;&amp; \"returnValue\" in window.event) { e.preventDefault = function() { window.event.returnValue = false; return false; }; } else { e.preventDefault = function() { return false; } } } //If not supported, adds stopPropagation compatibility to the event object: if (typeof(e.stopPropagation) === \"undefined\" || e.stopPropagation === null) { if (typeof(e.cancelBubble) !== \"undefined\" &amp;&amp; e.cancelBubble !== null) { e.stopPropagation = function() { e.cancelBubble = true; }; } else if (typeof(window.event) !== \"undefined\" &amp;&amp; typeof(window.event.cancelBubble) !== \"undefined\") { e.stopPropagation = function() { window.event.cancelBubble = true; }; } else { e.stopPropagation = function() { } } } //If not supported, adds the target property to the object: if (typeof(e.target) === \"undefined\" &amp;&amp; typeof(e.srcElement) !== \"undefined\") { e.target = e.srcElement; } //Prevents Safari bug (source: http://www.quirksmode.org/js/events_properties.html): if (typeof(e.target) !== \"undefined\" &amp;&amp; typeof(e.target.nodeType) !== \"undefined\" &amp;&amp; e.target.nodeType === 3) { try { e.target = e.target.parentNode; } catch(E) {} } //Adds target property (if possible): if (typeof(e.target) === \"undefined\" &amp;&amp; typeof(e.srcElement) !== \"undefined\") { e.target = e.srcElement; } return e; } /** * Returns the type of an event, if any (otherwise, returns an empty string). * @function * @param {Event} e - Event object. * @returns {string} */ CB_Events.getType = function(e) { e = CB_Events.normalize(e); if (typeof(e.type) !== \"undefined\" &amp;&amp; e.type !== null) { return e.type; } else { return \"\"; } } /** * Removes an event listener (even if it is not erasable). * @function * @param {Object} eventTarget - The target whose event listener we want to remove. * @param {string} eventName - The name of the event that we want to remove. * @param {function} eventFunction - The function (event listener) of the event that we want to remove. * @param {boolean} [useCapture=false] - Defines whether the event we want to remove was defined to use capture or not. */ CB_Events.remove = function(eventTarget, eventName, eventFunction, useCapture) { //If the target (node) is null or is not an object, exits: if (typeof(eventTarget) === \"undefined\" || eventTarget === null || typeof(eventTarget) !== \"object\") { return; } //If not defined, set default value for useCapture parameter: if (useCapture !== true &amp;&amp; useCapture !== false) { useCapture = false; } //Removes the event from the array: CB_Events._storedClear(eventTarget, eventName, eventFunction, useCapture); //Removes the event: if (typeof(eventTarget.addEventListener) !== \"undefined\" &amp;&amp; eventTarget.removeEventListener) { eventTarget.removeEventListener(eventName, eventFunction, useCapture); } else if (typeof(eventTarget.attachEvent) !== \"undefined\" &amp;&amp; eventTarget.detachEvent) { eventTarget.detachEvent(\"on\" + eventName, eventFunction); } } /** * Alias for {@link CB_Events.on}. * @function CB_Events.add * @see {@link CB_Events.on} */ /** * Adds an event listener. * @function * @param {Object} eventTarget - The target where we want to attach the event listener. * @param {string} eventName - The name of the event that we want to add. * @param {function} eventFunction - The function (event listener) of the event that we want to add. * @param {boolean} [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. * @param {boolean} [keepOldEventFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [erasable=true] - Defines whether the event listener will be erasable by {@link CB_Events.removeAll} or {@link CB_Events.removeByName} functions later or not (it will always be erasable if we force delete). * @todo Try to simulate \"useCapture\" when the \"addEventListener\" method is not available. */ CB_Events.on = CB_Events.add = function(eventTarget, eventName, eventFunction, useCapture, keepOldEventFunction, erasable) { //If the target (node) is null or is not an object, exits: if (typeof(eventTarget) === \"undefined\" || eventTarget === null || typeof(eventTarget) !== \"object\") { return; } //If not defined, set default values for optional parameters: if (useCapture !== true &amp;&amp; useCapture !== false) { useCapture = false; } if (typeof(keepOldEventFunction) === \"undefined\" || keepOldEventFunction === null) { keepOldEventFunction = true; } if (typeof(erasable) === \"undefined\" || erasable === null) { erasable = true; } //If we don't want to keep the old event functions, we delete them: if (!keepOldEventFunction) { CB_Events.removeByName(eventTarget, eventName); } //Adds the new event listeners: if (typeof(eventTarget.addEventListener) !== \"undefined\" &amp;&amp; eventTarget.addEventListener) { eventTarget.addEventListener(eventName, eventFunction, useCapture); } else if (typeof(eventTarget.attachEvent) !== \"undefined\" &amp;&amp; eventTarget.attachEvent) { eventTarget.attachEvent(\"on\" + eventName, eventFunction); } //else if (eventTarget &amp;&amp; typeof( eval(\"eventTarget.on\" + eventName) ) !== \"undefined\") else if (eventTarget &amp;&amp; typeof(eventTarget[\"on\" + eventName]) !== \"undefined\") { var newEventFunction = function(e) { //e = CB_Events.normalize(e); return CB_Events.executeByName(eventTarget, eventName, e); } eventTarget[\"on\" + eventName] = newEventFunction; } //Stores the event (so we could delete all from one type if we wanted): CB_Events._store(eventTarget, eventName, eventFunction, useCapture, erasable); //If we mind Iframes: if (CB_Configuration[CB_BASE_NAME].MIND_IFRAMES) { //If the event is \"keydown\", \"keyup\", \"keypress\", \"mousedown\" or \"click\": eventName = eventName.toLowerCase(); if (eventName === \"keydown\" || eventName === \"keyup\" || eventName === \"keydown\" || eventName === \"mousedown\" || eventName === \"click\") { try { var eventTargetParents = []; //If the event is the main window object (no one of its possible parents): if (eventTarget === window) { eventTargetParents = CB_Client.getWindowParents(); } //...otherwise if the event is the main document object (no one of its possible parents): else if (eventTarget === document) { eventTargetParents = CB_Client.getWindowParents().slice(0); CB_forEach ( eventTargetParents, function(element, index, array) { if (index &gt; 0) { array[index] = element.document; } } ); } //If there are parents, applies the same event listener to them: if (eventTargetParents.length &gt; 1) { CB_forEach ( eventTargetParents, function(element, index, array) { if (index &gt; 0) { CB_Events.add(element, eventName, eventFunction, useCapture, keepOldEventFunction, erasable); } } ); } } catch(E) { } } } } /** * Object that contains an event handler. * @memberof CB_Events * @typedef {Object} CB_Events.EVENT_HANDLER * @property {Object} eventTarget - The target of the event. * @property {string} eventName - The name of the event. * @property {function} eventFunction - The event listener. * @property {boolean} useCapture - Defines whether the event listener was defined to use capture or not. * @property {boolean} erasable - Defines whether the event handler is erasable (without forcing delete) or not. */ //Function that stores an event (so we could delete all from one type if we wanted): CB_Events._store = function(eventTarget, eventName, eventFunction, useCapture, erasable) { var x = CB_Events._stored.length; CB_Events._stored[x] = new Array(5); CB_Events._stored[x][\"eventTarget\"] = eventTarget; CB_Events._stored[x][\"eventName\"] = eventName; CB_Events._stored[x][\"eventFunction\"] = eventFunction; //Stores the function. CB_Events._stored[x][\"useCapture\"] = useCapture; //Stores the capture mode. CB_Events._stored[x][\"erasable\"] = erasable; //Stores whether is erasable or not. } //Function that clears (deletes) a stored event: CB_Events._storedClear = function(eventTarget, eventName, eventFunction, useCapture) { var CB_storedEventsLength = CB_Events._stored.length for (var x = 0; x &lt; CB_storedEventsLength; x++) { //If the target (node) exists: if (eventTarget === CB_Events._stored[x][\"eventTarget\"]) { //If the event exists if (eventName === CB_Events._stored[x][\"eventName\"]) { //If the function (event handler) exists: if (eventFunction === CB_Events._stored[x][\"eventFunction\"]) { //If it's the same capture mode: if (useCapture === CB_Events._stored[x][\"useCapture\"]) { CB_Events._stored[x] = Array(5); //Clears the array (deletes the stored event). break; //It exits so that way only one element will be cleared. } } } } } } /** * Deletes all handlers for an specific event from a node (target). * @function * @param {Object} eventTarget - The target whose event listeners we want to remove. * @param {string} eventName - The name of the event whose event listeners we want to remove. * @param {boolean} [forceDelete=false] - If it is set to true, it will remove any listener (even the ones which were added as not erasable). */ CB_Events.removeByName = function(eventTarget, eventName, forceDelete) { var CB_storedEventsLength = CB_Events._stored.length; for (var x = 0; x &lt; CB_storedEventsLength; x++) { //If the target (node) exists: if (eventTarget === CB_Events._stored[x][\"eventTarget\"]) { //If the event exists if (eventName === CB_Events._stored[x][\"eventName\"]) { //Removes the element if is erasable or is in force delete mode: if (forceDelete || CB_Events._stored[x][\"erasable\"]) { CB_Events.remove(eventTarget, eventName, CB_Events._stored[x][\"eventFunction\"], CB_Events._stored[x][\"useCapture\"]); } } } } } /** * Removes all event listeners. * @function * @param {boolean} [forceDelete=false] - If it is set to true, it will remove all event listeners (even the ones which were added as not erasable). */ CB_Events.removeAll = function(forceDelete) { //For every targets (nodes): var CB_storedEventsLength = CB_Events._stored.length; for (var x = 0; x &lt; CB_storedEventsLength; x++) { //If the event has not been cleared before: if (typeof(CB_Events._stored[x][\"eventTarget\"]) !== \"undefined\" &amp;&amp; typeof(CB_Events._stored[x][\"eventName\"]) !== \"undefined\") { CB_Events.removeByName(CB_Events._stored[x][\"eventTarget\"], CB_Events._stored[x][\"eventName\"], forceDelete); } } } /** * Executes all event listeners for an specific event from a node (target). * @function * @param {Object} eventTarget - The target whose event listeners we want to execute. It will be the value of \"this\" for every call to each listener. * @param {string} eventName - The name of the event whose event listeners we want to execute. * @param {Event} [e] - Event object that will be passed as the first and unique parameter for every call to each listener. * @param {*} [returnOnNothingExecuted] - The value that will be returned by the function if nothing is executed. * @returns {boolean} Returns the result of doing the AND operator of all return values of each listener executed. If only one listener is executed, it will return the result of doing the AND operator with its returning value and \"true\". Returns the value of the \"returnOnNothingExecuted\" parameter if nothing is executed. */ CB_Events.executeByName = function(eventTarget, eventName, e, returnOnNothingExecuted) { var CB_storedEventsLength = CB_Events._stored.length; var returnValue = true; var somethingExecuted = false; for (var x = 0; x &lt; CB_storedEventsLength; x++) { //If the target (node) exists: if (eventTarget === CB_Events._stored[x][\"eventTarget\"]) { //If the event exists if (eventName === CB_Events._stored[x][\"eventName\"]) { //if an event function exists: if (typeof(CB_Events._stored[x][\"eventFunction\"]) === \"function\") { returnValue = CB_Events._stored[x][\"eventFunction\"].call(eventTarget, e) &amp;&amp; returnValue; somethingExecuted = true; } } } } return somethingExecuted ? returnValue : returnOnNothingExecuted; } /** * Returns all handlers for an specific event from a node (target), if any. * @function * @param {Object} eventTarget - The target whose event listeners we want to get. * @param {string} eventName - The name of the event whose event listeners we want to get. * @param {boolean} [onlyWithFunction=false] - Defines whether to return only the handlers which have a function as the listener. * @returns {array} Returns an array of {@link CB_Events.EVENT_HANDLER} objects. */ CB_Events.getByName = function(eventTarget, eventName, onlyWithFunction) { var found = []; var CB_storedEventsLength = CB_Events._stored.length; for (var x = 0; x &lt; CB_storedEventsLength; x++) { //If the target (node) exists: if (eventTarget === CB_Events._stored[x][\"eventTarget\"]) { //If the event exists if (eventName === CB_Events._stored[x][\"eventName\"]) { if (!onlyWithFunction || typeof(CB_Events._stored[x][\"eventFunction\"]) === \"function\") { found[found.length] = CB_Events._stored[x]; } } } } return found; } /** * Returns all stored event handlers (if any). * @function * @returns {array} Returns an array of {@link CB_Events.EVENT_HANDLER} objects. */ CB_Events.getAll = function() { return CB_Events._stored; } } × Search results Close "},"CrossBase_audiovisual_image_CB_GraphicSpritesScene.js.html":{"id":"CrossBase_audiovisual_image_CB_GraphicSpritesScene.js.html","title":"Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js /** * @file Groups of graphic sprites management (2D or 3D). Internally, it manages {@link CB_GraphicSprites} objects. Contains the {@link CB_GraphicSpritesScene} class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * An object with the information that belongs to a group of graphic sprites. * @example { //'my_sprites_scene_1': id: \"my_sprites_scene_1\", srcType: CB_GraphicSprites.SRC_TYPES.IMAGE, srcLeft: 10, srcTop: 20, srcWidth: 64, srcHeight: 32, left: 10, top: 20, width: 64, height: 32, data: { datum_1: \"value_1\", datum_2: 2, datum_3: [ \"a\", \"b\", \"c\" ] }, //Sprites groups: spritesGroups: [ //'my_sprites_1': { id: \"my_sprites_1\", src: \"path/to/image.gif\", sprites: [ //'my_sprite_1': { id: \"my_sprite_1\", subSprites: [ //'my_subsprite_1': { id: \"my_subsprite_1\", srcLeft: 10, srcTop: 20, zIndex: 1 }, //'my_subsprite_2': { id: \"my_subsprite_2\", srcLeft: 20, srcTop: 40, zIndex: 2 } ] }, //'my_sprite_2': { id: \"my_sprite_2\", subSprites: [ //'my_subsprite_3': { id: \"my_subsprite_3\", srcLeft: 30, srcTop: 60, zIndex: 1 }, //'my_subsprite_4': { id: \"my_subsprite_4\", srcLeft: 40, srcTop: 80, zIndex: 2 } ] } ] }, //'my_sprites_2': { id: \"my_sprites_2\", src: \"path/to/image2.gif\", sprites: [ //'my_sprite_3': { id: \"my_sprite_3\", subSprites: [ //'my_subsprite_1': { id: \"my_subsprite_5\", srcLeft: 10, srcTop: 20, zIndex: 1 }, //'my_subsprite_2': { id: \"my_subsprite_6\", srcLeft: 20, srcTop: 40, zIndex: 2 } ] }, //'my_sprite_4': { id: \"my_sprite_4\", subSprites: [ //'my_subsprite_3': { id: \"my_subsprite_7\", srcLeft: 30, srcTop: 60, zIndex: 1 }, //'my_subsprite_4': { id: \"my_subsprite_8\", srcLeft: 40, srcTop: 80, zIndex: 2 } ] } ] } ] } * @memberof CB_GraphicSpritesScene * @typedef {Object} CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT * @property {string|*} [id='CB_GraphicSpritesScene_' + CB_GraphicSpritesScene._idUnique++] - Identifier of the sprites groups object and also for the graphic sprites scene (also used as the {@link CB_GraphicSprites.id} property for the {@link CB_GraphicSpritesScene} object). It should be unique. Recommended. It must be a value which evaluates to true. By default, it is generated automatically (with an internal counter). * @property {*} [src=\"\"] - The value for the \"src\" property which will be used as default if not provided (or the provided one was wrong) in the given {@link CB_GraphicSprites.SPRITES_OBJECT} objects (in the \"spritesGroups\" property), when creating the internal {@link CB_GraphicSprites} objects. * @property {string} [srcType={@link CB_GraphicSprites.SRC_TYPES_DEFAULT}] - The value for the \"srcType\" property which will be used as default if not provided (or the provided one was wrong) in the given {@link CB_GraphicSprites.SPRITES_OBJECT} objects (in the \"spritesGroups\" property), when creating the internal {@link CB_GraphicSprites} objects. It should point to a property of the {@link CB_GraphicSprites.SRC_TYPES} object. You can use other values of the {@link CB_GraphicSprites.SRC_TYPES} object or create new ones. * @property {number} [srcLeft={@link CB_GraphicSprites.LEFT_SOURCE_DEFAULT}] - The value for the \"srcLeft\" property which will be used as default if not provided (or the provided one was wrong) in the given {@link CB_GraphicSprites.SPRITES_OBJECT} objects (in the \"spritesGroups\" property), when creating the internal {@link CB_GraphicSprites} objects. * @property {number} [srcTop={@link CB_GraphicSprites.TOP_SOURCE_DEFAULT}] - The value for the \"srcTop\" property which will be used as default if not provided (or the provided one was wrong) in the given {@link CB_GraphicSprites.SPRITES_OBJECT} objects (in the \"spritesGroups\" property), when creating the internal {@link CB_GraphicSprites} objects. * @property {number} [srcWidth={@link CB_GraphicSprites.WIDTH_SOURCE_DEFAULT}] - The value for the \"srcWidth\" property which will be used as default if not provided (or the provided one was wrong) in the given {@link CB_GraphicSprites.SPRITES_OBJECT} objects (in the \"spritesGroups\" property), when creating the internal {@link CB_GraphicSprites} objects. * @property {number} [srcHeight={@link CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT}] - The value for the \"srcHeight\" property which will be used as default if not provided (or the provided one was wrong) in the given {@link CB_GraphicSprites.SPRITES_OBJECT} objects (in the \"spritesGroups\" property), when creating the internal {@link CB_GraphicSprites} objects. * @property {number} [left={@link CB_GraphicSprites.LEFT_DEFAULT}] - The value for the \"left\" property which will be used as default if not provided (or the provided one was wrong) in the given {@link CB_GraphicSprites.SPRITES_OBJECT} objects (in the \"spritesGroups\" property), when creating the internal {@link CB_GraphicSprites} objects. * @property {number} [top={@link CB_GraphicSprites.TOP_DEFAULT}] - The value for the \"top\" property which will be used as default if not provided (or the provided one was wrong) in the given {@link CB_GraphicSprites.SPRITES_OBJECT} objects (in the \"spritesGroups\" property), when creating the internal {@link CB_GraphicSprites} objects. * @property {number} [width={@link CB_GraphicSprites.WIDTH_DEFAULT}] - The value for the \"width\" property which will be used as default if not provided (or the provided one was wrong) in the given {@link CB_GraphicSprites.SPRITES_OBJECT} objects (in the \"spritesGroups\" property), when creating the internal {@link CB_GraphicSprites} objects. * @property {number} [height={@link CB_GraphicSprites.HEIGHT_DEFAULT}] - The value for the \"height\" property which will be used as default if not provided (or the provided one was wrong) in the given {@link CB_GraphicSprites.SPRITES_OBJECT} objects (in the \"spritesGroups\" property), when creating the internal {@link CB_GraphicSprites} objects. * @property {number} [zIndex={@link CB_GraphicSprites.ZINDEX_DEFAULT}] - The value for the \"zIndex\" property which will be used as default if not provided (or the provided one was wrong) in the given {@link CB_GraphicSprites.SPRITES_OBJECT} objects (in the \"spritesGroups\" property), when creating the internal {@link CB_GraphicSprites} objects. * @property {boolean} [disabled=false] - The value for the \"disabled\" property which will be used as default if not provided (or the provided one was wrong) in the given {@link CB_GraphicSprites.SPRITES_OBJECT} objects (in the \"spritesGroups\" property), when creating the internal {@link CB_GraphicSprites} objects. * @property {object} [data={ 'that' : CB_GraphicSprites.SPRITES_GROUPS_OBJECT, 'getThis' = function() { return this.that; } }] - Object with any additional data desired which can be any kind. It will always have a \"that\" property pointing to the {@link CB_GraphicSprites.SPRITES_GROUPS_OBJECT} object where it belongs to and a function in its \"getThis\" property returning the same value (added automatically). These properties (\"that\" and \"getThis\") cannot be overridden. The value given will also be used for the \"data\" property which will be used as default if not provided (or the provided one was wrong) in the given {@link CB_GraphicSprites.SPRITES_OBJECT} objects (in the \"spritesGroups\" property), when creating the internal {@link CB_GraphicSprites} objects. * @property {array} [spritesGroups=[]] - Numeric array containing {@link CB_GraphicSprites.SPRITES_OBJECT} objects with all the sprites groups that are useful for creating the internal {@link CB_GraphicSprites} objects. Recommended at least to provide one {@link CB_GraphicSprites.SPRITES_OBJECT} object in the first index. * @property {*} [parent=undefined] - Property pointing to or containing its parent (also used as the {@link CB_GraphicSpritesScene.parent} property for the {@link CB_GraphicSpritesScene} object). * @property {array} items - Read-only numeric array containing {@link CB_GraphicSprites} objects created internally. Their \"parent\" property will be set to point the current {@link CB_GraphicSpritesScene} object which contains them. * @property {array} itemsByZIndex - Read-only property containing a numeric array of all the {@link CB_GraphicSprites} objects ordered by their z-index (\"zIndex\" property). It is updated automatically when the z-index of a sprite is set with its {@link CB_GraphicSprites#setZIndex} method or when inserting/removing {@link CB_GraphicSprites} objects through the {@link CB_GraphicSpritesScene#insertSpritesGroups}, {@link CB_GraphicSpritesScene#insertSpritesGroup}, {@link CB_GraphicSpritesScene#removeSpritesGroup} or {@link CB_GraphicSpritesScene#removeSpritesGroupById} methods. * @property {boolean} [byReference_DEFAULT=false] - Default value to use as the \"byReference\" parameter for the constructor and for the {@link CB_GraphicSpritesScene#insertSpritesGroups} method. If a boolean value is not provided, it will be parsed to boolean (resulting undefined to be false). * @property {CB_GraphicSpritesScene} container - Read-only property pointing to the {@link CB_GraphicSpritesScene} object which contains it. * @property {boolean} isSpritesGroups - Read-only property which is always set to true to help identify this type of object. * @property {'spritesGroups'} type - Read-only property indicating the type of object (always \"spritesGroups\"). */ /** * Class to manage different groups of graphic sprites (2D or 3D). Internally, it manages {@link CB_GraphicSprites} objects. * @class * @classdesc Class to manage different groups of graphic sprites (2D or 3D). Internally, it manages {@link CB_GraphicSprites} objects. * @param {CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} [spritesGroups] - Object with the desired groups of sprites. The information will be used for the {@link CB_GraphicSpritesScene#spritesGroups} property. Used as the \"spritesGroups\" parameter when calling the {@link CB_GraphicSpritesScene#insertSpritesGroups} method internally. * @param {boolean} [byReference=false] - This value will be used as the \"byReference\" parameter of the constructor when creating the new internal {@link CB_GraphicSprites} objects. If a boolean value is not provided, it will use the value of the {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT.byReference_DEFAULT} property of the given {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} object (parsed to boolean). * @returns {CB_GraphicSpritesScene} Returns a new {@link CB_GraphicSpritesScene} object. * @todo Think about a \"createCopy\" parameter on different the insert methods (to insert sprites groups/graphic sprites objects, etc.) so it will make a copy of the object to avoid using/modifying the original one. If the \"createCopy\" is set to false, it should always use the object as reference (using/modifying it). * @todo Think about a method to remove a sprite group object when the same sprite group is received by parameter. The same to remove a {@link CB_GraphicSprites} object, receiving a {@link CB_GraphicSprites} object by parameter. The same to remove the sprites groups object, receiving a sprites groups object by parameter. Only remove them if they match exactly. * @todo Think about a method to insert {@link CB_GraphicSprites} object directly. The same with a method that inserts many {@link CB_GraphicSprites} objects (receiving an array with them). */ var CB_GraphicSpritesScene = function(spritesGroups, byReference) { //Creates an instance of this object and returns it in the case that it is being called from an unexpected context: if (this === window || !(this instanceof CB_GraphicSpritesScene)) { return new CB_GraphicSpritesScene(spritesGroups, byReference); } //Properties and variables: /** * Identifier of the sprites groups object (the \"id\" property of the {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} stored in the {@link CB_GraphicSpritesScene#spritesGroups} property) and the {@link CB_GraphicSpritesScene} object itself (same one). It should be unique. It must be a value which evaluates to true. By default, it is generated automatically (with an internal counter). * @var * @readonly * @type {string|*} * @default 'CB_GraphicSpritesScene_' + CB_GraphicSpritesScene._idUnique++ */ this.id = \"\"; /** * Property pointing to or containing its parent. It is the same as the \"parent\" property of the {@link CB_GraphicSprites.SPRITES_GROUPS_OBJECT} stored in the {@link CB_GraphicSprites#spritesGroups} property. * @var * @readonly * @type {*} * @default */ this.parent = undefined; /** * Object containing all the internally-created {@link CB_GraphicSprites} objects and their information. * @var * @readonly * @type {SPRITES_GROUPS_OBJECT} * @default */ this.spritesGroups = {}; //Calls the constructor of the object when creates an instance: return this._init(spritesGroups, byReference); } //Constants: /** * Property which is always set to true to help identify this type of object. * @constant * @type {boolean} * @default */ CB_GraphicSpritesScene.prototype.isSpritesScene = true; /** * Indicates the type of object (always \"spritesScene\"). * @constant * @type {string} * @default */ CB_GraphicSpritesScene.prototype.type = \"spritesScene\"; //Variables: CB_GraphicSpritesScene._idUnique = 0; //Counter to make the sprites group id unique. //Constructor: CB_GraphicSpritesScene.prototype._init = function(spritesGroups, byReference) { this.insertSpritesGroups(spritesGroups, byReference); return this; } /** * Destroys the graphic sprites scene object (removing all the sprites groups and the internal {@link CB_GraphicSprites} objects, etc.) and frees memory. * @function */ CB_GraphicSpritesScene.prototype.destructor = function() { //Destroys all the internal CB_GraphicSprites objects: this.executeFunctionAll(function() { this.destructor(); }); //Resets properties to their default value: this.removeSpritesGroups(); } /** * Alias for {@link CB_GraphicSpritesScene#removeSpritesGroups}. * @function CB_GraphicSpritesScene#removeAll * @see {@link CB_GraphicSpritesScene#removeSpritesGroups} */ /** * Alias for {@link CB_GraphicSpritesScene#removeSpritesGroups}. * @function CB_GraphicSpritesScene#removeSpritesGroupsAll * @see {@link CB_GraphicSpritesScene#removeSpritesGroups} */ /** * Removes all the sprites groups (and all the {@link CB_GraphicSprites} objects) by clearing the {@link CB_GraphicSprites#spritesGroups} property. * @function */ CB_GraphicSpritesScene.prototype.removeSpritesGroups = CB_GraphicSpritesScene.prototype.removeSpritesGroupsAll = CB_GraphicSpritesScene.prototype.removeAll = function() { this.spritesGroups = {}; } /** * Adds the desired groups of graphic sprites. Calls the {@link CB_GraphicSpritesScene#insertSpritesGroup} and {@link CB_GraphicSpritesScene#updateGraphicSpritesByZIndex} methods internally. * @function * @param {CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} [spritesGroups] - Object with the desired sprites groups. They will be stored in the \"{@link CB_GraphicSpritesScene#spritesGroups}.spritesGroups\" property and the {@link CB_GraphicSprites} objects created internally will be stored in the \"{@link CB_GraphicSpritesScene#spritesGroups}.items\" property. * @param {boolean} [byReference=!!{@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT.byReference_DEFAULT}] - This value will be used as the \"byReference\" parameter of the constructor when creating the new internal {@link CB_GraphicSprites} objects. If a boolean value is not provided, it will use the value of the {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT.byReference_DEFAULT} property of the given {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} object (parsed to boolean). * @returns {CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} Returns the {@link CB_GraphicSpritesScene#spritesGroups} property after updating it. */ CB_GraphicSpritesScene.prototype.insertSpritesGroups = function(spritesGroups, byReference) { //Sets the properties (sanitizing them): this.spritesGroups = this.spritesGroups || {}; spritesGroups = spritesGroups || {}; this.spritesGroups.isSpritesGroups = true; this.spritesGroups.type = \"spritesGroups\"; this.spritesGroups.container = this; this.parent = this.spritesGroups.parent = spritesGroups.parent; this.id = this.spritesGroups.id = spritesGroups.id = spritesGroups.id || \"CB_GraphicSpritesScene_\" + CB_GraphicSpritesScene._idUnique++; this.spritesGroups.src = spritesGroups.src = spritesGroups.src || !isNaN(spritesGroups.src) &amp;&amp; spritesGroups.src !== null ? spritesGroups.src : \"\"; this.spritesGroups.srcType = spritesGroups.srcType = spritesGroups.srcType || CB_GraphicSprites.SRC_TYPES_DEFAULT; spritesGroups.srcLeft = parseFloat(spritesGroups.srcLeft); this.spritesGroups.srcLeft = spritesGroups.srcLeft = !isNaN(spritesGroups.srcLeft) ? spritesGroups.srcLeft : parseFloat(CB_GraphicSprites.LEFT_SOURCE_DEFAULT) || 0; spritesGroups.left = parseFloat(spritesGroups.left); this.spritesGroups.left = spritesGroups.left = !isNaN(spritesGroups.left) ? spritesGroups.left : parseFloat(CB_GraphicSprites.LEFT_DEFAULT) || 0; spritesGroups.srcTop = parseFloat(spritesGroups.srcTop); this.spritesGroups.srcTop = spritesGroups.srcTop = !isNaN(spritesGroups.srcTop) ? spritesGroups.srcTop : parseFloat(CB_GraphicSprites.TOP_SOURCE_DEFAULT) || 0; spritesGroups.top = parseFloat(spritesGroups.top); this.spritesGroups.top = spritesGroups.top = !isNaN(spritesGroups.top) ? spritesGroups.top : parseFloat(CB_GraphicSprites.TOP_DEFAULT) || 0; spritesGroups.srcWidth = parseFloat(spritesGroups.srcWidth); this.spritesGroups.srcWidth = spritesGroups.srcWidth = !isNaN(spritesGroups.srcWidth) ? spritesGroups.srcWidth : parseFloat(CB_GraphicSprites.WIDTH_SOURCE_DEFAULT) || 0; spritesGroups.width = parseFloat(spritesGroups.width); this.spritesGroups.width = spritesGroups.width = !isNaN(spritesGroups.width) ? spritesGroups.width : parseFloat(CB_GraphicSprites.WIDTH_DEFAULT) || 0; spritesGroups.srcHeight = parseFloat(spritesGroups.srcHeight); this.spritesGroups.srcHeight = spritesGroups.srcHeight = !isNaN(spritesGroups.srcHeight) ? spritesGroups.srcHeight : parseFloat(CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT) || 0; spritesGroups.height = parseFloat(spritesGroups.height); this.spritesGroups.height = spritesGroups.height = !isNaN(spritesGroups.height) ? spritesGroups.height : parseFloat(CB_GraphicSprites.HEIGHT_DEFAULT) || 0; spritesGroups.zIndex = parseFloat(spritesGroups.zIndex); this.spritesGroups.zIndex = spritesGroups.zIndex = !isNaN(spritesGroups.zIndex) ? spritesGroups.zIndex : parseFloat(CB_GraphicSprites.ZINDEX_DEFAULT) || 0; this.spritesGroups.data = typeof(spritesGroups.data) === \"object\" &amp;&amp; spritesGroups.data !== null ? CB_copyObject(spritesGroups.data, false) : {}; //Accepts any object but not other values. this.spritesGroups.data.that = this.spritesGroups; this.spritesGroups.data.getThis = function() { return this.that; }; spritesGroups.spritesGroups = CB_isArray(spritesGroups.spritesGroups) ? spritesGroups.spritesGroups : []; //Inserts the given sprites groups, one by one: byReference = (byReference === true || byReference === false) ? byReference : !!spritesGroups.byReference_DEFAULT; var spritesGroupsLength = spritesGroups.spritesGroups.length; for (var x = 0; x &lt; spritesGroupsLength; x++) { this.insertSpritesGroup(spritesGroups.spritesGroups[x], true, byReference); } //Updates the array with the CB_GraphicSprites ordered by z-index: this.updateGraphicSpritesByZIndex(); //Returns the sprites: return this.spritesGroups; } /** * Alias for {@link CB_GraphicSpritesScene#updateGraphicSpritesByZIndex}. * @function CB_GraphicSpritesScene#updateItemsByZIndex * @see {@link CB_GraphicSpritesScene#updateGraphicSpritesByZIndex} */ /** * Updates (sorts again) the \"itemsByZIndex\" property (which is an array with the {@link CB_GraphicSprites} objects ordered by z-index, whose data comes from the array in the \"items\" property of the {@link CB_GraphicSpritesScene#spritesGroups} object) of the {@link CB_GraphicSpritesScene#spritesGroups} object. * @function * @returns {array} Returns the \"itemsByZIndex\" array of the {@link CB_GraphicSpritesScene#spritesGroups} object after updating it. Returns null if the property could not be obtained or updated. */ CB_GraphicSpritesScene.prototype.updateGraphicSpritesByZIndex = CB_GraphicSpritesScene.prototype.updateItemsByZIndex = function() { this.spritesGroups.items = this.spritesGroups.items || null; if (this.spritesGroups.items) { var spritesGroupLength = this.spritesGroups.items.length; if (spritesGroupLength) { var elementIndex = null; this.spritesGroups.itemsByZIndex = []; for (var x = 0; x &lt; spritesGroupLength; x++) { elementIndex = CB_GraphicSpritesScene._choosePositionByZIndex(this.spritesGroups.itemsByZIndex, this.spritesGroups.items[x]); this.spritesGroups.itemsByZIndex = CB_Arrays.insertElement(this.spritesGroups.itemsByZIndex, elementIndex, this.spritesGroups.items[x]); this.spritesGroups.items[x].positionByZIndex = elementIndex; } return this.spritesGroups.itemsByZIndex; } } return null; } /** * Alias for {@link CB_GraphicSpritesScene#removeSpritesGroup}. * @function CB_GraphicSpritesScene#remove * @see {@link CB_GraphicSpritesScene#removeSpritesGroup} */ /** * Alias for {@link CB_GraphicSpritesScene#removeSpritesGroup}. * @function CB_GraphicSpritesScene#removeGraphicSprites * @see {@link CB_GraphicSpritesScene#removeSpritesGroup} */ /** * Removes a sprites group and its {@link CB_GraphicSprites} object by its index (its position in the {@link CB_GraphicSpritesScene#spritesGroups.items} array). Calls the {@link CB_GraphicSpritesScene#updateGraphicSpritesByZIndex} method internally. * @function * @param {integer} [index=0] - The index where the {@link CB_GraphicSprites} object is located (its position in the {@link CB_GraphicSpritesScene#spritesGroups.items} array). * @returns {boolean} Returns true if the {@link CB_GraphicSprites} object has been deleted from the graphic sprites scene object or false otherwise. */ CB_GraphicSpritesScene.prototype.removeSpritesGroup = CB_GraphicSpritesScene.prototype.removeGraphicSprites = CB_GraphicSpritesScene.prototype.remove = function(index) { var removed = false; var spritesGroupsLeft = CB_Arrays.removeElementByPosition(this.spritesGroups.items, index, function() { removed = true; }); if (removed) { this.spritesGroups.spritesGroups = CB_Arrays.removeElementByPosition(this.spritesGroups.spritesGroups, index); this.spritesGroups.items = spritesGroupsLeft; //Updates the array with the CB_GraphicSprites ordered by z-index: this.updateGraphicSpritesByZIndex(); } return removed; } /** * Alias for {@link CB_GraphicSpritesScene#removeSpritesGroupById}. * @function CB_GraphicSpritesScene#removeById * @see {@link CB_GraphicSpritesScene#removeSpritesGroupById} */ /** * Alias for {@link CB_GraphicSpritesScene#removeSpritesGroupById}. * @function CB_GraphicSpritesScene#removeGraphicSpritesById * @see {@link CB_GraphicSpritesScene#removeSpritesGroupById} */ /** * Removes a sprites group and its {@link CB_GraphicSprites} object by its identifier. Calls the {@link CB_GraphicSpritesScene#updateGraphicSpritesByZIndex} method internally. * @function * @param {string|*} [id=undefined] - The identifier of the {@link CB_GraphicSprites} object. * @returns {boolean} Returns true if the {@link CB_GraphicSprites} object has been deleted from the graphic sprites scene object or false otherwise. * @todo Optimize it (perhaps using a cache matching the IDs with their position, maybe using the \"position\" or \"positionByZIndex\" properties). */ CB_GraphicSpritesScene.prototype.removeSpritesGroupById = CB_GraphicSpritesScene.prototype.removeGraphicSpritesById = CB_GraphicSpritesScene.prototype.removeById = function(id) { var removed = false; var index = null; var spritesGroupsLeft = CB_Arrays.removeDuplicated(this.spritesGroups.items, function(value, position, array) { if (value &amp;&amp; value.id === id) { removed = true; index = position; return true; }; return false; }, true); if (removed) { if (index !== null) { this.spritesGroups.spritesGroups = CB_Arrays.removeElementByPosition(this.spritesGroups.spritesGroups, index); } this.spritesGroups.items = spritesGroupsLeft; //Updates the array with the CB_GraphicSprites ordered by z-index: this.updateGraphicSpritesByZIndex(); } return removed; } /** * Object used as the returning value of the {@link CB_GraphicSpritesScene#insertSpritesGroup} method. * @memberof CB_GraphicSpritesScene * @typedef {Object} CB_GraphicSpritesScene.insertSpritesGroup_OBJECT * @property {CB_GraphicSprites.SPRITES_OBJECT} spritesGroup - The {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} which has been inserted (it could have been modified/sanitized from the given one and some missing properties or those which were wrong could have been inherited) and was used to create the internal {@link CB_GraphicSprites} object when calling its constructor. * @property {CB_GraphicSprites} item - The {@link CB_GraphicSprites} object created and inserted from the {@link CB_GraphicSprites.SPRITES_OBJECT}. */ /** * Alias for {@link CB_GraphicSpritesScene#insertSpritesGroup}. * @function CB_GraphicSpritesScene#insert * @see {@link CB_GraphicSpritesScene#insertSpritesGroup} */ /** * Adds the desired group of graphic sprites. Creates internal {@link CB_GraphicSprites} objects. * @function * @param {CB_GraphicSprites.SPRITES_OBJECT} [spritesGroup] - Object with the desired sprites group. It will be stored in the \"{@link CB_GraphicSpritesScene#spritesGroups}.spritesGroups\" property and the {@link CB_GraphicSprites} object created internally will be stored in the \"{@link CB_GraphicSpritesScene#spritesGroups}.items\" property. * @param {boolean} [avoidUpdatingGraphicSpritesByZIndex=false] - If set to true, it will not call the {CB_GraphicSpritesScene#updateGraphicSpritesByZIndex} method internally. Internal usage recommended only. * @param {boolean} [byReference=false] - This value will be used as the \"byReference\" parameter of the constructor when creating the new internal {@link CB_GraphicSprites} objects. * @returns {CB_GraphicSpritesScene.insertSpritesGroup_OBJECT} Returns an object whose \"spritesGroup\" property contains the {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} which has been inserted (it could have been modified/sanitized from the given one and some missing properties or those which were wrong could have been inherited) and was used to create the internal {@link CB_GraphicSprites} object when calling its constructor and the \"item\" property contains the {@link CB_GraphicSprites} object created and inserted. */ CB_GraphicSpritesScene.prototype.insertSpritesGroup = CB_GraphicSpritesScene.prototype.insert = function(spritesGroup, avoidUpdatingGraphicSpritesByZIndex, byReference) { //Sets the properties (sanitizing them): this.spritesGroups = this.spritesGroups || {}; spritesGroup = spritesGroup || {}; spritesGroup.parent = this; //Overwrites the parent to point to the CB_GraphicSprites itself which will contain it. spritesGroup.src = spritesGroup.src || !isNaN(spritesGroup.src) &amp;&amp; spritesGroup.src !== null ? spritesGroup.src : this.spritesGroups.src || !isNaN(this.spritesGroups.src) &amp;&amp; this.spritesGroups.src !== null ? this.spritesGroups.src : \"\"; spritesGroup.srcType = spritesGroup.srcType || this.spritesGroups.srcType || CB_GraphicSprites.SRC_TYPES_DEFAULT; spritesGroup.srcLeft = parseFloat(spritesGroup.srcLeft); spritesGroup.srcLeft = !isNaN(spritesGroup.srcLeft) ? spritesGroup.srcLeft : parseFloat(this.spritesGroups.srcLeft); spritesGroup.srcLeft = !isNaN(spritesGroup.srcLeft) ? spritesGroup.srcLeft : parseFloat(CB_GraphicSprites.LEFT_SOURCE_DEFAULT) || 0; spritesGroup.left = parseFloat(spritesGroup.left); spritesGroup.left = !isNaN(spritesGroup.left) ? spritesGroup.left : parseFloat(this.spritesGroups.left); spritesGroup.left = !isNaN(spritesGroup.left) ? spritesGroup.left : parseFloat(CB_GraphicSprites.LEFT_DEFAULT) || 0; spritesGroup.srcTop = parseFloat(spritesGroup.srcTop); spritesGroup.srcTop = !isNaN(spritesGroup.srcTop) ? spritesGroup.srcTop : parseFloat(this.spritesGroups.srcTop); spritesGroup.srcTop = !isNaN(spritesGroup.srcTop) ? spritesGroup.srcTop : parseFloat(CB_GraphicSprites.TOP_SOURCE_DEFAULT) || 0; spritesGroup.top = parseFloat(spritesGroup.top); spritesGroup.top = !isNaN(spritesGroup.top) ? spritesGroup.top : parseFloat(this.spritesGroups.top); spritesGroup.top = !isNaN(spritesGroup.top) ? spritesGroup.top : parseFloat(CB_GraphicSprites.TOP_DEFAULT) || 0; spritesGroup.srcWidth = parseFloat(spritesGroup.srcWidth); spritesGroup.srcWidth = !isNaN(spritesGroup.srcWidth) ? spritesGroup.srcWidth : parseFloat(this.spritesGroups.srcWidth); spritesGroup.srcWidth = !isNaN(spritesGroup.srcWidth) ? spritesGroup.srcWidth : parseFloat(CB_GraphicSprites.WIDTH_SOURCE_DEFAULT) || 0; spritesGroup.width = parseFloat(spritesGroup.width); spritesGroup.width = !isNaN(spritesGroup.width) ? spritesGroup.width : parseFloat(this.spritesGroups.width); spritesGroup.width = !isNaN(spritesGroup.width) ? spritesGroup.width : parseFloat(CB_GraphicSprites.WIDTH_DEFAULT) || 0; spritesGroup.srcHeight = parseFloat(spritesGroup.srcHeight); spritesGroup.srcHeight = !isNaN(spritesGroup.srcHeight) ? spritesGroup.srcHeight : parseFloat(this.spritesGroups.srcHeight); spritesGroup.srcHeight = !isNaN(spritesGroup.srcHeight) ? spritesGroup.srcHeight : parseFloat(CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT); spritesGroup.height = parseFloat(spritesGroup.height); spritesGroup.height = !isNaN(spritesGroup.height) ? spritesGroup.height : parseFloat(this.spritesGroups.height); spritesGroup.height = !isNaN(spritesGroup.height) ? spritesGroup.height : parseFloat(CB_GraphicSprites.HEIGHT_DEFAULT) || 0; spritesGroup.zIndex = parseFloat(spritesGroup.zIndex); spritesGroup.zIndex = !isNaN(spritesGroup.zIndex) ? spritesGroup.zIndex : parseFloat(this.spritesGroups.zIndex); spritesGroup.zIndex = !isNaN(spritesGroup.zIndex) ? spritesGroup.zIndex : parseFloat(CB_GraphicSprites.ZINDEX_DEFAULT) || 0; spritesGroup.disabled = !!spritesGroup.disabled || false; spritesGroup.data = typeof(spritesGroup.data) === \"object\" &amp;&amp; spritesGroup.data !== null ? spritesGroup.data : {}; //this.spritesGroups.data; if (typeof(this.spritesGroups.data) === \"object\" &amp;&amp; this.spritesGroups.data !== null) { spritesGroup.data = CB_combineJSON(this.spritesGroups.data, spritesGroup.data); } //Combine objects. spritesGroup.data = typeof(spritesGroup.data) === \"object\" &amp;&amp; spritesGroup.data !== null ? CB_copyObject(spritesGroup.data, false) : {}; //Note: the CB_GraphicSprites class will add the \"that\" and \"getThis\" properties to the \"data\". //Creates and inserts the sprites group: this.spritesGroups.items = this.spritesGroups.items || []; this.spritesGroups.spritesGroups = this.spritesGroups.spritesGroups || []; var item = new CB_GraphicSprites(spritesGroup, byReference); var position = this.getGraphicSpritesIndexById(item.id); //If there is a sprites group with the same ID, it will be replaced by the new one (in the same position). position = position !== -1 ? position : this.spritesGroups.items.length; item.position = position; this.spritesGroups.items[position] = item; spritesGroup.isSpritesGroup = true; //Adds the \"isSpritesGroup\" property to the sprites groups object. spritesGroup.type = \"spritesGroup\"; //Adds the \"type\" property to the sprites groups object. this.spritesGroups.spritesGroups[position] = spritesGroup; //Overrides the sprites groups object, sanitized. if (!avoidUpdatingGraphicSpritesByZIndex) { this.updateGraphicSpritesByZIndex(); } //Returns the sprites: return { \"spritesGroup\" : spritesGroup, \"item\" : item }; } //Returns the position that an element (subsprites group, sprite or sub-sprite) should have in a given array, having in mind that they are sorted by by z-index in that array (ascending order): CB_GraphicSpritesScene._choosePositionByZIndex = function(array, element) { if (array &amp;&amp; element) { var arrayLength = array.length; if (arrayLength) { for (var x = 0; x &lt; arrayLength; x++) { if (array[x] &amp;&amp; array[x].zIndex &gt; element.zIndex) { return x; } } return array.length; //By default, best position is at the end of the array (as a new element). } } return 0; } /** * Alias for {@link CB_GraphicSpritesScene#getSpritesGroups}. * @function CB_GraphicSpritesScene#getSpritesGroupsAll * @see {@link CB_GraphicSpritesScene#getSpritesGroups} */ /** * Gets the sprites groups object (the {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} object which is in the {@link CB_GraphicSpritesScene#spritesGroups} property), if any. * @function * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @returns {CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT|*} Returns the sprites groups object (the {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} object which is in the {@link CB_GraphicSpritesScene#spritesGroups} property), if any, or the value of \"returnValueOnFail\" otherwise. */ CB_GraphicSpritesScene.prototype.getSpritesGroups = CB_GraphicSpritesScene.prototype.getSpritesGroupsAll = function(returnValueOnFail) { return this.spritesGroups ? this.spritesGroups : returnValueOnFail; } /** * Alias for {@link CB_GraphicSpritesScene#getGraphicSpritesAll}. * @function CB_GraphicSpritesScene#getAll * @see {@link CB_GraphicSpritesScene#getGraphicSpritesAll} */ /** * Gets all the sprites graphic objects (the \"items\" property of the internal {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} object, if any). * @function * @param {boolean} [orderedByZIndex=false] - If set to true, it will return the {@link CB_GraphicSprites} objects sorted by their z-index (ascending order). * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @returns {array|*} Returns an array with all the {@link CB_GraphicSprites} objects or the value of \"returnValueOnFail\" otherwise. */ CB_GraphicSpritesScene.prototype.getGraphicSpritesAll = CB_GraphicSpritesScene.prototype.getAll = function(orderedByZIndex, returnValueOnFail) { if (this.spritesGroups) { if (!orderedByZIndex) { return (this.spritesGroups.items) ? this.spritesGroups.items : returnValueOnFail; } else { return (this.spritesGroups.itemsByZIndex) ? this.spritesGroups.itemsByZIndex : returnValueOnFail; } } return returnValueOnFail; } /** * Alias for {@link CB_GraphicSpritesScene#getGraphicSprites}. * @function CB_GraphicSpritesScene#get * @see {@link CB_GraphicSpritesScene#getGraphicSprites} */ /** * Gets a desired {@link CB_GraphicSprites} object through its index (its position in the {@link CB_GraphicSpritesScene#spritesGroups.items} array). Faster than getting it through its identifier with the {@link CB_GraphicSpritesScene#getGraphicSpritesById} method. * @function * @param {integer} [index=0] - The index where the desired {@link CB_GraphicSprites} object must be located (its position in the {@link CB_GraphicSpritesScene#spritesGroups.items} array). * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @returns {CB_GraphicSprites|*} Returns a {@link CB_GraphicSprites} object if found or the value of \"returnValueOnFail\" otherwise. */ CB_GraphicSpritesScene.prototype.getGraphicSprites = CB_GraphicSpritesScene.prototype.get = function(index, returnValueOnFail) { index = parseInt(index); index = isNaN(index) ? 0 : index; if (index &lt; 0) { index *= -1; } //It must be a positive integer. return this.spritesGroups &amp;&amp; this.spritesGroups.items &amp;&amp; this.spritesGroups.items[index] ? this.spritesGroups.items[index] : returnValueOnFail; } /** * Alias for {@link CB_GraphicSpritesScene#getGraphicSpritesById}. * @function CB_GraphicSpritesScene#getById * @see {@link CB_GraphicSpritesScene#getGraphicSpritesById} */ /** * Gets a desired {@link CB_GraphicSprites} object through its identifier. Slower than getting it through its index with the {@link CB_GraphicSpritesScene#getGraphicSprites} method. * @function * @param {string|*} [id=undefined] - The identifier of the {@link CB_GraphicSprites} object that we want to get. * @param {*} [returnValueOnFail=undefined] - The value we want it to return in the case that no value is found. If not provided, undefined will be returned. * @returns {CB_GraphicSprites|*} Returns a {@link CB_GraphicSprites} object if found or the value of \"returnValueOnFail\" otherwise. */ CB_GraphicSpritesScene.prototype.getGraphicSpritesById = CB_GraphicSpritesScene.prototype.getById = function(id, returnValueOnFail) { var index = this.getGraphicSpritesIndexById(id); return index !== -1 ? this.spritesGroups.items[index] : returnValueOnFail; } /** * Alias for {@link CB_GraphicSpritesScene#getGraphicSpritesIndexById}. * @function CB_GraphicSpritesScene#getIndexById * @see {@link CB_GraphicSpritesScene#getGraphicSpritesIndexById} */ /** * Gets the index (the position in the {@link CB_GraphicSpritesScene#spritesGroups.items} array) of a desired {@link CB_GraphicSprites} object by its identifier. * @function * @param {string|*} [id=undefined] - The identifier of the {@link CB_GraphicSprites} object whose index we want to get. * @returns {integer} Returns the index (the position in the {@link CB_GraphicSpritesScene#spritesGroups.items} array) of the desired {@link CB_GraphicSprites} object or -1 if not found. * @todo Optimize it (perhaps using a cache matching the IDs with their position, maybe using the \"position\" or \"positionByZIndex\" properties). */ CB_GraphicSpritesScene.prototype.getGraphicSpritesIndexById = CB_GraphicSpritesScene.prototype.getIndexById = function(id) { if (this.spritesGroups &amp;&amp; this.spritesGroups.items) { var spritesGroupsLength = this.spritesGroups.items.length; for (var x = 0; x &lt; spritesGroupsLength; x++) { if (this.spritesGroups.items[x].id === id) { return x; } } } return -1; } /** * Alias for {@link CB_GraphicSpritesScene#executeFunctionAll}. * @function CB_GraphicSpritesScene#executeAll * @see {@link CB_GraphicSpritesScene#executeFunctionAll} */ /** * Alias for {@link CB_GraphicSpritesScene#executeFunctionAll}. * @function CB_GraphicSpritesScene#forEach * @see {@link CB_GraphicSpritesScene#executeFunctionAll} */ /** * Alias for {@link CB_GraphicSpritesScene#executeFunctionAll}. * @function CB_GraphicSpritesScene#forEachGraphicSprites * @see {@link CB_GraphicSpritesScene#executeFunctionAll} */ /** * Performs a desired action, using the provided function, on all the existing {@link CB_GraphicSprites} objects or on the desired ones (if provided). Calls the {@link CB_Arrays.executeFunctionAll} function internally and returns its returning value. * @function * @param {CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} functionEach - Function that will be called for each {@link CB_GraphicSprites} object. As the first parameter it receives the {@link CB_GraphicSprites} object of the \"graphicSpritesObjects\" being looped, as the second parameter the position of this {@link CB_GraphicSprites} object in the \"graphicSpritesObjects\" array provided (or, if not provided, in the array returned by the {@link CB_GraphicSpritesScene#getGraphicSpritesAll} method), the third parameter is the array being looped and the fourth parameter will be the \"delayBetweenEach\" being used, being \"this\" the {@link CB_GraphicSprites} object itself. * @param {boolean} [orderedByZIndex=false] - If set to true, it will loop the {@link CB_GraphicSprites} sorted by their z-index (ascending order). * @param {number|CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK} [delayBetweenEach=0] - If a value greater than zero is used, it will be used as the delay desired between each call to the \"functionEach\" function (calling them using the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function internally). If not provided or the value is 0 (zero) or lower, each call to the \"functionEach\" function will be performed immediately one after the other. If a function is provided, it will be called with the same parameters as the \"functionEach\" function and its returning value will be used as the delay (executed every loop for each {@link CB_GraphicSprites} object). * @param {array} [graphicSpritesObjects={@link CB_GraphicSpritesScene#getGraphicSpritesAll}()] - A numeric array containing the {@link CB_GraphicSprites} objects that we want to loop. It should contain only {@link CB_GraphicSprites} objects which are already in the current {@link CB_GraphicSpritesScene} object. If not provided, it will use all the {@link CB_GraphicSprites} objects contained in the {@link CB_GraphicSpritesScene} object. * @param {boolean} [returnSetTimeoutsArray=false] - Defines whether we want the method to return an integer or a numeric array with information of each [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} call. Returning an array with information of each [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} call is only useful when the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function is called internally, which happens when the \"delayBetweenEach\" parameter is greater than 0 (zero). * @param {boolean} [delayBetweenEachAffectsFirst=false] - If set to true, the desired delay (if any) will also affect the first call to the \"functionEach\" function. * @param {CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK} [functionFinish] - Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. * @returns {integer|array} If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the {@link CB_GraphicSprites} objects given in the \"graphicSpritesObjects\" parameter). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a {@link CB_Arrays.executeFunctionAll_OBJECT} object for each {@link CB_GraphicSprites} given. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function. * @todo Think about only allowing {@link CB_GraphicSprites} objects (in the \"graphicSpritesObjects\" parameter) which are already in the {@link CB_GraphicSpritesScene} (identify them by their ID), to avoid problems. */ CB_GraphicSpritesScene.prototype.executeFunctionAll = CB_GraphicSpritesScene.prototype.executeAll = CB_GraphicSpritesScene.prototype.forEachGraphicSprites = CB_GraphicSpritesScene.prototype.forEach = function(functionEach, orderedByZIndex, delayBetweenEach, graphicSpritesObjects, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, functionFinish) { return CB_Arrays.executeFunctionAll(CB_isArray(graphicSpritesObjects) ? graphicSpritesObjects : this.getGraphicSpritesAll(orderedByZIndex, []), functionEach, delayBetweenEach, returnSetTimeoutsArray, delayBetweenEachAffectsFirst, functionFinish); } /** * Sets the desired value of a given property name to the {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} object as well to its {@link CB_GraphicSprites} objects and their children (their {@link CB_GraphicSprites.SPRITES_OBJECT} object, including their {@link CB_GraphicSprites.SPRITE_OBJECT} and their {@link CB_GraphicSprites.SUBSPRITE_OBJECT} objects). Calls the {@link CB_GraphicSprites#setPropertyCascade} method internally. * @function * @param {number} propertyName - The name of the property we want to affect. Also used as the \"propertyName\" parameter when calling the {@link CB_GraphicSprites#setPropertyCascade} method internally. * @param {*} [value=undefined] - The value desired for the given property. Also used as the \"value\" parameter when calling the {@link CB_GraphicSprites#setPropertyCascade} method internally. * @param {boolean} [onlyCurrent=false] - If set to true, it will only affect the current sprite and its sub-sprites of each {@link CB_GraphicSprites} object (and also the {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} object and the {@link CB_GraphicSprites.SPRITES_OBJECT} object of each {@link CB_GraphicSprites} object). Used as the \"propertyName\" parameter when calling the {@link CB_GraphicSprites#setPropertyCascade} method internally. * @returns {integer} Returns the number of elements affected (counting the {@link CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} object and the {@link CB_GraphicSprites.SPRITES_OBJECT} objects). */ CB_GraphicSpritesScene.prototype.setPropertyCascade = function(propertyName, value, onlyCurrent) { if (!propertyName) { return; } this.spritesGroups[propertyName] = value; var affected = 1; this.forEachGraphicSprites(function() { affected += this.setPropertyCascade(propertyName, value, onlyCurrent); }); return affected; } /** * Gets a new copy of this object with the same attributes (all sub-objects will be a copy, they will not the same reference). * @function * @param {boolean} [avoidCopyingPointers=false] - If set to true, it will not copy the {@link CB_GraphicSprites#pointer} property of each {@link CB_GraphicSprites} object. * @param {boolean} [avoidCopyingTimes=false] - If set to true, it will not copy neither the {@link CB_GraphicSprites#time} property of each {@link CB_GraphicSprites} object nor the \"time\" property of each of their sprites ({@link CB_GraphicSprites.SPRITE_OBJECT} objects). * @param {boolean} [clearReferences=false] - If set to true, it will not copy neither the \"container\" nor the \"parent\" nor the \"data.that\" nor the \"data.getThis\" properties of any element. Useful to be able to stringify the object preventing the \"TypeError: cyclic object value\" error. When set to true, calls the {@link CB_GraphicSprites.clearReferences} function internally. If set to true and the \"filterProperties\" parameter is also set to true, the {@link CB_GraphicSprites.filterProperties} will always be called before calling the {@link CB_GraphicSprites.clearReferences} function. * @param {boolean} [filterProperties=false] - If set to true, it will call the {@link CB_GraphicSprites.filterProperties} function internally to filter the properties that we do not want to keep (using the given \"propertiesToKeepObject\" as the parameter to call it). When set to true, calls the {@link CB_GraphicSprites.filterProperties} function internally. If set to true and the \"clearReferences\" parameter is also set to true, the {@link CB_GraphicSprites.filterProperties} will always be called before calling the {@link CB_GraphicSprites.clearReferences} function. * @param {CB_GraphicSprites.filterProperties_propertiesToKeepObject_TYPE} [propertiesToKeepObject=CB_GraphicSprites.filterProperties_DEFAULT_PROPERTIES] - The object with the properties that we want to keep. Only used when the \"filterProperties\" parameter is set to true, as the \"propertiesToKeepObject\" when calling the {@link CB_GraphicSprites.filterProperties} function internally. * @returns {CB_GraphicSpritesScene} Returns a copy of this object with the same attributes (all sub-objects will be a copy, not the same reference). */ CB_GraphicSpritesScene.prototype.getCopy = function(avoidCopyingPointers, avoidCopyingTimes, clearReferences, filterProperties, propertiesToKeepObject) { var spritesGroupsCopy = CB_copyObject(this.spritesGroups); var newCopy = new CB_GraphicSpritesScene(spritesGroupsCopy, false); CB_GraphicSprites._copyNeededProperties(newCopy, this) //Copies the needed properties from the original element. CB_GraphicSprites._copyNeededProperties(newCopy.spritesGroups, this.spritesGroups) //Copies the needed properties from the original element. this.forEach ( function(CB_GraphicSpritesObject, index) { CB_GraphicSprites._copyNeededProperties(newCopy.get(index), CB_GraphicSpritesObject) //Copies the needed properties from the original element. CB_GraphicSprites._copyNeededProperties(newCopy.get(index).spritesGroup, CB_GraphicSpritesObject.spritesGroup) //Copies the needed properties from the original element. //If desired, sets the same pointers of each CB_GraphicSprites object: if (!avoidCopyingPointers) { newCopy.get(index).pointer = this.pointer; newCopy.get(index).pointerPrevious = this.pointerPrevious; } if (!avoidCopyingTimes) { newCopy.get(index).time = this.time; } newCopy.get(index).time = this.time; this.forEach ( function(sprite, spriteIndex) { if (!avoidCopyingTimes) { newCopy.get(index).get(spriteIndex).time = this.time; } CB_GraphicSprites._copyNeededProperties(newCopy.get(index).get(spriteIndex), sprite) //Copies the needed properties from the original element. sprite.forEach ( function(subSprite, subSpriteIndex) { CB_GraphicSprites._copyNeededProperties(newCopy.get(index).get(spriteIndex).get(subSpriteIndex), subSprite) //Copies the needed properties from the original element. //If desired, sets the same times: if (!avoidCopyingTimes) { sprite.get(subSpriteIndex).time = this.time; } } ); } ); } ); //Sets the same parent: newCopy.parent = this.parent; //If we want to, filters the properties keeping just the desired ones: if (filterProperties) { newCopy = CB_GraphicSprites.filterProperties(newCopy, propertiesToKeepObject); } //If we want to, clears the references: if (clearReferences) { CB_GraphicSprites.clearReferences(newCopy); } return newCopy; } × Search results Close "},"CrossBase_input_CB_Keyboard.js.html":{"id":"CrossBase_input_CB_Keyboard.js.html","title":"Source: CrossBase/input/CB_Keyboard.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/input/CB_Keyboard.js /** * @file Keyboard management (and other devices which also fire [keyboard events]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent} as TV remote controls, game consoles' gamepads, etc.). Contains the {@link CB_Keyboard} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage the keyboard and other input devices that generate key codes. It will return itself if it is tried to be instantiated. * @namespace */ var CB_Keyboard = function() { return CB_Keyboard; }; { //CB_Keyboard.onKeyPressFunction; //Function that is executed when a key is pressed (onKeyPress event). //CB_Keyboard.onKeyDownFunction; //Function that is executed when a key is down (onKeyDown event). //CB_Keyboard.onKeyUpFunction; //Function that is executed when a key is released (onKeyUp event). //CB_Keyboard.firstEvent = \"\"; //Defines wheter the first event captured is onKeyDown or onKeyPress (compatibility reasons). //CB_Keyboard.onKeyDownOrPressFunction; //Function that is executed when either a key is down os pressed (onKeyDown or onKeyPress event) /** * Object that will store the status for each key detected, using the key code as index and a boolean as their value (true when down or false when released). * @var * @readonly * @type {Object} * @default */ CB_Keyboard.keysDown = {}; /** * Array with the codes of the keys pressed recently (it will be cleared after the chosen milliseconds set with the {@link CB_Keyboard.setKeysPressedExpiration} function). * @var * @readonly * @type {array} * @default */ CB_Keyboard.keysPressed = []; CB_Keyboard._keysPressedExpiration = 500; //Milliseconds before keys pressed array expires. CB_Keyboard._keysPressedExpirationTimeout = null; //It will store the timeout that clears the keys pressed array. /** * Array with the codes of the string typed recently (it will be cleared after the chosen milliseconds set with the {@link CB_Keyboard.setTypedStringExpiration} function). * @var * @readonly * @type {array} * @default */ CB_Keyboard.typedStringCodes = []; /** * Stores the string typed recently (it will be cleared after the chosen milliseconds set with the {@link CB_Keyboard.setTypedStringExpiration} function). * @var * @readonly * @type {string} * @default */ CB_Keyboard.typedString = \"\"; //Stores the string typed (it will be cleared after some milliseconds). CB_Keyboard._typedStringExpiration = 500; //Milliseconds before typed string expires. CB_Keyboard._typedStringExpirationTimeout = null; //It will store the timeout that clears the typed string. CB_Keyboard.initialized = false; //It will tells whether the object has been initialized or not. /** Property that keeps extended key codes for different systems and platforms. * @namespace CB_Keyboard.extended */ CB_Keyboard.extended = {}; /** * Smart TV Alliance and virtual keyboard key codes. * @memberof CB_Keyboard.extended * @name VK * @constant * @type {Object} * @default * @todo Consider adding more (found in {@link https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx} and {@link http://nehe.gamedev.net/article/msdn_virtualkey_codes/15009/}) * @property {number} ENTER - ENTER key. * @property {number} PAUSE - PAUSE key. * @property {number} PAGE_UP - PAGE UP key. * @property {number} PAGE_DOWN - PAGE DOWN key. * @property {number} LEFT - LEFT key. * @property {number} UP - UP key. * @property {number} RIGHT - RIGHT key. * @property {number} DOWN - DOWN key. * @property {number} _0 - 0 (zero) key. * @property {number} _1 - 1 key. * @property {number} _2 - 2 key. * @property {number} _3 - 3 key. * @property {number} _4 - 4 key. * @property {number} _5 - 5 key. * @property {number} _6 - 6 key. * @property {number} _7 - 7 key. * @property {number} _8 - 8 key. * @property {number} _9 - 9 key. * @property {number} 0 - Alias for {@link CB_Keyboard.extended.VK._0}. * @property {number} 1 - Alias for {@link CB_Keyboard.extended.VK._1}. * @property {number} 2 - Alias for {@link CB_Keyboard.extended.VK._2}. * @property {number} 3 - Alias for {@link CB_Keyboard.extended.VK._3}. * @property {number} 4 - Alias for {@link CB_Keyboard.extended.VK._4}. * @property {number} 5 - Alias for {@link CB_Keyboard.extended.VK._5}. * @property {number} 6 - Alias for {@link CB_Keyboard.extended.VK._6}. * @property {number} 7 - Alias for {@link CB_Keyboard.extended.VK._7}. * @property {number} 8 - Alias for {@link CB_Keyboard.extended.VK._8}. * @property {number} 9 - Alias for {@link CB_Keyboard.extended.VK._9}. * @property {number} REWIND - RW (REWIND) key. * @property {number} STOP - STOP key. * @property {number} PLAY - PLAY key. * @property {number} FAST_FWD - FF (FAST FORWARD) key. * @property {number} BACK - BACK key. * @property {number} PREV - PREVIOUS key. * @property {number} NEXT - NEXT key. * @property {number} INFO - INFORMATION key. * @property {number} RED - RED key. * @property {number} GREEN - GREEN key. * @property {number} YELLOW - YELLOW key. * @property {number} BLUE - BLUE key. * @property {number} SPACE - SPACE key. * @property {number} BACK_SPACE - BACK SPACE key. * @property {number} A - A key. * @property {number} B - B key. * @property {number} C - C key. * @property {number} D - D key. * @property {number} E - E key. * @property {number} F - F key. * @property {number} G - G key. * @property {number} H - H key. * @property {number} I - I key. * @property {number} J - J key. * @property {number} K - K key. * @property {number} L - L key. * @property {number} M - M key. * @property {number} N - N key. * @property {number} O - O key. * @property {number} P - P key. * @property {number} Q - Q key. * @property {number} R - R key. * @property {number} S - S key. * @property {number} T - T key. * @property {number} U - U key. * @property {number} V - V key. * @property {number} W - W key. * @property {number} X - X key. * @property {number} Y - Y key. * @property {number} Z - Z key. * @property {number} VOLUME_UP - VOLUME UP key. * @property {number} VOLUME_DOWN - VOLUME DOWN key. * @property {number} MUTE - MUTE key. * @property {number} PLAY_PAUSE - PLAY/PAUSE key. * @property {number} HELP - HELP key. * @property {number} SUBTITLE - SUBTITLE key. * @property {number} SEARCH - SEARCH key. * @property {number} AUDIODESCRIPTION - AUDIODESCRIPTION key. * @property {number} HD - HD (High Definition) key. */ CB_Keyboard.extended.VK = { //* Source: http://smarttv-alliance.org/Markets/Developers.aspx ENTER: window.VK_ENTER || 13, PAUSE: window.VK_PAUSE || 19, PAGE_UP: window.VK_PAGE_UP || 33, PAGE_DOWN: window.VK_PAGE_DOWN || 34, LEFT: window.VK_LEFT || 37, UP: window.VK_UP || 38, RIGHT: window.VK_RIGHT || 39, DOWN: window.VK_DOWN || 40, _0: window.VK_0 || 48, _1: window.VK_1 || 49, _2: window.VK_2 || 50, _3: window.VK_3 || 51, _4: window.VK_4 || 52, _5: window.VK_5 || 53, _6: window.VK_6 || 54, _7: window.VK_7 || 55, _8: window.VK_8 || 56, _9: window.VK_9 || 57, REWIND: window.VK_REWIND || 412, STOP: window.VK_STOP || 413, PLAY: window.VK_PLAY || 415, FAST_FWD: window.VK_FAST_FWD || 417, BACK: window.VK_BACK || 461, PREV: window.VK_PREV || 424, NEXT: window.VK_NEXT || 425, INFO: window.VK_INFO || 457, RED: window.VK_RED || 403, GREEN: window.VK_GREEN || 404, YELLOW: window.VK_YELLOW || 405, BLUE: window.VK_BLUE || 406, //More virtual keyboard keys: //* Source: https://fmtvp.github.io/tal/jsdoc/symbols/src/antie_static_script_events_keyevent.js.html SPACE: window.VK_SPACE || 32, BACK_SPACE: window.VK_BACK_SPACE || 8, A: window.VK_A || 65, B: window.VK_B || 66, C: window.VK_C || 67, D: window.VK_D || 68, E: window.VK_E || 69, F: window.VK_F || 70, G: window.VK_G || 71, H: window.VK_H || 72, I: window.VK_I || 73, J: window.VK_J || 74, K: window.VK_K || 75, L: window.VK_L || 76, M: window.VK_M || 77, N: window.VK_N || 78, O: window.VK_O || 79, P: window.VK_P || 80, Q: window.VK_Q || 81, R: window.VK_R || 82, S: window.VK_S || 83, T: window.VK_T || 84, U: window.VK_U || 85, V: window.VK_V || 86, W: window.VK_W || 87, X: window.VK_X || 88, Y: window.VK_Y || 89, Z: window.VK_Z || 90, VOLUME_UP: window.VK_VOLUME_UP || 447, VOLUME_DOWN: window.VK_VOLUME_DOWN || 448, MUTE: window.VK_MUTE || 449, PLAY_PAUSE: window.VK_PLAY_PAUSE || 402, HELP: window.VK_HELP || 156, SUBTITLE: window.VK_SUBTITLE || 460, SEARCH: window.VK_SEARCH || 112, //112 is the same code as the F1 key. AUDIODESCRIPTION: window.VK_AUDIODESCRIPTION || 113, //113 is the same code as the F2 key. HD: window.VK_HD || 114 //114 is the same code as the F3 key. }; CB_Keyboard.extended.VK[0] = CB_Keyboard.extended.VK._0; CB_Keyboard.extended.VK[1] = CB_Keyboard.extended.VK._1; CB_Keyboard.extended.VK[2] = CB_Keyboard.extended.VK._2; CB_Keyboard.extended.VK[3] = CB_Keyboard.extended.VK._3; CB_Keyboard.extended.VK[4] = CB_Keyboard.extended.VK._4; CB_Keyboard.extended.VK[5] = CB_Keyboard.extended.VK._5; CB_Keyboard.extended.VK[6] = CB_Keyboard.extended.VK._6; CB_Keyboard.extended.VK[7] = CB_Keyboard.extended.VK._7; CB_Keyboard.extended.VK[8] = CB_Keyboard.extended.VK._8; CB_Keyboard.extended.VK[9] = CB_Keyboard.extended.VK._9; CB_Keyboard.extended.VK._allowDuplicateKeyAliases = CB_Configuration[CB_BASE_NAME].CB_Keyboard_extended_VK_allowDuplicateKeyAliases; /** * Samsung Tizen TV key codes. * @memberof CB_Keyboard.extended * @name SAMSUNG_TIZEN_TV * @constant * @type {Object} * @default * @property {number} UP - UP button. * @property {number} DOWN - DOWN button. * @property {number} LEFT - LEFT button. * @property {number} RIGHT - RIGHT button. * @property {number} ENTER - ENTER button. * @property {number} MEDIA_PLAY_PAUSE - PLAY/PAUSE MEDIA button. * @property {number} MEDIA_REWIND - RW (REWIND) MEDIA button. * @property {number} MEDIA_FORWARD - FW (FORWARD) MEDIA button. * @property {number} MEDIA_PLAY - PLAY MEDIA button. * @property {number} MEDIA_PAUSE - PAUSE MEDIA button. * @property {number} MEDIA_STOP - STOP MEDIA button. * @property {number} RETURN - RETURN button. * @property {number} MEDIA_RECORD - RECORD MEDIA button. * @property {number} MEDIA_TRACK_PREVIOUS - PREVIOUS TRACK MEDIA button. * @property {number} MEDIA_TRACK_NEXT - NEXT TRACK MEDIA button. * @property {number} VOLUME_UP - VOLUME UP button. * @property {number} VOLUME_DOWN - VOLUME DOWN button. * @property {number} MUTE - MUTE button. * @property {number} _0 - 0 (zero) button. * @property {number} _1 - 1 button. * @property {number} _2 - 2 button. * @property {number} _3 - 3 button. * @property {number} _4 - 4 button. * @property {number} _5 - 5 button. * @property {number} _6 - 6 button. * @property {number} _7 - 7 button. * @property {number} _8 - 8 button. * @property {number} _9 - 9 button. * @property {number} 0 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TIZEN_TV._0}. * @property {number} 1 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TIZEN_TV._1}. * @property {number} 2 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TIZEN_TV._2}. * @property {number} 3 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TIZEN_TV._3}. * @property {number} 4 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TIZEN_TV._4}. * @property {number} 5 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TIZEN_TV._5}. * @property {number} 6 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TIZEN_TV._6}. * @property {number} 7 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TIZEN_TV._7}. * @property {number} 8 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TIZEN_TV._8}. * @property {number} 9 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TIZEN_TV._9}. * @property {number} RED - RED button. * @property {number} GREEN - GREEN button. * @property {number} YELLOW - YELLOW button. * @property {number} BLUE - BLUE button. * @property {number} INFO - INFORMATION button. * @property {number} EXIT - EXIT button. * @property {number} MINUS - MINUS button. * @property {number} CAPTION - CAPTION button. * @property {number} CH_UP - CHANNEL UP button. * @property {number} CH_DOWN - CHANNEL DOWN button. * @property {number} CH_PREVIOUS - PREVIOUS CHANNEL button. * @property {number} CH_LIST - CHANNEL LIST button. * @property {number} E_MANUAL - E-MANUAL button. * @property {number} SEARCH - SEARCH button. * @property {number} _3D - 3D button. * @property {number} 3D - Alias for {@link CB_Keyboard.extended.SAMSUNG_TIZEN_TV._3D}. * @property {number} GUIDE - GUIDE button. * @property {number} SOURCE - SOURCE button. * @property {number} PICTURE_SIZE - PICTURE SIZE button. * @property {number} EXTRA - EXTRA button. * @property {number} SOCCER - SOCCER button. * @property {number} MTS - MTS (Multichannel Television Sound) button. * @property {number} TELETEXT - TELETEXT button. * @property {number} MENU - MENU button. * @property {number} TOOLS - TOOLS button. */ CB_Keyboard.extended.SAMSUNG_TIZEN_TV = { UP: 38, DOWN: 40, LEFT: 37, RIGHT: 39, ENTER: 13, MEDIA_PLAY_PAUSE: 10252, MEDIA_REWIND: 412, MEDIA_FORWARD: 417, MEDIA_PLAY: 415, MEDIA_PAUSE: 19, MEDIA_STOP: 413, RETURN: 10009, MEDIA_RECORD: 416, MEDIA_TRACK_PREVIOUS: 10232, MEDIA_TRACK_NEXT: 10233, VOLUME_UP: 447, VOLUME_DOWN: 448, MUTE: 449, _0: 48, _1: 49, _2: 50, _3: 51, _4: 52, _5: 53, _6: 54, _7: 55, _8: 56, _9: 57, RED: 403, GREEN: 404, YELLOW: 405, BLUE: 406, INFO: 457, EXIT: 10182, MINUS: 189, CAPTION: 10221, CH_UP: 427, CH_DOWN: 428, CH_PREVIOUS: 10190, CH_LIST: 10073, E_MANUAL: 10146, SEARCH: 10225, _3D: 10199, GUIDE: 458, SOURCE: 10072, PICTURE_SIZE: 10140, EXTRA: 10253, SOCCER: 10228, MTS: 10195, TELETEXT: 10200, MENU: 457, TOOLS: 10135 }; CB_Keyboard.extended.SAMSUNG_TIZEN_TV[0] = CB_Keyboard.extended.SAMSUNG_TIZEN_TV._0; CB_Keyboard.extended.SAMSUNG_TIZEN_TV[1] = CB_Keyboard.extended.SAMSUNG_TIZEN_TV._1; CB_Keyboard.extended.SAMSUNG_TIZEN_TV[2] = CB_Keyboard.extended.SAMSUNG_TIZEN_TV._2; CB_Keyboard.extended.SAMSUNG_TIZEN_TV[3] = CB_Keyboard.extended.SAMSUNG_TIZEN_TV._3; CB_Keyboard.extended.SAMSUNG_TIZEN_TV[4] = CB_Keyboard.extended.SAMSUNG_TIZEN_TV._4; CB_Keyboard.extended.SAMSUNG_TIZEN_TV[5] = CB_Keyboard.extended.SAMSUNG_TIZEN_TV._5; CB_Keyboard.extended.SAMSUNG_TIZEN_TV[6] = CB_Keyboard.extended.SAMSUNG_TIZEN_TV._6; CB_Keyboard.extended.SAMSUNG_TIZEN_TV[7] = CB_Keyboard.extended.SAMSUNG_TIZEN_TV._7; CB_Keyboard.extended.SAMSUNG_TIZEN_TV[8] = CB_Keyboard.extended.SAMSUNG_TIZEN_TV._8; CB_Keyboard.extended.SAMSUNG_TIZEN_TV[9] = CB_Keyboard.extended.SAMSUNG_TIZEN_TV._9; CB_Keyboard.extended.SAMSUNG_TIZEN_TV[\"3D\"] = CB_Keyboard.extended.SAMSUNG_TIZEN_TV._3D; try { var tvKey = new Common.API.TVKeyValue(); } catch(E) { try { tvKey = sf.key; } catch(E) { tvKey = {}; } } /** * Samsung TV key codes. * @memberof CB_Keyboard.extended * @name SAMSUNG_TV * @constant * @type {Object} * @default * @property {number} TOOLS - TOOLS button. * @property {number} EMODE - EMODE button. * @property {number} DMA - DMA (Digital Media Adapter) button. * @property {number} SOURCE - SOURCE button. * @property {number} CHDOWN - CHANNEL DOWN button. * @property {number} CHUP - CHANNEL UP button. * @property {number} PANEL_CH_UP - CHANNEL UP PANEL button #1. * @property {number} PANEL_CH_DOWN - CHANNEL DOWN PANEL button #1. * @property {number} PANEL_CHUP - CHANNEL UP PANEL button #2. * @property {number} PANEL_CHDOWN - CHANNEL DOWN PANEL button #2. * @property {number} PIP_CHUP - CHANNEL UP PIP (Picture In Picture) button. * @property {number} PIP_CHDOWN - CHANNEL DOWN PIP (Picture In Picture) button. * @property {number} PRECH - PRE-CHANNEL (PREVIOUS CHANNEL) button. * @property {number} FAVCH - FAVOURITE CHANNEL button. * @property {number} CHLIST - CHANNEL LIST button. * @property {number} TTX_MIX - TELETEXT button. * @property {number} GUIDE - GUIDE button. * @property {number} ASPECT - ASPECT button. * @property {number} DOLBY_SRR - DOLBY SRR (SuRroundRight) button. * @property {number} MTS - MTS (Multichannel Television Sound) button. * @property {number} WHEELDOWN - WHEEL DOWN #1. * @property {number} WHEEL_DOWN - WHEEL DOWN #2. * @property {number} WHEELUP - WHEEL UP #1. * @property {number} WHEEL_UP - WHEEL UP #2. * @property {number} WHEELLEFT - WHEEL LEFT #1. * @property {number} WHEEL_LEFT - WHEEL LEFT #2. * @property {number} WHEELRIGHT - WHEEL RIGHT #1. * @property {number} WHEEL_RIGHT - WHEEL RIGHT #2. * @property {number} SMART - SMART TV button. * @property {number} EXIT - EXIT button. * @property {number} POWER - POWER button. * @property {number} PANEL_POWER - POWER PANEL button. * @property {number} POWEROFF - POWER OFF button. * @property {number} POWERON - POWER ON button. * @property {number} CONTENT - CONTENT button. * @property {number} WLINK - WLINK (Wiselink) button #1. * @property {number} W_LINK - WLINK (Wiselink) button #2. * @property {number} EMPTY - EMPTY button. * @property {number} CC - CC (Closed Captioning) button. * @property {number} REC - REC button. * @property {number} VOLUP - VOLUME UP button #1. * @property {number} VOL_UP - VOLUME UP button #2. * @property {number} VOLDOWN - VOLUME DOWN button #1. * @property {number} VOL_DOWN - VOLUME DOWN button #2. * @property {number} PANEL_VOLUP - PANEL VOLUME UP button #1. * @property {number} PANEL_VOL_UP - PANEL VOLUME UP button #2. * @property {number} PANEL_VOLDOW - PANEL VOLUME DOWN button #1. * @property {number} PANEL_VOLDOWN - PANEL VOLUME DOWN button #2. * @property {number} PANEL_VOL_DOWN - PANEL VOLUME DOWN button #3. * @property {number} MUTE - MUTE button. * @property {number} INFO - INFORMATION button. * @property {number} INFOLINK - INFOLINK button. * @property {number} MENU - MENU button. * @property {number} SUBTITLE - SUBTITLE button #1. * @property {number} SUB_TITLE - SUBTITLE button #2. * @property {number} PANEL_SOURCE - SOURCE PANEL button. * @property {number} _0 - 0 (zero) button. * @property {number} _1 - 1 button. * @property {number} _2 - 2 button. * @property {number} _3 - 3 button. * @property {number} _4 - 4 button. * @property {number} _5 - 5 button. * @property {number} _6 - 6 button. * @property {number} _7 - 7 button. * @property {number} _8 - 8 button. * @property {number} _9 - 9 button. * @property {number} _10 - 10 button. * @property {number} _11 - 11 button. * @property {number} _12 - 12 button. * @property {number} 0 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._0}. * @property {number} 1 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._1}. * @property {number} 2 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._2}. * @property {number} 3 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._3}. * @property {number} 4 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._4}. * @property {number} 5 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._5}. * @property {number} 6 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._6}. * @property {number} 7 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._7}. * @property {number} 8 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._8}. * @property {number} 9 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._9}. * @property {number} 10 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._10}. * @property {number} 11 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._11}. * @property {number} 12 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._12}. * @property {number} RED - RED button. * @property {number} GREEN - GREEN button. * @property {number} YELLOW - YELLOW button. * @property {number} BLUE - BLUE button. * @property {number} CYAN - CYAN button. * @property {number} RW - RW (REWIND) button #1. * @property {number} REWIND - RW (REWIND) button #2. * @property {number} REWIND_ - RW (REWIND) button #3. * @property {number} FF - FF (FAST FORWARD) button #1. * @property {number} FF_ - FF (FAST FORWARD) button #2. * @property {number} PAUSE - PAUSE button. * @property {number} PLAY - PLAY button. * @property {number} STOP - STOP button. * @property {number} SEARCH - SEARCH button. * @property {number} UP - UP button. * @property {number} DOWN - DOWN button. * @property {number} LEFT - LEFT button. * @property {number} RIGHT - RIGHT button. * @property {number} CH_UP - CHANNEL UP button. * @property {number} CH_DOWN - CHANNEL DOWN button. * @property {number} DISC_MENU - DISC MENU button. * @property {number} _3D - 3D button. * @property {number} 3D - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._3D}. * @property {number} PIP_ONOFF - PIP (Picture In Picture) ON/OFF button. * @property {number} AD - AD (Audio Description) button. * @property {number} PMODE - PICTURE MODE button. * @property {number} SMODE - SOUND MODE button. * @property {number} SLEEP - SLEEP button. * @property {number} D_AUDIO - DIGITAL AUDIO button. * @property {number} D_FRONT_PLAY - DIGITAL FRONT PLAY button. * @property {number} D_VIEW_MODE - DIGITAL VIEW MODE button. * @property {number} STEP - STEP button. * @property {number} CALLER_ID - CALLED ID button. * @property {number} ANTENNA - ANTENNA button. * @property {number} ZOOM_MOVE - MOVE ZOOM button. * @property {number} ZOOM1 - ZOOM 1 button. * @property {number} ZOOM2 - ZOOM 2 button. * @property {number} ZOOM_IN - ZOOM IN button. * @property {number} ZOOM_OUT - ZOOM OUT button. * @property {number} RETURN - RETURN button. * @property {number} PANEL_RETURN - RETURN PANEL button. * @property {number} ENTER - ENTER button. * @property {number} PANEL_ENTER - ENTER PANEL button. * @property {number} PANEL_MENU - MENU PANEL button. * @property {number} ADDDEL - ADD/DEL button. * @property {number} PIP_SWAP - PIP (Picture In Picture) SWAP button. * @property {number} PLUS100 - SAMSUNG AUTO MOTION PLUS 100 HZ button. * @property {number} CAPTION - CAPTION button. * @property {number} PICTURE_SIZE - PICTURE SIZE button. * @property {number} PIP_SIZE - PIP (Picture In Picture) SIZE button. * @property {number} MAGIC_CHANNEL - MAGIC CHANNEL button. * @property {number} PIP_SCAN - PIP (Picture In Picture) SCAN button. * @property {number} DEVICE_CONNECT - DEVICE CONNECT button. * @property {number} HELP - HELP button. * @property {number} CONVERGENCE - CONVERGENCE button. * @property {number} AUTO_PROGRAM - AUTO PROGRAM button. * @property {number} FACTORY - FACTORY button. * @property {number} _3SPEED - 3SPEED button. * @property {number} 3SPEED - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._3SPEED}. * @property {number} RSURF - R.SURF button. * @property {number} TOPMENU - TOP MENU button. * @property {number} GAME - GAME button. * @property {number} QUICK_REPLAY - QUICK REPLAY button. * @property {number} STILL_PICTURE - STILL PICTURE button. * @property {number} DTV - DTV (Digital Television) button. * @property {number} INSTANT_REPLAY - INSTANT REPLAY button. * @property {number} LINK - LINK button. * @property {number} ANGLE - ANGLE button. * @property {number} RESERVED1 - RESERVED1 button. * @property {number} RESERVED5 - RESERVED5 button. * @property {number} PROGRAM - PROGRAM button. * @property {number} BOOKMARK - BOOKMARK button. * @property {number} PRINT - PRINT button. * @property {number} CLEAR - CLEAR button. * @property {number} VCHIP - V-CHIP button. * @property {number} REPEAT - REPEAT button. * @property {number} DOOR - DOOR button. * @property {number} OPEN - OPEN button. * @property {number} TURBO - TURBO button. * @property {number} DVR_MENU - DVR (Digital Video Recorder) MENU button. * @property {number} TTX_SUBFACE - Teletext Subface button. * @property {number} CH_LIST - CHANNEL LIST button. * @property {number} DNIe - DNIe (Digital Natural Image Engine) button. * @property {number} DNSe - DNSe (Digital Natural Sound Engine) button. * @property {number} SRS - SRS (Sound Retrieval System) button. * @property {number} CONVERT_AUDIO_MAINSUB - CONVERT AUDIO MAIN/SUB button. * @property {number} MDC - MDC button. * @property {number} SEFFECT - SOUND EFFECT button. * @property {number} DVR - DVR (Digital Video Recorder) button. * @property {number} DTV_SIGNAL - DTV (Digital Television) SIGNAL button. * @property {number} LIVE - LIVE button. * @property {number} PERPECT_FOCUS - PERPECT FOCUS button. * @property {number} HOME - HOME button. * @property {number} ESAVING - ENERGY SAVING button. * @property {number} CONTENTS - CONTENTS button. * @property {number} SCALE - SCALE button. * @property {number} CLOCK_DISPLAY - CLOCK DISPLAY button. * @property {number} SETUP_CLOCK_TIMER - SETUP CLOCK TIMER button. * @property {number} MAGIC_BRIGHT - MAGIC BRIGHT button. * @property {number} FM_RADIO - FM RADIO button. * @property {number} VCR_MODE - VCR MODE button. * @property {number} CATV_MODE - CATV (Community Antenna Television) MODE button. * @property {number} DSS_MODE - DSS MODE button. * @property {number} DVD_MODE - DVD MODE button. * @property {number} STB_MODE - STB (Set-Top Box) MODE button. * @property {number} PCMODE - PC MODE button. * @property {number} TV_MODE - TV MODE button. * @property {number} TV - TV button. * @property {number} AV1 - AV #1 button. * @property {number} AV2 - AV #2 button. * @property {number} AV3 - AV #3 button. * @property {number} SVIDEO1 - S-VIDEO (Separated-Video) #1 button. * @property {number} SVIDEO2 - S-VIDEO (Separated-Video) #2 button. * @property {number} SVIDEO3 - S-VIDEO (Separated-Video) #3 button. * @property {number} COMPONENT1 - COMPONENT #1 button. * @property {number} COMPONENT2 - COMPONENT #2 button. * @property {number} DVI - DVI (Digital Visual Interface) button. * @property {number} HDMI - HDMI button. * @property {number} HDMI1 - HDMI #1 button. * @property {number} HDMI2 - HDMI #2 button. * @property {number} HDMI3 - HDMI #3 button. * @property {number} HDMI4 - HDMI #4 button. * @property {number} DTV_LINK - DTVLINK (DIGITAL TELEVISION LINK) button. * @property {number} APP_LIST - APP LIST button. * @property {number} BACK_MHP - BACK MHP (Multimedia Home Platform) button. * @property {number} ALT_MHP - ALTERNATE MHP (Multimedia Home Platform) button. * @property {number} RSS - RSS button. * @property {number} ENTERTAINMENT - ENTERTAINMENT button. * @property {number} ID_INPUT - ID INPUT button. * @property {number} ID_SETUP - ID SETUP button. * @property {number} ANYNET - ANYNET button. * @property {number} ANYVIEW - ANYVIEW button. * @property {number} MS - MS button. * @property {number} MORE - MORE button. * @property {number} _4_3 - 4:3 button. * @property {number} 4_3 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._4_3}. * @property {number} _16_9 - 16:9 button. * @property {number} 16_9 - Alias for {@link CB_Keyboard.extended.SAMSUNG_TV._16_9}. * @property {number} PANORAMA - PICTURE MODE PANORAMA button. * @property {number} DYNAMIC - PICTURE MODE DYNAMIC button. * @property {number} STANDARD - PICTURE MODE STANDARD button. * @property {number} MOVIE1 - PICTURE MODE MOVIE1 button. * @property {number} CUSTOM - PICTURE MODE CUSTOM button. * @property {number} AUTO_ARC_RESET - AUTO ARC (Audio Return Channel) RESET button. * @property {number} AUTO_ARC_LNA_ON - AUTO ARC (Audio Return Channel) LNA (Low Noise Amplifier) ON button. * @property {number} AUTO_ARC_LNA_OFF - AUTO ARC (Audio Return Channel) LNA (Low Noise Amplifier) OFF button. * @property {number} AUTO_ARC_ANYNET_MODE_OK - AUTO ARC (Audio Return Channel) ANYNET MODE OK button. * @property {number} AUTO_ARC_ANYNET_AUTO_START - AUTO ARC (Audio Return Channel) ANYNET AUTO START button. * @property {number} AUTO_ARC_CAPTION_ON - AUTO ARC (Audio Return Channel) CAPTION ON button. * @property {number} AUTO_ARC_CAPTION_OFF - AUTO ARC (Audio Return Channel) CAPTION OFF button. * @property {number} AUTO_ARC_PIP_DOUBLE - AUTO ARC (Audio Return Channel) PIP (Picture In Picture) DOUBLE button. * @property {number} AUTO_ARC_PIP_LARGE - AUTO ARC (Audio Return Channel) PIP (Picture In Picture) LARGE button. * @property {number} AUTO_ARC_PIP_SMALL - AUTO ARC (Audio Return Channel) PIP (Picture In Picture) SMALL button. * @property {number} AUTO_ARC_PIP_WIDE - AUTO ARC (Audio Return Channel) PIP (Picture In Picture) WIDE button. * @property {number} AUTO_ARC_PIP_LEFT_TOP - AUTO ARC (Audio Return Channel) PIP (Picture In Picture) LEFT TOP button. * @property {number} AUTO_ARC_PIP_RIGHT_TOP - AUTO ARC (Audio Return Channel) PIP (Picture In Picture) RIGHT TOP button. * @property {number} AUTO_ARC_PIP_LEFT_BOTTOM - AUTO ARC (Audio Return Channel) PIP (Picture In Picture) LEFT BOTTOM button. * @property {number} AUTO_ARC_PIP_RIGHT_BOTTOM - AUTO ARC (Audio Return Channel) PIP (Picture In Picture) RIGHT BOTTOM button. * @property {number} AUTO_ARC_PIP_CH_CHANGE - AUTO ARC (Audio Return Channel) PIP (Picture In Picture) CHANNEL CHANGE button. * @property {number} AUTO_ARC_PIP_SOURCE_CHANGE - AUTO ARC (Audio Return Channel) PIP (Picture In Picture) SOURCE CHANGE button. * @property {number} AUTO_ARC_AUTOCOLOR_SUCCESS - AUTO ARC (Audio Return Channel) AUTOCOLOR SUCCESS button. * @property {number} AUTO_ARC_AUTOCOLOR_FAIL - AUTO ARC (Audio Return Channel) AUTOCOLOR FAIL button. * @property {number} AUTO_ARC_C_FORCE_AGING - AUTO ARC (Audio Return Channel) C-FORCE AGING button. * @property {number} AUTO_ARC_USBJACK_INSPECT - AUTO ARC (Audio Return Channel) USB JACK INSPECT button. * @property {number} AUTO_ARC_JACK_IDENT - AUTO ARC (Audio Return Channel) JACK IDENT button. * @property {number} AUTO_ARC_CAPTION_KOR - AUTO ARC (Audio Return Channel) CAPTION KOREAN button. * @property {number} AUTO_ARC_CAPTION_ENG - AUTO ARC (Audio Return Channel) CAPTION ENGLISH button. * @property {number} AUTO_ARC_ANTENNA_AIR - AUTO ARC (Audio Return Channel) ANTENNA AIR button. * @property {number} AUTO_ARC_ANTENNA_CABLE - AUTO ARC (Audio Return Channel) ANTENNA CABLE button. * @property {number} AUTO_ARC_ANTENNA_SATELLITE - AUTO ARC (Audio Return Channel) ANTENNA SATELLITE button. * @property {number} AUTO_FORMAT - AUTO FORMAT button. * @property {number} DNET - D-NET button. * @property {number} NINE_SEPARATE - NINE SEPARATE button. * @property {number} MIC - MIC (MICROPHONE) button. * @property {number} EXT1 - EXT1 button. * @property {number} EXT2 - EXT2 button. * @property {number} EXT3 - EXT3 button. * @property {number} EXT4 - EXT4 button. * @property {number} EXT5 - EXT5 button. * @property {number} EXT6 - EXT6 button. * @property {number} EXT7 - EXT7 button. * @property {number} EXT8 - EXT8 button. * @property {number} EXT9 - EXT9 button. * @property {number} EXT10 - EXT10 button. * @property {number} EXT11 - EXT11 button. * @property {number} EXT12 - EXT12 button. * @property {number} EXT13 - EXT13 button. * @property {number} EXT14 - EXT14 button. * @property {number} EXT15 - EXT15 button. * @property {number} EXT16 - EXT16 button. * @property {number} EXT17 - EXT17 button. * @property {number} EXT18 - EXT18 button. * @property {number} EXT19 - EXT19 button. * @property {number} EXT20 - EXT20 button. * @property {number} EXT21 - EXT21 button. * @property {number} EXT22 - EXT22 button. * @property {number} EXT23 - EXT23 button. * @property {number} EXT24 - EXT24 button. * @property {number} EXT25 - EXT25 button. * @property {number} EXT26 - EXT26 button. * @property {number} EXT27 - EXT27 button. * @property {number} EXT28 - EXT28 button. * @property {number} EXT29 - EXT29 button. * @property {number} EXT30 - EXT30 button. * @property {number} EXT31 - EXT31 button. * @property {number} EXT32 - EXT32 button. * @property {number} EXT33 - EXT33 button. * @property {number} EXT34 - EXT34 button. * @property {number} EXT35 - EXT35 button. * @property {number} EXT36 - EXT36 button. * @property {number} EXT37 - EXT37 button. * @property {number} EXT38 - EXT38 button. * @property {number} EXT39 - EXT39 button. * @property {number} EXT40 - EXT40 button. * @property {number} EXT41 - EXT41 button. */ //* Source: https://forum.samygo.tv/viewtopic.php?t=1792 and http://www.openremote.org/pages/viewpage.action?pageId=19434990 and https://github.com/Ape/samsungctl/issues/87 CB_Keyboard.extended.SAMSUNG_TV = { TOOLS: tvKey.KEY_TOOLS || tvKey.TOOLS, //Same code as \"K\" key (75). EMODE: tvKey.KEY_EMODE || tvKey.EMODE, //148 DMA: tvKey.KEY_DMA || tvKey.DMA, //260 SOURCE: tvKey.KEY_SOURCE || tvKey.SOURCE, //222 CHDOWN: tvKey.KEY_CHDOWN || tvKey.CHDOWN, CHUP: tvKey.KEY_CHUP || tvKey.CHUP, PANEL_CH_UP: tvKey.KEY_PANEL_CH_UP || tvKey.PANEL_CH_UP, //105 (same code as \"9\" in the numeric pad). PANEL_CH_DOWN: tvKey.KEY_PANEL_CH_DOWN || tvKey.PANEL_CH_DOWN, //106 (same code as asterisk (\"*\") in the numeric pad). PANEL_CHUP: tvKey.KEY_PANEL_CHUP || tvKey.KEY_PANNEL_CHUP || tvKey.PANEL_CHUP || tvKey.PANNEL_CHUP, PANEL_CHDOWN: tvKey.KEY_PANEL_CHDOWN || tvKey.KEY_PANNEL_CHDOWN || tvKey.PANEL_CHDOWN || tvKey.PANNEL_CHDOWN, PIP_CHUP: tvKey.KEY_PIP_CHUP || tvKey.PIP_CHUP, //1050 PIP_CHDOWN: tvKey.KEY_PIP_CHDOWN || tvKey.PIP_CHDOWN, //1051 PRECH: tvKey.KEY_PRECH || tvKey.PRECH, //259 FAVCH: tvKey.KEY_FAVCH || tvKey.FAVCH, //256 CHLIST: tvKey.KEY_CHLIST || tvKey.CHLIST, //84 (same code as \"T\" key). TTX_MIX: tvKey.KEY_TTX_MIX || tvKey.TTX_MIX, //650 GUIDE: tvKey.KEY_GUIDE || tvKey.GUIDE, //651 ASPECT: tvKey.KEY_ASPECT || tvKey.ASPECT, //653 DOLBY_SRR: tvKey.KEY_DOLBY_SRR || tvKey.DOLBY_SRR, //654 MTS: tvKey.KEY_MTS || tvKey.MTS, //655 WHEELDOWN: tvKey.KEY_WHEELDOWN || tvKey.WHEELDOWN, //29469 WHEEL_DOWN: tvKey.KEY_WHEEL_DOWN || tvKey.WHEEL_DOWN, WHEELUP: tvKey.KEY_WHEELUP || tvKey.WHEELUP, //29468 WHEEL_UP: tvKey.KEY_WHEEL_UP || tvKey.WHEEL_UP, WHEELLEFT: tvKey.KEY_WHEELLEFT || tvKey.WHEELLEFT, WHEEL_LEFT: tvKey.KEY_WHEEL_LEFT || tvKey.WHEEL_LEFT, WHEELRIGHT: tvKey.KEY_WHEELRIGHT || tvKey.WHEELRIGHT, WHEEL_RIGHT: tvKey.KEY_WHEEL_RIGHT || tvKey.WHEEL_RIGHT, SMART: tvKey.KEY_SMART || tvKey.SMART, EXIT: tvKey.KEY_EXIT || tvKey.EXIT, //Same code as INS key (45). POWER: tvKey.KEY_POWER || tvKey.POWER, //76 (same code as \"L\" key). PANEL_POWER: tvKey.KEY_PANEL_POWER || tvKey.KEY_PANNEL_POWER || tvKey.PANEL_POWER || tvKey.PANNEL_POWER, //614 POWEROFF: tvKey.KEY_POWEROFF || tvKey.POWEROFF, POWERON: tvKey.KEY_POWERON || tvKey.POWERON, CONTENT: tvKey.KEY_CONTENT || tvKey.CONTENT, //261 WLINK: tvKey.KEY_WLINK || tvKey.WLINK, //115 (same code as F4 key) W_LINK: tvKey.KEY_W_LINK || tvKey.W_LINK, EMPTY: tvKey.KEY_EMPTY || tvKey.EMPTY, //0 CC: tvKey.KEY_CC || tvKey.CC, //118 (same code as F7 key) REC: tvKey.KEY_REC || tvKey.REC, //192 VOLUP: tvKey.KEY_VOLUP || tvKey.VOLUP, VOL_UP: tvKey.KEY_VOL_UP || tvKey.VOL_UP, //7 VOLDOWN: tvKey.KEY_VOLDOWN || tvKey.VOLDOWN, VOL_DOWN: tvKey.KEY_VOL_DOWN || tvKey.VOL_DOWN, //1 PANEL_VOLUP: tvKey.KEY_PANEL_VOLUP || tvKey.KEY_PANNEL_VOLUP || tvKey.PANEL_VOLUP || tvKey.PANNEL_VOLUP, PANEL_VOL_UP: tvKey.KEY_PANEL_VOL_UP || tvKey.PANEL_VOL_UP, //203 PANEL_VOLDOW: tvKey.KEY_PANEL_VOLDOW || tvKey.KEY_PANNEL_VOLDOW || tvKey.PANEL_VOLDOW || tvKey.PANNEL_VOLDOW, PANEL_VOLDOWN: tvKey.KEY_PANEL_VOLDOWN || tvKey.KEY_PANNEL_VOLDOWN || tvKey.PANEL_VOLDOWN || tvKey.PANNEL_VOLDOWN, PANEL_VOL_DOWN: tvKey.KEY_PANEL_VOL_DOWN || tvKey.PANEL_VOL_DOWN, //204 MUTE: tvKey.KEY_MUTE || tvKey.MUTE, //Same code as ESC key (27). INFO: tvKey.KEY_INFO || tvKey.INFO, //31 INFOLINK: tvKey.KEY_INFOLINK || tvKey.INFOLINK, //147 MENU: tvKey.KEY_MENU || tvKey.MENU, //262 SUBTITLE: tvKey.KEY_SUBTITLE || tvKey.SUBTITLE, //652 SUB_TITLE: tvKey.KEY_SUB_TITLE || tvKey.SUB_TITLE, //1089 PANEL_SOURCE: tvKey.KEY_PANEL_SOURCE || tvKey.KEY_PANNEL_SOURCE || tvKey.PANEL_SOURCE || tvKey.PANNEL_SOURCE, //612 _0: tvKey.KEY_0 || tvKey.N0 || tvKey._0 || tvKey[\"0\"], //17 (same code as CTRL or META key, depending on the system). _1: tvKey.KEY_1 || tvKey.N1 || tvKey._1 || tvKey[\"1\"], //101 (same code as \"5\" in the numeric pad). _2: tvKey.KEY_2 || tvKey.N2 || tvKey._2 || tvKey[\"2\"], //98 (same code as \"2\" in the numeric pad). _3: tvKey.KEY_3 || tvKey.N3 || tvKey._3 || tvKey[\"3\"], //6 _4: tvKey.KEY_4 || tvKey.N4 || tvKey._4 || tvKey[\"4\"], //8 _5: tvKey.KEY_5 || tvKey.N5 || tvKey._5 || tvKey[\"5\"], //9 _6: tvKey.KEY_6 || tvKey.N6 || tvKey._6 || tvKey[\"6\"], //10 _7: tvKey.KEY_7 || tvKey.N7 || tvKey._7 || tvKey[\"7\"], //12 _8: tvKey.KEY_8 || tvKey.N8 || tvKey._8 || tvKey[\"8\"], //13 _9: tvKey.KEY_9 || tvKey.N9 || tvKey._9 || tvKey[\"9\"], //14 _10: tvKey.KEY_10 || tvKey.N10 || tvKey._10 || tvKey[\"10\"], _11: tvKey.KEY_11 || tvKey.N11 || tvKey._11 || tvKey[\"11\"], _12: tvKey.KEY_12 || tvKey.N12 || tvKey._12 || tvKey[\"12\"], //1057 RED: tvKey.KEY_RED || tvKey.RED, //Same code as SEPARATOR key (108). GREEN: tvKey.KEY_GREEN || tvKey.GREEN, //Same code as CAPS_LOCK key (20). YELLOW: tvKey.KEY_YELLOW || tvKey.YELLOW, //21 BLUE: tvKey.KEY_BLUE || tvKey.BLUE, //22 CYAN: tvKey.KEY_CYAN || tvKey.CYAN, RW: tvKey.KEY_RW || tvKey.RW, //69 (same code as \"E\" key). PAUSE: tvKey.KEY_PAUSE || tvKey.PAUSE, //74 (same code as \"J\" key). FF: tvKey.KEY_FF || tvKey.FF, //72 (same code as \"H\" key). FF_: tvKey.KEY_FF_ || tvKey.FF_, //1078 REWIND: tvKey.KEY_REWIND || tvKey.REWIND, REWIND_: tvKey.KEY_REWIND_ || tvKey.REWIND_, //1080 PLAY: tvKey.KEY_PLAY || tvKey.PLAY, //71 (same code as \"G\" key). STOP: tvKey.KEY_STOP || tvKey.STOP, //70 (same code as \"F\" key). SEARCH: tvKey.KEY_SEARCH || tvKey.SEARCH, UP: tvKey.KEY_UP || tvKey.UP, //29460. DOWN: tvKey.KEY_DOWN || tvKey.DOWN, //29461 LEFT: tvKey.KEY_LEFT || tvKey.LEFT, //4 RIGHT: tvKey.KEY_RIGHT || tvKey.RIGHT, //5 CH_UP: tvKey.KEY_CH_UP || tvKey.CH_UP, //68 (same code as \"D\" key) CH_DOWN: tvKey.KEY_CH_DOWN || tvKey.CH_DOWN, //65 (same code as \"A\" key) DISC_MENU: tvKey.KEY_DISC_MENU || tvKey.DISC_MENU, //1086 _3D: tvKey.KEY_3D || tvKey._3D || tvKey[\"3D\"], //1219 PIP_ONOFF: tvKey.KEY_PIP_ONOFF || tvKey.PIP_ONOFF, //1032 AD: tvKey.KEY_AD || tvKey.AD, //1039 PMODE: tvKey.KEY_PMODE || tvKey.PMODE, //1040 SMODE: tvKey.KEY_SMODE || tvKey.SMODE, //1043 SLEEP: tvKey.KEY_SLEEP || tvKey.SLEEP, //1097 D_AUDIO: tvKey.KEY_D_AUDIO || tvKey.D_AUDIO, //1236 D_FRONT_PLAY: tvKey.KEY_D_FRONT_PLAY || tvKey.D_FRONT_PLAY, //1243 (for BD) D_VIEW_MODE: tvKey.KEY_D_VIEW_MODE || tvKey.D_VIEW_MODE, //1249 STEP: tvKey.KEY_STEP || tvKey.STEP, //1023 (REC PAUSE(BD)) CALLER_ID: tvKey.KEY_CALLER_ID || tvKey.CALLER_ID, //1128 (FULL SCREEN (BD)) ANTENNA: tvKey.KEY_ANTENA || tvKey.ANTENA || tvKey.KEY_ANTENNA || tvKey.ANTENNA, //1054 (for CN) ZOOM_MOVE: tvKey.KEY_ZOOM_MOVE || tvKey.ZOOM_MOVE, ZOOM1: tvKey.KEY_ZOOM1 || tvKey.ZOOM1, //1083 ZOOM2: tvKey.KEY_ZOOM2 || tvKey.ZOOM2, ZOOM_IN: tvKey.KEY_ZOOM_IN || tvKey.ZOOM_IN, ZOOM_OUT: tvKey.KEY_ZOOM_OUT || tvKey.ZOOM_OUT, RETURN: tvKey.KEY_RETURN || tvKey.RETURN, //Same code as \"X\" key (88). PANEL_RETURN: tvKey.KEY_PANEL_RETURN || tvKey.PANEL_RETURN, ENTER: tvKey.KEY_ENTER || tvKey.ENTER, //29443 PANEL_ENTER: tvKey.KEY_PANEL_ENTER || tvKey.KEY_PANNEL_ENTER || tvKey.PANEL_ENTER || tvKey.PANNEL_ENTER, //309 PANEL_MENU: tvKey.KEY_PANEL_MENU || tvKey.KEY_PANNEL_MENU || tvKey.PANEL_MENU || tvKey.PANNEL_MENU, //613 ADDDEL: tvKey.KEY_ADDDEL || tvKey.ADDDEL, PIP_SWAP: tvKey.KEY_PIP_SWAP || tvKey.PIP_SWAP, PLUS100: tvKey.KEY_PLUS100 || tvKey.PLUS100, CAPTION: tvKey.KEY_CAPTION || tvKey.CAPTION, PICTURE_SIZE: tvKey.KEY_PICTURE_SIZE || tvKey.PICTURE_SIZE, PIP_SIZE: tvKey.KEY_PIP_SIZE || tvKey.PIP_SIZE, MAGIC_CHANNEL: tvKey.KEY_MAGIC_CHANNEL || tvKey.MAGIC_CHANNEL, PIP_SCAN: tvKey.KEY_PIP_SCAN || tvKey.PIP_SCAN, DEVICE_CONNECT: tvKey.KEY_DEVICE_CONNECT || tvKey.DEVICE_CONNECT, HELP: tvKey.KEY_HELP || tvKey.HELP, CONVERGENCE: tvKey.KEY_CONVERGENCE || tvKey.CONVERGENCE, AUTO_PROGRAM: tvKey.KEY_AUTO_PROGRAM || tvKey.AUTO_PROGRAM, FACTORY: tvKey.KEY_FACTORY || tvKey.FACTORY, _3SPEED: tvKey.KEY_3SPEED || tvKey._3SPEED || tvKey[\"3SPEED\"], RSURF: tvKey.KEY_RSURF || tvKey.RSURF, TOPMENU: tvKey.KEY_TOPMENU || tvKey.TOPMENU, GAME: tvKey.KEY_GAME || tvKey.GAME, QUICK_REPLAY: tvKey.KEY_QUICK_REPLAY || tvKey.QUICK_REPLAY, STILL_PICTURE: tvKey.KEY_STILL_PICTURE || tvKey.STILL_PICTURE, DTV: tvKey.KEY_DTV || tvKey.DTV, INSTANT_REPLAY: tvKey.KEY_INSTANT_REPLAY || tvKey.INSTANT_REPLAY, LINK: tvKey.KEY_LINK || tvKey.LINK, ANGLE: tvKey.KEY_ANGLE || tvKey.ANGLE, RESERVED1: tvKey.KEY_RESERVED1 || tvKey.RESERVED1, RESERVED5: tvKey.KEY_RESERVED5 || tvKey.RESERVED5, PROGRAM: tvKey.KEY_PROGRAM || tvKey.PROGRAM, BOOKMARK: tvKey.KEY_BOOKMARK || tvKey.BOOKMARK, PRINT: tvKey.KEY_PRINT || tvKey.PRINT, CLEAR: tvKey.KEY_CLEAR || tvKey.CLEAR, VCHIP: tvKey.KEY_VCHIP || tvKey.VCHIP, REPEAT: tvKey.KEY_REPEAT || tvKey.REPEAT, DOOR: tvKey.KEY_DOOR || tvKey.DOOR, OPEN: tvKey.KEY_OPEN || tvKey.OPEN, TURBO: tvKey.KEY_TURBO || tvKey.TURBO, DVR_MENU: tvKey.KEY_DVR_MENU || tvKey.DVR_MENU, TTX_SUBFACE: tvKey.KEY_TTX_SUBFACE || tvKey.TTX_SUBFACE, CH_LIST: tvKey.KEY_CH_LIST || tvKey.CH_LIST, DNIe: tvKey.KEY_DNIe || tvKey.KEY_DNIE || tvKey.DNIe || tvKey.DNIE, DNSe: tvKey.KEY_DNSe || tvKey.KEY_DNSE || tvKey.DNSe || tvKey.DNSE, SRS: tvKey.KEY_SRS || tvKey.SRS, CONVERT_AUDIO_MAINSUB: tvKey.KEY_CONVERT_AUDIO_MAINSUB || tvKey.CONVERT_AUDIO_MAINSUB, MDC: tvKey.KEY_MDC || tvKey.MDC, SEFFECT: tvKey.KEY_SEFFECT || tvKey.SEFFECT, DVR: tvKey.KEY_DVR || tvKey.DVR, DTV_SIGNAL: tvKey.KEY_DTV_SIGNAL || tvKey.DTV_SIGNAL, LIVE: tvKey.KEY_LIVE || tvKey.LIVE, PERPECT_FOCUS: tvKey.KEY_PERPECT_FOCUS || tvKey.PERPECT_FOCUS, HOME: tvKey.KEY_HOME || tvKey.HOME, ESAVING: tvKey.KEY_ESAVING || tvKey.ESAVING, CONTENTS: tvKey.KEY_CONTENTS || tvKey.CONTENTS, SCALE: tvKey.KEY_SCALE || tvKey.SCALE, CLOCK_DISPLAY: tvKey.KEY_CLOCK_DISPLAY || tvKey.CLOCK_DISPLAY, SETUP_CLOCK_TIMER: tvKey.KEY_SETUP_CLOCK_TIMER || tvKey.SETUP_CLOCK_TIMER, MAGIC_BRIGHT: tvKey.KEY_MAGIC_BRIGHT || tvKey.MAGIC_BRIGHT, FM_RADIO: tvKey.KEY_FM_RADIO || tvKey.FM_RADIO, VCR_MODE: tvKey.KEY_VCR_MODE || tvKey.VCR_MODE, CATV_MODE: tvKey.KEY_CATV_MODE || tvKey.CATV_MODE, DSS_MODE: tvKey.KEY_DSS_MODE || tvKey.DSS_MODE, DVD_MODE: tvKey.KEY_DVD_MODE || tvKey.DVD_MODE, STB_MODE: tvKey.KEY_STB_MODE || tvKey.STB_MODE, PCMODE: tvKey.KEY_PCMODE || tvKey.PCMODE, TV_MODE: tvKey.KEY_TV_MODE || tvKey.TV_MODE, TV: tvKey.KEY_TV || tvKey.TV, //77 AV1: tvKey.KEY_AV1 || tvKey.AV1, AV2: tvKey.KEY_AV2 || tvKey.AV2, AV3: tvKey.KEY_AV3 || tvKey.AV3, SVIDEO1: tvKey.KEY_SVIDEO1 || tvKey.SVIDEO1, SVIDEO2: tvKey.KEY_SVIDEO2 || tvKey.SVIDEO2, SVIDEO3: tvKey.KEY_SVIDEO3 || tvKey.SVIDEO3, COMPONENT1: tvKey.KEY_COMPONENT1 || tvKey.COMPONENT1, COMPONENT2: tvKey.KEY_COMPONENT2 || tvKey.COMPONENT2, DVI: tvKey.KEY_DVI || tvKey.DVI, HDMI: tvKey.KEY_HDMI || tvKey.HDMI, HDMI1: tvKey.KEY_HDMI1 || tvKey.HDMI1, HDMI2: tvKey.KEY_HDMI2 || tvKey.HDMI2, HDMI3: tvKey.KEY_HDMI3 || tvKey.HDMI3, HDMI4: tvKey.KEY_HDMI4 || tvKey.HDMI4, DTV_LINK: tvKey.KEY_DTV_LINK || tvKey.DTV_LINK, APP_LIST: tvKey.KEY_APP_LIST || tvKey.APP_LIST, BACK_MHP: tvKey.KEY_BACK_MHP || tvKey.BACK_MHP, ALT_MHP: tvKey.KEY_ALT_MHP || tvKey.ALT_MHP, RSS: tvKey.KEY_RSS || tvKey.RSS, ENTERTAINMENT: tvKey.KEY_ENTERTAINMENT || tvKey.ENTERTAINMENT, ID_INPUT: tvKey.KEY_ID_INPUT || tvKey.ID_INPUT, ID_SETUP: tvKey.KEY_ID_SETUP || tvKey.ID_SETUP, ANYNET: tvKey.KEY_ANYNET || tvKey.ANYNET, ANYVIEW: tvKey.KEY_ANYVIEW || tvKey.ANYVIEW, MS: tvKey.KEY_MS || tvKey.MS, MORE: tvKey.KEY_MORE || tvKey.MORE, _4_3: tvKey.KEY_4_3 || tvKey._4_3 || tvKey[\"4_3\"], _16_9: tvKey.KEY_16_9 || tvKey._16_9 || tvKey[\"16_9\"], PANORAMA: tvKey.KEY_PANORAMA || tvKey.PANORAMA, DYNAMIC: tvKey.KEY_DYNAMIC || tvKey.DYNAMIC, STANDARD: tvKey.KEY_STANDARD || tvKey.STANDARD, MOVIE1: tvKey.KEY_MOVIE1 || tvKey.MOVIE1, CUSTOM: tvKey.KEY_CUSTOM || tvKey.CUSTOM, AUTO_ARC_RESET: tvKey.KEY_AUTO_ARC_RESET || tvKey.AUTO_ARC_RESET, AUTO_ARC_LNA_ON: tvKey.KEY_AUTO_ARC_LNA_ON || tvKey.AUTO_ARC_LNA_ON, AUTO_ARC_LNA_OFF: tvKey.KEY_AUTO_ARC_LNA_OFF || tvKey.AUTO_ARC_LNA_OFF, AUTO_ARC_ANYNET_MODE_OK: tvKey.KEY_AUTO_ARC_ANYNET_MODE_OK || tvKey.AUTO_ARC_ANYNET_MODE_OK, AUTO_ARC_ANYNET_AUTO_START: tvKey.KEY_AUTO_ARC_ANYNET_AUTO_START || tvKey.AUTO_ARC_ANYNET_AUTO_START, AUTO_ARC_CAPTION_ON: tvKey.KEY_AUTO_ARC_CAPTION_ON || tvKey.AUTO_ARC_CAPTION_ON, AUTO_ARC_CAPTION_OFF: tvKey.KEY_AUTO_ARC_CAPTION_OFF || tvKey.AUTO_ARC_CAPTION_OFF, AUTO_ARC_PIP_DOUBLE: tvKey.KEY_AUTO_ARC_PIP_DOUBLE || tvKey.AUTO_ARC_PIP_DOUBLE, AUTO_ARC_PIP_LARGE: tvKey.KEY_AUTO_ARC_PIP_LARGE || tvKey.AUTO_ARC_PIP_LARGE, AUTO_ARC_PIP_SMALL: tvKey.KEY_AUTO_ARC_PIP_SMALL || tvKey.AUTO_ARC_PIP_SMALL, AUTO_ARC_PIP_WIDE: tvKey.KEY_AUTO_ARC_PIP_WIDE || tvKey.AUTO_ARC_PIP_WIDE, AUTO_ARC_PIP_LEFT_TOP: tvKey.KEY_AUTO_ARC_PIP_LEFT_TOP || tvKey.AUTO_ARC_PIP_LEFT_TOP, AUTO_ARC_PIP_RIGHT_TOP: tvKey.KEY_AUTO_ARC_PIP_RIGHT_TOP || tvKey.AUTO_ARC_PIP_RIGHT_TOP, AUTO_ARC_PIP_LEFT_BOTTOM: tvKey.KEY_AUTO_ARC_PIP_LEFT_BOTTOM || tvKey.AUTO_ARC_PIP_LEFT_BOTTOM, AUTO_ARC_PIP_RIGHT_BOTTOM: tvKey.KEY_AUTO_ARC_PIP_RIGHT_BOTTOM || tvKey.AUTO_ARC_PIP_RIGHT_BOTTOM, AUTO_ARC_PIP_CH_CHANGE: tvKey.KEY_AUTO_ARC_PIP_CH_CHANGE || tvKey.AUTO_ARC_PIP_CH_CHANGE, AUTO_ARC_PIP_SOURCE_CHANGE: tvKey.KEY_AUTO_ARC_PIP_SOURCE_CHANGE || tvKey.AUTO_ARC_PIP_SOURCE_CHANGE, AUTO_ARC_AUTOCOLOR_SUCCESS: tvKey.KEY_AUTO_ARC_AUTOCOLOR_SUCCESS || tvKey.AUTO_ARC_AUTOCOLOR_SUCCESS, AUTO_ARC_AUTOCOLOR_FAIL: tvKey.KEY_AUTO_ARC_AUTOCOLOR_FAIL || tvKey.AUTO_ARC_AUTOCOLOR_FAIL, AUTO_ARC_C_FORCE_AGING: tvKey.KEY_AUTO_ARC_C_FORCE_AGING || tvKey.AUTO_ARC_C_FORCE_AGING, AUTO_ARC_USBJACK_INSPECT: tvKey.KEY_AUTO_ARC_USBJACK_INSPECT || tvKey.AUTO_ARC_USBJACK_INSPECT, AUTO_ARC_JACK_IDENT: tvKey.KEY_AUTO_ARC_JACK_IDENT || tvKey.AUTO_ARC_JACK_IDENT, AUTO_ARC_CAPTION_KOR: tvKey.KEY_AUTO_ARC_CAPTION_KOR || tvKey.AUTO_ARC_CAPTION_KOR, AUTO_ARC_CAPTION_ENG: tvKey.KEY_AUTO_ARC_CAPTION_ENG || tvKey.AUTO_ARC_CAPTION_ENG, AUTO_ARC_ANTENNA_AIR: tvKey.KEY_AUTO_ARC_ANTENNA_AIR || tvKey.AUTO_ARC_ANTENNA_AIR, AUTO_ARC_ANTENNA_CABLE: tvKey.KEY_AUTO_ARC_ANTENNA_CABLE || tvKey.AUTO_ARC_ANTENNA_CABLE, AUTO_ARC_ANTENNA_SATELLITE: tvKey.KEY_AUTO_ARC_ANTENNA_SATELLITE || tvKey.AUTO_ARC_ANTENNA_SATELLITE, AUTO_FORMAT: tvKey.KEY_AUTO_FORMAT || tvKey.AUTO_FORMAT, DNET: tvKey.KEY_DNET || tvKey.DNET, NINE_SEPARATE: tvKey.KEY_NINE_SEPERATE || tvKey.NINE_SEPERATE || tvKey.KEY_NINE_SEPARATE || tvKey.NINE_SEPARATE, MIC: tvKey.KEY_MIC || tvKey.MIC, EXT1: tvKey.KEY_EXT1 || tvKey.EXT1, EXT2: tvKey.KEY_EXT2 || tvKey.EXT2, EXT3: tvKey.KEY_EXT3 || tvKey.EXT3, EXT4: tvKey.KEY_EXT4 || tvKey.EXT4, EXT5: tvKey.KEY_EXT5 || tvKey.EXT5, EXT6: tvKey.KEY_EXT6 || tvKey.EXT6, EXT7: tvKey.KEY_EXT7 || tvKey.EXT7, EXT8: tvKey.KEY_EXT8 || tvKey.EXT8, EXT9: tvKey.KEY_EXT9 || tvKey.EXT9, EXT10: tvKey.KEY_EXT10 || tvKey.EXT10, EXT11: tvKey.KEY_EXT11 || tvKey.EXT11, EXT12: tvKey.KEY_EXT12 || tvKey.EXT12, EXT13: tvKey.KEY_EXT13 || tvKey.EXT13, EXT14: tvKey.KEY_EXT14 || tvKey.EXT14, EXT15: tvKey.KEY_EXT15 || tvKey.EXT15, EXT16: tvKey.KEY_EXT16 || tvKey.EXT16, EXT17: tvKey.KEY_EXT17 || tvKey.EXT17, EXT18: tvKey.KEY_EXT18 || tvKey.EXT18, EXT19: tvKey.KEY_EXT19 || tvKey.EXT19, EXT20: tvKey.KEY_EXT20 || tvKey.EXT20, EXT21: tvKey.KEY_EXT21 || tvKey.EXT21, EXT22: tvKey.KEY_EXT22 || tvKey.EXT22, EXT23: tvKey.KEY_EXT23 || tvKey.EXT23, EXT24: tvKey.KEY_EXT24 || tvKey.EXT24, EXT25: tvKey.KEY_EXT25 || tvKey.EXT25, EXT26: tvKey.KEY_EXT26 || tvKey.EXT26, EXT27: tvKey.KEY_EXT27 || tvKey.EXT27, EXT28: tvKey.KEY_EXT28 || tvKey.EXT28, EXT29: tvKey.KEY_EXT29 || tvKey.EXT29, EXT30: tvKey.KEY_EXT30 || tvKey.EXT30, EXT31: tvKey.KEY_EXT31 || tvKey.EXT31, EXT32: tvKey.KEY_EXT32 || tvKey.EXT32, EXT33: tvKey.KEY_EXT33 || tvKey.EXT33, EXT34: tvKey.KEY_EXT34 || tvKey.EXT34, EXT35: tvKey.KEY_EXT35 || tvKey.EXT35, EXT36: tvKey.KEY_EXT36 || tvKey.EXT36, EXT37: tvKey.KEY_EXT37 || tvKey.EXT37, EXT38: tvKey.KEY_EXT38 || tvKey.EXT38, EXT39: tvKey.KEY_EXT39 || tvKey.EXT39, EXT40: tvKey.KEY_EXT40 || tvKey.EXT40, EXT41: tvKey.KEY_EXT41 || tvKey.EXT41 }; CB_Keyboard.extended.SAMSUNG_TV[0] = CB_Keyboard.extended.SAMSUNG_TV._0; CB_Keyboard.extended.SAMSUNG_TV[1] = CB_Keyboard.extended.SAMSUNG_TV._1; CB_Keyboard.extended.SAMSUNG_TV[2] = CB_Keyboard.extended.SAMSUNG_TV._2; CB_Keyboard.extended.SAMSUNG_TV[3] = CB_Keyboard.extended.SAMSUNG_TV._3; CB_Keyboard.extended.SAMSUNG_TV[4] = CB_Keyboard.extended.SAMSUNG_TV._4; CB_Keyboard.extended.SAMSUNG_TV[5] = CB_Keyboard.extended.SAMSUNG_TV._5; CB_Keyboard.extended.SAMSUNG_TV[6] = CB_Keyboard.extended.SAMSUNG_TV._6; CB_Keyboard.extended.SAMSUNG_TV[7] = CB_Keyboard.extended.SAMSUNG_TV._7; CB_Keyboard.extended.SAMSUNG_TV[8] = CB_Keyboard.extended.SAMSUNG_TV._8; CB_Keyboard.extended.SAMSUNG_TV[9] = CB_Keyboard.extended.SAMSUNG_TV._9; CB_Keyboard.extended.SAMSUNG_TV[10] = CB_Keyboard.extended.SAMSUNG_TV._10; CB_Keyboard.extended.SAMSUNG_TV[11] = CB_Keyboard.extended.SAMSUNG_TV._11; CB_Keyboard.extended.SAMSUNG_TV[12] = CB_Keyboard.extended.SAMSUNG_TV._12; CB_Keyboard.extended.SAMSUNG_TV[\"3D\"] = CB_Keyboard.extended.SAMSUNG_TV._3D; CB_Keyboard.extended.SAMSUNG_TV[\"3SPEED\"] = CB_Keyboard.extended.SAMSUNG_TV._3SPEED; CB_Keyboard.extended.SAMSUNG_TV[\"4_3\"] = CB_Keyboard.extended.SAMSUNG_TV._4_3; CB_Keyboard.extended.SAMSUNG_TV[\"16_9\"] = CB_Keyboard.extended.SAMSUNG_TV._16_9; CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases = CB_Configuration[CB_BASE_NAME].CB_Keyboard_extended_SAMSUNG_TV_allowDuplicateKeyAliases; /** * Amazon Fire TV remote control key codes. * @memberof CB_Keyboard.extended * @name AMAZON_FIRE_TV_REMOTE * @constant * @type {Object} * @default * @property {number} UP - UP button. * @property {number} DOWN - DOWN button. * @property {number} LEFT - LEFT button. * @property {number} RIGHT - RIGHT button. * @property {number} SELECT - SELECT button. * @property {number} PLAY_PAUSE - PLAY/PAUSE button. * @property {number} RW - RW (REWIND) button. * @property {number} FF - FF (FAST FORWARD) button. */ CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE = { UP: 38, DOWN: 40, LEFT: 37, RIGHT: 39, SELECT: 13, PLAY_PAUSE: 179, RW: 227, FF: 228 }; /** * Amazon Fire TV game controller key codes. * @memberof CB_Keyboard.extended * @name AMAZON_FIRE_TV_GAME_CONTROLLER * @constant * @type {Object} * @default * @property {number} UP - UP button. * @property {number} DOWN - DOWN button. * @property {number} LEFT - LEFT button. * @property {number} RIGHT - RIGHT button. * @property {number} A - \"A\" button. * @property {number} B - \"B\" button. * @property {number} X - \"X\" button. * @property {number} Y - \"Y\" button. */ CB_Keyboard.extended.AMAZON_FIRE_TV_GAME_CONTROLLER = { UP: 38, DOWN: 40, LEFT: 37, RIGHT: 39, A: 13, B: 8, //Same as BACKSPACE. X: 13, //Same code as A button. Y: 13 //Same code as A button. } /** * Nintendo Wii (Wiimote) key codes. * @memberof CB_Keyboard.extended * @name WII * @constant * @type {Object} * @default * @property {number} UP - D-PAD UP button. * @property {number} DOWN - D-PAD DOWN button. * @property {number} LEFT - D-PAD LEFT button. * @property {number} RIGHT - D-PAD RIGHT button. * @property {number} A - \"A\" button. * @property {number} B - \"B\" button. * @property {number} MINUS - MINUS (\"-\") button. * @property {number} PLUS - PLUS (\"+\") button. * @property {number} ONE - \"1\" button. * @property {number} _1 - Alias for {@link CB_Keyboard.extended.WII.ONE}. * @property {number} 1 - Alias for {@link CB_Keyboard.extended.WII.ONE}. * @property {number} TWO - \"2\" button. * @property {number} _2 - Alias for {@link CB_Keyboard.extended.WII.TWO}. * @property {number} 2 - Alias for {@link CB_Keyboard.extended.WII.TWO}. * @property {number} HOME - HOME button. */ //* Source: tomy @ https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes CB_Keyboard.extended.WII = { UP: 175, //D-PAD: UP (also scrolls up). Note: same code as \"VOL_UP\" key. DOWN: 176, //D-PAD DOWN (also scrolls down). Note: same code as \"MEDIA_FORWARD\" key. LEFT: 178, //D-PAD LEFT (also scrolls left). Note: same code as \"MEDIA_STOP\" key. RIGHT: 177, //D-PAD RIGHT (also scrolls right). Note: same code as \"MEDIA_BACK\" key. A: 13, //\"A\" button. Note: same code as ENTER key. B: 171, //\"B\" button. Note: same code as BROWSER_FAVORITES key and PLUS (\"+\") in Firefox browser. MINUS: 170, //Minus (\"-\") button (also zooms out). Note: same code as BROWSER_SEARCH key. PLUS: 174, //Plus (\"+\") button (also zooms in). Note: same code as VOL_DOWN key. ONE: 172, //\"1\" button. Note: same code as BROWSER_HOME key. TWO: 173, //\"2\" button (also splits screen into single column mode). Note: same code as MUTE key and MINUS (\"-\") in Firefox browser. HOME: 2 //Home button (also leaves the browser). }; CB_Keyboard.extended.WII[1] = CB_Keyboard.extended.WII._1 = CB_Keyboard.extended.WII.ONE; //\"1\" button. Note: same code as BROWSER_HOME key. CB_Keyboard.extended.WII[2] = CB_Keyboard.extended.WII._2 = CB_Keyboard.extended.WII.TWO; //\"2\" button (also splits screen into single column mode). Note: same code as MUTE key and MINUS (\"-\") in Firefox browser. CB_Keyboard.extended.WII._allowDuplicateKeyAliases = CB_Configuration[CB_BASE_NAME].CB_Keyboard_extended_WII_allowDuplicateKeyAliases; /** * Sony PlayStation 3 key codes. * @memberof CB_Keyboard.extended * @name PS3 * @constant * @type {Object} * @default * @property {number} UP - UP button. * @property {number} DOWN - DOWN button. * @property {number} LEFT - LEFT button. * @property {number} RIGHT - RIGHT button. * @property {number} CROSS - CROSS button. */ //* Source: tomy @ https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes CB_Keyboard.extended.PS3 = { UP: 38, DOWN: 40, LEFT: 37, RIGHT: 39, CROSS: 63 //Caution, also clicks! Note: same code as \"?\" symbol key. //CIRCLE: 27 //Not sure. }; /** * Sony PlayStation 4 key codes. * @memberof CB_Keyboard.extended * @name PS4 * @constant * @type {Object} * @default * @property {number} UP - D-PAD UP button. * @property {number} DOWN - D-PAD DOWN button. * @property {number} LEFT - D-PAD LEFT button. * @property {number} RIGHT - D-PAD RIGHT button. * @property {number} TRIANGLE - TRIANGLE button. * @property {number} SQUARE - SQUARE button. * @property {number} CIRCLE - CIRCLE button. * @property {number} L1 - L1 button. * @property {number} L2 - L2 button. * @property {number} R1 - R1 button. * @property {number} R2 - R2 button. * @property {number} LEFT_STICK_CLICK - LEFT STICK CLICK button. * @property {number} RIGHT_STICK_CLICK - RIGHT STICK CLICK button. * @property {number} OPTIONS - OPTIONS button. */ //* Source: http://coding.vdhdesign.co.nz/?p=351 (https://web.archive.org/web/20140222065645/http://coding.vdhdesign.co.nz/?p=351) CB_Keyboard.extended.PS4 = { UP: 38, //D-PAD: UP. DOWN: 40, //D-PAD: DOWN. LEFT: 37, //D-PAD: LEFT. RIGHT: 39, //D-PAD: RIGHT. TRIANGLE: 112, //Also initiates search bar. Note: same code as F1 key. SQUARE: 113, //Also initiates full screen mode. Note: same code as F2 key. CIRCLE: 27, //Browser history back. Note: same code as ESC key. //CROSS: undefined, //No keycode event was fired for this button, as this is used as a mouse left click. L1: 116, //History Back. It seems the web browser does not send any event for L1 button. Note: same codes as F5 key. L2: 118, //Goes to browser tab to the left. Note: same codes as F7 key. R1: 117, //History Forward. Note: same codes as F6 key. R2: 119, //Goes to browser tab to the right. Note: same codes as F8 key. LEFT_STICK_CLICK: 120, //Zooms browser out. Note: same codes as F9 key. RIGHT_STICK_CLICK: 121, //Zooms browser In. Note: same codes as F10 key. OPTIONS: 114 //Opens up options menu. Note: same codes as F3 key. //SHARE: undefined //Share Button (goes directly to a native application, no key code was fires). }; CB_Keyboard.extended.PS4._allowDuplicateKeyAliases = CB_Configuration[CB_BASE_NAME].CB_Keyboard_extended_PS4_allowDuplicateKeyAliases; /** * Sony PlayStation Vita key codes. * @memberof CB_Keyboard.extended * @name PSVITA * @constant * @type {Object} * @default * @property {number} UP - UP button. * @property {number} DOWN - DOWN button. * @property {number} LEFT - LEFT button. * @property {number} RIGHT - RIGHT button. */ //* Source: https://github.com/goldenratio/console-browsers-gamepad/tree/master/playstation CB_Keyboard.extended.PSVITA = { UP: 38, //UP. DOWN: 40, //DOWN. LEFT: 37, //LEFT. RIGHT: 39 //RIGHT. }; /** * LG Smart TV (Linux 35230) key codes. * @memberof CB_Keyboard.extended * @name LG_SMART_TV_LINUX_35230 * @constant * @type {Object} * @default * @property {number} _0 - 0 (zero) button. * @property {number} _1 - 1 button. * @property {number} _2 - 2 button. * @property {number} _3 - 3 button. * @property {number} _4 - 4 button. * @property {number} _5 - 5 button. * @property {number} _6 - 6 button. * @property {number} _7 - 7 button. * @property {number} _8 - 8 button. * @property {number} _9 - 9 button. * @property {number} 0 - Alias for {@link CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._0}. * @property {number} 1 - Alias for {@link CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._1}. * @property {number} 2 - Alias for {@link CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._2}. * @property {number} 3 - Alias for {@link CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._3}. * @property {number} 4 - Alias for {@link CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._4}. * @property {number} 5 - Alias for {@link CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._5}. * @property {number} 6 - Alias for {@link CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._6}. * @property {number} 7 - Alias for {@link CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._7}. * @property {number} 8 - Alias for {@link CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._8}. * @property {number} 9 - Alias for {@link CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._9}. * @property {number} FORWARD - FORWARD button. * @property {number} REWIND - REWIND button. * @property {number} PLAY - PLAY button. * @property {number} PAUSE - PAUSE button. */ //* Source: tomy @ https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes CB_Keyboard.extended.LG_SMART_TV_LINUX_35230 = { //TODO: add more codes (if there is any more) and use them in CB_Keyboard.keys. _0: 48, _1: 49, _2: 50, _3: 51, _4: 52, _5: 53, _6: 54, _7: 55, _8: 56, _9: 57, FORWARD: 417, //Forward button. REWIND: 412, //Rewind button. PLAY: 445, //Play button. PAUSE: 19 //Pause button. }; CB_Keyboard.extended.LG_SMART_TV_LINUX_35230[0] = CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._0; CB_Keyboard.extended.LG_SMART_TV_LINUX_35230[1] = CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._1; CB_Keyboard.extended.LG_SMART_TV_LINUX_35230[2] = CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._2; CB_Keyboard.extended.LG_SMART_TV_LINUX_35230[3] = CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._3; CB_Keyboard.extended.LG_SMART_TV_LINUX_35230[4] = CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._4; CB_Keyboard.extended.LG_SMART_TV_LINUX_35230[5] = CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._5; CB_Keyboard.extended.LG_SMART_TV_LINUX_35230[6] = CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._6; CB_Keyboard.extended.LG_SMART_TV_LINUX_35230[7] = CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._7; CB_Keyboard.extended.LG_SMART_TV_LINUX_35230[8] = CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._8; CB_Keyboard.extended.LG_SMART_TV_LINUX_35230[9] = CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._9; /** * Object whose properties are aliases for key codes (each property can contain an array with one or more integers which belong to the key codes). * @namespace * @type {Object} */ CB_Keyboard.keys = { /** * The Escape (ESC) key. * @type {array} * @default */ \"ESC\" : [27], /** * The F1 key. * @type {array} * @default */ \"F1\" : [112], /** * The F2 key. * @type {array} * @default */ \"F2\" : [113], /** * The F3 key. * @type {array} * @default */ \"F3\" : [114], /** * The F4 key. * @type {array} * @default */ \"F4\" : [115], /** * The F5 key. * @type {array} * @default */ \"F5\" : [116], /** * The F6 key. * @type {array} * @default */ \"F6\" : [117], /** * The F7 key. * @type {array} * @default */ \"F7\" : [118], /** * The F8 key. * @type {array} * @default */ \"F8\" : [119], /** * The F9 key. * @type {array} * @default */ \"F9\" : [120], /** * The F10 key. * @type {array} * @default */ \"F10\" : [121], /** * The F11 key. * @type {array} * @default */ \"F11\" : [122], /** * The F12 key. * @type {array} * @default */ \"F12\" : [123], /** * The Control key. * @type {array} * @default */ \"CTRL\" : [17, 162, 163], /** * The Alt key. * @type {array} * @default */ \"ALT\" : [18], /** * The Shift (left or right) key. * @type {array} * @default */ \"SHIFT\" : [16, 160, 161], /** * The meta (Windows Start, Apple Command, etc.) key. * @type {array} * @default */ \"META\" : [/*17,*/ 91, 92, 219, 220, 224], /** * The up arrow key. * @type {array} * @default */ \"UP\" : [ 38, CB_Keyboard.extended.WII._allowDuplicateKeyAliases ? CB_Keyboard.extended.WII.UP : null, //Note: same code as \"VOL_UP\" key (175). CB_Keyboard.extended.VK.UP, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV.UP, //29460 CB_Keyboard.extended.SAMSUNG_TIZEN_TV.UP, CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE.UP, CB_Keyboard.extended.AMAZON_FIRE_TV_GAME_CONTROLLER.UP, CB_Keyboard.extended.PS3.UP, CB_Keyboard.extended.PS4.UP, CB_Keyboard.extended.PSVITA.UP ], /** * The down arrow key. * @type {array} * @default */ \"DOWN\" : [ 40, CB_Keyboard.extended.WII._allowDuplicateKeyAliases ? CB_Keyboard.extended.WII.DOWN : null, //Note: same code as \"MEDIA_FORWARD\" key (176). CB_Keyboard.extended.VK.DOWN, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV.DOWN, //29461 CB_Keyboard.extended.SAMSUNG_TIZEN_TV.DOWN, CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE.DOWN, CB_Keyboard.extended.AMAZON_FIRE_TV_GAME_CONTROLLER.DOWN, CB_Keyboard.extended.PS3.DOWN, CB_Keyboard.extended.PS4.DOWN, CB_Keyboard.extended.PSVITA.DOWN ], /** * The left arrow key. * @type {array} * @default */ \"LEFT\" : [ 37, CB_Keyboard.extended.WII._allowDuplicateKeyAliases ? CB_Keyboard.extended.WII.LEFT : null, //Note: same code as \"MEDIA_STOP\" key (178). CB_Keyboard.extended.VK.LEFT, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV.LEFT, //4 CB_Keyboard.extended.SAMSUNG_TIZEN_TV.LEFT, CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE.LEFT, CB_Keyboard.extended.AMAZON_FIRE_TV_GAME_CONTROLLER.LEFT, CB_Keyboard.extended.PS3.LEFT, CB_Keyboard.extended.PS4.LEFT, CB_Keyboard.extended.PSVITA.LEFT ], /** * The right arrow key. * @type {array} * @default */ \"RIGHT\" : [ 39, CB_Keyboard.extended.WII._allowDuplicateKeyAliases ? CB_Keyboard.extended.WII.RIGHT : null, //Note: same code as \"MEDIA_BACK\" key (177). CB_Keyboard.extended.VK.RIGHT, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV.RIGHT, //5 CB_Keyboard.extended.SAMSUNG_TIZEN_TV.RIGHT, CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE.RIGHT, CB_Keyboard.extended.AMAZON_FIRE_TV_GAME_CONTROLLER.RIGHT, CB_Keyboard.extended.PS3.RIGHT, CB_Keyboard.extended.PS4.RIGHT, CB_Keyboard.extended.PSVITA.RIGHT ], /** * The Enter (Return) key. * @type {array} * @default */ \"ENTER\" : [ 13, //10, //Safari Mobile (probaby old). Source: http://mscerts.programming4.us/programming/coding%20javascript%20for%20mobile%20browsers%20%28part%2011%29.aspx CB_Keyboard.extended.VK.ENTER, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV.ENTER, //29443 CB_Keyboard.extended.SAMSUNG_TV.PANEL_ENTER, //309 CB_Keyboard.extended.SAMSUNG_TIZEN_TV.ENTER, CB_Keyboard.extended.PS3.CROSS, //Caution, also clicks! Note: same code as \"?\" symbol key. CB_Keyboard.extended.PS4._allowDuplicateKeyAliases ? CB_Keyboard.extended.PS4.SQUARE : null //Also initiates full screen mode. Note: same code as F2 key. ], /** * The Backspace key. * @type {array} * @default */ \"BACKSPACE\" : [ 8, 127, //Safari Mobile (probaby old). Source: http://mscerts.programming4.us/programming/coding%20javascript%20for%20mobile%20browsers%20%28part%2011%29.aspx CB_Keyboard.extended.VK.BACK_SPACE ], /** * The Spacebar key. * @type {array} * @default */ \"SPACEBAR\" : [ 32, CB_Keyboard.extended.VK.SPACE ], /** * The Tabulator (Tab) key. * @type {array} * @default */ \"TAB\" : [9], /** * The Caps Lock key. * @type {array} * @default */ \"CAPS_LOCK\" : [20], /** * The Num Lock (Numeric Lock) key. * @type {array} * @default */ \"NUM_LOCK\" : [144], /** * The Scroll Lock key. * @type {array} * @default */ \"SCROLL_LOCK\" : [145], /** * Alias for {@link CB_Keyboard.keys.0}. * @var CB_Keyboard.keys._0 * @see {@link CB_Keyboard.keys.0} */ /** * The 0 (zero) key. * @type {array} * @default */ \"0\" : [ 48, //For keydown for normal keyboard and for keypress. 96, //For keydown for numeric pad. CB_Keyboard.extended.VK._0, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV._0 : null, //17 (same code as CTRL or META key, depending on the system). CB_Keyboard.extended.SAMSUNG_TIZEN_TV._0, CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._0 ], /** * Alias for {@link CB_Keyboard.keys.1}. * @var CB_Keyboard.keys._1 * @see {@link CB_Keyboard.keys.1} */ /** * The 1 key. * @type {array} * @default */ \"1\" : [ 49, //For keydown for normal keyboard and for keypress. 97, //For keydown for numeric pad. CB_Keyboard.extended.VK._1, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV._1 : null, //101 (same code as \"5\" in the numeric pad). CB_Keyboard.extended.SAMSUNG_TIZEN_TV._1, CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._1 ], /** * Alias for {@link CB_Keyboard.keys.2}. * @var CB_Keyboard.keys._2 * @see {@link CB_Keyboard.keys.2} */ /** * The 2 key. * @type {array} * @default */ \"2\" : [ 50, //For keydown for normal keyboard and for keypress. 98, //For keydown for numeric pad. CB_Keyboard.extended.VK._2, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV._2 : null, //98 (same code as \"2\" in the numeric pad). CB_Keyboard.extended.SAMSUNG_TIZEN_TV._2, CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._2 ], /** * Alias for {@link CB_Keyboard.keys.3}. * @var CB_Keyboard.keys._3 * @see {@link CB_Keyboard.keys.3} */ /** * The 3 key. * @type {array} * @default */ \"3\" : [ 51, //For keydown for normal keyboard and for keypress. 99, //For keydown for numeric pad. CB_Keyboard.extended.VK._3, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV._3, //6 CB_Keyboard.extended.SAMSUNG_TIZEN_TV._3, CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._3 ], /** * Alias for {@link CB_Keyboard.keys.4}. * @var CB_Keyboard.keys._4 * @see {@link CB_Keyboard.keys.4} */ /** * The 4 key. * @type {array} * @default */ \"4\" : [ 52, //For keydown for normal keyboard and for keypress. 100, //For keydown for numeric pad. CB_Keyboard.extended.VK._4, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV._4, //8 CB_Keyboard.extended.SAMSUNG_TIZEN_TV._4, CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._4 ], /** * Alias for {@link CB_Keyboard.keys.5}. * @var CB_Keyboard.keys._5 * @see {@link CB_Keyboard.keys.5} */ /** * The 5 key. * @type {array} * @default */ \"5\" : [ 53, //For keydown for normal keyboard and for keypress. 101, //For keydown for numeric pad. CB_Keyboard.extended.VK._5, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV._5, //9 CB_Keyboard.extended.SAMSUNG_TIZEN_TV._5, CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._5 ], /** * Alias for {@link CB_Keyboard.keys.6}. * @var CB_Keyboard.keys._6 * @see {@link CB_Keyboard.keys.6} */ /** * The 6 key. * @type {array} * @default */ \"6\" : [ 54, //For keydown for normal keyboard and for keypress. 102, //For keydown for numeric pad. CB_Keyboard.extended.VK._6, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV._6, //10 CB_Keyboard.extended.SAMSUNG_TIZEN_TV._6, CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._6 ], /** * Alias for {@link CB_Keyboard.keys.7}. * @var CB_Keyboard.keys._7 * @see {@link CB_Keyboard.keys.7} */ /** * The 7 key. * @type {array} * @default */ \"7\" : [ 55, //For keydown for normal keyboard and for keypress. 103, //For keydown for numeric pad. CB_Keyboard.extended.VK._7, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV._7, //12 CB_Keyboard.extended.SAMSUNG_TIZEN_TV._7, CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._7 ], /** * Alias for {@link CB_Keyboard.keys.8}. * @var CB_Keyboard.keys._8 * @see {@link CB_Keyboard.keys.8} */ /** * The 8 key. * @type {array} * @default */ \"8\" : [ 56, //For keydown for normal keyboard and for keypress. 104, //For keydown for numeric pad. CB_Keyboard.extended.VK._8, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV._8, //13 CB_Keyboard.extended.SAMSUNG_TIZEN_TV._8, CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._8 ], /** * Alias for {@link CB_Keyboard.keys.9}. * @var CB_Keyboard.keys._9 * @see {@link CB_Keyboard.keys.9} */ /** * The 9 key. * @type {array} * @default */ \"9\" : [ 57, //For keydown for normal keyboard and for keypress. 105, //For keydown for numeric pad. CB_Keyboard.extended.VK._9, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV._9, //14 CB_Keyboard.extended.SAMSUNG_TIZEN_TV._9, CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._9 ], /** * The \"+\" (plus) symbol key. NOTE: In some keyboards (for example in Chinese ones), you have to press EQUAL (code 61) with SHIFT to access to \"+\". * @type {array} * @default */ \"PLUS\" : [ 107, //For keydown for numeric pad. 171, //For keydown for normal keyboard in Firefox. 187 //For keydown for normal keyboard in Chrome and IE8. ], /** * The \"-\" (minus) symbol key. * @type {array} * @default */ \"MINUS\" : [ 109, //For keydown for numeric pad. 173, //For keydown for normal keyboard in Firefox. Note: 173 is also used for \"MUTE\" 189, //For keydown for normal keyboard in Chrome and IE8. CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MINUS ], /** * The \"&amp;#42;\" (asterisk) symbol key. NOTE: In some keyboards (for example in Spanish for Spain ones), you have to press PLUS (code 187) with SHIFT to access to \"*\". * @type {array} * @default */ \"ASTERISK\" : [ //Note: For * and #, Nokia and Samsung report a keyCode of 56/51, Sony Ericsson reports a keyCode of 83/72, onkeypress Nokia, Samsung and Sony Ericsson report both as 42/35. //* Source: http://www.quirksmode.org/m/table.html 106 //For keydown for numeric pad. ], /** * The \"/\" (slash) symbol key. NOTE: In some keyboards (for example in Spanish for Spain ones), you have to press 7 (code 55) with SHIFT to access to \"/\". * @type {array} * @default */ \"SLASH\" : [ 111 //For keydown for numeric pad. ], /** * The \".\" (dot) symbol key. * @type {array} * @default */ \"DOT\" : [ 190 //For keydown for normal keyboard. ], /** * The \",\" (comma) symbol key. * @type {array} * @default */ \"COMMA\" : [ 188 //For keydown for normal keyboard. ], /** * The Home key. * @type {array} * @default */ \"HOME\" : [ 36, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.HOME : null ], /** * The End key. * @type {array} * @default */ \"END\" : [35], /** * The Page Up key. * @type {array} * @default */ \"PAGE_UP\" : [ 33, CB_Keyboard.extended.VK.PAGE_UP ], /** * The Page Down key. * @type {array} * @default */ \"PAGE_DOWN\" : [ 34, CB_Keyboard.extended.VK.PAGE_DOWN ], /** * The Ins (Insert) key. * @type {array} * @default */ \"INS\" : [45], /** * The Del (Delete) key. * @type {array} * @default */ \"DEL\" : [46], /** * The \"A\" key. * @type {array} * @default */ \"A\" : [65, CB_Keyboard.extended.VK.A], /** * The \"B\" key. * @type {array} * @default */ \"B\" : [66, CB_Keyboard.extended.VK.B], /** * The \"C\" key. * @type {array} * @default */ \"C\" : [67, CB_Keyboard.extended.VK.C], /** * The \"D\" key. * @type {array} * @default */ \"D\" : [68, CB_Keyboard.extended.VK.D], /** * The \"E\" key. * @type {array} * @default */ \"E\" : [69, CB_Keyboard.extended.VK.E], /** * The \"F\" key. * @type {array} * @default */ \"F\" : [70, CB_Keyboard.extended.VK.F], /** * The \"G\" key. * @type {array} * @default */ \"G\" : [71, CB_Keyboard.extended.VK.G], /** * The \"H\" key. * @type {array} * @default */ \"H\" : [72, CB_Keyboard.extended.VK.H], /** * The \"I\" key. * @type {array} * @default */ \"I\" : [73, CB_Keyboard.extended.VK.I], /** * The \"J\" key. * @type {array} * @default */ \"J\" : [74, CB_Keyboard.extended.VK.J], /** * The \"K\" key. * @type {array} * @default */ \"K\" : [75, CB_Keyboard.extended.VK.K], /** * The \"L\" key. * @type {array} * @default */ \"L\" : [76, CB_Keyboard.extended.VK.L], /** * The \"M\" key. * @type {array} * @default */ \"M\" : [77, CB_Keyboard.extended.VK.M], /** * The \"N\" key. * @type {array} * @default */ \"N\" : [78, CB_Keyboard.extended.VK.N], /** * The \"O\" key. * @type {array} * @default */ \"O\" : [79, CB_Keyboard.extended.VK.O], /** * The \"P\" key. * @type {array} * @default */ \"P\" : [80, CB_Keyboard.extended.VK.P], /** * The \"Q\" key. * @type {array} * @default */ \"Q\" : [81, CB_Keyboard.extended.VK.Q], /** * The \"R\" key. * @type {array} * @default */ \"R\" : [82, CB_Keyboard.extended.VK.R], /** * The \"S\" key. * @type {array} * @default */ \"S\" : [83, CB_Keyboard.extended.VK.S], /** * The \"T\" key. * @type {array} * @default */ \"T\" : [84, CB_Keyboard.extended.VK.T], /** * The \"U\" key. * @type {array} * @default */ \"U\" : [85, CB_Keyboard.extended.VK.U], /** * The \"V\" key. * @type {array} * @default */ \"V\" : [86, CB_Keyboard.extended.VK.V], /** * The \"W\" key. * @type {array} * @default */ \"W\" : [87, CB_Keyboard.extended.VK.W], /** * The \"X\" key. * @type {array} * @default */ \"X\" : [88, CB_Keyboard.extended.VK.X], /** * The \"Y\" key. * @type {array} * @default */ \"Y\" : [89, CB_Keyboard.extended.VK.Y], /** * The \"Z\" key. * @type {array} * @default */ \"Z\" : [90, CB_Keyboard.extended.VK.Z], /** * The Pause key. * @type {array} * @default */ \"PAUSE\" : [ 19, CB_Keyboard.extended.VK.PAUSE, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.PAUSE : null, //74 (same code as \"J\" key). CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_PAUSE, CB_Keyboard.extended.LG_SMART_TV_LINUX_35230.PAUSE ], /** * The Clear key. * @type {array} * @default */ \"CLEAR\" : [ 12, 254, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.CLEAR : null ], /** * The Select key (for Windows' Virtual keyboard). * @type {array} * @default */ \"SELECT\" : [41], /** * The Print key. * @type {array} * @default */ \"PRINT\" : [ 42, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.PRINT : null ], /** * The Print Screen key. * @type {array} * @default */ \"PRINT_SCREEN\" : [44], //Print screen key. Note: 44 is the same code as comma (\",\") keypress code. /** * The Execute key. * @type {array} * @default */ \"EXECUTE\" : [43], //Execute key. Note: 43 is the same code as plus (\"+\") keypress code. /** * The Help key. * @type {array} * @default */ \"HELP\" : //Help key. Note: 47 is the same code as slash (\"/\") keypress code: [ 47, CB_Keyboard.extended.VK.HELP, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.HELP : null ], /** * The Apps (Applications) key. * @type {array} * @default */ \"APPS\" : [93], /** * The Sleep key. * @type {array} * @default */ \"SLEEP\" : [ 95, CB_Keyboard.extended.SAMSUNG_TV.SLEEP //1097 ], /** * The Separator key. * @type {array} * @default */ \"SEPARATOR\" : [108], //Separator key. Note: 108 is the same code as L lowercase (\"l\") keypress code. /** * The Decimal key (for numeric pads). NOTE: In some decimal systems, as in Spanish, it is a comma (\",\"). Normally, numeric keypads in Spanish for Spain keyboards show a dot (\".\") but others as German keyboards shows a comma (\",\"). * @type {array} * @default */ \"DECIMAL\" : [110], /** * The Menu key. * @type {array} * @default */ \"MENU\" : [ 164, 165, CB_Keyboard.extended.SAMSUNG_TV.MENU, //262 CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.PANEL_MENU : null, CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MENU ], /** * The mouse's left button (for Windows' Virtual Keyboard). * @type {array} * @default */ \"MOUSE_LEFT_BUTTON\" : [1], /** * The mouse's middle button (for Windows' Virtual Keyboard). * @type {array} * @default */ \"MOUSE_MIDDLE_BUTTON\" : [4], /** * The mouse's right button (for Windows' Virtual Keyboard). * @type {array} * @default */ \"MOUSE_RIGHT_BUTTON\" : [2], //For Windows' Virtual keyboard. /** * The mouse's X1 button (for Windows' Virtual Keyboard). * @type {array} * @default */ \"MOUSE_X1_BUTTON\" : [5], //For Windows' Virtual keyboard. /** * The mouse's X2 button (for Windows' Virtual Keyboard). * @type {array} * @default */ \"MOUSE_X2_BUTTON\" : [6], //For Windows' Virtual keyboard. /** * The Mute key. * @type {array} * @default */ \"MUTE\" : //Mute key. Note: 173 is the same code as minus (\"-\" symbol) in normal keyboard in Firefox: [ 173, 181, CB_Keyboard.extended.VK.MUTE, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.MUTE : null, //Same code as ESC key (27). CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MUTE ], /** * The Volume Up key. * @type {array} * @default */ \"VOL_UP\" : //Volume up key. Note: 175 is same code as \"UP\" for Wii (Wiimote) D-PAD: [ 175, 183, CB_Keyboard.extended.VK.VOLUME_UP, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.VOLUP : null, CB_Keyboard.extended.SAMSUNG_TV.VOL_UP, //7 CB_Keyboard.extended.SAMSUNG_TV.PANEL_VOL_UP, //203 CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.PANEL_VOLUP : null, CB_Keyboard.extended.SAMSUNG_TIZEN_TV.VOLUME_UP ], /** * The Volume Down key. * @type {array} * @default */ \"VOL_DOWN\" : [ 174, 182, CB_Keyboard.extended.VK.VOLUME_DOWN, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.VOLDOWN : null, CB_Keyboard.extended.SAMSUNG_TV.VOL_DOWN, //1 CB_Keyboard.extended.SAMSUNG_TV.PANEL_VOL_DOWN, //204 CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.PANEL_VOLDOW : null, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.PANEL_VOLDOWN : null, CB_Keyboard.extended.SAMSUNG_TIZEN_TV.VOLUME_DOWN ], /** * The Multimedia Forward key. * @type {array} * @default */ \"MEDIA_FORWARD\" : //Multimedia forward key. Note: 176 is same code as \"DOWN\" for Wii (Wiimote) D-PAD: [ 176, 228, CB_Keyboard.extended.LG_SMART_TV_LINUX_35230.FORWARD, //LG Smart TV (Linux 35230). CB_Keyboard.extended.VK.FAST_FWD, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV.FF_, //1078 CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.FF : null, //72 (same code as \"H\" key). CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_FORWARD, CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE.FF ], /** * The Multimedia Rewind key. * @type {array} * @default */ \"MEDIA_REWIND\" : //Multimedia rewind key. Note: 177 is same code as \"RIGHT\" for Wii (Wiimote) D-PAD: [ 177, 227, CB_Keyboard.extended.VK.REWIND, //Smart TV Alliance. CB_Keyboard.extended.LG_SMART_TV_LINUX_35230.REWIND, //LG Smart TV (Linux 35230). CB_Keyboard.extended.SAMSUNG_TV.REWIND_, //1080 CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.RW : null, //69 (same code as \"E\" key). CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.REWIND : null, CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_REWIND, CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE.RW ], /** * The Multimedia Stop key. * @type {array} * @default */ \"MEDIA_STOP\" : //Multimedia stop key. Note: 178 is same code as \"LEFT\" for Wii (Wiimote) D-PAD: [ 178, CB_Keyboard.extended.VK.STOP, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.STOP : null, //70 (same code as \"F\" key). CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_STOP ], /** * The Multimedia Play/Pause key. * @type {array} * @default */ \"MEDIA_PLAY_PAUSE\" : [ 179, CB_Keyboard.extended.VK.PLAY_PAUSE, CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_PLAY_PAUSE, CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE.PLAY_PAUSE ], /** * The Browser's Back key. * @type {array} * @default */ \"BROWSER_BACK\" : [ 166, CB_Keyboard.extended.VK.PREV, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.RETURN : null, //Same code as \"X\" key (88). CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.PANEL_RETURN : null, CB_Keyboard.extended.SAMSUNG_TIZEN_TV.RETURN, CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_TRACK_PREVIOUS, CB_Keyboard.extended.VK.BACK //Smart TV Alliance. ], /** * The Browser's Forward key. * @type {array} * @default */ \"BROWSER_FORWARD\" : [ 167, CB_Keyboard.extended.VK.NEXT, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_TRACK_NEXT ], /** * The Browser's Refresh (Reload) key. * @type {array} * @default */ \"BROWSER_REFRESH\" : [168], /** * The Browser's Stop key. * @type {array} * @default */ \"BROWSER_STOP\" : [169], /** * The Browser's Search key. * @type {array} * @default */ \"BROWSER_SEARCH\" : [ 170, CB_Keyboard.extended.VK._allowDuplicateKeyAliases ? CB_Keyboard.extended.VK.SEARCH : null, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.SEARCH : null, CB_Keyboard.extended.SAMSUNG_TIZEN_TV.SEARCH ], /** * The Browser's Favorites key. * @type {array} * @default */ \"BROWSER_FAVORITES\" : [171], //Browser favourites key. Note: 171 is the same code as plus (\"+\") in normal keyboard in Firefox. /** * The Browser's Home key. * @type {array} * @default */ \"BROWSER_HOME\" : [ 172 ], /** * The Mail key. * @type {array} * @default */ \"MAIL\" : [180], /** * The Select Media key. * @type {array} * @default */ \"MEDIA_SELECT\" : [181], //Select media key. Note: 181 is the same code as mute key. /** * The App1 key. * @type {array} * @default */ \"APP1\" : [182], //App1 key. Note: 182 is the same code as volume down key. /** * The App2 key. * @type {array} * @default */ \"APP2\" : [183], //App2 key. Note: 182 is the same code as volume up key. /** * The Attn key. * @type {array} * @default */ \"ATTN\" : [246], /** * The CrSel key. * @type {array} * @default */ \"CRSEL\" : [247], /** * The ExSel key. * @type {array} * @default */ \"EXSEL\" : [248], /** * The EREOF (Erase EOF) key. * @type {array} * @default */ \"EREOF\" : [249], /** * The Play key. * @type {array} * @default */ \"PLAY\" : [ 250, CB_Keyboard.extended.LG_SMART_TV_LINUX_35230.PLAY, //LG Smart TV (Linux 35230). CB_Keyboard.extended.VK.PLAY, //Smart TV Alliance. CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.PLAY : null, //71 (same code as \"G\" key). CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_PLAY ], /** * The Zoom key. * @type {array} * @default */ \"ZOOM\" : [ 251, CB_Keyboard.extended.SAMSUNG_TV.ZOOM1, //1083 CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.ZOOM2 : null, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.ZOOM_IN : null//, //CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.ZOOM_OUT : null ], /** * The PA1 key. * @type {array} * @default */ \"PA1\" : [253], /** * The Info (Information) key. * @type {array} * @default */ \"INFO\" : [ CB_Keyboard.extended.VK.INFO, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.INFO : null, //31 CB_Keyboard.extended.SAMSUNG_TIZEN_TV.INFO ], /** * The Audio Description key. * @type {array} * @default */ \"AUDIODESCRIPTION\" : [ CB_Keyboard.extended.VK._allowDuplicateKeyAliases ? CB_Keyboard.extended.VK.AUDIODESCRIPTION : null, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.CAPTION : null, CB_Keyboard.extended.SAMSUNG_TIZEN_TV.CAPTION ], /** * The Subtitle key. * @type {array} * @default */ \"SUBTITLE\" : [ CB_Keyboard.extended.VK.SUBTITLE, CB_Keyboard.extended.SAMSUNG_TV.SUBTITLE, //652 CB_Keyboard.extended.SAMSUNG_TV.SUB_TITLE //1089 ], /** * The HD (High Definition) key. * @type {array} * @default */ \"HD\" : [ CB_Keyboard.extended.VK._allowDuplicateKeyAliases ? CB_Keyboard.extended.VK.HD : null ], /** * The Red colour button. * @type {array} * @default */ \"RED\" : [ CB_Keyboard.extended.VK.RED, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.RED : null, //Same code as SEPARATOR key (108). CB_Keyboard.extended.SAMSUNG_TIZEN_TV.RED ], /** * The Green colour button. * @type {array} * @default */ \"GREEN\" : [ CB_Keyboard.extended.VK.GREEN, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.GREEN : null, //Same code as CAPS_LOCK key (20). CB_Keyboard.extended.SAMSUNG_TIZEN_TV.GREEN ], /** * The Yellow colour button. * @type {array} * @default */ \"YELLOW\" : [ CB_Keyboard.extended.VK.YELLOW, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.YELLOW : null, //21 CB_Keyboard.extended.SAMSUNG_TIZEN_TV.YELLOW ], /** * The Blue colour button. * @type {array} * @default */ \"BLUE\" : [ CB_Keyboard.extended.VK.BLUE, CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.BLUE : null, //22 CB_Keyboard.extended.SAMSUNG_TIZEN_TV.BLUE ], /** * The Cyan colour button. * @type {array} * @default */ \"CYAN\" : [ CB_Keyboard.extended.SAMSUNG_TV._allowDuplicateKeyAliases ? CB_Keyboard.extended.SAMSUNG_TV.CYAN : null ] }; for (CB_Keyboard._x = 0; CB_Keyboard._x &lt; 10; CB_Keyboard._x++) { CB_Keyboard.keys[\"_\" + CB_Keyboard._x] = CB_Keyboard.keys[CB_Keyboard._x]; } //Sets CB_Keyboard.keys._NUMBER = CB_Keyboard.keys[NUMBER] from 0 to 9. CB_Keyboard._x = undefined; /** * Object whose properties are aliases for char codes (each property can contain an array with one or more integers which belong to the char codes). * @namespace * @type {Object} */ CB_Keyboard.chars = { /** * The \"0\" (zero) character. * @type {array} * @default */ \"0\" : [48], /** * The \"1\" character. * @type {array} * @default */ \"1\" : [49], /** * The \"2\" character. * @type {array} * @default */ \"2\" : [50], /** * The \"3\" character. * @type {array} * @default */ \"3\" : [51], /** * The \"4\" character. * @type {array} * @default */ \"4\" : [52], /** * The \"5\" character. * @type {array} * @default */ \"5\" : [53], /** * The \"6\" character. * @type {array} * @default */ \"6\" : [54], /** * The \"7\" character. * @type {array} * @default */ \"7\" : [55], /** * The \"8\" character. * @type {array} * @default */ \"8\" : [56], /** * The \"9\" character. * @type {array} * @default */ \"9\" : [57], /** * The \"+\" (plus) character. * @type {array} * @default */ \"PLUS\" : [43], /** * The \"-\" (minus) character. * @type {array} * @default */ \"MINUS\" : [45], /** * The \"*\" (asterisk) character. * @type {array} * @default */ \"ASTERISK\" : [42], /** * The \"/\" (slash) character. * @type {array} * @default */ \"SLASH\" : [47], /** * The \".\" (dot) character. * @type {array} * @default */ \"DOT\" : [46], /** * The \",\" (comma) character. * @type {array} * @default */ \"COMMA\" : [44], /** * The \"A\" letter, upper case (capitalized). * @type {array} * @default */ \"A\" : [65], /** * The \"a\" letter, lower case. * @type {array} * @default */ \"a\" : [97], /** * The \"B\" letter, upper case (capitalized). * @type {array} * @default */ \"B\" : [66], /** * The \"b\" letter, lower case. * @type {array} * @default */ \"b\" : [98], /** * The \"C\" letter, upper case (capitalized). * @type {array} * @default */ \"C\" : [67], /** * The \"c\" letter, lower case. * @type {array} * @default */ \"c\" : [99], /** * The \"D\" letter, upper case (capitalized). * @type {array} * @default */ \"D\" : [68], /** * The \"d\" letter, lower case. * @type {array} * @default */ \"d\" : [100], /** * The \"E\" letter, upper case (capitalized). * @type {array} * @default */ \"E\" : [69], /** * The \"e\" letter, lower case. * @type {array} * @default */ \"e\" : [101], /** * The \"F\" letter, upper case (capitalized). * @type {array} * @default */ \"F\" : [70], /** * The \"f\" letter, lower case. * @type {array} * @default */ \"f\" : [102], /** * The \"G\" letter, upper case (capitalized). * @type {array} * @default */ \"G\" : [71], /** * The \"g\" letter, lower case. * @type {array} * @default */ \"g\" : [103], /** * The \"H\" letter, upper case (capitalized). * @type {array} * @default */ \"H\" : [72], /** * The \"h\" letter, lower case. * @type {array} * @default */ \"h\" : [104], /** * The \"I\" letter, upper case (capitalized). * @type {array} * @default */ \"I\" : [73], /** * The \"i\" letter, lower case. * @type {array} * @default */ \"i\" : [105], /** * The \"J\" letter, upper case (capitalized). * @type {array} * @default */ \"J\" : [74], /** * The \"j\" letter, lower case. * @type {array} * @default */ \"j\" : [106], /** * The \"K\" letter, upper case (capitalized). * @type {array} * @default */ \"K\" : [75], /** * The \"k\" letter, lower case. * @type {array} * @default */ \"k\" : [107], /** * The \"L\" letter, upper case (capitalized). * @type {array} * @default */ \"L\" : [76], /** * The \"l\" letter, lower case. * @type {array} * @default */ \"l\" : [108], /** * The \"M\" letter, upper case (capitalized). * @type {array} * @default */ \"M\" : [77], /** * The \"m\" letter, lower case. * @type {array} * @default */ \"m\" : [109], /** * The \"N\" letter, upper case (capitalized). * @type {array} * @default */ \"N\" : [78], /** * The \"n\" letter, lower case. * @type {array} * @default */ \"n\" : [110], /** * The \"O\" letter, upper case (capitalized). * @type {array} * @default */ \"O\" : [79], /** * The \"o\" letter, lower case. * @type {array} * @default */ \"o\" : [111], /** * The \"P\" letter, upper case (capitalized). * @type {array} * @default */ \"P\" : [80], /** * The \"p\" letter, lower case. * @type {array} * @default */ \"p\" : [112], /** * The \"Q\" letter, upper case (capitalized). * @type {array} * @default */ \"Q\" : [81], /** * The \"q\" letter, lower case. * @type {array} * @default */ \"q\" : [113], /** * The \"R\" letter, upper case (capitalized). * @type {array} * @default */ \"R\" : [82], /** * The \"r\" letter, lower case. * @type {array} * @default */ \"r\" : [114], /** * The \"S\" letter, upper case (capitalized). * @type {array} * @default */ \"S\" : [83], /** * The \"s\" letter, lower case. * @type {array} * @default */ \"s\" : [115], /** * The \"T\" letter, upper case (capitalized). * @type {array} * @default */ \"T\" : [84], /** * The \"t\" letter, lower case. * @type {array} * @default */ \"t\" : [116], /** * The \"U\" letter, upper case (capitalized). * @type {array} * @default */ \"U\" : [85], /** * The \"u\" letter, lower case. * @type {array} * @default */ \"u\" : [117], /** * The \"V\" letter, upper case (capitalized). * @type {array} * @default */ \"V\" : [86], /** * The \"v\" letter, lower case. * @type {array} * @default */ \"v\" : [118], /** * The \"W\" letter, upper case (capitalized). * @type {array} * @default */ \"W\" : [87], /** * The \"w\" letter, lower case. * @type {array} * @default */ \"w\" : [119], /** * The \"X\" letter, upper case (capitalized). * @type {array} * @default */ \"X\" : [88], /** * The \"x\" letter, lower case. * @type {array} * @default */ \"x\" : [120], /** * The \"Y\" letter, upper case (capitalized). * @type {array} * @default */ \"Y\" : [89], /** * The \"y\" letter, lower case. * @type {array} * @default */ \"y\" : [121], /** * The \"Z\" letter, upper case (capitalized). * @type {array} * @default */ \"Z\" : [90], /** * The \"z\" letter, lower case. * @type {array} * @default */ \"z\" : [122] }; //Initializes all values: CB_Keyboard.init = function() { if (CB_Keyboard.initialized) { return CB_Keyboard; } //The object has been initialized: CB_Keyboard.initialized = true; //Removes possible key codes duplicated or not really defined (undefined or null): for (var k in CB_Keyboard.keys) { CB_Keyboard.keys[k] = CB_Arrays.removeDuplicated(CB_Keyboard.keys[k], function(v) { return (typeof(v) === \"undefined\" || v === null || isNaN(v)); }); } //Every time that focus is lost, it will clear the keysDown array: ////CB_Events.add(window, \"blur\", function() { CB_Keyboard.keysDown = {}; }, true, true, false); try //using catch due some web clients doesn't allow to manipulate the window object of parent iframes: { //CB_Events.add(CB_Client.getWindow(), \"blur\", function() { CB_Keyboard.keysDown = {}; }, true, true, false); CB_Events.add(CB_Client.getWindow(), \"blur\", CB_Keyboard.clearKeysDown, true, true, false); } catch(E) { //CB_Events.add(window, \"blur\", function() { CB_Keyboard.keysDown = {}; }, true, true, false); CB_Events.add(window, \"blur\", CB_Keyboard.clearKeysDown, true, true, false); } //Every time that visibility is changed, it will clear the array: //CB_Screen.onVisibilityChange(function() { CB_Keyboard.keysDown = {}; }); //Sets the default keyboard events: CB_Keyboard._setDefaultEvents(); return CB_Keyboard; } //Sets the default Keyboard events to an object (document by default): CB_Keyboard._setDefaultEvents = function(target) { if (typeof(target) === \"undefined\" || target === null) { target = document; } var keyDownCallbackFunction = undefined; //If we want to prevent the Firefox bug that affects SockJS library (see https://github.com/sockjs/sockjs-client/issues/18): if (CB_Configuration[CB_BASE_NAME].CB_Net_Sockets_PREVENT_FIREFOX_ESC_BUG) { keyDownCallbackFunction = function(e, keyDown, updateKeysPressed, callbackFunction, keyCode) { if (keyCode === 27) { e.preventDefault(); } }; } //Sets the event that will check if a key is down: CB_Events.add(target, \"keydown\", function(e) { /*e = CB_Events.normalize(e);*/ CB_Keyboard._updateKeysDown(e, true, true, keyDownCallbackFunction); }, true, true, false); //Prevents F11 key if the web client is compatible with Fullscreen API: //CB_Events.add(target, \"keydown\", function(e) { e = CB_Events.normalize(e); CB_Keyboard.preventF11Key(e); }, true, true, false); //Sets the event that will check if a key is released: CB_Events.add(target, \"keyup\", function(e) { /*e = CB_Events.normalize(e);*/ CB_Keyboard._updateKeysDown(e, false, true); }, true, true, false); //Sets the event that will store the typed string (or clear it): //CB_Events.add(target, \"keydown\", function(e) { /*e = CB_Events.normalize(e);*/ CB_Keyboard._updateTypedString(e); }, true, true, false); CB_Events.add(target, \"keypress\", function(e) { /*e = CB_Events.normalize(e);*/ CB_Keyboard._updateTypedString(e); }, true, true, false); } /** * Tries to return the given [keyboard event]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent} with some properties normalized (since different clients can use different values) and perhaps some new properties added (in the case they were missing), when possible. The new attached methods and properties may include polyfills, etc. It also calls the {@link CB_Events.normalize} function internally. Some properties added or affected could be [keyCode]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode}, [location]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/location}, [ctrlKey]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/ctrlKey}, [altKey]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/altKey}, [shiftKey]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/shiftKey}, etc. * @function * @param {Event} e - [Keyboard event]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent} object. If not provided, it will use the value of \"event\", \"window.event\", \"Event\" or an empty object (\"{}\"). * @returns {Event} Returns the [keyboard event]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent} object normalized. * @todo Calculate (if possible) the values for location, ctrlKey, altKey, etc. when added, to simulate the expected behaviour. */ CB_Keyboard.normalizeEvent = function(e) { e = CB_Events.normalize(e); //If the web client doesn't support it, sets the keyCode property: if (typeof(e.keyCode) === \"undefined\" || e.keyCode === null) { e.keyCode = CB_Keyboard.getKeyCode(e, true); } //Sometimes the property keyCode cannot be overwritten, so we defines this function: e.getKeyCode = e.getKeyCode || function() { return CB_Keyboard.getKeyCode(this); }; //If the web client doesn't support it, sets the location property: if (typeof(e.location) === \"undefined\" || e.location === null) { e.location = e.keyLocation ? e.keyLocation : 0; } //If the web client doesn't support it, determines whether the CTRL, ALT, SHIFT or META keys are pressed: if (typeof(e.ctrlKey) === \"undefined\" || e.ctrlKey === null) { e.ctrlKey = CB_Keyboard.isKeyDown(CB_Keyboard.keys.CTRL); } if (typeof(e.altKey) === \"undefined\" || e.altKey === null) { e.altKey = CB_Keyboard.isKeyDown(CB_Keyboard.keys.ALT); } if (typeof(e.shiftKey) === \"undefined\" || e.shiftKey === null) { e.shiftKey = CB_Keyboard.isKeyDown(CB_Keyboard.keys.SHIFT); } /*if (typeof(e.metaKey) === \"undefined\" || e.metaKey === null) { e.metaKey = CB_Keyboard.isKeyDown(CB_Keyboard.keys.META); }*/ return e; } /** * Returns the key code that is contained in the given [keyboard event]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent}. * @function * @param {Event} e - [Keyboard event]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent} object. * @param {boolean} [avoidNormalize=false] - If it is not set to true, it will call the {@link CB_Events.normalize} function internally before. * @returns {integer} Returns the key code. * @todo Have in mind that [keyCode]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode} is deprecated. */ CB_Keyboard.getKeyCode = function(e, avoidNormalize) { if (!avoidNormalize) { e = CB_Events.normalize(e); } var keyCode = null; if (e.keyCode) { keyCode = e.keyCode; } else if (e.key &amp;&amp; typeof(e.key) === \"number\") { keyCode = e.key; } //For SLCanvas. else if (window.Event &amp;&amp; e.which) { keyCode = e.which; } else if (typeof(e.charCode) === \"number\") { keyCode = e.charCode; } return keyCode; } //Updates array keysDown (this is called whenever a key is down or released): CB_Keyboard._updateKeysDown = function(e, keyDown, updateKeysPressed, callbackFunction) { //By default, updates keys pressed array: if (typeof(updateKeysPressed) === \"undefined\" || updateKeysPressed === null) { updateKeysPressed = true; } //Defines the code of the key pressed: //e = CB_Events.normalize(e); e = CB_Keyboard.normalizeEvent(e); //var keyCode = CB_Keyboard.getKeyCode(e); //var keyCode = e.keyCode; var keyCode = e.getKeyCode(); //If the key code is defined: if (keyCode !== null) { //Sets the status of the key (being pressed/down or relased): CB_Keyboard.keysDown[keyCode] = keyDown; //If pressed, stores the key code pressed in the keys pressed array: if (updateKeysPressed &amp;&amp; keyDown) { CB_Keyboard._updateKeysPressed(keyCode); } if (typeof(callbackFunction) === \"function\") { callbackFunction(e, keyDown, updateKeysPressed, callbackFunction, keyCode); } } } /** * Clears (empties totally or partially) the {@link CB_Keyboard.keysDown} object which contains the detected keys pressed or released. * @function * @param {boolean} keepPressed - If set to true, it will keep the pressed keys. */ CB_Keyboard.clearKeysDown = function(keepPressed) { if (!keepPressed) { CB_Keyboard.keysDown = {}; } else { var keysDown = {}; for (var keyCode in CB_Keyboard.keysDown) { if (CB_Keyboard.keysDown[keyCode]) { keysDown[keyCode] = true; } } CB_Keyboard.keysDown = keysDown; } } /** * Returns the {@link CB_Keyboard.keysDown} object which contains the detected keys pressed or released. * @function * @returns {Object} Returns the {@link CB_Keyboard.keysDown} object. */ CB_Keyboard.getKeysDown = function() { return CB_Keyboard.keysDown; } /** * Returns whether the given key codes are being pressed (any of them or all at the same time, depending on the \"allPressed\" parameter). * @function * @param {integer|array|Object} keyCodes - An integer with the key code or a numeric array with the key codes that we want to check. It can also be an array of arrays, being each element a numeric array with the key codes that we want to check. Although not recommended (for performance purposes), this parameter can also support an object whose indexes are the keycodes (it will be converted to a numeric array internally). * @param {boolean} [allPressed=false] - If set true, the function will only return true in the case that all given key codes are currently being pressed. Otherwise, if set to false, the function will return true in the case that any of the given key codes is currently being pressed. When the \"keyCodes\" is an array of arrays with key codes, it will be considered that all keys are being pressed if each single array (all of them) has at least one of its key codes pressed. * @returns {boolean} If \"allPressed\" parameter is set to true, returns true in the case that all given key codes are currently being pressed. If \"allPressed\" parameter is set to false, returns true in the case that any of the given key codes is currently being pressed. In all other cases, it returns false. */ CB_Keyboard.isKeyDown = function(keyCodes, allPressed) { var isDown = false; //If the parameter given is not an array, we force it to be an array: if (!isNaN(keyCodes)) { keyCodes = [parseInt(keyCodes)]; } //If a number has been received, it will be the first and unique element of the array. Note that parseInt could return a NaN. if (!CB_isArray(keyCodes)) //If we have received an object which is not an array: { var keyCodesArray = []; for (var keyCode in keyCodes) { if (!isNaN(keyCode)) { keyCodesArray[keyCodesArray.length] = parseInt(keyCode); } //Only stores } keyCodes = keyCodesArray; } var keysDown = CB_Keyboard.getKeysDown(); var keyCodesLength = keyCodes.length; for (var x = 0; x &lt; keyCodesLength; x++) { //If the code given is a number, it exists in the keysDown array and it is being pressed: if (typeof(keyCodes[x]) !== \"undefined\" &amp;&amp; keyCodes[x] !== null &amp;&amp; !isNaN(keyCodes[x]) &amp;&amp; typeof(keysDown[keyCodes[x]]) !== \"undefined\" &amp;&amp; keysDown[keyCodes[x]]) { isDown = true; //if (!allPressed) { break; } } //...otherwise, if the value belongs to an array, calls itself recursively: else if (CB_isArray(keyCodes[x])) { isDown = CB_Keyboard.isKeyDown(keyCodes[x], false); //If any key is pressed is enough. } //...otherwise, if the user wanted to know whether all given keys were pressed: else if (allPressed) { //Not all given keys are pressed so it exits: isDown = false; //break; } if (allPressed &amp;&amp; !isDown) { break; } else if (!allPressed &amp;&amp; isDown) { break; } //If the user does not want to know whether all are keys given are pressed, with one is enough so it exits. } return isDown; } //Updates the keys pressed array: CB_Keyboard._updateKeysPressed = function(keyCode) { //Clears the timeout that clears the keys pressed: clearTimeout(CB_Keyboard._keysPressedExpirationTimeout); //Updates the keys pressed and its codes: CB_Keyboard.keysPressed[CB_Keyboard.keysPressed.length] = keyCode; //Sets the timeout that clears the array after some milliseconds: CB_Keyboard._keysPressedExpirationTimeout = setTimeout ( function() { CB_Keyboard.keysPressed = []; }, CB_Keyboard._keysPressedExpiration ); } /** * Clears (empties totally or partially) the {@link CB_Keyboard.keysPressed} array which contains the key codes pressed recently. * @function * @param {boolean} keepPressed - If set to true, it will keep the pressed keys (taken from the {@link CB_Keyboard.keysDown} object). */ CB_Keyboard.clearKeysPressed = function(keepPressed) { //Clears the timeout that clears the keys pressed: clearTimeout(CB_Keyboard._keysPressedExpirationTimeout); if (!keepPressed) { CB_Keyboard.keysPressed = []; } else { var keysPressed = []; for (var keyCode in CB_Keyboard.keysDown) { if (CB_Keyboard.keysDown[keyCode]) { keysPressed[keysPressed.length] = keyCode; } } CB_Keyboard.keysPressed = keysPressed; } } /** * Returns the {@link CB_Keyboard.keysPressed} array which contains the key codes pressed recently (it will be cleared after the chosen milliseconds set with the {@link CB_Keyboard.setKeysPressedExpiration} function). * @function * @returns {array} Returns the {@link CB_Keyboard.keysPressed} array. */ CB_Keyboard.getKeysPressed = function() { return CB_Keyboard.keysPressed; } /** * Sets the milliseconds after which the {@link CB_Keyboard.keysPressed} array is always cleared (emptied). The time always starts counting from zero when a key is pressed ([onKeyDown]{@link https://developer.mozilla.org/en-US/docs/Web/Events/keydown} event is fired). * @function * @param {integer} keysPressedExpiration - An integer greater than 0 (zero) representing the milliseconds after which we desire that the {@link CB_Keyboard.keysPressed} array is cleared (emptied), if no key is pressed during this time. * @returns {boolean} Returns true if the given time could be applied or false otherwise. */ CB_Keyboard.setKeysPressedExpiration = function(keysPressedExpiration) { //Only allows numbers greater than zero: if (typeof(keysPressedExpiration) !== \"undefined\" &amp;&amp; keysPressedExpiration !== null &amp;&amp; !isNaN(keysPressedExpiration) &amp;&amp; keysPressedExpiration &gt; 0) { CB_Keyboard._keysPressedExpiration = parseInt(keysPressedExpiration); return true; } return false; } /** * Returns the milliseconds after which the {@link CB_Keyboard.keysPressed} array is always cleared (emptied). The time always starts counting from zero again when a key is pressed ([onKeyDown]{@link https://developer.mozilla.org/en-US/docs/Web/Events/keydown} event is fired). To define this amount of time, the {@link CB_Keyboard.setKeysPressedExpiration} method must be used. * @function * @returns {integer} Returns the milliseconds of expiration defined for the {@link CB_Keyboard.keysPressed} array. */ CB_Keyboard.getKeysPressedExpiration = function() { return CB_Keyboard._keysPressedExpiration; } //Updates the string typed (CAUTION: using String.fromCharCode(keyCode) internally as keyCode was a char code and it is not!): CB_Keyboard._updateTypedString = function(e) { //Clears the timeout that clears the typed string: clearTimeout(CB_Keyboard._typedStringExpirationTimeout); //Defines the code of the key pressed: //e = CB_Events.normalize(e); e = CB_Keyboard.normalizeEvent(e); //var keyCode = CB_Keyboard.getKeyCode(e); var keyCode = e.getKeyCode(); //var keyCode = e.keyCode; if (keyCode !== null) { //Gets the character typed: var characterTyped = String.fromCharCode(keyCode); //CAUTION: using keyCode as it was a char code and it is not! //var charCode = keyCode - 48 * Math.floor(keyCode / 48); //var characterTyped = String.fromCharCode((keyCode &gt; 96) ? keyCode : charCode); //Updates the string typed and its codes: CB_Keyboard.typedStringCodes[CB_Keyboard.typedStringCodes.length] = keyCode; CB_Keyboard.typedString += characterTyped; //Easter egg: if (CB_Keyboard.typedString.substring(CB_Keyboard.typedString.length - 11) === \"CrossBrowdy\") { setTimeout ( function() { alert(\"Congratulations, you have found a CrossBrowdy Eastern egg!!! ;)\"); CB_Keyboard.typedStringCodes = []; //Clears the typed string codes. CB_Keyboard.typedString = \"\"; //Clears the typed string. }, 100 ); //Executes the function after some milliseconds allowing others get the typed string updated. } //Sets the timeout that clears the string after some milliseconds: CB_Keyboard._typedStringExpirationTimeout = setTimeout ( function() { CB_Keyboard.typedStringCodes = []; CB_Keyboard.typedString = \"\"; }, CB_Keyboard._typedStringExpiration ); } } /** * Clears (empties totally or partially) the {@link CB_Keyboard.typedString} string and the {@link CB_Keyboard.typedStringCodes} array. * @function * @param {boolean} keepPressed - If set to true, it will keep the values belonging to the currently-pressed keys (taken from the {@link CB_Keyboard.keysDown} object). */ CB_Keyboard.clearTypedString = function(keepPressed) //CAUTION: using String.fromCharCode(keyCode) internally as keyCode was a char code and it is not! { //Clears the timeout that clears the typed string: clearTimeout(CB_Keyboard._typedStringExpirationTimeout); if (!keepPressed) { CB_Keyboard.typedStringCodes = []; CB_Keyboard.typedString = \"\"; } else { var typedStringCodes = []; var typedString = \"\"; var characterTyped = null; var keyCode = null; var typedStringCodesLength = CB_Keyboard.typedStringCodes.length; for (var x = 0; x &lt; typedStringCodesLength; x++) { keyCode = CB_Keyboard.typedStringCodes[x]; if (CB_Keyboard.keysDown[keyCode]) { typedStringCodes[typedStringCodes.length] = keyCode; characterTyped = String.fromCharCode(keyCode); //CAUTION: using keyCode as it was a char code and it is not! typedString += characterTyped; } } /* for (var keyCode in CB_Keyboard.keysDown) { if (CB_Keyboard.keysDown[keyCode]) { typedStringCodes[typedStringCodes.length] = keyCode; characterTyped = String.fromCharCode(keyCode); //CAUTION: using keyCode as it was a char code and it is not! typedString += characterTyped; } } */ CB_Keyboard.typedStringCodes = typedStringCodes; CB_Keyboard.typedString = typedString; } } /** * Returns the {@link CB_Keyboard.typedString} string which contains the string typed recently (it will be cleared after the chosen milliseconds set with the {@link CB_Keyboard.setTypedStringExpiration} function). * @function * @returns {string} Returns the {@link CB_Keyboard.typedString} string. */ CB_Keyboard.getTypedString = function() { return CB_Keyboard.typedString; } /** * Returns the {@link CB_Keyboard.typedStringCodes} array which contains the key codes pressed that belongs to the string typed recently (it will be cleared after the chosen milliseconds set with the {@link CB_Keyboard.setTypedStringExpiration} function). * @function * @returns {array} Returns the {@link CB_Keyboard.typedStringCodes} array. */ CB_Keyboard.getTypedStringCodes = function() { return CB_Keyboard.typedStringCodes; } /** * Sets the milliseconds after which the {@link CB_Keyboard.typedString} string and the {@link CB_Keyboard.typedStringCodes} array are always cleared (emptied). The time always starts counting from zero when a key is pressed ([onKeyPress]{@link https://developer.mozilla.org/en-US/docs/Web/Events/keypress} event is fired). * @function * @param {integer} keysPressedExpiration - An integer greater than 0 (zero) representing the milliseconds after which we desire that the {@link CB_Keyboard.typedString} string and the {@link CB_Keyboard.typedStringCodes} array are cleared (emptied), if no key is pressed during this time. * @returns {boolean} Returns true if the given time could be applied or false otherwise. */ CB_Keyboard.setTypedStringExpiration = function(typedStringExpiration) { //Only allows numbers greater than zero: if (typeof(typedStringExpiration) !== \"undefined\" &amp;&amp; typedStringExpiration !== null &amp;&amp; !isNaN(typedStringExpiration) &amp;&amp; typedStringExpiration &gt; 0) { CB_Keyboard._typedStringExpiration = parseInt(typedStringExpiration); return true; } return false; } /** * Returns the milliseconds after which the {@link CB_Keyboard.typedString} string and the {@link CB_Keyboard.typedStringCodes} array are always cleared (emptied). The time always starts counting from zero again when a key is pressed ([onKeyPress]{@link https://developer.mozilla.org/en-US/docs/Web/Events/keypress} event is fired). To define this amount of time, the {@link CB_Keyboard.setTypedStringExpiration} method must be used. * @function * @returns {integer} Returns the milliseconds of expiration defined for the {@link CB_Keyboard.typedString} string and the {@link CB_Keyboard.typedStringCodes} array. */ CB_Keyboard.getTypedStringExpiration = function() { return CB_Keyboard._typedStringExpiration; } /** * Tries to prevent the default behaviour that would produce the \"F11\" key of a given [keyboard event]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent} when the client is compatible with the HTML5 Fullscreen API and uses it to toggle (enable or disable) the fullscreen mode. It calls the {@link CB_Keyboard.normalizeEvent} function internally. * @function * @param {Event} e - [Keyboard event]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent} object. */ CB_Keyboard.preventF11Key = function(e) { //e = CB_Events.normalize(e); e = CB_Keyboard.normalizeEvent(e); //var keyCode = CB_Keyboard.getKeyCode(e); //var keyCode = e.keyCode; var keyCode = e.getKeyCode(); //If the F11 key has been pressed: if (CB_Keyboard.keys.F11.indexOf(keyCode) !== -1) { //If it's compatible with the FullScreen API, Prevents the use of F11 key and uses FullScreen API instead: if (CB_Screen.isFullScreenAPICompatible() &amp;&amp; typeof(e.preventDefault) !== \"undefined\" &amp;&amp; e.preventDefault !== null) { //If it's in fullscreen mode, we cancel it: if (CB_Screen.isFullScreen()) { //setTimeout(function(){CB_Screen.setFullScreen(false);},100); CB_Screen.setFullScreen(false); } //...otherwise, we request fullscreen mode: else { //setTimeout(function(){CB_Screen.setFullScreen();},100); CB_Screen.setFullScreen(); } e.preventDefault(); } } } /** * Callback that is called before loading a file and should return true if we want to load the file or false otherwise. * @memberof CB_Keyboard * @callback CB_Keyboard.EVENT_CALLBACK * @param {Event} e - [Keyboard event]{@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent} object. * @param {integer} keyCode - Key code which fired the event. */ /** * Sets a function to execute when a key is pressed ([onKeyPress]{@link https://developer.mozilla.org/en-US/docs/Web/Events/keypress} event) or removes it. * @function * @param {CB_Keyboard.EVENT_CALLBACK|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first parameter received for this function will be the event object (already normalized by the {@link CB_Keyboard.normalizeEvent} function) and the second one will be the key code associated. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Keyboard.onKeyPress = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Keyboard._setEvent(\"keypress\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when a key is down ([onKeyDown]{@link https://developer.mozilla.org/en-US/docs/Web/Events/keydown} event) or removes it. * @function * @param {CB_Keyboard.EVENT_CALLBACK|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first parameter received for this function will be the event object (already normalized by the {@link CB_Keyboard.normalizeEvent} function) and the second one will be the key code associated. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Keyboard.onKeyDown = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Keyboard._setEvent(\"keydown\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when a key is released ([onKeyUp]{@link https://developer.mozilla.org/en-US/docs/Web/Events/keyup} event) or removes it. * @function * @param {CB_Keyboard.EVENT_CALLBACK|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first parameter received for this function will be the event object (already normalized by the {@link CB_Keyboard.normalizeEvent} function) and the second one will be the key code associated. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Keyboard.onKeyUp = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Keyboard._setEvent(\"keyup\", callbackFunction, keepOldFunction, useCapture, target); } //Sets a function to execute when a keyboard event happens: CB_Keyboard._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture, target) { //If they are not set, use default values for optional parameters: if (typeof(keepOldFunction) === \"undefined\" || keepOldFunction === null) { keepOldFunction = true; } //If not set, it keeps old function by default. if (typeof(target) === \"undefined\" || target === null) { target = document; } //If a function has been sent: if (typeof(eventFunction) === \"function\") { //If able, adds the function given to the event: //eventFunctionHolder = functionToAdd; CB_Events.add ( target, eventName, function(e) { //e = CB_Events.normalize(e); e = CB_Keyboard.normalizeEvent(e); if (eventName === \"keydown\" || eventName === \"keyup\") { CB_Keyboard._updateKeysDown(e, (eventName === \"keydown\"), false); //Updates keys down. } //var keyCode = CB_Keyboard.getKeyCode(e); if (typeof(eventFunction) === \"function\") { //return eventFunction(e, e.keyCode); return eventFunction(e, e.getKeyCode()); } return true; }, useCapture, keepOldFunction, true ); } //...but if the function given is null, it will cancel the event: else if (eventFunction === null)// &amp;&amp; eventFunctionHolder !== null) { //CB_Events.remove(target, eventName, eventFunctionHolder, useCapture); CB_Events.removeByName(target, eventName); //eventFunctionHolder = null; } } } //End of the static class CB_Keyboard. × Search results Close "},"CrossBase_net_CB_Net.js.html":{"id":"CrossBase_net_CB_Net.js.html","title":"Source: CrossBase/net/CB_Net.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/net/CB_Net.js /** * @file Management for things related with the net. Contains the {@link CB_Net} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage things related to the net. It will return itself if it is tried to be instantiated. * @namespace CB_Net */ if (typeof(CB_Net) === \"undefined\") { var CB_Net = function() { return CB_Net; }; } { CB_Net.initialized = false; //It will tells whether the object has been initialized or not. //Initializes all values: CB_Net.init = function() { if (CB_Net.initialized) { return CB_Net; } //The object has been initialized: CB_Net.initialized = true; //TODO. return CB_Net; } /** * Alias for {@link CB_Net.URIValueEncode}. * @function CB_Net.URLValueEncode * @see {@link CB_Net.URIValueEncode} */ /** * Encodes a given URI value. Uses the native [encodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent} function internally if available or fallbacks to the native [escape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape} function otherwise. * @function * @param {string|number} value - The value that we want to encode. Normally, it should be either a string or a number. * @returns {string} * @todo Think about using another thing since [escape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape} maybe is not a good fallback. Probably a polyfill to simulate the [encodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent} function. */ CB_Net.URIValueEncode = CB_Net.URLValueEncode = function(value) { if (typeof(encodeURIComponent) !== \"undefined\") { return encodeURIComponent(value); } else { return escape(value); } //TODO: think about using another thing since escape maybe is not a good fallback. Probably a polyfill to simulate the encodeURIComponent function. } /** * Alias for {@link CB_Net.URIValueDecode}. * @function CB_Net.URLValueDecode * @see {@link CB_Net.URIValueDecode} */ /** * Decodes a given URI value. Uses the native [decodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent} function internally if available or fallbacks to the native [unescape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/unescape} function otherwise. * @function * @param {string|number} value - The value that we want to decode. Normally, it should be either a string or a number. * @returns {string} * @todo Think about using another thing since [unescape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/unescape} maybe is not a good fallback. Probably a polyfill to simulate the [decodeURIComponent]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent} function. */ CB_Net.URIValueDecode = CB_Net.URLValueDecode = function(value) { if (typeof(decodeURIComponent) !== \"undefined\") { return decodeURIComponent(value); } else { return unescape(value); } //TODO: think about using another thing since unescape maybe is not a good fallback. Probably a polyfill to simulate the decodeURIComponent function. } /** * Alias for {@link CB_Net.URIEncode}. * @function CB_Net.URLEncode * @see {@link CB_Net.URIEncode} */ /** * Encodes a given URI. Uses the native [encodeURI]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI} function internally if available or fallbacks to the native [escape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape} function otherwise. * @function * @param {string|number} URI - The URI that we want to encode. Normally, it should be either a string or a number. * @returns {string} * @todo Think about using another thing since [escape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape} maybe is not a good fallback. Probably a polyfill to simulate the [encodeURI]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI} function. */ CB_Net.URIEncode = CB_Net.URLEncode = function(URI) { if (typeof(encodeURI) !== \"undefined\") { return encodeURI(URI); } else { return escape(URI); } //TODO: think about using another thing since escape maybe is not a good fallback. Probably a polyfill to simulate the encodeURI function. } /** * Alias for {@link CB_Net.URIDecode}. * @function CB_Net.URLDecode * @see {@link CB_Net.URIDecode} */ /** * Encodes a given URI. Uses the native [decodeURI]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI} function internally if available or fallbacks to the native [unescape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/unescape} function otherwise. * @function * @param {string|number} URI - The URI that we want to decode. Normally, it should be either a string or a number. * @returns {string} * @todo Think about using another thing since [unescape]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/unescape} maybe is not a good fallback. Probably a polyfill to simulate the [decodeURI]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI} function. */ CB_Net.URIDecode = CB_Net.URLDecode = function(URI) { if (typeof(decodeURI) !== \"undefined\") { return decodeURI(URI); } else { return unescape(URI); } //TODO: think about using another thing since unescape maybe is not a good fallback. Probably a polyfill to simulate the decodeURI function. } /** * Gets all the \"GET\" (query) parameters (names and their values) from a given URI or from the current URL. &lt;br /&gt; For example, if the URI provided is \"http://whatever.com/index.html?parameter1=value1&amp;amp;parameter2=value2#hash_parameter1=hash_value1&amp;amp;hash_parameter2=hash_value2\", it will return \"parameter1=value1&amp;amp;parameter2=value2\" (using the default options). * @function * @param {string} [URI=[window.location]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/location}.href] - The URI that we want to work with. If not provided, it will try to use the current URL (by using [window.location]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/location}.href). * @param {array} [exclude] - A numeric array containing the name of the parameters that we want to exclude in the returned string. It will exclude them even if they are contained in the given \"includeOnly\" parameter (if any). * @param {array} [includeOnly] - A numeric array containing the name of the parameters that we want to include in the returned string. If provided, it will only include these ones to the returned string (unless they are included in the \"exclude\" parameter). * @param {boolean} [includeIfNotExists=false] - If it is set to true and an array is given as the \"includeOnly\" parameter, it will add the parameters in the \"includeOnly\" array (with empty values) in the returned string even when they did not exist in the original URI provided. * @param {boolean} [trim=true] - Defines whether we want to trim the spaces around the values or not. * @param {string} [firstDelimiter='?'] - The string that indicates where the parameters start. If it is not provided, it will be \"?\" as default. If not provided and \"lastDelimiter\" is not provided either, it will be \"?\" and \"lastDelimiter\" will be \"#\". * @param {string} [lastDelimiter=undefined|'#'] - The string that indicates where the parameters end. If not provided and \"firstDelimiter\" is provided, it will stop at the end of the given URI. If it is not provided and \"firstDelimiter\" is not provided either, \"firstDelimiter\" will be \"?\" and \"lastDelimiter\" will be \"#\". * @param {string} [concatenator='&amp;'] - The string that joints the different parameters. * @param {string} [nameValueSeparator='='] - The string that is the separator for the parameters and their values. * @returns {string} An empty string will be returned if no parameters can be found. */ CB_Net.getURIParameters = function(URI, exclude, includeOnly, includeIfNotExists, trim, firstDelimiter, lastDelimiter, concatenator, nameValueSeparator) { concatenator = CB_trim(concatenator); if (concatenator === \"\") { concatenator = \"&amp;\"; } nameValueSeparator = CB_trim(nameValueSeparator); if (nameValueSeparator === \"\") { nameValueSeparator = \"=\"; } firstDelimiter = CB_trim(firstDelimiter); lastDelimiter = CB_trim(lastDelimiter); if (firstDelimiter === \"\") { firstDelimiter = \"?\"; if (lastDelimiter === \"\") { lastDelimiter = \"#\"; } } URI = CB_trim(URI); if (URI === \"\") { URI = window.location.href; } if (URI.indexOf(firstDelimiter) !== -1) { URI = URI.substring(URI.indexOf(firstDelimiter) + firstDelimiter.length); } else { return \"\"; } if (lastDelimiter !== \"\" &amp;&amp; URI.indexOf(lastDelimiter) !== -1) { URI = URI.substring(0, URI.indexOf(lastDelimiter)); } URI = CB_trim(URI); var filteredURI = URI; if (typeof(trim) === \"undefined\" || trim === null) { trim = true; } //If set, only includes the desired ones: if (CB_isArray(includeOnly) &amp;&amp; includeOnly.length &gt; 0) { filteredURI = \"\"; URI = firstDelimiter + URI; for (var x = 0, includeOnlyLength = includeOnly.length; x &lt; includeOnlyLength; x++) { if (includeIfNotExists || URI.toUpperCase().indexOf(includeOnly[x].toUpperCase() + nameValueSeparator) !== -1) { filteredURI += includeOnly[x] + nameValueSeparator + CB_Net.getParameter(includeOnly[x], trim, URI, firstDelimiter, lastDelimiter, concatenator, nameValueSeparator) + concatenator; } } filteredURI = CB_rtrim(filteredURI, [concatenator]); } //If set, excludes the desired ones and/or trims values if desired: var excludePending = false; if (CB_isArray(exclude) &amp;&amp; exclude.length &gt; 0) { excludePending = true; } if (trim || excludePending) { var parametersArray = filteredURI.split(concatenator); var parameterArray; filteredURI = \"\"; for (x = 0, parametersArrayLength = parametersArray.length; x &lt; parametersArrayLength; x++) { parameterArray = parametersArray[x].split(nameValueSeparator); if (trim || excludePending &amp;&amp; CB_indexOf(exclude, parameterArray[0]) === -1) { if (typeof(parameterArray[1]) !== \"undefined\" &amp;&amp; parameterArray[1] !== null) { filteredURI += parameterArray[0] + nameValueSeparator + (trim ? CB_trim(parameterArray[1]) : parameterArray[1]) + concatenator; } else { filteredURI += parameterArray[0] + concatenator; } } } filteredURI = CB_rtrim(filteredURI, [concatenator]); } filteredURI = CB_trim(filteredURI, [concatenator]); return filteredURI; } /** * Gets all the hash parameters (names and their values) from a given URI or from the current URL. &lt;br /&gt; For example, if the URI provided is \"http://whatever.com/index.html?parameter1=value1&amp;amp;parameter2=value2#hash_parameter1=hash_value1&amp;amp;hash_parameter2=hash_value2\", it will return \"hash_parameter1=hash_value1&amp;amp;hash_parameter2=hash_value2\" (using the default options). * @function * @param {string} [URI=[window.location]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/location}.href] - The URI that we want to work with. If not provided, it will try to use the current URL (by using [window.location]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/location}.href). * @param {array} [exclude] - A numeric array containing the name of the parameters that we want to exclude in the returned string. It will exclude them even if they are contained in the given \"includeOnly\" parameter (if any). * @param {array} [includeOnly] - A numeric array containing the name of the parameters that we want to include in the returned string. If provided, it will only include these ones to the returned string (unless they are included in the \"exclude\" parameter). * @param {boolean} [includeIfNotExists=false] - If it is set to true and an array is given as the \"includeOnly\" parameter, it will add the parameters in the \"includeOnly\" array (with empty values) in the returned string even when they did not exist in the original URI provided. * @param {boolean} [trim=true] - It will use this option when it calls the {@link CB_Net.getURIParameters} function internally. * @returns {string} An empty string will be returned if no parameters can be found. */ CB_Net.getHashParameters = function(URI, exclude, includeOnly, includeIfNotExists, trim) { return CB_Net.getURIParameters(URI, exclude, includeOnly, includeIfNotExists, trim, \"#\"); } /** * Gets the value of a specific URI parameter (query or hash), respecting GET/URL rules by default, from the current URL or a desired one (with the given delimiters). &lt;br /&gt; For example, if the URI provided is \"http://whatever.com/index.html?parameter1=value1&amp;amp;parameter2=value2#hash_parameter1=hash_value1&amp;amp;hash_parameter2=hash_value2\" and the index given is \"parameter1\", it will return \"value1\" (using the default options). * @function * @param {string} index - The name of the parameter whose value we want to get. * @param {boolean} [trim=true] - It will trim the value (using {@link CB_trim} internally) before returning it. * @param {string} [URI=[window.location]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/location}.href] - The URI that we want to work with. If not provided, it will try to use the current URL (by using [window.location]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/location}.href). * @param {string} [firstDelimiter='?'] - The string that indicates where the parameters start. If it is not provided, it will be \"?\" as default. If not provided and \"lastDelimiter\" is not provided either, it will be \"?\" and \"lastDelimiter\" will be \"#\". * @param {string} [lastDelimiter=undefined|'#'] - The string that indicates where the parameters end. If not provided and \"firstDelimiter\" is provided, it will stop at the end of the given URI. If it is not provided and \"firstDelimiter\" is not provided either, \"firstDelimiter\" will be \"?\" and \"lastDelimiter\" will be \"#\". * @param {string} [concatenator='&amp;'] - The string that joints the different parameters. * @param {string} [nameValueSeparator='='] - The string that is the separator for the parameters and their values. * @returns {string} An empty string will be returned if the value of the given parameter cannot be found. */ CB_Net.getParameter = function(index, trim, URI, firstDelimiter, lastDelimiter, concatenator, nameValueSeparator) { if (typeof(trim) === \"undefined\" || trim === null) { trim = true; } index = CB_trim(index).toUpperCase(); if (index === \"\") { return \"\"; } concatenator = CB_trim(concatenator); if (concatenator === \"\") { concatenator = \"&amp;\"; } nameValueSeparator = CB_trim(nameValueSeparator); if (nameValueSeparator === \"\") { nameValueSeparator = \"=\"; } firstDelimiter = CB_trim(firstDelimiter); lastDelimiter = CB_trim(lastDelimiter); if (firstDelimiter === \"\") { firstDelimiter = \"?\"; if (lastDelimiter === \"\") { lastDelimiter = \"#\"; } } URI = CB_trim(URI); if (URI === \"\") { URI = window.location.href; } if (URI.indexOf(firstDelimiter) !== -1) { URI = URI.substring(URI.indexOf(firstDelimiter) + firstDelimiter.length); } else { return \"\"; } if (lastDelimiter !== \"\" &amp;&amp; URI.indexOf(lastDelimiter) !== -1) { URI = URI.substring(0, URI.indexOf(lastDelimiter)); } URI = CB_trim(URI); if (URI === \"\") { return \"\"; } var value = \"\"; var URIUpperCase = URI.toUpperCase(); var indexOfFound = URIUpperCase.indexOf(index + nameValueSeparator); if (indexOfFound !== -1) { URI = URI.substring(indexOfFound + index.length + nameValueSeparator.length); if (URI.indexOf(concatenator) !== -1) { URI = URI.substring(0, URI.indexOf(concatenator)); } value = URI; } if (trim) { value = CB_trim(value); } return CB_Net.URIValueDecode(value); } /** * Gets the value of a specific URI \"GET\" parameter (query) from the current URL or a desired URI. &lt;br /&gt; For example, if the URI provided is \"http://whatever.com/index.html?parameter1=value1&amp;amp;parameter2=value2#hash_parameter1=hash_value1&amp;amp;hash_parameter2=hash_value2\" and the index given is \"parameter1\", it will return \"value1\" (using the default options). * @function * @param {string} index - The name of the parameter whose value we want to get. * @param {boolean} [trim=true] - It will trim the value (using {@link CB_Net.getParameter} internally) before returning it. * @param {string} [URI=[window.location]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/location}.href] - The URI that we want to work with. If not provided, it will try to use the current URL (by using [window.location]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/location}.href). * @returns {string} An empty string will be returned if the value of the given parameter cannot be found. */ CB_Net.getURIValue = function(index, trim, URI) { return CB_Net.getParameter(index, trim, URI, \"?\", \"#\"); } /** * Gets the value of a specific hash (string after \"#\") parameter from the current URL or a desired URI. &lt;br /&gt; For example, if the URI provided is \"http://whatever.com/index.html?parameter1=value1&amp;amp;parameter2=value2#hash_parameter1=hash_value1&amp;amp;hash_parameter2=hash_value2\" and the index given is \"hash_parameter1\", it will return \"hash_value1\" (using the default options). * @function * @param {string} index - The name of the parameter whose value we want to get. * @param {boolean} [trim=true] - It will trim the value (using {@link CB_Net.getParameter} internally) before returning it. * @param {string} [URI=[window.location]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/location}.href] - The URI that we want to work with. If not provided, it will try to use the current URL (by using [window.location]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/location}.href). * @returns {string} An empty string will be returned if the value of the given parameter cannot be found. */ CB_Net.getHashValue = function(index, trim, URI) { return CB_Net.getParameter(index, trim, URI, \"#\"); } /** * Alias for {@link CB_Net.combineURIParameters}. * @function CB_Net.combineURLParameters * @see {@link CB_Net.combineURIParameters} */ /** * Alias for {@link CB_combineURIParameters}. * @function CB_Net.combineURIParameters * @see {@link CB_combineURIParameters} */ CB_Net.combineURIParameters = CB_Net.combineURLParameters = function(parametersA, parametersB) { return CB_combineURIParameters(parametersA, parametersB); }; } × Search results Close "},"CrossBase_net_fetch_CB_Net_Fetch.js.html":{"id":"CrossBase_net_fetch_CB_Net_Fetch.js.html","title":"Source: CrossBase/net/fetch/CB_Net_Fetch.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/net/fetch/CB_Net_Fetch.js /** * @file [Fetch API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API} management. Contains the {@link CB_Net.Fetch} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ if (typeof(CB_Net) === \"undefined\") { var CB_Net = function() { return CB_Net; }; } /** * Static class to manage things related to the [Fetch API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API}. It will return itself if it is tried to be instantiated. * @namespace */ CB_Net.Fetch = function() { return CB_Net.Fetch; }; { CB_Net.Fetch.initialized = false; //It will tells whether the object has been initialized or not. //Initializes all values: CB_Net.Fetch.init = function() { if (CB_Net.Fetch.initialized) { return CB_Net.Fetch; } //The object has been initialized: CB_Net.Fetch.initialized = true; //TODO. return CB_Net.Fetch; } /** * Function that points to the [fetch]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch} method. If the [Fetch API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API} is not supported natively, the [fetch]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch} function will be a polyfill. * @function * @param {string|Request} resource - First parameter of the [fetch]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch} method. * @param {Object} [init] - Second parameter of the [fetch]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch} method. * @returns {Promise} */ CB_Net.Fetch.get = function() { return fetch.apply(CB_this || window, arguments); }; //Points to the \"fetch\" function. } × Search results Close "},"CrossBase_net_REST_CB_Net_REST.js.html":{"id":"CrossBase_net_REST_CB_Net_REST.js.html","title":"Source: CrossBase/net/REST/CB_Net_REST.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/net/REST/CB_Net_REST.js /** * @file [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} client, services and related management. Contains the {@link CB_Net.REST} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ if (typeof(CB_Net) === \"undefined\") { var CB_Net = function() { return CB_Net; }; } /** * Static class to manage [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} services and related. It will return itself if it is tried to be instantiated. * @namespace * @todo Think about accepting an onAbort function as option (with also default and permanent). */ CB_Net.REST = function() { return CB_Net.REST; }; { CB_Net.REST.initialized = false; //It will tells whether the object has been initialized or not. /** * Defines the URL for the default [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} server to use when the \"serverURL\" parameter is not available. Used by the {@link CB_Net.XHR.callREST} function as the default \"serverURL\" parameter. * @var * @type {string} * @default */ CB_Net.REST.SERVER_URL_DEFAULT = \"http://localhost/CrossBrowdy/tests/net/fake_rest_server/index.php\"; //CHANGE THIS! /** * Default value when the \"avoidProxy\" parameter is not available. Used by the {@link CB_Net.REST.actionProcess} function. &lt;br /&gt; NOTE: Edit the \"CB_proxy.config.php\" file to configure the default proxy (set by default in the value of the {@link CB_Configuration.CrossBase.CB_Net_XHR_PROXY_URL} property). Apart from configuring it, adding some security measures is highly recommended. Have in mind that, for safety reasons, the default proxy only allows to request the URLs defined in the \"$allowedURLs\" array in the \"CB_proxy.config.php\" file. Just edit it to allow other URLs. * @var * @type {boolean} * @default */ CB_Net.REST.avoidProxy_DEFAULT = false; /** * Default \"method\" for [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} actions. Used by the {@link CB_Net.REST.actionProcess} function. * @var * @type {string} * @default */ CB_Net.REST.method_DEFAULT = \"GET\"; /** * Default \"responseType\" for [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} actions when it is not provided and it is not null. Used by the {@link CB_Net.REST.actionProcess} function. * @var * @type {string} * @default */ CB_Net.REST.responseType_DEFAULT = \"text\"; /** * Callback returning an object that will be used for parsing the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} route. The object returned should follow the same rules as the \"JSONObject\" parameter of the {@link CB_renderString} function. * @callback CB_Net.REST.actionProcess_ROUTE_WILDCARD_DATA * @param {string} actionName - The name of the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed. It should be the name of an index defined in the {@link CB_Net.REST.actions} object whose value should be a {@link CB_Net.REST.actionProcess_ACTIONS} object. * @param {*} additionalData - Any additional data associated to the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed (belongs to the \"additionalData\" parameter used when the {@link CB_Net.REST.actionProcess} function was called). * @returns {Object|null} It should return an object containing the wildcards that will be used to parse the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} route of the action being performed. Return null in the case that we do not want to modify anything. The object returned (if any) will be used as the \"JSONObject\" parameter of the {@link CB_renderString} function (the first parameter will be the route which should be a string) when it is called by {@link CB_Net.REST.actionProcess} internally. */ /** * Permanent function (must return a [JSON]{@link https://en.wikipedia.org/wiki/JSON} object or null if we do not want to modify it) to execute the same way as the \"routeWildcardData\" parameter (if other \"routeWildcardData\" are provided or set, they will be executed before this one). The function assigned by default returns null. Used by the {@link CB_Net.REST.actionProcess} function. This is permanent for each [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action. * @var * @type {CB_Net.REST.actionProcess_ROUTE_WILDCARD_DATA} * @default */ CB_Net.REST.routeWildcardData_PERMANENT = function(actionName, additionalData) { return null; }; /** * Default \"routeWildcardData\" for [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} actions (must be a function returning a [JSON]{@link https://en.wikipedia.org/wiki/JSON} object or null if we do not want to modify the route). The function assigned by default returns null. Used by the {@link CB_Net.REST.actionProcess} function. * @var * @type {CB_Net.REST.actionProcess_ROUTE_WILDCARD_DATA} * @default */ CB_Net.REST.routeWildcardData_DEFAULT = function(actionName, additionalData) { return null; }; /** * Tells whether to force [JSON]{@link https://en.wikipedia.org/wiki/JSON} response by default or not. Used by the {@link CB_Net.REST.actionProcess} function when the REST action does not provided it and it is not null, as the \"forceJSON\" option. * @var * @type {boolean} * @default */ CB_Net.REST.forceJSON_DEFAULT = true; /** * Tells whether get response [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} by default or not. Used by the {@link CB_Net.REST.actionProcess} function when the REST action does not provided it and it is not null, as the \"getHeaders\" option. * @var * @type {boolean} * @default */ CB_Net.REST.getHeaders_DEFAULT = false; /** * Tells whether to get response [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} in one-dimension array by default or not (needs \"getHeaders\" set to true). Used by the {@link CB_Net.REST.actionProcess} function when the REST action does not provided it and it is not null, as the \"getHeadersOneDimension\" option. * @var * @type {boolean} * @default */ CB_Net.REST.getHeadersOneDimension_DEFAULT = false; /** * Tells whether to get response [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} values in one-dimension (just one value per key) by default or not (needs \"getHeaders\" set to true). Used by the {@link CB_Net.REST.actionProcess} function when the REST action does not provided it and it is not null, as the \"getHeadersOneDimensionValues\" option. * @var * @type {boolean} * @default */ CB_Net.REST.getHeadersOneDimensionValues_DEFAULT = false; /** * Callback returning an object containing the [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} which will be used as the \"headers\" parameter when the {@link CB_Net.XHR.callREST} function is called internally by {@link CB_Net.REST.actionProcess}. * @callback CB_Net.REST.actionProcess_HEADERS * @param {string} actionName - The name of the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed. It should be the name of an index defined in the {@link CB_Net.REST.actions} object whose value should be a {@link CB_Net.REST.actionProcess_ACTIONS} object. * @param {*} additionalData - Any additional data associated to the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed (belongs to the \"additionalData\" parameter used when the {@link CB_Net.REST.actionProcess} function was called). * @returns {CB_Net.XHR.HEADERS|null} It should return an object containing the [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers}. Return null in the case that we do not want to add anything. The object returned (if any) will be used as the \"headers\" parameter of the {@link CB_Net.XHR.callREST} function when it is called by {@link CB_Net.REST.actionProcess} internally. */ /** * Permanent function (must be a function returning a {@link CB_Net.XHR.HEADERS} object with the [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers}) to execute the same way as the \"headers\" parameter. The function assigned by default returns { \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" }. Used by the {@link CB_Net.REST.actionProcess} function. This is permanent for each [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action. * @var * @type {CB_Net.REST.actionProcess_HEADERS} * @default */ CB_Net.REST.headers_PERMANENT = function(actionName, additionalData) { return { \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" } }; /** * Default \"headers\" for [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} actions (must be a function returning a {@link CB_Net.XHR.HEADERS} object with the [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers}). The function assigned by default returns { \"Content-Type\" : \"application/x-www-form-urlencoded; charset=UTF-8\" }. Used by the {@link CB_Net.REST.actionProcess} function. * @var * @type {CB_Net.REST.actionProcess_HEADERS} * @default */ CB_Net.REST.headers_DEFAULT = function(actionName, additionalData) { return { \"Content-Type\" : \"application/x-www-form-urlencoded; charset=UTF-8\" }; }; /** * Tells whether get status transparently from the server by default or not. Used by the {@link CB_Net.REST.actionProcess} function when the REST action does not provided it and it is not null, as the \"transparentStatus\" option. * @var * @type {boolean} * @default */ CB_Net.REST.transparentStatus_DEFAULT = true; /** * Tells whether get [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} transparently from the server by default or not. Used by the {@link CB_Net.REST.actionProcess} function when the REST action does not provided it and it is not null, as the \"transparentHeaders\" option. * @var * @type {boolean} * @default */ CB_Net.REST.transparentHeaders_DEFAULT = true; /** * Callback returning a string containing the URL (GET) data which will be used as the \"dataURL\" parameter when the {@link CB_Net.XHR.callREST} function is called internally by {@link CB_Net.REST.actionProcess}. * @callback CB_Net.REST.actionProcess_DATA_URL * @param {string} actionName - The name of the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed. It should be the name of an index defined in the {@link CB_Net.REST.actions} object whose value should be a {@link CB_Net.REST.actionProcess_ACTIONS} object. * @param {*} additionalData - Any additional data associated to the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed (belongs to the \"additionalData\" parameter used when the {@link CB_Net.REST.actionProcess} function was called). * @returns {string} It should return a string containing the URL (GET) data. Return an empty string in the case that we do not want to add anything. The string returned (if any) will be used as the \"dataURL\" parameter of the {@link CB_Net.XHR.callREST} function when it is called by {@link CB_Net.REST.actionProcess} internally. */ /** * Permanent function (must return a string in URL/GET parameters format) to execute the same way as the \"dataURL\" parameter. The function assigned by default returns an empty string (\"\"). Used by the {@link CB_Net.REST.actionProcess} function. The returning data will be placed in the beginning of the URL, followed by the rest of the \"dataURL\" desired (if any). NOTE: remember to use {@link CB_Net.URLValueEncode} if needed. This is permanent for each [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action. * @var * @type {CB_Net.REST.actionProcess_DATA_URL} * @default */ CB_Net.REST.dataURL_PERMANENT = //NOTE: remember to use CB_Net.URLValueEncode if needed. function(actionName, additionalData) { return \"\"; }; /** * Default \"dataURL\" for [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} actions (must return a string in URL/GET parameters format). The function assigned by default returns an empty string (\"\"). Used by the {@link CB_Net.REST.actionProcess} function. NOTE: remember to use {@link CB_Net.URLValueEncode} if needed. * @var * @type {CB_Net.REST.actionProcess_DATA_URL} * @default */ CB_Net.REST.dataURL_DEFAULT = //NOTE: remember to use CB_Net.URLValueEncode if needed. function(actionName, additionalData) { return \"\"; }; /** * Callback returning the data (string or object) which will be used as the \"data\" parameter when the {@link CB_Net.XHR.callREST} function is called internally by {@link CB_Net.REST.actionProcess}. The values returned by all functions that are mean to return the data should always return the same type of data (all strinngs or all objects) since {@link CB_Net.REST.actionProcess} will use the {@link CB_combineAutomatically} function to combine them. * @callback CB_Net.REST.actionProcess_DATA * @param {string} actionName - The name of the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed. It should be the name of an index defined in the {@link CB_Net.REST.actions} object whose value should be a {@link CB_Net.REST.actionProcess_ACTIONS} object. * @param {*} additionalData - Any additional data associated to the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed (belongs to the \"additionalData\" parameter used when the {@link CB_Net.REST.actionProcess} function was called). * @returns {string|Object} It should return a string or object containing the data. Return null or an empty string (recommended) in the case that we do not want to add anything. The value returned (if any) will be used as the \"data\" parameter of the {@link CB_Net.XHR.callREST} function when it is called by {@link CB_Net.REST.actionProcess} internally. */ /** * Permanent function (must return a string in URL/GET parameters format or a [JSON]{@link https://en.wikipedia.org/wiki/JSON} format string) to execute the same way as the \"data\" parameter. The function assigned by default returns an empty string (\"\"). Used by the {@link CB_Net.REST.actionProcess} function. The values returned by all functions that are mean to return the data should always return the same type of data (all strinngs or all objects) since {@link CB_Net.REST.actionProcess} will use the {@link CB_combineAutomatically} function to combine them. This is permanent for each [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action. NOTE: remember to use {@link CB_Net.URLValueEncode} if needed. * @var * @type {CB_Net.REST.actionProcess_DATA} * @default */ CB_Net.REST.data_PERMANENT = //NOTE: remember to use CB_Net.URLValueEncode if needed. function(actionName, additionalData) { return \"\"; }; /** * Default \"data\" for [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} actions (must return a string in URL/GET parameters format or a [JSON]{@link https://en.wikipedia.org/wiki/JSON} format string). The function assigned by default returns an empty string (\"\"). Used by the {@link CB_Net.REST.actionProcess} function. The values returned by all functions that are mean to return the data should always return the same type of data (all strinngs or all objects) since {@link CB_Net.REST.actionProcess} will use the {@link CB_combineAutomatically} function to combine them. NOTE: remember to use {@link CB_Net.URLValueEncode} if needed. * @var * @type {CB_Net.REST.actionProcess_DATA} * @default */ CB_Net.REST.data_DEFAULT = //NOTE: remember to use CB_Net.URLValueEncode if needed. function(actionName, additionalData) { return \"\"; }; /** * Permanent values for the \"allowedSuccessStatuses\" parameter, containing the statuses to considerer a successful [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action (must be a numeric array of integers). Used by the {@link CB_Net.REST.actionProcess} function. This is permanent for each [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action. * @var * @type {array} * @default */ CB_Net.REST.allowedSuccessStatuses_PERMANENT = []; /** * Default \"allowedSuccessStatuses\", containing the statuses to considerer a successful [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action (must be a numeric array of integers). Used by the {@link CB_Net.REST.actionProcess} function. * @var * @type {array} * @default */ CB_Net.REST.allowedSuccessStatuses_DEFAULT = [200, 201, 206]; /** * Callback that will be run before performing a [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action and must return a boolean defining whether we want to continue performing the action (returning true) or not (returning false). * @callback CB_Net.REST.actionProcess_CALLBACK_BEFORE * @param {string} actionName - The name of the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed. It should be the name of an index defined in the {@link CB_Net.REST.actions} object whose value should be a {@link CB_Net.REST.actionProcess_ACTIONS} object. * @param {*} additionalData - Any additional data associated to the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed (belongs to the \"additionalData\" parameter used when the {@link CB_Net.REST.actionProcess} function was called). * @returns {boolean} It should return true in the case that we want to continue performing the current [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action or false otherwise. */ /** * Permanent callback function before performing each [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action returning a boolean (to decide whether to do it or not). Executed before the default or the set \"callbackBefore\" function (if any). The function assigned by default returns true. Used by the {@link CB_Net.REST.actionProcess} function. This is permanent for each [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action. * @var * @type {CB_Net.REST.actionProcess_CALLBACK_BEFORE} * @default */ CB_Net.REST.callbackBefore_PERMANENT = function(actionName, additionalData) { return true; //Must return true if we want to perform the action. }; /** * Default \"callbackBefore\", containing a callback function before performing each [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action returning a boolean (to decide whether to do it or not). The function assigned by default returns true. Used by the {@link CB_Net.REST.actionProcess} function. * @var * @type {CB_Net.REST.actionProcess_CALLBACK_BEFORE} * @default */ CB_Net.REST.callbackBefore_DEFAULT = function(actionName, additionalData) { return true; //Must return true if we want to perform the action. }; /** * Callback that will be run when the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action has been performed successfully. * @callback CB_Net.REST.actionProcess_CALLBACK_OK * @param {string} actionName - The name of the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed. It should be the name of an index defined in the {@link CB_Net.REST.actions} object whose value should be a {@link CB_Net.REST.actionProcess_ACTIONS} object. * @param {Object} [XHR] - The [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} object that has been used to perform the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action. * @param {CB_Net.REST.actionProcess_CALLBACK_ERROR} callbackError - The error callback function associated to the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed, just in case we want to call it. * @param {*} additionalData - Any additional data associated to the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed (belongs to the \"additionalData\" parameter used when the {@link CB_Net.REST.actionProcess} function was called). */ /** * Permanent callback function when each [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action has been successful. Used by the {@link CB_Net.REST.actionProcess} function. Executed before the default or the set \"callbackOk\" function (if any). This is permanent for each [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action. * @var * @type {CB_Net.REST.actionProcess_CALLBACK_OK} * @default */ CB_Net.REST.callbackOk_PERMANENT = function(actionName, XHR, callbackError, additionalData) { //Do things here. }; /** * Default \"callbackOk\", containing a callback function when the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action has been successful. Used by the {@link CB_Net.REST.actionProcess} function. * @var * @type {CB_Net.REST.actionProcess_CALLBACK_OK} * @default */ CB_Net.REST.callbackOk_DEFAULT = function(actionName, XHR, callbackError, additionalData) { //Do things here. }; /** * Callback that will be run when the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action has been performed successfully. * @callback CB_Net.REST.actionProcess_CALLBACK_ERROR * @param {string} actionName - The name of the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed. It should be the name of an index defined in the {@link CB_Net.REST.actions} object whose value should be a {@link CB_Net.REST.actionProcess_ACTIONS} object. * @param {Object} [XHR] - The [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} object that has been used to perform the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action. * @param {*} additionalData - Any additional data associated to the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed (belongs to the \"additionalData\" parameter used when the {@link CB_Net.REST.actionProcess} function was called). */ /** * Permanent callback function when an error happens processing any [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action. Used by the {@link CB_Net.REST.actionProcess} function. Executed before the default or the set \"callbackError\" function (if any). This is permanent for each [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action. * @var * @type {CB_Net.REST.actionProcess_CALLBACK_ERROR} * @default */ CB_Net.REST.callbackError_PERMANENT = function(actionName, XHR, additionalData) { //Do things here. }; /** * Default \"callbackError\", containing a callback function when an error happens processing the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action. Used by the {@link CB_Net.REST.actionProcess} function. * @var * @type {CB_Net.REST.actionProcess_CALLBACK_ERROR} * @default */ CB_Net.REST.callbackError_DEFAULT = function(actionName, XHR, additionalData) { //Do things here. }; /** * Object that represents a [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action. * @memberof CB_Net.REST * @typedef {Object} CB_Net.REST.actionProcess_ACTIONS * @property {string} route - The [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} route (path). Belongs to the \"route\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally. It is mandatory. * @property {CB_Net.REST.actionProcess_CALLBACK_BEFORE} [callbackBefore={@link CB_Net.REST.callbackBefore_DEFAULT}] - Callback run before performing the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action which will decide whether to continue with it or not. * @property {boolean} [avoidProxy={@link CB_Net.REST.avoidProxy_DEFAULT}] - Belongs to the \"avoidProxy\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally. * @property {CB_Net.REST.actionProcess_ROUTE_WILDCARD_DATA} [routeWildcardData={@link CB_Net.REST.routeWildcardData_DEFAULT}] - Callback returning an object that will be used for parsing the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} route. The object returned should follow the same rules as the \"JSONObject\" parameter of the {@link CB_renderString} function. * @property {CB_Net.REST.actionProcess_DATA_URL} [dataURL={@link CB_Net.REST.dataURL_DEFAULT}] - Belongs to the \"dataURL\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally. * @property {CB_Net.REST.actionProcess_DATA} [data={@link CB_Net.REST.data_DEFAULT}] - Belongs to the \"data\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally. * @property {CB_Net.REST.actionProcess_HEADERS} [headers={@link CB_Net.REST.headers_DEFAULT}] - Belongs to the \"headers\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally. * @property {array} [allowedSuccessStatuses={@link CB_Net.REST.allowedSuccessStatuses_DEFAULT}] - Belongs to the \"allowedSuccessStatuses\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally. * @property {CB_Net.REST.actionProcess_CALLBACK_ERROR} [callbackError={@link CB_Net.REST.callbackError_DEFAULT}] - Callback run when the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action has not been performed successfully. * @property {CB_Net.REST.actionProcess_CALLBACK_OK} [callbackOk={@link CB_Net.REST.callbackOk_DEFAULT}] - Callback run when the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action has been performed successfully. * @property {string} [serverURL={@link CB_Net.REST.SERVER_URL_DEFAULT}] - Belongs to the \"serverURL\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally. * @property {string} [method={@link CB_Net.REST.method_DEFAULT}] - Belongs to the \"method\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally. * @property {string} [responseType={@link CB_Net.REST.responseType_DEFAULT}] - Belongs to the \"responseType\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally and will be sent even it is null. If it is undefined, it will use the value of {@link CB_Net.REST.responseType_DEFAULT} instead. * @property {boolean} [forceJSON={@link CB_Net.REST.forceJSON_DEFAULT}] - Belongs to the \"forceJSON\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally and will be sent even it is null. If it is undefined, it will use the value of {@link CB_Net.REST.forceJSON_DEFAULT} instead. * @property {boolean} [getHeaders={@link CB_Net.REST.getHeaders_DEFAULT}] - Belongs to the \"getHeaders\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally and will be sent even it is null. If it is undefined, it will use the value of {@link CB_Net.REST.getHeaders_DEFAULT} instead. * @property {boolean} [getHeadersOneDimension={@link CB_Net.REST.getHeadersOneDimension_DEFAULT}] - Belongs to the \"getHeadersOneDimension\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally and will be sent even it is null. If it is undefined, it will use the value of {@link CB_Net.REST.getHeadersOneDimension_DEFAULT} instead. * @property {boolean} [getHeadersOneDimensionValues={@link CB_Net.REST.getHeadersOneDimensionValues_DEFAULT}] - Belongs to the \"getHeadersOneDimensionValues\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally and will be sent even it is null. If it is undefined, it will use the value of {@link CB_Net.REST.getHeadersOneDimensionValues_DEFAULT} instead. * @property {boolean} [transparentStatus={@link CB_Net.REST.transparentStatus_DEFAULT}] - Belongs to the \"transparentStatus\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally and will be sent even it is null. If it is undefined, it will use the value of {@link CB_Net.REST.transparentStatus_DEFAULT} instead. * @property {boolean} [transparentHeaders={@link CB_Net.REST.transparentHeaders_DEFAULT}] - Belongs to the \"transparentHeaders\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally and will be sent even it is null. If it is undefined, it will use the value of {@link CB_Net.REST.transparentHeaders_DEFAULT} instead. */ /** * List of [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} actions. Each property name is the name of the action and its value is a {@link CB_Net.REST.actionProcess_ACTIONS} object. Used by the {@link CB_Net.REST.actionProcess} function. * @var * @type {Object} * @default */ CB_Net.REST.actions = {}; //Read the documentation to know how to add new REST actions. //Initializes all values: CB_Net.REST.init = function() { if (CB_Net.REST.initialized) { return CB_Net.REST; } //The object has been initialized: CB_Net.REST.initialized = true; //TODO. return CB_Net.REST; } /** * Processes a desired [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action (which must be previously defined in the {@link CB_Net.REST.actions} object) by its name. &lt;br /&gt; NOTE: Edit the \"CB_proxy.config.php\" file to configure the default proxy (set by default in the value of the {@link CB_Configuration.CrossBase.CB_Net_XHR_PROXY_URL} property). Apart from configuring it, adding some security measures is highly recommended. Have in mind that, for safety reasons, the default proxy only allows to request the URLs defined in the \"$allowedURLs\" array in the \"CB_proxy.config.php\" file. Just edit it to allow other URLs. * @function * @param {string} actionName - The name of the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action that we want to perform. It should be the name of an index defined in the {@link CB_Net.REST.actions} object whose value should be a {@link CB_Net.REST.actionProcess_ACTIONS} object. * @param {*} [additionalData] - Any additional data desired. It will be passed as a parameter when different callbacks are called internally, as their \"additionalData\" parameter. * @param {Object} [XHR] - Used for the \"XHR\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally. * @param {string} [serverURL] - Used for the \"serverURL\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally. If provided, the value defined in the \"serverURL\" parameter of the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed (if any) will be ignored. * @param {boolean} [avoidProxy] - Used for the \"avoidProxy\" parameter of the {@link CB_Net.XHR.callREST} function when it is called internally. If provided, the value defined in the \"avoidProxy\" parameter of the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action being performed (if any) and the default one defined in {@link CB_Net.REST.avoidProxy_DEFAULT} (if any) will be both ignored. * @returns {Object|null} Returns null if the {@link CB_Net.XHR.callREST} function is not called at all (because [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} is not supported or the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action object cannot be found or the route is not well defined or the \"callbackBefore\" returns false, etc.). Otherwise, returns the same that the {@link CB_Net.XHR.callREST} function returns (called internally). */ CB_Net.REST.actionProcess = function(actionName, additionalData, XHR, serverURL, avoidProxy) { if (!CB_Net.XHR.supported()) { return null; } if (typeof(CB_Net.REST.actions[actionName]) === \"undefined\" || CB_Net.REST.actions[actionName] === null) { return null; } else if (typeof(CB_Net.REST.actions[actionName][\"route\"]) === \"undefined\" || CB_Net.REST.actions[actionName][\"route\"] === null) { return null; } //Performs the previous callback (if any): var callbackBeforeReturn = typeof(CB_Net.REST.callbackBefore_PERMANENT === \"function\") ? CB_Net.REST.callbackBefore_PERMANENT(actionName, additionalData) : null; if (callbackBeforeReturn !== false) { if (typeof(CB_Net.REST.actions[actionName][\"callbackBefore\"]) === \"function\") { callbackBeforeReturn = CB_Net.REST.actions[actionName][\"callbackBefore\"](actionName, additionalData); } else if (typeof(CB_Net.REST.actions[actionName][\"callbackBefore\"]) === \"undefined\" &amp;&amp; typeof(CB_Net.REST.callbackBefore_DEFAULT) === \"function\") { callbackBeforeReturn = CB_Net.REST.callbackBefore_DEFAULT(actionName, additionalData); } } if (callbackBeforeReturn === false) { return null; } //If we do not want to perform the action, exists and returns NULL. serverURL = CB_trim(serverURL); if (serverURL === \"\" &amp;&amp; typeof(CB_Net.REST.actions[actionName][\"serverURL\"]) !== \"undefined\" &amp;&amp; CB_isString(CB_Net.REST.actions[actionName][\"serverURL\"])) { serverURL = CB_trim(CB_Net.REST.actions[actionName][\"serverURL\"]); } if (avoidProxy !== true &amp;&amp; avoidProxy !== false) { if (typeof(CB_Net.REST.actions[actionName][\"avoidProxy\"]) !== \"undefined\" &amp;&amp; (CB_Net.REST.actions[actionName][\"avoidProxy\"] === true || CB_Net.REST.actions[actionName][\"avoidProxy\"] === false)) { avoidProxy = CB_Net.REST.actions[actionName][\"avoidProxy\"]; } else if (typeof(CB_Net.REST.avoidProxy_DEFAULT) !== \"undefined\" &amp;&amp; (CB_Net.REST.avoidProxy_DEFAULT === true || CB_Net.REST.avoidProxy_DEFAULT === false)) { avoidProxy = CB_Net.REST.avoidProxy_DEFAULT; } } var route = CB_Net.REST.actions[actionName][\"route\"]; var wildcardData = null; if (typeof(CB_Net.REST.actions[actionName][\"routeWildcardData\"]) === \"function\") { wildcardData = CB_Net.REST.actions[actionName][\"routeWildcardData\"](actionName, additionalData); } else if (typeof(CB_Net.REST.actions[actionName][\"routeWildcardData\"]) === \"undefined\" &amp;&amp; typeof(CB_Net.REST.routeWildcardData_DEFAULT) === \"function\") { wildcardData = CB_Net.REST.routeWildcardData_DEFAULT(actionName, additionalData); } wildcardData = CB_combineAutomatically(CB_Net.REST.routeWildcardData_PERMANENT(actionName, additionalData), wildcardData, false); if (wildcardData !== null) { route = CB_renderString(CB_Net.REST.actions[actionName][\"route\"], wildcardData); } //Gets the data for URL (GET): var dataURL = \"\"; if (typeof(CB_Net.REST.actions[actionName][\"dataURL\"]) === \"function\") { dataURL = CB_Net.REST.actions[actionName][\"dataURL\"](actionName, additionalData); } else if (typeof(CB_Net.REST.actions[actionName][\"dataURL\"]) === \"undefined\" &amp;&amp; typeof(CB_Net.REST.dataURL_DEFAULT) === \"function\") { dataURL = CB_Net.REST.dataURL_DEFAULT(actionName, additionalData); } dataURL = CB_trim(CB_trim(dataURL), [\"?\", \"&amp;\", \" \"]); var dataURLPermanent = CB_Net.REST.dataURL_PERMANENT(actionName, additionalData); dataURLPermanent = CB_trim(CB_trim(dataURLPermanent), [\"?\", \"&amp;\", \" \"]); if (dataURLPermanent !== \"\") { dataURL = CB_combineAutomatically(dataURLPermanent, dataURL, false); } //Defines the data: var data = \"\"; if (typeof(CB_Net.REST.actions[actionName][\"data\"]) === \"function\") { data = CB_Net.REST.actions[actionName][\"data\"](actionName, additionalData); } else if (typeof(CB_Net.REST.actions[actionName][\"data\"]) === \"undefined\" &amp;&amp; typeof(CB_Net.REST.data_DEFAULT) === \"function\") { data = CB_Net.REST.data_DEFAULT(actionName, additionalData); } data = CB_combineAutomatically(CB_Net.REST.data_PERMANENT(actionName, additionalData), data, false); //Defines the headers: var headers = null; if (typeof(CB_Net.REST.actions[actionName][\"headers\"]) === \"function\") { headers = CB_Net.REST.actions[actionName][\"headers\"](actionName, additionalData); } else if (typeof(CB_Net.REST.actions[actionName][\"headers\"]) === \"undefined\" &amp;&amp; typeof(CB_Net.REST.headers_DEFAULT) === \"function\") { headers = CB_Net.REST.headers_DEFAULT(actionName, additionalData); } headers = CB_combineAutomatically(CB_Net.REST.headers_PERMANENT(actionName, additionalData), headers, false); //Defines the allowed statuses considered as successful: var allowedSuccessStatuses = CB_Net.REST.allowedSuccessStatuses_DEFAULT; if (typeof(CB_Net.REST.actions[actionName][\"allowedSuccessStatuses\"]) !== \"undefined\") { allowedSuccessStatuses = CB_Net.REST.actions[actionName][\"allowedSuccessStatuses\"]; } allowedSuccessStatuses = CB_combineAutomatically(CB_Net.REST.allowedSuccessStatuses_PERMANENT, allowedSuccessStatuses, true); //Defines the callback functions: var callbackError = function(actionName, XHRObject, additionalData) { if (typeof(CB_Net.REST.callbackError_PERMANENT) === \"function\") { CB_Net.REST.callbackError_PERMANENT(actionName, XHRObject, additionalData); } if (typeof(CB_Net.REST.actions[actionName][\"callbackError\"]) === \"function\") { CB_Net.REST.actions[actionName][\"callbackError\"](actionName, XHRObject, additionalData); } else if (typeof(CB_Net.REST.actions[actionName][\"callbackError\"]) === \"undefined\" &amp;&amp; typeof(CB_Net.REST.callbackError_DEFAULT) === \"function\") { CB_Net.REST.callbackError_DEFAULT(actionName, XHRObject, additionalData); } }; var callbackErrorWrapper = function(XHRObject) { if (typeof(callbackError) === \"function\") { callbackError.call(XHRObject, actionName, XHRObject, additionalData); } }; var callbackOkWrapper = function(XHRObject) { if (CB_Net.REST.actionIsAborted(XHRObject)) { return; } if (typeof(CB_Net.REST.callbackOk_PERMANENT) === \"function\") { CB_Net.REST.callbackOk_PERMANENT.call(XHRObject, actionName, XHRObject, callbackError, additionalData); } if (typeof(CB_Net.REST.actions[actionName][\"callbackOk\"]) === \"function\") { CB_Net.REST.actions[actionName][\"callbackOk\"].call(XHRObject, actionName, XHRObject, callbackError, additionalData); } else if (typeof(CB_Net.REST.actions[actionName][\"callbackOk\"]) === \"undefined\" &amp;&amp; typeof(CB_Net.REST.callbackOk_DEFAULT) === \"function\") { CB_Net.REST.callbackOk_DEFAULT.call(XHRObject, actionName, XHRObject, callbackError, additionalData); } }; //Calls the REST server: return CB_Net.XHR.callREST ( //typeof(CB_Net.REST.actions[actionName][\"serverURL\"]) !== \"undefined\" &amp;&amp; CB_isString(CB_Net.REST.actions[actionName][\"serverURL\"]) &amp;&amp; CB_trim(CB_Net.REST.actions[actionName][\"serverURL\"]) !== \"\" ? CB_trim(CB_Net.REST.actions[actionName][\"serverURL\"]) : serverURL, //serverURL serverURL, //serverURL route, //route dataURL, //dataURL typeof(CB_Net.REST.actions[actionName][\"method\"]) !== \"undefined\" &amp;&amp; CB_isString(CB_Net.REST.actions[actionName][\"method\"]) &amp;&amp; CB_trim(CB_Net.REST.actions[actionName][\"method\"]) !== \"\" ? CB_trim(CB_Net.REST.actions[actionName][\"method\"]) : CB_Net.REST.method_DEFAULT, //method data, //data headers, //headers typeof(CB_Net.REST.actions[actionName][\"responseType\"]) !== \"undefined\" ? CB_Net.REST.actions[actionName][\"responseType\"] : CB_Net.REST.responseType_DEFAULT, //responseType avoidProxy, //avoidProxy typeof(CB_Net.REST.actions[actionName][\"forceJSON\"]) !== \"undefined\" ? CB_Net.REST.actions[actionName][\"forceJSON\"] : CB_Net.REST.forceJSON_DEFAULT, //forceJSON typeof(CB_Net.REST.actions[actionName][\"getHeaders\"]) !== \"undefined\" ? CB_Net.REST.actions[actionName][\"getHeaders\"] : CB_Net.REST.getHeaders_DEFAULT, //getHeaders typeof(CB_Net.REST.actions[actionName][\"getHeadersOneDimension\"]) !== \"undefined\" ? CB_Net.REST.actions[actionName][\"getHeadersOneDimension\"] : CB_Net.REST.getHeadersOneDimension_DEFAULT, //headersForceOneDimension typeof(CB_Net.REST.actions[actionName][\"getHeadersOneDimensionValues\"]) !== \"undefined\" ? CB_Net.REST.actions[actionName][\"getHeadersOneDimensionValues\"] : CB_Net.REST.getHeadersOneDimensionValues_DEFAULT, //headersForceOneDimensionValues typeof(CB_Net.REST.actions[actionName][\"transparentStatus\"]) !== \"undefined\" ? CB_Net.REST.actions[actionName][\"transparentStatus\"] : CB_Net.REST.transparentStatus_DEFAULT, //transparentStatus typeof(CB_Net.REST.actions[actionName][\"transparentHeaders\"]) !== \"undefined\" ? CB_Net.REST.actions[actionName][\"transparentHeaders\"] : CB_Net.REST.transparentHeaders_DEFAULT, //transparentHeaders callbackOkWrapper, //callbackOk callbackErrorWrapper, //callbackError allowedSuccessStatuses, //allowedSuccessStatuses XHR //XHR ); } /** * Cancels a [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action (by its [AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)}/[XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} request associated) by executing the \"abort\" method of the given [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} object (if available) and sets its \"aborted\" property to true if succeeds. When a [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action is aborted, the callbackOk functions associated (if any) will not be called (unless they have been called already). * @function * @param {Object} XHR - The [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} object that we want to abort. * @returns {boolean} Returns true if the \"abort\" method of the given [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} object could be called and the \"aborted\" property was set to true. Otherwise, returns false. */ CB_Net.REST.actionAbort = function(XHR) { if (typeof(XHR) === \"object\" &amp;&amp; XHR !== null &amp;&amp; typeof(XHR.abort) === \"function\") { XHR.abort(); XHR.aborted = true; return true; } return false; } /** * Tries to revert the abortion of a [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action (by its [AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)}/[XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} request associated) by setting the \"aborted\" property of the given [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} object to false. If this function is called before the \"callbackOk\" functions associated to the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action (if any) are called, they could finally be called perhaps (depending on each case, could be different). Have in mind that, after calling {@link CB_Net.REST.actionAbort}, the \"abort\" method of the [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} object was probably called already (if available). * @function * @param {Object} XHR - The [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} object whose abortion we want to cancel. * @returns {boolean} Returns true if the \"aborted\" property was set to false. Otherwise, returns false. */ CB_Net.REST.actionAbortCancel = function(XHR) { if (typeof(XHR) === \"object\" &amp;&amp; XHR !== null) { XHR.aborted = false; return true; } return false; } /** * Returns whether a [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} action is aborted or not (by its [AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)}/[XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} request associated). * @function * @param {Object} XHR - The [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} object that we want to check. * @returns {boolean} Returns true if the \"aborted\" property is set to true. Otherwise, returns false. */ CB_Net.REST.actionIsAborted = function(XHR) { return (typeof(XHR) === \"object\" &amp;&amp; XHR !== null &amp;&amp; XHR.aborted === true); } } × Search results Close "},"CrossBase_net_sockets_CB_Net_Sockets.js.html":{"id":"CrossBase_net_sockets_CB_Net_Sockets.js.html","title":"Source: CrossBase/net/sockets/CB_Net_Sockets.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/net/sockets/CB_Net_Sockets.js /** * @file Sockets and related management. Contains the {@link CB_Net.Sockets} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ if (typeof(CB_Net) === \"undefined\") { var CB_Net = function() { return CB_Net; }; } /** * Static class to manage sockets and related. It will return itself if it is tried to be instantiated. It uses [SockJS-client]{@link https://github.com/sockjs/sockjs-client}. * @namespace */ CB_Net.Sockets = function() { return CB_Net.Sockets; }; { CB_Net.Sockets.initialized = false; //It will tells whether the object has been initialized or not. /** Property that contains the functions and properties related with the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library. * @namespace CB_Net.Sockets.SockJS */ CB_Net.Sockets.SockJS = {}; //Keeps the methods and properties related to SockJS library. /** * Keeps the last SockJS created. * @var * @readonly * @type {Object|null} * @default */ CB_Net.Sockets.SockJS.websocketLast = null; //Keeps the last websocket object. //Initializes all values: CB_Net.Sockets.init = function() { if (CB_Net.Sockets.initialized) { return CB_Net.Sockets; } //The object has been initialized: CB_Net.Sockets.initialized = true; //TODO. return CB_Net.Sockets; } /** * Alias for {@link CB_Net.Sockets.SockJS.listen}. * @function CB_Net.Sockets.SockJS.open * @see {@link CB_Net.Sockets.SockJS.listen} */ /** * Creates the websockets object and sets the listeners. Using the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library internally. * @function * @param {string} serverURL - The URL of the SockJS server. This will be used as the first parameter when it calls the constructor of SockJS internally. Following the same rules as in the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library documentation (the parameter is called \"url\"). * @param {function} [onOpen] - Function for the event \"onopen\" used by the SockJS object. Following the same rules as in the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library documentation. * @param {function} [onClose] - Function for the event \"onclose\" used by the SockJS object. Following the same rules as in the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library documentation. * @param {function} [onMessage] - Function for the event \"onmessage\" used by the SockJS object. Following the same rules as in the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library documentation. * @param {function} [onError] - Function for the event \"onerror\" used by the SockJS object. Following the same rules as in the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library documentation. * @param {Object} [options] - The desired options for the SockJS object. This will be used as the third parameter when it calls the constructor of SockJS internally. Following the same rules as in the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library documentation (the parameter is called \"options\"). * @param {array} [protocols] - This will be used as the second parameter when it calls the constructor of SockJS internally. Following the same rules as in the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library documentation (the parameter is called \"_reserved\"). * @returns {Object|null} Returns a SockJS object. Read the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library documentation for more information. In the case of error, returns null. */ CB_Net.Sockets.SockJS.listen = function(serverURL, onOpen, onClose, onMessage, onError, options, protocols) { try { var websocket = new SockJS(serverURL, protocols || undefined, options || undefined); //Creates the SockJS object. if (typeof(websocket) === \"undefined\" || websocket === null) { if (typeof(onError) === \"function\") { onError({ \"error\" : \"CANNOT OPEN THE CONNECTION TO \" + serverURL }); } return null; } if (typeof(onOpen) === \"function\") { websocket.onopen = onOpen; } //Example: function webSocketsOnOpen(evt) { CB_console(websocket.transport); } if (typeof(onClose) === \"function\") { websocket.onclose = onClose; } //Example: function webSocketsOnClose(evt) { CB_console(\"Websocket closed. Reason: \" + evt.reason); } if (typeof(onMessage) === \"function\") { websocket.onmessage = onMessage; } //Example: function webSocketsOnMessage(evt) { CB_console(evt.data); } if (typeof(onError) === \"function\") { websocket.onerror = onError; } //Example: function webSocketsOnError(evt) { CB_console(\"Websocket error: \" + JSON.stringify(evt)); } CB_Net.Sockets.SockJS.websocketLast = websocket; //Stores the object as the last one. return websocket; } catch(E) { if (typeof(onError) === \"function\") { onError({ \"error\" : \"ERROR CALLING 'listen': \" + E }); } return null; } } /** * Sends a websockets message. Using the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library internally. * @function * @param {string} message - The message that we want to send. This will be used as the first and unique parameter when it calls the \"send\" function of the SockJS object internally. Following the same rules as in the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library documentation. * @param {function} [websocket={@link CB_Net.Sockets.SockJS.websocketLast}] - The SockJS object that we want to use. If not provided, it will try to use the last one created (if any) which is stored in {@link CB_Net.Sockets.SockJS.websocketLast}. * @param {function} [onError] - Function for the event \"onerror\" used by the SockJS object. If provided, it will replace the previous one (if any). Following the same rules as in the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library documentation. * @returns {undefined|false} Returns undefined (the same as the \"send\" function of the SockJS object) if the SockJS has been used or false otherwise. */ CB_Net.Sockets.SockJS.send = function(message, websocket, onError) { websocket = websocket || CB_Net.Sockets.SockJS.websocketLast; if (typeof(websocket) !== \"undefined\" &amp;&amp; websocket !== null &amp;&amp; typeof(websocket.send) === \"function\") { if (typeof(onError) === \"function\") { websocket.onerror = onError; } //Example: function webSocketsOnError(evt) { CB_console(\"Websocket error: \" + JSON.stringify(evt)); } var returnValue = false; try { returnValue = websocket.send(message); } catch(E) { if (typeof(onError) === \"function\") { onError({ \"error\" : \"ERROR CALLING 'send': \" + E }); } returnValue = false; } return returnValue; } else { if (typeof(onError) === \"function\") { onError({ \"error\" : \"CANNOT FIND WEBSOCKETS OBJECT\" }); } return false; } } /** * Tries to close the websockets connection. Using the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library internally. * @function * @param {function} [websocket={@link CB_Net.Sockets.SockJS.websocketLast}] - The SockJS object that we want to use. If not provided, it will try to use the last one created (if any) which is stored in {@link CB_Net.Sockets.SockJS.websocketLast}. * @param {function} [onError] - Function for the event \"onerror\" used by the SockJS object. If provided, it will replace the previous one (if any). Following the same rules as in the [SockJS client]{@link https://github.com/sockjs/sockjs-client} library documentation. * @returns {undefined|false} Returns undefined (the same as the \"close\" function of the SockJS object) if the SockJS has been used or false otherwise. */ CB_Net.Sockets.SockJS.close = function(websocket, onError) { websocket = websocket || CB_Net.Sockets.SockJS.websocketLast; if (typeof(websocket) !== \"undefined\" &amp;&amp; websocket !== null &amp;&amp; typeof(websocket.close) === \"function\") { if (typeof(onError) === \"function\") { websocket.onerror = onError; } //Example: function webSocketsOnError(evt) { CB_console(\"Websocket error: \" + JSON.stringify(evt)); } var returnValue = false; try { returnValue = websocket.close(); if (websocket === CB_Net.Sockets.SockJS.websocketLast) { CB_Net.Sockets.SockJS.websocketLast = null; } } catch(E) { if (typeof(onError) === \"function\") { onError({ \"error\" : \"ERROR CALLING 'close': \" + E }); } returnValue = false; } return returnValue; } else { if (typeof(onError) === \"function\") { onError({ \"error\" : \"CANNOT FIND WEBSOCKETS OBJECT\" }); } return false; } } } × Search results Close "},"CrossBase_net_XHR_CB_Net_XHR.js.html":{"id":"CrossBase_net_XHR_CB_Net_XHR.js.html","title":"Source: CrossBase/net/XHR/CB_Net_XHR.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/net/XHR/CB_Net_XHR.js /** * @file [XMLHttpRequest]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} ([XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest}, [AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)}) and related management. Contains the {@link CB_Net.XHR} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ if (typeof(CB_Net) === \"undefined\") { var CB_Net = function() { return CB_Net; }; } /** * Static class to manage [XMLHttpRequest]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} ([XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest}, [AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)}) and related. It will return itself if it is tried to be instantiated. * @namespace * @todo Think about providing an easy way to abort XHR (AJAX) calls. */ CB_Net.XHR = function() { return CB_Net.XHR; }; { CB_Net.XHR.initialized = false; //It will tells whether the object has been initialized or not. //Initializes all values: CB_Net.XHR.init = function() { if (CB_Net.XHR.initialized) { return CB_Net.XHR; } //The object has been initialized: CB_Net.XHR.initialized = true; //TODO. return CB_Net.XHR; } CB_Net.XHR._supportedReturnCache = null; /** * Returns whether [AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)} ([XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest}) is available or not. * @function * @returns {boolean} Returns true if [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} ([AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)}) objects can be used. */ CB_Net.XHR.supported = function() { if (CB_Net.XHR._supportedReturnCache !== null) { return CB_Net.XHR._supportedReturnCache; } else { CB_Net.XHR._supportedReturnCache = (CB_Net.XHR.get() !== null); return CB_Net.XHR._supportedReturnCache; } } //Returns an AJAX object: //var CB_Net.XHR._getXmlHttpVersionsIE = [\"Msxml2.XMLHTTP.7.0\", \"MSXML2.XmlHttp.6.0\", \"MSXML2.XmlHttp.5.0\", \"MSXML2.XmlHttp.4.0\", \"MSXML2.XmlHttp.3.0\", \"Msxml2.XMLHTTP\", \"Microsoft.XMLHTTP\"]; CB_Net.XHR._getXmlHttpVersionsIE = [\"MSXML2.XmlHttp.6.0\", \"MSXML2.XmlHttp.3.0\", \"Msxml2.XMLHTTP\", \"Microsoft.XMLHTTP\"]; //XmlHttpVersions in order of preference for old IE versions. CB_Net.XHR._getXmlHttpVersionsIELastIndexWorked = null; //Defines the last index of CB_XmlHttpVersion that worked (for optimization). /** * Returns a new [AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)} ([XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest}) object, if possible. * @function * @returns {Object|null} Returns a new [AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)} ([XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest}) object if it has been possible to create it or null otherwise. */ CB_Net.XHR.get = function() { if (typeof XMLHttpRequest !== \"undefined\") //if (window.XMLHttpRequest). { return new XMLHttpRequest(); } else if (typeof(ActiveXObject) !== \"undefined\") { if (CB_Net.XHR._getXmlHttpVersionsIELastIndexWorked !== null) { return new ActiveXObject(CB_Net.XHR._getXmlHttpVersionsIE[CB_Net.XHR._getXmlHttpVersionsIELastIndexWorked]); } else { var XHR = null; for (var x = 0, getXmlHttpVersionsIELength = CB_Net.XHR._getXmlHttpVersionsIE.length; x &lt; getXmlHttpVersionsIELength; x++) { try { XHR = new ActiveXObject(CB_Net.XHR._getXmlHttpVersionsIE[x]); CB_Net.XHR._getXmlHttpVersionsIELastIndexWorked = x; //Defines this index as the last working one (for optimization). return XHR; } catch(E) {} } return null; } } return null; } /** * Object containing the [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} and their values. * @memberof CB_Net.XHR * @typedef {Object} CB_Net.XHR.HEADERS * @property {Object} HTTPHeaderName - Each property name is an [HTTP header]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} and its value is the desired one for this header. * @example { \"Content-Type\" : \"text/plain; charset=x-user-defined\", \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" } */ /** * Performs an [AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)} ([XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest}) call. * @function * @param {string} URL - The URL that we want to call. It can also contain URL (GET) parameters. * @param {string} [method='POST'] - The [HTTP method]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods} that will be used to perform the call (GET, POST, PUT, DELETE, etc.). * @param {string|Object} [data] - The data that we want to send. If a string is given and \"GET\" method is being used, it will assume they are GET (URL) parameters and will be attached at the end of the URL given. If something which is not a string is given, it will assume it is a [JSON]{@link https://en.wikipedia.org/wiki/JSON} object and will try to convert it into a string (using the [JSON.stringify]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify} function internally) before sending it. * @param {CB_Net.XHR.HEADERS} [headers] - Object containing the [HTTP header]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} names and their values that we want to send (used internally by the [setRequestHeader]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader} method of the [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest}). * @param {string} [responseType] - If provided, it will be used for the [responseType]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType} property of the [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} (if available). * @param {string} [mimeType] - [MIME type]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types} that will be used to override the default one returned by the server. Only used when the client supports the [overrideMimeType]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/overrideMimeType} method of the [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest}. * @param {function} [callbackFunction] - Function that will be used for the [onreadystatechange]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange} property of the [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest}. The unique parameter that it will receive is the [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} used by the request. If provided, the \"callbackFunctionOK\" and \"callbackFunctionError\" parameters will not be used even they were also provided. * @param {function} [callbackFunctionOK] - Function that will be called by an internally-created function used in the [onreadystatechange]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange} property of the [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} when the [readyState]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState} property is 4 and the [status]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status} property is included in the \"allowedSuccessStatuses\" desired. The first parameter it will receive is the [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} used by the request and the second one will be the \"callbackFunctionError\" function provided (if any). It will not be used if the parameter \"callbackFunction\" is provided. * @param {function} [callbackFunctionError] - Function that will be called by an internally-created function used in the [onreadystatechange]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange} property of the [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} when the [readyState]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState} property is 4 and the [status]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status} property is not included in the \"allowedSuccessStatuses\" desired. The first parameter it will receive is the [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} used by the request and the second one will be the \"callbackFunctionOk\" function provided (if any). It will not be used if the parameter \"callbackFunction\" is provided. * @param {integer|array} [allowedSuccessStatuses=200] - An integer or a numeric array with a list of integers with the status or statuses that will be considered as a success call by the \"callbackFunctionOK\" function (only when it is used) when the response comes. * @param {boolean} [asynchronous=true] - Defines whether to make a request asynchronously or not. It will be used for the third parameter of the method [open]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open} of the [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest}. * @param {Object} [XHR] - The [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} that we want to use for the call. If not provided, it will try to create a new one internally. * @returns {Object|null} Returns null if the URL provided was empty or the [AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)} ([XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest}) object provided is not a valid object or it could not be created a new one internally. Otherwise, it returns the [AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)} ([XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest}) object used to try to perform the call (even that maybe it failed or will fail later). * @todo Think about providing a way to choose whether we want the \"data\" provided to be added to the URL when the \"GET\" method is used or not. * @todo Describe better what kind of [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} will the different callbacks receive, as in some cases (as when using [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer}) they can contain some special properties with [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers}, etc. */ CB_Net.XHR.call = function(URL, method, data, headers, responseType, mimeType, callbackFunction, callbackFunctionOK, callbackFunctionError, allowedSuccessStatuses, asynchronous, XHR) { var failFunction = function(XHR) { if (typeof(callbackFunction) === \"function\") { callbackFunction.call(XHR, XHR); } else if (typeof(callbackFunctionError) === \"function\") { callbackFunctionError.call(XHR, XHR, callbackFunctionOK); } }; //If the URL is empty, exits the function: URL = CB_trim(URL); if (URL === \"\") { failFunction({ readyState: 4, status: 400, errorMessage: \"URL is empty\", originalXHR: XHR }); return null; } //If not given, sets the default parameters: method = CB_trim(method).toUpperCase(); if (method === \"\") { method = \"POST\"; } //Request method by default. if (typeof(headers) !== \"object\" || headers === null) //Sets headers by default: { headers = {}; } mimeType = CB_trim(mimeType); //If it was unset or null, it will be an empty string. responseType = CB_trim(responseType).toLowerCase(); //If it was unset or null, it will be an empty string. if (asynchronous !== false) { asynchronous = true; } //Async by default. //By default, allows 200 success status only: if (!CB_isArray(allowedSuccessStatuses)) { allowedSuccessStatuses = [200]; } //Creates the AJAX object: if (typeof(XHR) === \"undefined\" || XHR === null || !XHR) { XHR = CB_Net.XHR.get(); } //If the XHR object is null, exits the function: if (XHR === null) { failFunction({ readyState: 4, status: 400, errorMessage: \"XHR is null\", originalXHR: XHR }); return null; } //Processes the data (if any): if (typeof(data) !== \"undefined\" &amp;&amp; data !== null &amp;&amp; !CB_isString(data)) //If data is not a string, we assume it is JSON data. { data = JSON.stringify(data); //data = CB_Net.URLEncode(JSON.stringify(data)); } else { data = CB_trim(data); //If there are data and the method is GET, it adds them to the URL: if (data !== \"\" &amp;&amp; method === \"GET\") { if (CB_indexOf(URL, \"?\") === -1) { URL += \"?\" + data; } //There was not ? symbol in the URL, so we add it. else { URL += \"&amp;\" + data; } //There was ? symbol in the URL, so we add the &amp; symbol. //TODO: consider setting \"data\" to null or empty string since we do not need them to send them in the \"send\" method (we have already added them in the \"URL\" variable). } } //Opens the connection: try //Using try-catch to avoid problems with IE5.5: { XHR.open(method, URL, asynchronous); } catch(E) { var originalXHR = XHR; var fakeXHR = { readyState: 4, status: 500, errorMessage: \"Failed when using open method\", originalXHR: XHR }; try { XHR.readyState = 4; XHR.status = 500; XHR.errorMessage = \"Failed when using open method\"; } catch(E) { XHR = fakeXHR; } if (XHR.readyState !== 4) { XHR = fakeXHR; } //Some web clients as IE9 will not fail when try to edit properties but they will not end being modified. failFunction(XHR); return originalXHR; } //Applies the given headers (if any): //if (mimeType !== null) { headers[\"Content-Type\"] = mimeType; } for (var headerName in headers) { XHR.setRequestHeader(headerName, headers[headerName]); } //Applies the given mime type (if any): if (XHR.overrideMimeType &amp;&amp; mimeType !== \"\") { //XHR.overrideMimeType(\"text/plain; charset=UTF-8\"); XHR.overrideMimeType(mimeType); } //Applies the given response type (if any): if (typeof(XHR.responseType) !== \"undefined\" &amp;&amp; responseType !== \"\") { XHR.responseType = responseType; } /* else { if (responseType === \"\" || responseType === \"text\") { XHR.overrideMimeType(\"text/plain; charset=UTF-8\"); } else if (responseType === \"xml\") { XHR.overrideMimeType(\"text/xml\"); } else if (responseType === \"arraybuffer\") { //XHR.overrideMimeType(\"text/plain; charset=x-user-defined\"); } }*/ //If set, defines the callback function: if (typeof(callbackFunction) === \"function\") { XHR.onreadystatechange = function() { callbackFunction.call(XHR, XHR); }; } //...otherwise, defines the callback functions for OK and error status: else { XHR.onreadystatechange = function() { //if (XHR.readyState == 4) if (XHR.readyState === 4) { //if (XHR.status == 200 || allowOtherSuccessStatus &amp;&amp; XHR.status == 206) if (CB_indexOf(allowedSuccessStatuses, parseInt(XHR.status)) !== -1) { if (typeof(callbackFunctionOK) === \"function\") { callbackFunctionOK.call(XHR, XHR, callbackFunctionError); } } //else if (XHR.readyState == 4 &amp;&amp; (XHR.status == 0 || XHR.status == 502 || XHR.status == 12002 || XHR.status == 12029 || XHR.status == 12030 || XHR.status == 12031 || XHR.status == 12029 || XHR.status == 12152 || XHR.status == 12159)) //else if (XHR.status !== 12152 &amp;&amp; XHR.status !== 12030 &amp;&amp; XHR.status !== 0 &amp;&amp; XHR.status !== 12002 &amp;&amp; XHR.status !== 12007 &amp;&amp; XHR.status !== 12029 &amp;&amp; XHR.status !== 12031) else { if (typeof(callbackFunctionError) === \"function\") { callbackFunctionError.call(XHR, XHR, callbackFunctionOK); } } } } } //Sends the XHR request: XHR.send(data); //Returns the XHR object: return XHR; } /** * Performs a standard [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} request to send form data by POST (no files). Uses the {@link CB_Net.XHR.call} function internally with \"POST\" method, asynchronously and \"mimeType\" parameter not provided. * @function * @param {string} URL - Used for the \"URL\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {string|Object} [data] - Used for the \"data\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {CB_Net.XHR.HEADERS} [headers={ \"Content-Type\" : \"application/x-www-form-urlencoded; charset=\" + charset, \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" }] - Object containing the [HTTP header]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} names and their values that we want to send. If not provided, it will use the default one that will include the charset defined by the \"charset\" parameter. An empty object ({}) can be used if we do not want to send any [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} at all. Used for the \"headers\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {string} [responseType] - Used for the [responseType]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType} parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {string} [charset='UTF-8'] - The charset for the \"Content-Type\" [HTTP header]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} that will be sent by default only when no \"headers\" parameter is provided. * @param {function} [callbackFunction] - Used for the \"callbackFunction\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {function} [callbackFunctionOK] - Used for the \"callbackFunctionOK\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {function} [callbackFunctionError] - Used for the \"callbackFunctionError\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {integer|array} [allowedSuccessStatuses=200] - Used for the \"allowedSuccessStatuses\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {Object} [XHR] - Used for the \"XHR\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @returns {Object|null} Returns the same that the {@link CB_Net.XHR.call} function returns (called internally). */ CB_Net.XHR.callForm = function(URL, data, headers, responseType, charset, callbackFunction, callbackFunctionOK, callbackFunctionError, allowedSuccessStatuses, XHR) { //If not given, sets the default parameters: charset = CB_trim(charset); if (typeof(charset) === \"undefined\" || charset === \"\") { charset = \"UTF-8\"; } //Default charset. if (typeof(headers) !== \"object\" || headers === null) { headers = { \"Content-Type\" : \"application/x-www-form-urlencoded; charset=\" + charset, \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" }; } //Makes the AJAX request function and returns the same: return CB_Net.XHR.call ( URL, //URL \"POST\", //method data, //data headers, //headers responseType, //responseType null, //mimeType callbackFunction, //callbackFunction callbackFunctionOK, //callbackFunctionOK callbackFunctionError, //callbackFunctionError allowedSuccessStatuses, //allowedSuccessStatuses true, //asynchronous XHR //XHR object ); } /** * Performs a standard [XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} request for a binary file. Uses the {@link CB_Net.XHR.call} function internally with \"GET\" method, using \"text/plain; charset=x-user-defined\" for the \"mimeType\" parameter and asynchronously. * @function * @param {string} URL - Used for the \"URL\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {string|Object} [data] - Used for the \"data\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {CB_Net.XHR.HEADERS} [headers={ \"Content-Type\" : \"text/plain; charset=x-user-defined\", \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" }] - Object containing the [HTTP header]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} names and their values that we want to send. If not provided, it will use the default one. An empty object ({}) can be used if we do not want to send any [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} at all. Used for the \"headers\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {'arraybuffer'|'blob'|''} [blobOrArrayBuffer='arraybuffer'] - Used for the [responseType]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType} parameter of the {@link CB_Net.XHR.call} function when it is called internally. If an empty string is provided, the [responseType]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType} parameter will not be modified. * @param {function} [callbackFunction] - Used for the \"callbackFunction\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {function} [callbackFunctionOK] - Used for the \"callbackFunctionOK\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {function} [callbackFunctionError] - Used for the \"callbackFunctionError\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {integer|array} [allowedSuccessStatuses=200] - Used for the \"allowedSuccessStatuses\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @param {Object} [XHR] - Used for the \"XHR\" parameter of the {@link CB_Net.XHR.call} function when it is called internally. * @returns {Object|null} Returns the same that the {@link CB_Net.XHR.call} function returns (called internally). */ CB_Net.XHR.callBinary = function(URL, data, headers, blobOrArrayBuffer, callbackFunction, callbackFunctionOK, callbackFunctionError, allowedSuccessStatuses, XHR) { //If not given, sets the default parameters: if (typeof(headers) !== \"object\" || headers === null) { headers = { \"Content-Type\" : \"text/plain; charset=x-user-defined\", \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" }; } blobOrArrayBuffer = typeof(blobOrArrayBuffer) === \"undefined\" || blobOrArrayBuffer === null ? \"arraybuffer\" : CB_trim(blobOrArrayBuffer).toLowerCase(); if (blobOrArrayBuffer !== \"blob\" &amp;&amp; blobOrArrayBuffer !== \"\") //Only allows to be \"blob\", \"arraybuffer\" or an empty string: { blobOrArrayBuffer = \"arraybuffer\"; } //Makes the AJAX request function and returns the same: return CB_Net.XHR.call ( URL, //URL \"GET\", //method data, //data headers, //headers blobOrArrayBuffer, //responseType \"text/plain; charset=x-user-defined\", //mimeType callbackFunction, //callbackFunction callbackFunctionOK, //callbackFunctionOK callbackFunctionError, //callbackFunctionError allowedSuccessStatuses, //allowedSuccessStatuses true, //asynchronous XHR //XHR object ); } /** * Performs an [AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)} ([XHR]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest}) call through the proxy (made with [PHP]{@link https://en.wikipedia.org/wiki/PHP} language and using [cURL]{@link https://en.wikipedia.org/wiki/CURL}, so it will need a server which supports that) to avoid [cross-domain request]{@link https://en.wikipedia.org/wiki/Cross-origin_resource_sharing} limitations of [AJAX]{@link https://en.wikipedia.org/wiki/Ajax_(programming)}. Uses the {@link CB_Net.XHR.callForm} function (with \"headers\" and \"charset\" parameters not provided) internally to call the proxy. &lt;br /&gt; NOTE: Edit the \"CB_proxy.config.php\" file to configure the default proxy (set by default in the value of the {@link CB_Configuration.CrossBase.CB_Net_XHR_PROXY_URL} property). Apart from configuring it, adding some security measures is highly recommended. Have in mind that, for safety reasons, the default proxy only allows to request the URLs defined in the \"$allowedURLs\" array in the \"CB_proxy.config.php\" file. Just edit it to allow other URLs. * @function * @param {string} URL - The URL that we want the proxy to call for us. It can also contain URL (GET) parameters. * @param {string} [method='POST'] - The [HTTP method]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods} (GET, POST, PUT, DELETE, etc.) that we want the proxy to use for us when performing the call. * @param {string|Object} [data] - The data that we want to send through the proxy to the final server. If something which is not a string is given, it will assume it is a [JSON]{@link https://en.wikipedia.org/wiki/JSON} object and will try to convert it into a string (using the [JSON.stringify]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify} function internally) before sending it. * @param {CB_Net.XHR.HEADERS} [headers] - Object ([JSON]{@link https://en.wikipedia.org/wiki/JSON} format) containing the [HTTP header]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} names and their values that we want the proxy to send to the final server. Even if not provided, the proxy could end sending some [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} depending on the [cURL]{@link https://en.wikipedia.org/wiki/CURL} configuration used. * @param {string} [responseType] - Used for the [responseType]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType} parameter of the {@link CB_Net.XHR.callForm} function when it is called internally. * @param {boolean} [forceJSON=false] - If it is set to true, the response from the proxy will be a [JSON]{@link https://en.wikipedia.org/wiki/JSON} object with the [status]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status} property containing the [HTTP status]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Status} of the reply, the [response]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response} property with the response content itself and the \"headers\" property (only when \"getHeaders\" parameters is set to true) with the [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} of the reply, all belonging to the response from the final server. * @param {boolean} [getHeaders=false] - If it is set to true, the proxy will answer including the [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} from the final server. The [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} will be included in the final response string at the beginning (before the response content) if the \"forceJSON\" parameter is not set to true or in the \"headers\" property of the [JSON]{@link https://en.wikipedia.org/wiki/JSON} object that belongs to the response otherwise. * @param {boolean} [headersForceOneDimension=false] - If it is set to true, the proxy will consider that the [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} of the response from the final server are not multidimensional which means that the final server would never reply the same [HTTP header]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} repeated multiple times (with different values, normally) in different chunks separated by double new lines (\"\\r\\n\\r\\n\"). Default value (false) is recommended. Needs \"getHeaders\" set to true. * @param {boolean} [headersForceOneDimensionValues=false] - If it is set to true, the proxy will only consider one value per [HTTP header]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} from the response from the final server. Default value (false) is recommended. Needs \"getHeaders\" set to true. * @param {boolean} [transparentStatus=false] - If it is set to true, the proxy will reply us with the same status as the final server in its HTTP response. * @param {boolean} [transparentHeaders=false] - If it is set to true, the proxy will reply us with the same [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} as the final server in its HTTP response. * @param {function} [callbackFunction] - Used for the \"callbackFunction\" parameter of the {@link CB_Net.XHR.callForm} function when it is called internally. * @param {function} [callbackFunctionOK] - Used for the \"callbackFunctionOK\" parameter of the {@link CB_Net.XHR.callForm} function when it is called internally. * @param {function} [callbackFunctionError] - Used for the \"callbackFunctionError\" parameter of the {@link CB_Net.XHR.callForm} function when it is called internally. * @param {integer|array} [allowedSuccessStatuses=200] - Used for the \"allowedSuccessStatuses\" parameter of the {@link CB_Net.XHR.callForm} function when it is called internally. * @param {Object} [XHR] - Used for the \"XHR\" parameter of the {@link CB_Net.XHR.callForm} function when it is called internally. * @returns {Object|null} Returns the same that the {@link CB_Net.XHR.callForm} function returns (called internally). * @todo Document PHP proxy more. */ CB_Net.XHR.callProxy = function(URL, method, data, headers, responseType, forceJSON, getHeaders, headersForceOneDimension, headersForceOneDimensionValues, transparentStatus, transparentHeaders, callbackFunction, callbackFunctionOK, callbackFunctionError, allowedSuccessStatuses, XHR) { //Adds the proxy data and session (for users without cookies enabled) to the data: var proxyVariables = \"p_url=\" + CB_Net.URLValueEncode(URL); method = CB_trim(method).toUpperCase(); if (method === \"\") { method = \"POST\"; } //Request method by default. proxyVariables += \"&amp;p_method=\" + CB_Net.URLValueEncode(method); if (typeof(headers) === \"object\" &amp;&amp; headers !== null) { proxyVariables += \"&amp;p_headers=\" + CB_Net.URLValueEncode(JSON.stringify(headers)); } if (forceJSON) { proxyVariables += \"&amp;p_force_json=yes\"; } if (getHeaders) { proxyVariables += \"&amp;p_get_headers=yes\"; } if (headersForceOneDimension) { proxyVariables += \"&amp;p_get_headers_on_dimension=yes\"; } if (headersForceOneDimensionValues) { proxyVariables += \"&amp;p_get_headers_on_dimension_values=yes\"; } if (transparentStatus) { proxyVariables += \"&amp;p_transparent_status=yes\"; } if (transparentHeaders) { proxyVariables += \"&amp;p_transparent_headers=yes\"; } //proxyVariables += \"&amp;\" + SESSION_PARAMETER; //proxyVariables += \"&amp;ajax=true\"; //proxyVariables += \"&amp;php_root=\" + PROJECT_PATH_FROM_PROXY; if (typeof(data) !== \"undefined\" &amp;&amp; data !== null &amp;&amp; !CB_isString(data)) //If data is not a string, we assume it is JSON data. { data = JSON.stringify(data); } else { data = CB_trim(data); } if (data !== \"\") { data = \"p_data=\" + CB_Net.URLValueEncode(data) + \"&amp;\" + proxyVariables; } else { data = proxyVariables; } //Calls the proxy by post method: return CB_Net.XHR.callForm ( CB_Configuration[CB_BASE_NAME].CB_Net_XHR_PROXY_URL, //URL of the proxy. data, //data null, //headers responseType, //responseType null, //charset callbackFunction, //callbackFunction callbackFunctionOK, //callbackFunctionOK callbackFunctionError, //callbackFunctionError allowedSuccessStatuses, //allowedSuccessStatuses XHR //XHR ); } /** * Performs a [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} call to a [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} server. Uses the {@link CB_Net.XHR.callProxy} function (without \"callbackFunction\" parameter provided) internally if we do not want to avoid the proxy or uses the {@link CB_Net.XHR.call} function (asynchronously, with \"mimeType\" and \"callbackFunction\" parameters not provided) otherwise. * @function * @param {string} [serverURL={@link CB_Net.REST.SERVER_URL_DEFAULT}] - The URL of the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} server that we want to call. It should not contain URL (GET) parameters. It can also contain the [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} path (route), although it is recommended to set it in the \"route\" parameter. * @param {string} [route] - The [REST]{@link https://en.wikipedia.org/wiki/Representational_state_transfer} path (route) we want to request. It can also contain URL (GET) parameters, although it is recommended to set them in the \"dataURL\" parameter. * @param {string} [dataURL] - The URL (GET) data that we want to send. * @param {string} [method='POST'] - Used for the \"method\" parameter for the {@link CB_Net.XHR.callProxy} function or for the {@link CB_Net.XHR.call} function (if no proxy is allowed) when it is called internally. * @param {string|Object} [data] - Used for the \"data\" parameter of the {@link CB_Net.XHR.callProxy} function or of the {@link CB_Net.XHR.call} function (if no proxy is allowed) when it is called internally. * @param {CB_Net.XHR.HEADERS} [headers=undefined|{ \"Content-Type\" : \"application/x-www-form-urlencoded; charset=UTF-8\", \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" }] - Used for the \"headers\" parameter of the {@link CB_Net.XHR.callProxy} function or of the {@link CB_Net.XHR.call} function (if no proxy is allowed) when it is called internally. If not provided and the {@link CB_Net.XHR.call} function is used (if no proxy is allowed), the default value will be: { \"Content-Type\" : \"application/x-www-form-urlencoded; charset=UTF-8\", \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" } * @param {string} [responseType] - Used for the [responseType]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType} parameter of the {@link CB_Net.XHR.callProxy} function or of the {@link CB_Net.XHR.call} function (if no proxy is allowed) when it is called internally. * @param {boolean} [avoidProxy=false] - If it is set to true, it will call the {@link CB_Net.XHR.call} internally. Otherwise, it will use the {@link CB_Net.XHR.callProxy} function internally. * @param {boolean} [forceJSON=false] - Used for the \"forceJSON\" parameter of the {@link CB_Net.XHR.callProxy} function (if the proxy is allowed) when it is called internally. * @param {boolean} [getHeaders=false] - Used for the \"getHeaders\" parameter of the {@link CB_Net.XHR.callProxy} function (if the proxy is allowed) when it is called internally. * @param {boolean} [headersForceOneDimension=false] - Used for the \"headersForceOneDimension\" parameter of the {@link CB_Net.XHR.callProxy} function (if the proxy is allowed) when it is called internally. * @param {boolean} [headersForceOneDimensionValues=false] - Used for the \"headersForceOneDimensionValues\" parameter of the {@link CB_Net.XHR.callProxy} function (if the proxy is allowed) when it is called internally. * @param {boolean} [transparentStatus=false] - Used for the \"transparentStatus\" parameter of the {@link CB_Net.XHR.callProxy} function (if the proxy is allowed) when it is called internally. * @param {boolean} [transparentHeaders=false] - Used for the \"transparentHeaders\" parameter of the {@link CB_Net.XHR.callProxy} function (if the proxy is allowed) when it is called internally. * @param {function} [callbackFunctionOK] - Used for the \"callbackFunctionOK\" parameter of the {@link CB_Net.XHR.callProxy} function or of the {@link CB_Net.XHR.call} function (if no proxy is allowed) when it is called internally. * @param {function} [callbackFunctionError] - Used for the \"callbackFunctionError\" parameter of the {@link CB_Net.XHR.callProxy} function or of the {@link CB_Net.XHR.call} function (if no proxy is allowed) when it is called internally. * @param {integer|array} [allowedSuccessStatuses=200] - Used for the \"allowedSuccessStatuses\" parameter of the {@link CB_Net.XHR.callProxy} function or of the {@link CB_Net.XHR.call} function (if no proxy is allowed) when it is called internally. * @param {Object} [XHR] - Used for the \"XHR\" parameter of the {@link CB_Net.XHR.callProxy} function or of the {@link CB_Net.XHR.call} function (if no proxy is allowed) when it is called internally. * @returns {Object|null} When using the proxy is allowed, returns the same that the {@link CB_Net.XHR.callProxy} function returns (called internally). Otherwise, it returns the same that the {@link CB_Net.XHR.call} function returns (called internally). */ CB_Net.XHR.callREST = function(serverURL, route, dataURL, method, data, headers, responseType, avoidProxy, forceJSON, getHeaders, headersForceOneDimension, headersForceOneDimensionValues, transparentStatus, transparentHeaders, callbackFunctionOK, callbackFunctionError, allowedSuccessStatuses, XHR) { serverURL = CB_trim(serverURL); //if (serverURL === \"\") { serverURL = CB_trim(CB_Net.REST.SERVER_URL_DEFAULT); } if (serverURL === \"\") { serverURL = CB_Net.REST.SERVER_URL_DEFAULT; } serverURL += CB_trim(route); dataURL = CB_trim(dataURL); if (dataURL !== \"\") { serverURL = CB_rtrim(serverURL, [\"?\", \"&amp;\", \" \"]); if (CB_indexOf(serverURL, \"?\") !== -1) { serverURL += \"&amp;\" + dataURL; } else { serverURL += \"?\" + dataURL; } } if (!avoidProxy) { return CB_Net.XHR.callProxy ( serverURL, //URL of the REST server. method, //method data, //data headers, //headers responseType, //responseType forceJSON, //forceJSON getHeaders, //getHeaders headersForceOneDimension, //headersForceOneDimension headersForceOneDimensionValues, //headersForceOneDimensionValues transparentStatus, //transparentStatus transparentHeaders, //transparentHeaders null, //callbackFunction callbackFunctionOK, //callbackFunctionOK callbackFunctionError, //callbackFunctionError allowedSuccessStatuses, //allowedSuccessStatuses XHR //XHR ); } else { if (typeof(headers) !== \"object\" || headers === null) { headers = { \"Content-Type\" : \"application/x-www-form-urlencoded; charset=UTF-8\", \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" }; } //Makes the AJAX request function and returns the same: return CB_Net.XHR.call ( serverURL, //URL method, //method data, //data headers, //headers responseType, //responseType null, //mimeType null, //callbackFunction callbackFunctionOK, //callbackFunctionOK callbackFunctionError, //callbackFunctionError allowedSuccessStatuses, //allowedSuccessStatuses true, //asynchronous XHR //XHR object ); } } /** * Returns the [HTTP headers]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers} (it should be an object) from the [JSON]{@link https://en.wikipedia.org/wiki/JSON} response generated by the \"getSslPage\" function used by the [PHP]{@link https://en.wikipedia.org/wiki/PHP} proxy (\"headers\" property). Useful to parse the response from the {@link CB_Net.XHR.callProxy} (or {@link CB_Net.XHR.callREST} and related) function when it has been called with the \"forceJSON\" parameter set to true. * @function * @param {Object|string} response - The [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} which contains the [responseText]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText} property or the value of the [responseText]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText} property (string) itself which should contain the [JSON]{@link https://en.wikipedia.org/wiki/JSON} response generated by the \"getSslPage\" function used by the [PHP]{@link https://en.wikipedia.org/wiki/PHP} proxy. If a string is provided, tries to parse it as a [JSON]{@link https://en.wikipedia.org/wiki/JSON} object. The \"headers\" property will be tried to be returned from it. * @param {boolean} [sanitize=true] - If it is set to true and the \"headers\" property is not found, it will return an empty object ({}) instead of returning null. * @returns {Object|null} Returns the content of the \"headers\" property if possible (it should be a {@link CB_Net.XHR.HEADERS} object). If it is not possible, it will return null if the parameter \"sanitize\" is set to false or an empty object ({}) otherwise. * @todo Consider adding the parameter \"headerNameFirst\". */ CB_Net.XHR.getResponseHeaders = function(response, sanitize) //TODO: Add parameter headerNameFirst { if (typeof(sanitize) === \"undefined\" || sanitize === null) { sanitize = true; } //Sanitizes by default. var headers = CB_getJSONPropertyValue(response.responseText ? response.responseText : response, \"headers\", null); if (sanitize &amp;&amp; headers === null) { return {}; } //If the property is not found or null and we want to sanitize, returns an empty object by default. return headers; //Can be NULL. } /** * Returns the [HTTP status]{@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Status} code from an [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} ([status]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status} property) or from the info array generated by the [PHP]{@link https://en.wikipedia.org/wiki/PHP}'s [curl_getinfo]{@link http://php.net/manual/function.curl-getinfo.php} function (\"http_code\" index) or from the [JSON]{@link https://en.wikipedia.org/wiki/JSON} response generated by the \"getSslPage\" function used by the [PHP]{@link https://en.wikipedia.org/wiki/PHP} proxy ([status]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status} property). Useful to parse the response from the {@link CB_Net.XHR.callProxy} (or {@link CB_Net.XHR.callREST} and related) function when it has been called with the \"forceJSON\" parameter set to true. * @function * @param {Object|string} response - The [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} which contains the [status]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status} property or the value of the [responseText]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText} property (string) itself which should contain the [JSON]{@link https://en.wikipedia.org/wiki/JSON} response generated by the \"getSslPage\" function used by the [PHP]{@link https://en.wikipedia.org/wiki/PHP} proxy. If a string is provided, tries to parse it as a [JSON]{@link https://en.wikipedia.org/wiki/JSON} object. The [status]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status} property will be tried to be returned from it (or the \"http_code\" property as a fallback). * @param {boolean} [sanitize=true] - If it is set to true and neither the \"status\" nor the \"http_code\" property are found (or is not a number), it will return the value of \"statusDefault\" instead of returning null. * @param {boolean} [statusDefault=-1] - Default value to return when the status cannot be found (or is not a number). Only used when the \"sanitize\" parameter is set to true. * @returns {integer|*} Returns the content of the [status]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status} (or \"http_code\") property if possible (it should be an integer). If it is not possible, it will return null if the parameter \"sanitize\" is set to false or the value of \"statusDefault\" otherwise. */ CB_Net.XHR.getStatusCode = function(response, statusDefault, sanitize) { if (typeof(sanitize) === \"undefined\" || sanitize === null) { sanitize = true; } //Sanitizes by default. if (typeof(statusDefault) === \"undefined\" || statusDefault === null) { statusDefault = -1; } var statusCode = CB_getJSONPropertyValue(response, \"status\", null); if (statusCode === null || isNaN(statusCode)) { statusCode = CB_getJSONPropertyValue(response, \"http_code\", null); } if (sanitize &amp;&amp; (statusCode === null || isNaN(statusCode))) { return statusDefault; } //If the property is not found or null and we want to sanitize, returns -1 by default. return !isNaN(statusCode) ? parseInt(statusCode) : null; //Can be NULL. } /** * Returns the response content from an [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} (from its [responseText]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText} property) or from the [JSON]{@link https://en.wikipedia.org/wiki/JSON} response generated by the \"getSslPage\" function used by the [PHP]{@link https://en.wikipedia.org/wiki/PHP} proxy ([response]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response} property). Useful to parse the response from the {@link CB_Net.XHR.callProxy} (or {@link CB_Net.XHR.callREST} and related) function when it has been called with the \"forceJSON\" parameter set to true. * @function * @param {Object|string} response - The [XHR object]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest} which contains the [responseText]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText} property or the value of the [responseText]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText} property (string) itself which should contain the [JSON]{@link https://en.wikipedia.org/wiki/JSON} response generated by the \"getSslPage\" function used by the [PHP]{@link https://en.wikipedia.org/wiki/PHP} proxy. If a string is provided, tries to parse it as a [JSON]{@link https://en.wikipedia.org/wiki/JSON} object. The [responseText]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText} property (or the [response]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response} property as a fallback) will be tried to be returned from it. * @param {boolean} [sanitize=true] - If it is set to true and neither the [responseText]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText} nor the [response]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response} properties are found, it will return an empty string (\"\") instead of returning null. * @returns {string|null} Returns the content of the [responseText]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText} (or [response]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response}) property if possible. If it is not possible, it will return null if the parameter \"sanitize\" is set to false or an empty string (\"\") otherwise. */ CB_Net.XHR.getResponseContent = function(responseOrXHR, sanitize) { if (typeof(sanitize) === \"undefined\" || sanitize === null) { sanitize = true; } //Sanitizes by default. var response = null; try //Prevents the \"InvalidStateError: responseText is only available if responseType is '' or 'text'.\" error in Firefox. { response = CB_getJSONPropertyValue(responseOrXHR, \"responseText\", responseOrXHR); } catch(E) {} response = CB_getJSONPropertyValue(response, \"response\", response); if (sanitize &amp;&amp; response === null) { return \"\"; } //If the property is not found or null and we want to sanitize, returns an empty string by default. return response ? response : null; } } × Search results Close "},"CrossBase_input_CB_Pointer.js.html":{"id":"CrossBase_input_CB_Pointer.js.html","title":"Source: CrossBase/input/CB_Pointer.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/input/CB_Pointer.js /** * @file Pointer management. Contains the {@link CB_Pointer} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage the pointer, using the [Pointer API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events} if available and falling back to internal emulation otherwise. It will return itself if it is tried to be instantiated. * @namespace */ var CB_Pointer = function() { return CB_Pointer; }; { //Events to emulate Pointer API in web clients that do not support it: CB_Pointer._eventEquivalents = { //Note: \"MSPointerHover\", which was different from \"MSPointerOver\" (note the \"H\") is deprecated and it does not have any equivalent now. pointerdown : { mouse: \"mousedown\", touch: \"touchstart\", IE : \"MSPointerDown\", touchFired: false }, pointerup : { mouse: \"mouseup\", touch: \"touchend\", IE : \"MSPointerUp\", touchFired: false }, pointercancel : { mouse: null, touch: \"touchcancel\", IE : \"MSPointerCancel\", touchFired: false }, pointerenter : { mouse: \"mouseenter\", touch: null, IE : \"MSPointerEvent\", touchFired: false }, pointerleave : { mouse: \"mouseleave\", touch: null, IE : \"MSPointerLeave\", touchFired: false }, pointerover : { mouse: \"mouseover\", touch: null, IE : \"MSPointerOver\", touchFired: false }, pointerout : { mouse: \"mouseout\", touch: null, IE : \"MSPointerOut\", touchFired: false }, pointermove : { mouse: \"mousemove\", touch: \"touchmove\", IE : \"MSPointerMove\", touchFired: false }, gotpointercapture : { mouse : null, touch: null, IE : \"MSGotPointerCapture\", touchFired: false }, lostpointercapture : { mouse : null, touch: null, IE : \"MSLostPointerCapture\", touchFired: false } }; CB_Pointer._POINTER_TYPE_TOUCH = \"touch\"; CB_Pointer._POINTER_TYPE_MOUSE = \"mouse\"; CB_Pointer._POINTER_TYPE_PEN = \"pen\"; CB_Pointer.initialized = false; //It will tells whether the object has been initialized or not. //Initializes all values: CB_Pointer.init = function() { if (CB_Pointer.initialized) { return CB_Pointer; } //The object has been initialized: CB_Pointer.initialized = true; //Creates aliases for the lock functions: CB_Pointer.isLockSupported = CB_Mouse.isLockSupported; CB_Pointer.isLocked = CB_Mouse.isLocked; CB_Pointer.wasLocked = CB_Mouse.wasLocked; CB_Pointer.getLockElement = CB_Mouse.getLockElement; CB_Pointer.lock = CB_Mouse.lock; CB_Pointer.unlock = CB_Mouse.unlock; CB_Pointer.onLockChange = CB_Mouse.onLockChange; CB_Pointer.onLockError = CB_Mouse.onLockError; //Normalizes some properties (if possible): if (navigator &amp;&amp; typeof(navigator.pointerEnabled) === \"undefined\") { if (navigator.msPointerEnabled) { navigator.pointerEnabled = true; navigator.maxTouchPoints = navigator.msMaxTouchPoints; } //else { navigator.maxTouchPoints = 1; } //Assumes it is just capable to perform one touch at the same time. } //TODO. return CB_Pointer; } /** * Tries to return the given [pointer event]{@link https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent} with some properties normalized (since different clients can use different values) and perhaps some new properties added (in the case they were missing), when possible. The new attached methods and properties may include polyfills, etc. It also calls the {@link CB_Events.normalize} function internally. Some properties added or affected could be \"POINTER_TYPE_TOUCH\", \"POINTER_TYPE_MOUSE\", \"POINTER_TYPE_PEN\", \"[pointerId]{@link https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId}\", \"[pointerType]{@link https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType}\", \"[pressure]{@link https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure}\", \"[tangentialPressure]{@link https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tangentialPressure}\", \"[tiltX]{@link https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX}\", \"[tiltY]{@link https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY}\", \"[width]{@link https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width}\", \"[height]{@link https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height}\", \"[currentTarget]{@link https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget}\", \"[isPrimary]{@link https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary}\", \"[twist]{@link https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/twist}\", etc. * @function * @param {Event} e - Pointer event object. If not provided, it will use the value of \"event\", \"window.event\", \"Event\" or an empty object (\"{}\"). * @returns {Event} Returns the pointer event object normalized. * @todo Think about using Object.defineProperty with \"writable: true\" as option to prevent some web clients problems that have read only properties. * @todo Maybe e.width and e.height should be both 1 as default (?). */ CB_Pointer.normalizeEvent = function(e) { e = CB_Events.normalize(e); //NOTE: Think about using Object.defineProperty with writable: true as option to prevent some web clients problems that have readonly properties. if (typeof(e.POINTER_TYPE_TOUCH) === \"undefined\") { e.POINTER_TYPE_TOUCH = CB_Pointer._POINTER_TYPE_TOUCH; } if (typeof(e.POINTER_TYPE_MOUSE) === \"undefined\") { e.POINTER_TYPE_MOUSE = CB_Pointer._POINTER_TYPE_MOUSE; } if (typeof(e.POINTER_TYPE_PEN) === \"undefined\") { e.POINTER_TYPE_PEN = CB_Pointer._POINTER_TYPE_PEN; } if (typeof(e.pointerType) === \"undefined\") { if (typeof(e.screenX) !== \"undefined\") { e.pointerType = e.POINTER_TYPE_TOUCH; } //Touch events have screenX property and mouse ones do not (unless I am wrong!). else { e.pointerType = e.POINTER_TYPE_MOUSE; } //Assumed a mouse event. } if (typeof(e.pressure) === \"undefined\") { e.pressure = (typeof(e.force) !== \"undefined\" &amp;&amp; e.force !== null) ? e.force : CB_Touch.DEFAULT_FORCE; } if (typeof(e.tangentialPressure) === \"undefined\") { e.tangentialPressure = 0; } //TODO: maybe it would be better to use e.pressure. if (typeof(e.twist) === \"undefined\") { e.twist = 0; } if (typeof(e.tiltX) === \"undefined\") { e.tiltX = 0; } if (typeof(e.tiltY) === \"undefined\") { e.tiltY = 0; } if (typeof(e.width) === \"undefined\") { e.width = 0; } //TODO: maybe e.width and e.height should be both 1 as default (?). if (typeof(e.height) === \"undefined\") { e.height = 0; } if (typeof(e.currentTarget) === \"undefined\") { e.currentTarget = e.target; } if (typeof(e.isPrimary) === \"undefined\") { e.isPrimary = true; } if (typeof(e.pointerId) === \"undefined\") { e.pointerId = 0; } return e; } /** * Sets the desired value for the CSS' style [pointer-events]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events} property of a given element. * @function * @param {Element} element - Element whose CSS' style \"[pointer-events]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events}\" property we want to edit. * @param {string} value - CSS code for the CSS' style \"[pointer-events]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events}\" property. * @param {boolean} [important=false] - If set to true, it will add the \" !important\" text to the \"[pointer-events]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events}\" property. */ CB_Pointer.setPointerEventsProperty = function(element, value, important) { try { value = CB_trim(value); value = (important &amp;&amp; value.toLowerCase().indexOf(\"!important\") === -1) ? value + \" !important\" : value; element.style.pointerEvents = value; } catch(E) { CB_console(\"Cannot execute CB_Pointer.setPointerEventsProperty: \" + e); } } /** * Sets a function to execute when the \"[onPointerDown]{@link https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onpointerdown}\" event is fired or removes it. More information: [Pointer events]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Pointer.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Pointer.onDown = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Pointer._setEvent(\"pointerdown\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when the \"[onPointerUp]{@link https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onpointerup}\" event is fired or removes it. More information: [Pointer events]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Pointer.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Pointer.onUp = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Pointer._setEvent(\"pointerup\", callbackFunction, keepOldFunction, useCapture, target, true); } /** * Sets a function to execute when the \"[onPointerCancel]{@link https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onpointercancel}\" event is fired or removes it. More information: [Pointer events]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Pointer.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Pointer.onCancel = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Pointer._setEvent(\"pointercancel\", callbackFunction, keepOldFunction, useCapture, target, true); } /** * Sets a function to execute when the \"[onPointerEnter]{@link https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onpointerenter}\" event is fired or removes it. More information: [Pointer events]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Pointer.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Pointer.onEnter = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Pointer._setEvent(\"pointerenter\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when the \"[onPointerLeave]{@link https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onpointerleave}\" event is fired or removes it. More information: [Pointer events]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Pointer.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Pointer.onLeave = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Pointer._setEvent(\"pointerleave\", callbackFunction, keepOldFunction, useCapture, target, true); } /** * Sets a function to execute when the \"[onPointerOver]{@link https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onpointerover}\" event is fired or removes it. More information: [Pointer events]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Pointer.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Pointer.onOver = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Pointer._setEvent(\"pointerover\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when the \"[onPointerOut]{@link https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onpointerout}\" event is fired or removes it. More information: [Pointer events]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Pointer.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Pointer.onOut = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Pointer._setEvent(\"pointerout\", callbackFunction, keepOldFunction, useCapture, target, true); } /** * Sets a function to execute when the \"[onPointerMove]{@link https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onpointermove}\" event is fired or removes it. More information: [Pointer events]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Pointer.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Pointer.onMove = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Pointer._setEvent(\"pointermove\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when the \"[onGotPointerCapture]{@link https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/ongotpointercapture}\" event is fired or removes it. More information: [Pointer events]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Pointer.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Pointer.onGotPointCapture = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Pointer._setEvent(\"gotpointercapture\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when the \"[onLostPointerCapture]{@link https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onlostpointercapture}\" event is fired or removes it. More information: [Pointer events]{@link https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Pointer.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Pointer.onLostPointCapture = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Pointer._setEvent(\"lostpointercapture\", callbackFunction, keepOldFunction, useCapture, target, true); } //Sets a function to execute when a pointer event happens: CB_Pointer._lastRealPointerID = 0; CB_Pointer._currentPointerID = 0; CB_Pointer._currentPointerIDIncreased = false; CB_Pointer._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture, target, increasePointerID) { //If they are not set, use default values for optional parameters: if (typeof(keepOldFunction) === \"undefined\" || keepOldFunction === null) { keepOldFunction = true; } //If not set, it keeps old function by default. if (typeof(target) === \"undefined\" || target === null) { target = document; } eventName = eventName.toLowerCase(); if (typeof(CB_Pointer._eventEquivalents[eventName]) === \"undefined\" || CB_Pointer._eventEquivalents[eventName] === null) { return false; } //If a function has been sent: if (typeof(eventFunction) === \"function\") { var oldEventName = null; var eventFunctionWrapper = function(e, increaseUnits) { e = CB_Pointer.normalizeEvent(e); increaseUnits = increaseUnits || 0; try { if (CB_trim(CB_Elements.getStyleProperty(target, \"pointerEvents\", true)).toLowerCase().indexOf(\"none\") !== -1) { return; } //Exists if the pointerEvents is \"none\". } catch(E) {} e.usingEmulation = e.usingEmulation || false; e.typeReal = e.type; try { e.type = oldEventName || e.type; } catch(E) { } e.typeEmulated = oldEventName; //If it is a real pointer event, keeps the real pointer ID to use it: if (!e.usingEmulation) { CB_Pointer._currentPointerID = CB_Pointer._lastRealPointerID = e.pointerId; increaseUnits = 0; } //If the pointer is not used anymore (it is an event that cancels it), increases the pointer ID (for the next time): if (!increasePointerID) { CB_Pointer._currentPointerIDIncreased = false; } else if (!CB_Pointer._currentPointerIDIncreased &amp;&amp; !CB_Pointer._lastRealPointerID) //Only increases the pointer ID when there has never been a real one. { CB_Pointer._currentPointerID += increaseUnits; CB_Pointer._currentPointerIDIncreased = true; } if (typeof(eventFunction) === \"function\") { return eventFunction(e); } return true; }; var newEventFunctionWrapper = null; //If the Pointer API is not supported: if (!navigator || !navigator.pointerEnabled || typeof(target.onpointerdown) === \"undefined\") { //If the Pointer API is supported with the MS prefix (IE) and an equivalent event has been found: if (navigator &amp;&amp; navigator.msPointerEnabled &amp;&amp; typeof(target.onmspointerdown) !== \"undefined\" &amp;&amp; CB_Pointer._eventEquivalents[eventName].IE) { oldEventName = eventName; eventName = CB_Pointer._eventEquivalents[eventName].IE; } //...otherwise, uses emulation: else { //If the event can be emulated with a touch event: if (CB_Pointer._eventEquivalents[eventName].touch) { oldEventName = eventName; newEventFunctionWrapper = function(e) { CB_Pointer._eventEquivalents[eventName].touchFired = true; //Sets as already fired by a touch event. var returnValues = true; if (typeof(eventFunctionWrapper) === \"function\") { //Dispatches the event for each touch: e = CB_Touch.normalizeEvent(e); for (var x = 0; x &lt; e.changedTouches.length; x++) { try { e.clientX = e.changedTouches[0].clientX; e.clientY = e.changedTouches[0].clientY; e.pageX = e.changedTouches[0].pageX; e.pageY = e.changedTouches[0].pageY; e.force = e.changedTouches[0].force; e.currentTarget = e.changedTouches[0].currentTarget;// || target; e.isPrimary = (x === 0); //Maybe this is not totally right! TODO: try to find out whether this is right or not. e.pointerId = CB_Pointer._currentPointerID + x; //(x + 1); //TODO: Think about this, maybe it should not be increased. e.pointerType = CB_Pointer._POINTER_TYPE_TOUCH; e.usingEmulation = true; returnValues = returnValues &amp;&amp; eventFunctionWrapper(e, 1); //TODO: see whether is possible to calculate tiltX and tiltY with radiusX, radiusY and rotationAngle. //TODO: calculate e.offsetX and e.offsetY from touch events. } catch(E) {} } } return returnValues; }; //If able, adds the function given to the emulation event: CB_Events.add(target, CB_Pointer._eventEquivalents[eventName].touch, newEventFunctionWrapper, useCapture, keepOldFunction, true); } //If the event can be emulated with a mouse event: if (CB_Pointer._eventEquivalents[eventName].mouse) { oldEventName = eventName; newEventFunctionWrapper = function(e) { //If a touch event already fired, deletes the event and exits: if (CB_Pointer._eventEquivalents[eventName].touchFired) { //Only deletes it if the defined touch and mouse events are different: if (CB_Pointer._eventEquivalents[eventName].mouse !== CB_Pointer._eventEquivalents[eventName].touch) { CB_Events.removeByName(target, CB_Pointer._eventEquivalents[eventName].mouse); } return true; } e = CB_Mouse.normalizeEvent(e); e.pointerId = CB_Pointer._currentPointerID; e.isPrimary = true; e.currentTarget = e.currentTarget || target; e.pointerType = CB_Pointer._POINTER_TYPE_MOUSE; e.usingEmulation = true; if (typeof(eventFunctionWrapper) === \"function\") { return eventFunctionWrapper(e, 1); } return true; }; //If able, adds the function given to the emulation event: CB_Events.add(target, CB_Pointer._eventEquivalents[eventName].mouse, newEventFunctionWrapper, useCapture, keepOldFunction, true); } } } //If able, adds the function given to the event (only if no emulation event was defined before): if (typeof(newEventFunctionWrapper) !== \"function\") { CB_Events.add(target, eventName, eventFunctionWrapper, useCapture, keepOldFunction, true); } } //...but if the function given is null, it will cancel the event: else if (eventFunction === null)// &amp;&amp; eventFunctionHolder !== null) { //If the Pointer API is not supported: if (!navigator || !navigator.pointerEnabled || typeof(target.onpointerdown) === \"undefined\") { //If the Pointer API is supported with the MS prefix (IE) and an equivalent event has been found: if (navigator &amp;&amp; navigator.msPointerEnabled &amp;&amp; typeof(target.onmspointerdown) !== \"undefined\" &amp;&amp; CB_Pointer._eventEquivalents[eventName].IE) { CB_Events.removeByName(target, \"MS\" + CB_Pointer._eventEquivalents[eventName].IE); } //...otherwise, uses emulation: else { //If the event can be emulated with a touch event: if (CB_Pointer._eventEquivalents[eventName].touch) { CB_Events.removeByName(target, CB_Pointer._eventEquivalents[eventName].touch); } //If the event can be emulated with a mouse event: if (CB_Pointer._eventEquivalents[eventName].mouse) { CB_Events.removeByName(target, CB_Pointer._eventEquivalents[eventName].mouse); } } } CB_Events.removeByName(target, eventName); } } } × Search results Close "},"CrossBase_audiovisual_image_CB_Screen.js.html":{"id":"CrossBase_audiovisual_image_CB_Screen.js.html","title":"Source: CrossBase/audiovisual/image/CB_Screen.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/audiovisual/image/CB_Screen.js /** * @file Screen management. Contains the {@link CB_Screen} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage the screen. It will return itself if it is tried to be instantiated. It can use [detect-zoom]{@link https://github.com/tombigel/detect-zoom} and [NoSleep.js]{@link https://github.com/richtr/NoSleep.js?utm_source=recordnotfound.com}. * @namespace */ var CB_Screen = function() { return CB_Screen; }; { CB_Screen._screenWidth = 0; //Screen width resolution. CB_Screen._screenHeight = 0; //Screen height resolution. CB_Screen._previousScreenWidth = 0; //Previous screen width resolution. CB_Screen._previousScreenHeight = 0; //Previous screen height resolution. CB_Screen._screenAvailableWidth = 0; //Screen available width resolution. CB_Screen._screenAvailableHeight = 0; //Screen available height resolution. CB_Screen._previousScreenAvailableWidth = 0; //Previous screen available width resolution. CB_Screen._previousScreenAvailableHeight = 0; //Previous screen available height resolution. CB_Screen._windowWidth = 0; //Window width resolution. CB_Screen._windowHeight = 0; //Window height resolution. CB_Screen._previousWindowWidth = 0; //Previous window width resolution. CB_Screen._previousWindowHeight = 0; //Previous window height resolution. CB_Screen._screenColorDepth = 0; //Screen color depth. CB_Screen._scrollLeft = null; //Left scroll value. CB_Screen._scrollTop = null; //Top scroll value. CB_Screen._previousScrollLeft = null; //Previous left scroll value. CB_Screen._previousScrollTop = null; //Previous top scroll value. CB_Screen._zoom = 1; //Zoom applied to the web. CB_Screen._pixelRatio = 1; //Pixel ratio multiplied by the zoom. CB_Screen._previousZoom = 0; //Zoom applied to the web. CB_Screen._previousPixelRatio = 0; //Pixel ratio multiplied by the zoom. CB_Screen._isLandscape = null; //Tells whether web is displayed in landscape or portrait position. CB_Screen._isVisible = null; //Tells whether web is visible or not. CB_Screen._isFocused = null; //Tells whether web is focused or not (has lost the focus). CB_Screen._isFullScreen = null; //Tells whether full screen mode is enabled or not. CB_Screen._screenLock = null; //Keeps the MozWakeLock object to be able to release the lock related with the screen (so far, only works in Firefox/Firefox OS). CB_Screen._noSleep = null; //Keeps the last NoSleep object for the NoSleep.js library. CB_Screen._noSleepEnabled = false; //Boolean to keeps the status of the noSleep.js object (enabled or disabled). CB_Screen._eventsHolder = {}; //Keeps the functions to fire for every special event (if any). /* CB_Screen.onResizeFunction; //Function that is executed when window is resized (onResize event). CB_Screen.onScrollLeftFunction; //Function that is executen when scroll left is changed. CB_Screen.onScrollTopFunction; //Function that is executen when scroll top is changed. CB_Screen.onVisibilityChangeFunction; //Function that is executed when window gets or losts the visibility. CB_Screen.onFocusChangeFunction; //Function that is executed when window gets or losts the focus. CB_Screen.onResizeOrZoomFunction; //Function that is executed when window is resized or zoom is applied. CB_Screen.onOrientationChangeFunction; //Function that is executed when orientation changes (landscape or portrait). CB_Screen.onFullScreenChangeFunction; //Function that is executed when full screen mode changes. */ CB_Screen._storedScreenWidth = 0; //Old screen available width resolution (internal use only). CB_Screen._storedScreenHeight = 0; //Old screen available height resolution (internal use only). CB_Screen._storedScreenAvailableWidth = 0; //Old screen available width resolution (internal use only). CB_Screen._storedScreenAvailableHeight = 0; //Old screen available height resolution (internal use only). CB_Screen._storedWindowWidth = 0; //Old window width resolution (internal use only). CB_Screen._storedWindowHeight = 0; //Old window height resolution (internal use only). CB_Screen._storedZoom = 0; //Zoom applied to the web. CB_Screen._storedPixelRatio = 0; //Pixel ratio multiplied by the zoom. CB_Screen._refreshTimeout = null; //It will store the timeout that refresh screen properties all the time. CB_Screen.initialized = false; //It will tells whether the object has been initialized or not. //Initializes all values: CB_Screen.init = function() { if (CB_Screen.initialized) { return CB_Screen; } //Sets that the object has already been initialized: CB_Screen.initialized = true; //Stores first values for both old window width and height: CB_Screen._storedScreenWidth = CB_Screen._screenWidth; CB_Screen._storedScreenHeight = CB_Screen._screenHeight; CB_Screen._storedScreenAvailableWidth = CB_Screen._screenAvailableWidth; CB_Screen._storedScreenAvailableHeight = CB_Screen._screenAvailableHeight; CB_Screen._storedWindowWidth = CB_Screen._windowWidth; CB_Screen._storedWindowHeight = CB_Screen._windowHeight; //It also stores for both zoom level and pixel ratio: CB_Screen._storedZoom = CB_Screen._zoom; CB_Screen._storedPixelRatio = CB_Screen._pixelRatio; //Sets the handler for the scroll event: CB_Events.add(window, \"scroll\", function() { CB_Screen.getScrollTop(); CB_Screen.getScrollLeft(); }, true, true, false); //It will check all the time if visibility changes: CB_Screen._isVisible = true; //By default, window is visible. NOTE: this can produce a false positive if the script is loading being not visible. if (\"hidden\" in document) { CB_Events.add(document, \"visibilitychange\", CB_Screen._visibilityChanged, true, true, false); } //document.addEventListener(\"visibilitychange\", CB_Screen._visibilityChanged); } else if (\"mozHidden\" in document) { CB_Events.add(document, \"mozvisibilitychange\", CB_Screen._visibilityChanged, true, true, false); } //document.addEventListener(\"mozvisibilitychange\", CB_Screen._visibilityChanged); } else if (\"webkitHidden\" in document) { CB_Events.add(document, \"webkitvisibilitychange\", CB_Screen._visibilityChanged, true, true, false); } //document.addEventListener(\"webkitvisibilitychange\", CB_Screen._visibilityChanged); } else if (\"msHidden\" in document) { CB_Events.add(document, \"msvisibilitychange\", CB_Screen._visibilityChanged, true, true, false); } // document.addEventListener(\"msvisibilitychange\", CB_Screen._visibilityChanged); } //else if (\"onfocusin\" in document) { document.onfocusin = document.onfocusout = CB_Screen._visibilityChanged; } //else if (\"onfocusin\" in document) { document.onfocusin = document.onfocusout = function() { CB_Screen._visibilityChanged(); CB_Screen._focusChanged(); } } //else { window.onfocus = window.onblur = CB_Screen._visibilityChanged; } //else { window.onfocus = window.onblur = function() { CB_Screen._visibilityChanged(); CB_Screen._focusChanged(); } } //It will check all the time if focus changes: CB_Screen._isFocused = true; //By default, window is focused. NOTE: this can produce a false positive if the script is loading being not visible. var focusOrBlurEventWorks = false; try //Using catch due some web clients doesn't allow to manipulate the window object of parent iframes: { CB_Events.add(CB_Client.getWindow(), \"focus\", function() { focusOrBlurEventWorks = true; CB_Screen._focusChanged(true); }, true, true, false); CB_Events.add(CB_Client.getWindow(), \"blur\", function() { focusOrBlurEventWorks = true; CB_Screen._focusChanged(false); }, true, true, false); } catch(E) { CB_Events.add(window, \"focus\", function() { focusOrBlurEventWorks = true; CB_Screen._focusChanged(true); }, true, true, false); CB_Events.add(window, \"blur\", function() { focusOrBlurEventWorks = true; CB_Screen._focusChanged(false); }, true, true, false); } CB_Events.add(document, \"mousedown\", function() { if (focusOrBlurEventWorks) { return; } CB_Screen._focusChanged(true); }, true, true, false); //Mouse click will set focus too (IE8 fix). CB_Events.add(document, \"click\", function() { if (focusOrBlurEventWorks) { return; } CB_Screen._focusChanged(true); }, true, true, false); //Click will set focus too (IE8 fix). //CB_Events.add(document, \"keydown\", function() { if (focusOrBlurEventWorks) { return; } CB_Screen._focusChanged(true); }, true, true, false); //Key down event will set focus too (IE8 fix). //CB_Events.add(document, \"mousemove\", function() { if (focusOrBlurEventWorks) { return; } CB_Screen._focusChanged(true); }, true, true, false); //Mouse movemenet will set focus too (IE8 fix). //Starts running the loop: CB_Screen._mainLoop(); return CB_Screen; } //Loop to watch the screen changes: CB_Screen._mainLoop = function() { //Cancels the timeout (if any): clearTimeout(CB_Screen._refreshTimeout); CB_Screen.getWidth(); //Defines screen width resolution. CB_Screen.getHeight(); //Defines screen height resolution. CB_Screen.getWidthPrevious(); //Defines previous window width resolution. CB_Screen.getHeightPrevious(); //Defines previous window height resolution. CB_Screen.getAvailableWidth(); //Defines screen available width resolution. CB_Screen.getAvailableHeight(); //Defines screen available height resolution. CB_Screen.getAvailableWidthPrevious(); //Defines previous window width resolution. CB_Screen.getAvailableHeightPrevious(); //Defines previous window height resolution. CB_Screen.getWindowWidth(); //Defines window width resolution. CB_Screen.getWindowHeight(); //Defines window height resolution. CB_Screen.getWindowWidthPrevious(); //Defines previous window width resolution. CB_Screen.getWindowHeightPrevious(); //Defines previous window height resolution. CB_Screen.getColorDepth(); //Defines screen color depth. //CB_Screen.getScrollLeft(); //Defines scroll left (and executes defined function if it changes). //CB_Screen.getScrollTop(); //Defines scroll top (and executes defined function if it changes). CB_Screen.getZoom(); //Defines zoom level. CB_Screen.getPixelRatio(); //Defines pixel ratio multiplied by the zoom level. CB_Screen.isLandscape(); //Defines whether device is in landscape or portrait position (and executes defined function if it changes). CB_Screen.isFullScreen(); //Defines whether it's in full screen mode or not (and executes defined function if it changes). //Executes the function defined for Resize and Zoom events (if any): CB_Screen._processOnResizeOrZoomFunction(); //Executes the function defined for Full screen change event (if any): //CB_Screen.onFullScreenChangeFunction(CB_Screen.onFullScreenChangeFunction, false); //Executes the function again: CB_Screen._refreshTimeout = setTimeout(CB_Screen._mainLoop, 1); //Calls itself again to update values all the time. } /** * Gets the current screen width (horizontal resolution). Uses the [window.screen.width]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/width} property internally, when possible. * @function * @returns {number} Returns the current screen width (horizontal resolution) in pixels. */ CB_Screen.getWidth = function() { if (screen &amp;&amp; screen.width &amp;&amp; !isNaN(screen.width)) { CB_Screen._screenWidth = screen.width; } return CB_Screen._screenWidth; } /** * Gets the current screen height (vertical resolution). Uses the [window.screen.height]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/height} property internally, when possible. * @function * @returns {number} Returns the current screen height (vertical resolution) in pixels. */ CB_Screen.getHeight = function() { if (screen &amp;&amp; screen.height &amp;&amp; !isNaN(screen.height)) { CB_Screen._screenHeight = screen.height; } return CB_Screen._screenHeight; } /** * Gets the previous screen width (horizontal resolution). Calculated through the [window.screen.width]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/width} property internally, when possible. Useful when the resolution (screen size and/or orientation) changed. * @function * @returns {number} Returns the previous screen width (horizontal resolution) in pixels. */ CB_Screen.getWidthPrevious = function() { if (CB_Screen._previousScreenWidth === 0) { CB_Screen._previousScreenWidth = CB_Screen.getWidth(); } return CB_Screen._previousScreenWidth; } /** * Gets the previous screen height (vertical resolution). Calculated through the [window.screen.height]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/height} property internally, when possible. Useful when the resolution (screen size and/or orientation) changed. * @function * @returns {number} Returns the previous screen height (vertical resolution) in pixels. */ CB_Screen.getHeightPrevious = function() { if (CB_Screen._previousScreenHeight === 0) { CB_Screen._previousScreenHeight = CB_Screen.getHeight(); } return CB_Screen._previousScreenHeight; } /** * Gets the current available screen width (horizontal resolution). Uses the [window.screen.availWidth]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/availWidth} property internally, when possible. * @function * @returns {number} Returns the current available screen width (horizontal resolution) in pixels. */ CB_Screen.getAvailableWidth = function() { if (screen &amp;&amp; screen.availWidth &amp;&amp; !isNaN(screen.availWidth)) { CB_Screen._screenAvailableWidth = screen.availWidth; } return CB_Screen._screenAvailableWidth; } /** * Gets the current available screen height (vertical resolution). Uses the [window.screen.availHeight]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/availHeight} property internally, when possible. * @function * @returns {number} Returns the current available screen height (vertical resolution) in pixels. */ CB_Screen.getAvailableHeight = function() { if (screen &amp;&amp; screen.availHeight &amp;&amp; !isNaN(screen.availHeight)) { CB_Screen._screenAvailableHeight = screen.availHeight; } return CB_Screen._screenAvailableHeight; } /** * Gets the previous available screen width (horizontal resolution). Useful when the resolution (screen size and/or orientation) changed. Uses the [window.screen.availWidth]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/availWidth} property internally, when possible. * @function * @returns {number} Returns the previous available screen width (horizontal resolution) in pixels. */ CB_Screen.getAvailableWidthPrevious = function() { if (CB_Screen._previousScreenAvailableWidth === 0) { CB_Screen._previousScreenAvailableWidth = CB_Screen.getAvailableWidth(); } return CB_Screen._previousScreenAvailableWidth; } /** * Gets the previous available screen height (vertical resolution). Useful when the resolution (screen size and/or orientation) changed. Uses the [window.screen.availHeight]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/availHeight} property internally, when possible. * @function * @returns {number} Returns the previous available screen height (vertical resolution) in pixels. */ CB_Screen.getAvailableHeightPrevious = function() { if (CB_Screen._previousScreenAvailableHeight === 0) { CB_Screen._previousScreenAvailableHeight = CB_Screen.getAvailableHeight(); } return CB_Screen._previousScreenAvailableHeight; } /** * Gets the current window width (horizontal resolution). Internally, uses the [window.innerWidth]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth} if possible and fallbacks to [document.documentElement.clientWidth]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth} or [document.body.clientWidth]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth} property otherwise, when possible. * @function * @returns {number} Returns the current window width (horizontal resolution) in pixels. */ CB_Screen.getWindowWidth = function() { if (window &amp;&amp; window.innerWidth &amp;&amp; !isNaN(window.innerWidth)) { CB_Screen._windowWidth = window.innerWidth; } else if (document &amp;&amp; document.documentElement &amp;&amp; document.documentElement.clientWidth &amp;&amp; !isNaN(document.documentElement.clientWidth) &amp;&amp; document.documentElement.clientWidth &gt; 0) { CB_Screen._windowWidth = document.documentElement.clientWidth; } else if (document &amp;&amp; document.body &amp;&amp; document.body.clientWidth &amp;&amp; !isNaN(document.body.clientWidth) &amp;&amp; document.body.clientWidth &gt; 0) { CB_Screen._windowWidth = document.body.clientWidth; } return CB_Screen._windowWidth; } /** * Gets the current window height (vertical resolution). Internally, uses the [window.innerHeight]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/innerHeight} if possible and fallbacks to [document.documentElement.clientHeight]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight} or [document.body.clientHeight]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight} property otherwise, when possible. * @function * @returns {number} Returns the current window height (vertical resolution) in pixels. */ CB_Screen.getWindowHeight = function() { if (window &amp;&amp; window.innerHeight &amp;&amp; !isNaN(window.innerHeight)) { CB_Screen._windowHeight = window.innerHeight; } else if (document &amp;&amp; document.documentElement &amp;&amp; document.documentElement.clientHeight &amp;&amp; !isNaN(document.documentElement.clientHeight) &amp;&amp; document.documentElement.clientHeight &gt; 0) { CB_Screen._windowHeight = document.documentElement.clientHeight; } else if (document &amp;&amp; document.body &amp;&amp; document.body.clientHeight &amp;&amp; !isNaN(document.body.clientHeight) &amp;&amp; document.body.clientHeight &gt; 0) { CB_Screen._windowHeight = document.body.clientHeight; } return CB_Screen._windowHeight; } /** * Gets the previous window width (horizontal resolution). Useful when the resolution (screen size and/or orientation) or window size changed. Internally, uses the [window.innerWidth]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth} if possible and fallbacks to [document.documentElement.clientWidth]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth} or [document.body.clientWidth]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth} property otherwise, when possible. * @function * @returns {number} Returns the previous window width (horizontal resolution) in pixels. */ CB_Screen.getWindowWidthPrevious = function() { if (CB_Screen._previousWindowWidth === 0) { CB_Screen._previousWindowWidth = CB_Screen.getWindowWidth(); } return CB_Screen._previousWindowWidth; } /** * Gets the previous window height (vertical resolution). Useful when the resolution (screen size and/or orientation) or window size changed. Internally, uses the [window.innerHeight]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/innerHeight} if possible and fallbacks to [document.documentElement.clientHeight]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight} or [document.body.clientHeight]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight} property otherwise, when possible. * @function * @returns {number} Returns the previous window height (vertical resolution) in pixels. */ CB_Screen.getWindowHeightPrevious = function() { if (CB_Screen._previousWindowHeight === 0) { CB_Screen._previousWindowHeight = CB_Screen.getWindowHeight(); } return CB_Screen._previousWindowHeight; } /** * Gets the current color depth. Uses the [window.screen.colorDepth]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/colorDepth} property internally, when possible. * @function * @returns {number} Returns the current color depth. */ CB_Screen.getColorDepth = function() { if (screen &amp;&amp; screen.colorDepth &amp;&amp; !isNaN(screen.colorDepth)) { CB_Screen._screenColorDepth = screen.colorDepth; } return CB_Screen._screenColorDepth; } /** * Gets the current scroll left position (horizontal scroll) of the screen (main window). Uses the {@link CB_Elements.getScrollLeftById} function internally. * @function * @returns {number|null} Returns the current scroll left position (horizontal scroll) of the screen (main window). It could return null if something fails. */ CB_Screen.getScrollLeft = function() { CB_Screen._previousScrollLeft = CB_Screen._scrollLeft; return CB_Elements.getScrollLeftById ( window, //elementId function(scrollLeft, scrollLeftPrevious, scrollWidth, visiblePixels, scrollRelative, scrollRelativePrevious) //onScrollLeftChanges: { //If there is any defined function: if (typeof(CB_Screen._eventsHolder[\"onScrollLeft\"]) === \"function\") { //Sets the new and old positions (just in case the function needs it): CB_Screen._previousScrollLeft = CB_Screen._scrollLeft; CB_Screen._scrollLeft = scrollLeft; //Executes the function: CB_Screen._eventsHolder[\"onScrollLeft\"](); } }, true, //fireFirstTime false, //fireAlways null, //timeoutMs true, //returnNullOnFail undefined //timeout ); } /** * Gets the current scroll top position (vertical scroll) of the screen (main window). Uses the {@link CB_Elements.getScrollTopById} function internally. * @function * @returns {number|null} Returns the current scroll top position (vertical scroll) of the screen (main window). It could return null if something fails. */ CB_Screen.getScrollTop = function() { CB_Screen._previousScrollTop = CB_Screen._scrollTop; return CB_Elements.getScrollTopById ( window, //elementId function(scrollTop, scrollTopPrevious, scrollHeight, visiblePixels, scrollRelative, scrollRelativePrevious) //onScrollTopChanges: { //If there is any defined function: if (typeof(CB_Screen._eventsHolder[\"onScrollTop\"]) === \"function\") { //Sets the new and old positions (just in case the function needs it): CB_Screen._previousScrollTop = CB_Screen._scrollTop; CB_Screen._scrollTop = scrollTop; //Executes the function: CB_Screen._eventsHolder[\"onScrollTop\"](); } }, true, //fireFirstTime false, //fireAlways null, //timeoutMs true, //returnNullOnFail undefined //timeout ); } /** * Gets the current zoom level of the screen (main window). Uses [detect-zoom]{@link https://github.com/tombigel/detect-zoom} internally. * @function * @returns {number} Returns the current zoom level of the screen (main window). Default zoom level is 1 (one) even when it fails. * @todo Find a better and more-compatible way to detect zoom which supports as many web clients as possible. */ CB_Screen.getZoom = function() { //if (typeof(detectZoom) !== \"undefined\" &amp;&amp; detectZoom !== null &amp;&amp; detectZoom &amp;&amp; typeof(detectZoom.zoom) !== \"undefined\" &amp;&amp; detectZoom.zoom !== null &amp;&amp; detectZoom.zoom &amp;&amp; typeof(detectZoom.zoom) === \"function\") if (typeof(detectZoom) !== \"undefined\" &amp;&amp; detectZoom !== null &amp;&amp; typeof(detectZoom.zoom) === \"function\") { CB_Screen._zoom = detectZoom.zoom(); //if (CB_Screen._zoom === null || CB_Screen._zoom === 0 || !CB_Screen._zoom) { CB_Screen._zoom = 1; } if (!CB_Screen._zoom) { CB_Screen._zoom = 1; } //} else { CB_Screen._zoom = CB_Screen._previousZoom = 0; } } else { CB_Screen._zoom = CB_Screen._previousZoom = 1; } return CB_Screen._zoom; } /** * Gets the previous zoom level of the screen (main window). Useful when the zoom changed. Uses [detect-zoom]{@link https://github.com/tombigel/detect-zoom} internally. * @function * @returns {number} Returns the previous zoom level of the screen (main window). Default previous zoom level is 0 (zero) even when it fails. */ CB_Screen.getZoomPrevious = function() { return CB_Screen._previousZoom; } /** * Gets the current pixel ratio of the screen (main window). Uses [detect-zoom]{@link https://github.com/tombigel/detect-zoom} internally. * @function * @returns {number} Returns the current pixel ratio of the screen (main window). Default pixel ratio is 1 (one) even when it fails. * @todo Find a better and more-compatible way to detect pixel ratio which supports as many web clients as possible. */ CB_Screen.getPixelRatio = function() { //if (typeof(detectZoom) !== \"undefined\" &amp;&amp; detectZoom !== null &amp;&amp; detectZoom &amp;&amp; typeof(detectZoom.device) !== \"undefined\" &amp;&amp; detectZoom.device !== null &amp;&amp; detectZoom.device &amp;&amp; typeof(detectZoom.device) === \"function\") if (typeof(detectZoom) !== \"undefined\" &amp;&amp; detectZoom !== null &amp;&amp; typeof(detectZoom.device) === \"function\") { CB_Screen._pixelRatio = detectZoom.device(); //} else { CB_Screen._pixelRatio = CB_Screen._previousPixelRatio = 0; } //if (CB_Screen._pixelRatio === null || CB_Screen._pixelRatio === 0 || !CB_Screen._pixelRatio) { CB_Screen._pixelRatio = 1; } if (!CB_Screen._pixelRatio) { CB_Screen._pixelRatio = 1; } } else { CB_Screen._pixelRatio = CB_Screen._previousPixelRatio = 1; } return CB_Screen._pixelRatio; } /** * Gets the previous pixel ratio of the screen (main window). Useful when the zoom/pixel-ratio changed. Uses [detect-zoom]{@link https://github.com/tombigel/detect-zoom} internally. * @function * @returns {number} Returns the previous pixel ratio of the screen (main window). Default previous pixel ratio is 0 (zero) even when it fails. * @todo Find a better and more-compatible way to detect pixel ratio which supports as many web clients as possible. */ CB_Screen.getPixelRatioPrevious = function() { return CB_Screen._previousPixelRatio; } /** * Tells whether the screen (main window) is in landscape position. * @function * @returns {boolean} Returns whether the screen is in landscape position. */ CB_Screen.isLandscape = function() { var isLandscape = false; if (CB_Screen.getWindowWidth() &gt; CB_Screen.getWindowHeight()) { isLandscape = true; } //If it's not the first time and position has been changed, calls the onOrientationChange function (if any): if (CB_Screen._isLandscape !== null &amp;&amp; CB_Screen._isLandscape !== isLandscape) { //If there is any defined function: if (typeof(CB_Screen._eventsHolder[\"onOrientationChange\"]) === \"function\") { //Sets the new position (just in case the function needs it): CB_Screen._isLandscape = isLandscape; //Executes the function: CB_Screen._eventsHolder[\"onOrientationChange\"](); } } //Sets the new position: CB_Screen._isLandscape = isLandscape; return CB_Screen._isLandscape; } //Sets whether the web is visible (called every time that visibility changes): CB_Screen._visibilityChanged = function(e) { var isVisible = true; //By default is visible. //if (!e) { e = window.event; } e = CB_Events.normalize(e); // if (e.type === \"focus\" || e.type === \"focusin\") { // isVisible = true; } // else if (e.type === \"blur\" || e.type === \"focusout\") { // isVisible = false; } // else { var hidden = \"\"; if (typeof(document.hidden) !== \"undefined\") { hidden = \"hidden\"; } else if (typeof(document.mozHidden) !== \"undefined\") { hidden = \"mozHidden\"; } else if (typeof document.msHidden !== \"undefined\") { hidden = \"msHidden\"; } else if (typeof document.webkitHidden !== \"undefined\") { hidden = \"webkitHidden\"; } //if (hidden !== \"\") { isVisible = document[hidden] ? false : true; } if (hidden !== \"\") { isVisible = !document[hidden]; } } //Calls the onVisibilityChange function (if any): if (typeof(CB_Screen._eventsHolder[\"onVisibilityChange\"]) === \"function\") { //Sets the new visibility (just in case the function needs it): CB_Screen._isVisible = isVisible; //Executes the function: CB_Screen._eventsHolder[\"onVisibilityChange\"](); } //Sets the new visibility: CB_Screen._isVisible = isVisible; } /** * Tells whether the main window is visible or not. * @function * @returns {boolean} Returns whether the main window is visible or not. */ CB_Screen.isVisible = function() { return CB_Screen._isVisible; } /* //Called every time that focus is lost: CB_Screen.focusLost = function() { //Focus has not been recovered (yet): CB_Screen.focusRecovered = false; //If focus is not recovered, set as not focused: setTimeout( function() { if (!CB_Screen.focusRecovered) { CB_Screen._focusChanged(false); } }, 500); return; } */ //Sets whether the web is focused (called every time that focus changes): CB_Screen._focusChanged = function(isFocused) { //If is focused, the focus has been recovered: //if (isFocused) { CB_Screen.focusRecovered = true; } //Calls the onFocusChange function (if any): if (typeof(CB_Screen._eventsHolder[\"onFocusChange\"]) === \"function\") { //Sets whether is focused or not (just in case the function needs it): CB_Screen._isFocused = isFocused; //Executes the function: CB_Screen._eventsHolder[\"onFocusChange\"](); } //Sets whether is focused or not: CB_Screen._isFocused = isFocused; } /** * Tells whether the main window is focused or not. * @function * @returns {boolean} Returns whether the main window is focused or not. */ CB_Screen.isFocused = function() { return CB_Screen._isFocused; } /** * Sets the focus to the main window (if possible). * @function */ CB_Screen.focus = function() { //try { CB_Client.getWindow(true).focus(); } catch(E) {} CB_Client.getWindow(false).focus(); } /** * Sets a function to execute when the left scroll position (horizontal scroll) is changed in the screen (main window) or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. */ CB_Screen.onScrollLeft = function(callbackFunction, keepOldFunction) { return CB_Screen._setSpecialEventFunction(\"onScrollLeft\", callbackFunction, keepOldFunction); } /** * Sets a function to execute when the top scroll position (vertical scroll) is changed in the screen (main window) or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. */ CB_Screen.onScrollTop = function(callbackFunction, keepOldFunction) { return CB_Screen._setSpecialEventFunction(\"onScrollTop\", callbackFunction, keepOldFunction); } /** * Sets a function to execute when the screen (main window) orientation is changed (portrait or landscape) or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. */ CB_Screen.onOrientationChange = function(callbackFunction, keepOldFunction) { return CB_Screen._setSpecialEventFunction(\"onOrientationChange\", callbackFunction, keepOldFunction); } /** * Sets a function to execute when the screen (main window) visibility is changed or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. */ CB_Screen.onVisibilityChange = function(callbackFunction, keepOldFunction) { return CB_Screen._setSpecialEventFunction(\"onVisibilityChange\", callbackFunction, keepOldFunction); } /** * Sets a function to execute when the screen (main window) focus is changed or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. */ CB_Screen.onFocusChange = function(callbackFunction, keepOldFunction) { return CB_Screen._setSpecialEventFunction(\"onFocusChange\", callbackFunction, keepOldFunction); } /** * Sets a function to execute when the screen (main window) is resized ([onResize]{@link https://developer.mozilla.org/en-US/docs/Web/Events/resize} event) or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. */ CB_Screen.onResize = function(callbackFunction, keepOldFunction, useCapture) { //If they are not set, use default values for optional parameters: if (typeof(keepOldFunction) === \"undefined\" || keepOldFunction === null) { keepOldFunction = true; } //If not set, it keeps old function by default. //If a function has been sent: if (typeof(callbackFunction) === \"function\") { //If able, adds the function given to the event: var functionToAdd = function() { CB_Screen.init(); //Updates screen properties. if (typeof(callbackFunction) === \"function\") { return callbackFunction(); } return true; }; ///////CB_Screen._eventsHolder[\"onResize\"] = functionToAdd; CB_Events.add(window, \"resize\", functionToAdd, useCapture, keepOldFunction, true); } //...but if the function given is null, it will cancel the event: else if (callbackFunction === null)/////// &amp;&amp; CB_Screen._eventsHolder[\"onResize\"] !== null) { //CB_Events.remove(window, \"resize\", CB_Screen._eventsHolder[\"onResize\"], useCapture); CB_Events.removeByName(window, \"resize\"); ////////CB_Screen._eventsHolder[\"onResize\"] = null; } } //Sets a function to execute when window is resized or zoom is applied: CB_Screen._processOnResizeOrZoomFunction = function() { //If there is no function to process, exits: if (typeof(CB_Screen._eventsHolder[\"onResizeOrZoom\"]) !== \"function\") { return; } //If this is the first time, set stored values: if (CB_Screen._storedScreenWidth === 0) { CB_Screen._storedScreenWidth = CB_Screen.getWidth(); } if (CB_Screen._storedScreenHeight === 0) { CB_Screen._storedScreenHeight = CB_Screen.getHeight(); } if (CB_Screen._storedScreenAvailableWidth === 0) { CB_Screen._storedScreenAvailableWidth = CB_Screen.getAvailableWidth(); } if (CB_Screen._storedScreenAvailableHeight === 0) { CB_Screen._storedScreenAvailableHeight = CB_Screen.getAvailableHeight(); } if (CB_Screen._storedWindowWidth === 0) { CB_Screen._storedWindowWidth = CB_Screen.getWindowWidth(); } if (CB_Screen._storedWindowHeight === 0) { CB_Screen._storedWindowHeight = CB_Screen.getWindowHeight(); } if (CB_Screen._storedZoom === 0) { CB_Screen._storedZoom = CB_Screen.getZoom(); } if (CB_Screen._storedPixelRatio === 0) { CB_Screen._storedPixelRatio = CB_Screen.getPixelRatio(); } //If the window has been resized or zoomed, stores the previous values: var windowResizedOrZoomed = false; if (CB_Screen._storedWindowWidth !== CB_Screen.getWindowWidth() || CB_Screen._storedWindowHeight !== CB_Screen.getWindowHeight() || CB_Screen._storedZoom !== CB_Screen.getZoom() || CB_Screen._storedPixelRatio !== CB_Screen.getPixelRatio()) { //Window has been resized or zoomed: windowResizedOrZoomed = true; //Stores the previous width and height: CB_Screen._previousWindowWidth = CB_Screen._storedWindowWidth; CB_Screen._previousWindowHeight = CB_Screen._storedWindowHeight; CB_Screen._previousScreenWidth = CB_Screen._storedScreenWidth; CB_Screen._previousScreenHeight = CB_Screen._storedScreenHeight; CB_Screen._previousScreenAvailableWidth = CB_Screen._storedScreenAvailableWidth; CB_Screen._previousScreenAvailableHeight = CB_Screen._storedScreenAvailableHeight; //If the zoom has been changed, stores the previous zoom and pixel ratio: if (CB_Screen._storedZoom !== CB_Screen.getZoom() || CB_Screen._storedPixelRatio !== CB_Screen.getPixelRatio()) { CB_Screen._previousZoom = CB_Screen._storedZoom; CB_Screen._previousPixelRatio = CB_Screen._storedPixelRatio; } //Stores the current window width and height: CB_Screen._storedScreenWidth = CB_Screen.getWidth(); CB_Screen._storedScreenHeight = CB_Screen.getHeight(); CB_Screen._storedScreenAvailableWidth = CB_Screen.getAvailableWidth(); CB_Screen._storedScreenAvailableHeight = CB_Screen.getAvailableHeight(); CB_Screen._storedWindowWidth = CB_Screen.getWindowWidth(); CB_Screen._storedWindowHeight = CB_Screen.getWindowHeight(); //Stores the current zoom and pixel ratio: CB_Screen._storedZoom = CB_Screen.getZoom(); CB_Screen._storedPixelRatio = CB_Screen.getPixelRatio(); } //If the window has been resized or zoomed, executes the function: if (windowResizedOrZoomed) { CB_Screen.init(); //It also refresh CB_Screen properties before calling the function. CB_Screen._eventsHolder[\"onResizeOrZoom\"](); //Executes the function. } } /** * Sets a function to execute when the screen (main window) is resized or the zoom is changed, or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. */ CB_Screen.onResizeOrZoom = function(onResizeOrZoomFunction, keepOldFunction) { return CB_Screen._setSpecialEventFunction(\"onResizeOrZoom\", onResizeOrZoomFunction, keepOldFunction); } /** * Sets a function to execute when full screen mode is changed (enabled or disabled) or removes it. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. */ CB_Screen.onFullScreenChange = function(onFullScreenChangeFunction, keepOldFunction) { return CB_Screen._setSpecialEventFunction(\"onFullScreenChange\", onFullScreenChangeFunction, keepOldFunction); } //Sets a function to execute when an event happens (a non-existing event on JavaScript): CB_Screen._setSpecialEventFunction = function(eventName, eventFunction, keepOldFunction) { //If no function has been sent, cancel all previous functions and exits: if (typeof(eventFunction) !== \"function\") { if (eventFunction === null) { CB_Screen._eventsHolder[eventName] = null; } return; } //If not set, it keeps old function by default: if (typeof(keepOldFunction) === \"undefined\" || keepOldFunction === null) { keepOldFunction = true; } //If we don't want to keep the old function: if (!keepOldFunction) { CB_Screen._eventsHolder[eventName] = eventFunction; } //...otherwise if we want to keep the old function, we keep it: else { //Stores old function: var eventFunctionOld = CB_Screen._eventsHolder[eventName]; //Stores old function of eventFunctionHolder. CB_Screen._eventsHolder[eventName] = function() //TODO: remember to use \"e\" in the case it uses parameters in the future. { if (typeof(eventFunctionOld) === \"function\") { eventFunctionOld(); } eventFunction(); }; } } /** * Tells whether the web client is compatible with the [FullScreen API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API} or not. * @function * @returns {boolean} Returns whether the web client is compatible with the [FullScreen API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API} or not. */ CB_Screen.isFullScreenAPICompatible = function() { if (document.documentElement) { element = document.documentElement; } else { element = document.body; } var isFullScreenAPICompatible = false; //Gets the function compatible with Fullscreen API (if any): var callFullScreen = element.requestFullscreen || element.mozRequestFullScreen || element.webkitRequestFullscreen || element.oRequestFullScreen || element.msRequestFullscreen || element.msRequestFullScreen || element.webkitEnterFullScreen || element.webkitEnterFullscreen; if (typeof(callFullScreen) !== \"undefined\" &amp;&amp; callFullScreen) { isFullScreenAPICompatible = true; } return isFullScreenAPICompatible; } /** * Toggles between full screen and normal mode. Uses the [Fullscreen API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API} and fallbacks to other methods internally, including [NW.js (formerly node-webkit)]{@link https://nwjs.io/} and [Electron (Electron.js)]{@link https://electronjs.org/} ones, when not available. Recommended to be called through an event fired by the user as onclick or ontouchstart, etc. * @function * @param {boolean} [useFullScreen=true] - If set to true, it will try to enable full screen mode. Otherwise, it will try to enable normal mode. * @param {Element} [element=document.documentElement|document.body] - Element which we want to use in full screen mode. By default uses the whole document body. Only used when the \"useFullScreen\" parameter is set to true. If an element is provided, it will use neither [NW.js (formerly node-webkit)]{@link https://nwjs.io/} nor [Electron (Electron.js)]{@link https://electronjs.org/} methods. * @param {boolean} [allowReload=false] - If set to true and \"useFullScreen\" is set to true but it fails to enable full screen normally, it will try to reload the entire current document again in a new bigger window. Useful for very old web clients. Only used when the \"useFullScreen\" parameter is set to true. */ CB_Screen.setFullScreen = function(useFullScreen, element, allowReload) { var documentBase = CB_Client.getDocumentBase(); //Defines default parameters: if (typeof(useFullScreen) === \"undefined\" || useFullScreen === null) { useFullScreen = true; } //By default, full screen mode will be used: var elementGiven = true; //Tells whether an element was given or not (useful for NW.js and Electron). if (typeof(element) === \"undefined\" || element === null) { //if (documentBase.documentElement) { element = documentBase.documentElement; } //else { element = documentBase.body; } if (document.documentElement) { element = document.documentElement; } else { element = document.body; } elementGiven = false; } //If we want full screen mode: if (useFullScreen) { var fullScreenApplied = false; if (!elementGiven) { //Tries to use NW.js (node-webkit) if available to enter full screen: if (CB_Client.isRunningOnNWjs()) { if (typeof(nw) !== \"undefined\" &amp;&amp; nw !== null &amp;&amp; nw.Window &amp;&amp; typeof(nw.Window.get) === \"function\") { try { var win = nw.Window.get(); if (win !== null) { win.enterFullscreen(); fullScreenApplied = win.isFullscreen; if (!fullScreenApplied) { win.enterKioskMode(); fullScreenApplied = win.isKioskMode; } } } catch(E) { fullScreenApplied = false; } } if (!fullScreenApplied &amp;&amp; typeof(require) === \"function\") { var gui = require(\"nw.gui\"); if (typeof(gui) !== \"undefined\" &amp;&amp; gui !== null &amp;&amp; typeof(gui.Window) !== \"undefined\" &amp;&amp; gui.Window !== null &amp;&amp; typeof(gui.Window.get) === \"function\") { try { var win = gui.Window.get(); if (win !== null) { win.enterFullscreen(); fullScreenApplied = win.isFullscreen; if (!fullScreenApplied) { win.enterKioskMode(); fullScreenApplied = win.isKioskMode; } } } catch(E) { fullScreenApplied = false; } } } } //Tries to use Electron (Electron.js) if available to enter full screen: if (CB_Client.isRunningOnElectron() &amp;&amp; typeof(require) === \"function\") { try { fullScreenApplied = require(\"electron\").remote.getCurrentWindow().setFullScreen(true); } catch(E) { try { fullScreenApplied = require(\"electron\").remote.getCurrentWindow().setSimpleFullScreen(true); } catch(E) { fullScreenApplied = false; } } } } if (!fullScreenApplied) { //Gets the function compatible with Fullscreen API (if any): var callFullScreen = element.requestFullscreen || element.mozRequestFullScreen || element.webkitRequestFullscreen || element.oRequestFullScreen || element.msRequestFullscreen || element.msRequestFullScreen || element.webkitEnterFullScreen || element.webkitEnterFullscreen; //If there is any function compatible with Fullscreen API, we call it: if (typeof(callFullScreen) !== \"undefined\" &amp;&amp; callFullScreen) { if (Element.ALLOW_KEYBOARD_INPUT) { callFullScreen.call(element, Element.ALLOW_KEYBOARD_INPUT); //For Webkit. } else { callFullScreen.call(element); } fullScreenApplied = true; } //..otherwise, we try to use ActiveX (if it's not already in full screen): else if (typeof(window.ActiveXObject) !== \"undefined\") { try { var wscript = new ActiveXObject(\"WScript.Shell\"); //If ActiveX object has been created: if (wscript !== null) { //ActiveX object working, so we press the key: wscript.SendKeys(\"{F11}\"); fullScreenApplied = true; } } //If ActiveX is not enabled or has not been accepted: catch(E) { fullScreenApplied = false; } } } //If the full screen mode has not been applied, we try to resize the window: if (!fullScreenApplied) { /* if (typeof(window.fullscreen) !== \"undefined\") { try { window.fullscreen = true; } catch(E) { } } */ //if (typeof(top.window.outerWidth) !== \"undefined\" &amp;&amp; typeof(screen.availWidth) !== \"undefined\" &amp;&amp; top.window.outerWidth !== null &amp;&amp; screen.availWidth !== null) var screenAvailableWidth = CB_Screen.getAvailableWidth(); if (typeof(top.window.outerWidth) !== \"undefined\" &amp;&amp; top.window.outerWidth !== null &amp;&amp; screenAvailableWidth &gt; 0) { //top.window.outerWidth = screen.availWidth; top.window.outerWidth = screenAvailableWidth; } //if (typeof(top.window.outerHeight) !== \"undefined\" &amp;&amp; typeof(screen.availHeight) !== \"undefined\" &amp;&amp; top.window.outerHeight !== null &amp;&amp; screen.availHeight !== null) var screenAvailableHeight = CB_Screen.getAvailableHeight(); if (typeof(top.window.outerHeight) !== \"undefined\" &amp;&amp; top.window.outerHeight !== null &amp;&amp; screenAvailableHeight &gt; 0) { //top.window.outerHeight = screen.availHeight; top.window.outerHeight = screenAvailableHeight; } /* var hdiff; window.resizeTo(screen.width/2,screen.height/2) window.moveTo(0,10) hdiff=window.screenTop; window.moveTo(-6,-hdiff+6); window.resizeTo(screen.width+13,screen.height+hdiff+26) */ var screenWidth = CB_Screen.getWidth(); var screenHeight = CB_Screen.getHeight(); try { //window.moveTo(0, 0); //GIVES PROBLEMS WHEN YOU USE THE SCRIPT ON AN IFRAME!!! //window.resizeTo(screenWidth, screenHeight); //GIVES PROBLEMS WHEN YOU USE THE SCRIPT ON AN IFRAME!!! } catch(E) {} ////////////////// //If the full screen mode is still not applied and we allow to reload web: if (allowReload &amp;&amp; !(/iPad|iPhone|iPod/.test(navigator.userAgent) &amp;&amp; !window.MSStream || navigator.platform &amp;&amp; /iPad|iPhone|iPod/.test(navigator.platform))) //Checks whether it is not iOS. { var currentWindow = window.self; currentWindow.opener = window.self; var newWindow = window.open(\"\" + window.location, \"CB_fullScreenWindow\", \"type=fullWindow, fullscreen=yes, scrollbars=auto, toolbar=no, location=no, directories=no, status=no, menubar=no, resizable=no, channelmode=1\"); //currentWindow.location.href = \"about:blank\"; newWindow.focus(); //currentWindow.close(); //newWindow.focus(); } } } //...otherwise, if we want normal screen mode (not full screen): else { var fullScreenLeft = false; if (!elementGiven) { //Tries to use NW.js (node-webkit) if available to leave full screen: if (CB_Client.isRunningOnNWjs()) { if (typeof(nw) !== \"undefined\" &amp;&amp; nw !== null &amp;&amp; nw.Window &amp;&amp; typeof(nw.Window.get) === \"function\") { try { var win = nw.Window.get(); if (win !== null) { win.leaveFullscreen(); fullScreenLeft = !win.isFullscreen; if (!fullScreenLeft) { win.leaveKioskMode(); fullScreenLeft = !win.isKioskMode; } } } catch(E) { fullScreenLeft = false; } } if (!fullScreenLeft &amp;&amp; typeof(require) === \"function\") { var gui = require(\"nw.gui\"); if (typeof(gui) !== \"undefined\" &amp;&amp; gui !== null &amp;&amp; typeof(gui.Window) !== \"undefined\" &amp;&amp; gui.Window !== null &amp;&amp; typeof(gui.Window.get) === \"function\") { try { var win = gui.Window.get(); if (win !== null) { win.leaveFullscreen(); fullScreenLeft = !win.isFullscreen; if (!fullScreenLeft) { win.leaveKioskMode(); fullScreenLeft = !win.isKioskMode; } } } catch(E) { fullScreenLeft = false; } } } } //Tries to use Electron (Electron.js) if available to leave full screen: if (CB_Client.isRunningOnElectron() &amp;&amp; typeof(require) === \"function\") { try { fullScreenLeft = require(\"electron\").remote.getCurrentWindow().setFullScreen(true); } catch(E) { try { fullScreenLeft = require(\"electron\").remote.getCurrentWindow().setSimpleFullScreen(true); } catch(E) { fullScreenLeft = false; } } } } if (!fullScreenLeft) { //Gets the function compatible with Fullscreen API (if any): var cancelFullScreen = documentBase.exitFullscreen || documentBase.cancelFullScreen || documentBase.mozCancelFullScreen || documentBase.webkitCancelFullScreen || documentBase.oCancelFullScreen || documentBase.msExitFullscreen || documentBase.msExitFullScreen || documentBase.msCancelFullScreen || documentBase.webkitExitFullScreen || documentBase.webkitExitFullscreen; var useDocumentBase = true; if (typeof(cancelFullScreen) === \"undefined\" || cancelFullScreen === null) { cancelFullScreen = document.exitFullscreen || document.cancelFullScreen || document.mozCancelFullScreen || document.webkitCancelFullScreen || document.oCancelFullScreen || document.msExitFullscreen || document.msExitFullScreen || document.msCancelFullScreen || document.webkitExitFullScreen || document.webkitExitFullscreen; useDocumentBase = false; } //If there is any function compatible with Fullscreen API, we call it: if (typeof(cancelFullScreen) !== \"undefined\" &amp;&amp; cancelFullScreen) { cancelFullScreen.call(useDocumentBase ? documentBase : document); } //..otherwise, we try to use ActiveX (if it's not in full screen already): else if (typeof(window.ActiveXObject) !== \"undefined\" &amp;&amp; !CB_Screen.isFullScreen()) { try { var wscript = new ActiveXObject(\"WScript.Shell\"); //If ActiveX object has been created: if (wscript !== null) { //ActiveX object working, so we press the key: wscript.SendKeys(\"{F11}\"); } } //If ActiveX is not enabled or has not been accepted: catch(E) {} } } } } /** * Tells whether we are in full screen mode or not. Uses the [Fullscreen API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API} and fallbacks to other methods internally, including [NW.js (formerly node-webkit)]{@link https://nwjs.io/} and [Electron (Electron.js)]{@link https://electronjs.org/} ones, when not available. * @function * @param {number} [allowedWidthMarginPercentage=CB_Configuration.CrossBase.CB_Screen_isFullScreen_ALLOWED_WIDTH_MARGIN_PERCENTAGE] - Allowed width margin, in percentage, of the total screen available to detect whether it is in full screen or not. Needed by old web clients without [Fullscreen API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API} support, mainly. * @param {number} [allowedHeightMarginPercentage=CB_Configuration.CrossBase.CB_Screen_isFullScreen_ALLOWED_HEIGHT_MARGIN_PERCENTAGE] - Allowed height margin, in percentage, of the total screen available to detect whether it is in full screen or not. Needed by old web clients without [Fullscreen API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API} support, mainly. * @returns {boolean} Returns whether we are in full screen mode or not. */ CB_Screen.isFullScreen = function(allowedWidthMarginPercentage, allowedHeightMarginPercentage) { //Gets the variable compatible with Fullscreen API (if any): var documentBase = CB_Client.getDocumentBase(); /* var isFullScreenApplied = (documentBase.fullScreenElement &amp;&amp; documentBase.fullScreenElement !== null) || (documentBase.fullscreenElement &amp;&amp; documentBase.fullscreenElement !== null) || (documentBase.msFullscreenElement &amp;&amp; documentBase.msFullscreenElement !== null) || documentBase.fullScreen || documentBase.mozFullScreen || documentBase.fullScreen || documentBase.webkitIsFullScreen || documentBase.oIsFullScreen || documentBase.msIsFullscreen || documentBase.msIsFullScreen || documentBase.webkitDisplayingFullScreen || documentBase.webkitDisplayingFullscreen; */ var isFullScreenApplied = false; //Tries to use NW.js (node-webkit) to detect whether we are in fullscreen mode or not: if (CB_Client.isRunningOnNWjs()) { if (typeof(nw) !== \"undefined\" &amp;&amp; nw !== null &amp;&amp; nw.Window &amp;&amp; typeof(nw.Window.get) === \"function\") { try { var win = nw.Window.get(); if (win !== null) { isFullScreenApplied = win.isFullscreen || win.isKioskMode; } } catch(E) { isFullScreenApplied = false; } } if (!isFullScreenApplied &amp;&amp; typeof(require) === \"function\") { var gui = require(\"nw.gui\"); if (typeof(gui) !== \"undefined\" &amp;&amp; gui !== null &amp;&amp; typeof(gui.Window) !== \"undefined\" &amp;&amp; gui.Window !== null &amp;&amp; typeof(gui.Window.get) === \"function\") { try { var win = gui.Window.get(); if (win !== null) { if (win !== null) { isFullScreenApplied = win.isFullscreen || win.isKioskMode; } } } catch(E) { isFullScreenApplied = false; } } } } //Tries to use Electron (Electron.js) to detect whether we are in fullscreen mode or not: if (CB_Client.isRunningOnElectron() &amp;&amp; typeof(require) === \"function\") { try { isFullScreenApplied = (require(\"electron\").remote.getCurrentWindow().isFullScreen() === true); } catch(E) { isFullScreenApplied = false; } } if (!isFullScreenApplied) { isFullScreenApplied = documentBase.fullScreenElement || documentBase.fullscreenElement || documentBase.msFullscreenElement || documentBase.fullScreen || documentBase.mozFullScreen || documentBase.fullScreen || documentBase.webkitIsFullScreen || documentBase.oIsFullScreen || documentBase.msIsFullscreen || documentBase.msIsFullScreen || documentBase.webkitDisplayingFullScreen || documentBase.webkitDisplayingFullscreen; //var useDocumentBase = true; if (typeof(isFullScreenApplied) === \"undefined\" || isFullScreenApplied === null) { /* isFullScreenApplied = (document.fullScreenElement &amp;&amp; document.fullScreenElement !== null) || (document.fullscreenElement &amp;&amp; document.fullscreenElement !== null) || (document.msFullscreenElement &amp;&amp; document.msFullscreenElement !== null) || document.fullScreen || document.mozFullScreen || window.fullScreen || document.webkitIsFullScreen || document.oIsFullScreen || document.msIsFullscreen || document.msIsFullScreen || document.webkitDisplayingFullScreen || document.webkitDisplayingFullscreen; */ isFullScreenApplied = document.fullScreenElement || document.fullscreenElement || document.msFullscreenElement || document.fullScreen || document.mozFullScreen || window.fullScreen || document.webkitIsFullScreen || document.oIsFullScreen || document.msIsFullscreen || document.msIsFullScreen || document.webkitDisplayingFullScreen || document.webkitDisplayingFullscreen; //useDocumentBase = false; } //If there is not compatibility with Fullscreen API, we use other methods: if (typeof(isFullScreenApplied) === \"undefined\" || isFullScreenApplied === null) { if (CB_Client.getBrowser() === \"Explorer\") //Only IE since Chrome would do false positives: { //if (typeof(window.screenTop) !== \"undefined\" &amp;&amp; window.screenTop !== null &amp;&amp; !window.screenTop) if (window.screenTop) { isFullScreenApplied = true; } //else if (typeof(window.screenY) !== \"undefined\" &amp;&amp; window.screenY !== null &amp;&amp; !window.screenY) else if (window.screenY) { isFullScreenApplied = true; } } if (\"standalone\" in window.navigator &amp;&amp; window.navigator.standalone) //For some WebKit browsers. { isFullScreenApplied = true; } if (typeof(document.fullscreenElement) !== \"undefined\") { if (document.fullscreenElement === null) { isFullScreenApplied = false; } } } //If there is still not compatibility with Fullscreen API and the methods above didn't work, we use other methods: if (typeof(isFullScreenApplied) === \"undefined\" || isFullScreenApplied === null) //if (typeof(isFullScreenApplied) === \"undefined\" || isFullScreenApplied === null) { //If the web client is not compatible with Fullscreen API (except the ones which are but don't detect full screen mode when we press F11): var element = documentBase.body; if (documentBase.documentElement) { element = documentBase.documentElement; } //TODO: Add more browsers in callFullScreen that are compatible with Fullscreen API but don't detect fullscreen when you press F11. var callFullScreen = element.mozRequestFullScreen;// || element.msRequestFullScreen; if (typeof(callFullScreen) === \"undefined\") { //We will check the size of the window (having mind zoom level): var currentZoom = CB_Screen.getZoom(); //Gets the available screen size (or the screen size if it's not avaiable): var screenAvailableWidth_ = CB_Screen.getAvailableWidth(); //if (typeof(screenAvailableWidth_) === \"undefined\" || screenAvailableWidth_ === null || screenAvailableWidth_ === 0) { screenAvailableWidth_ = CB_Screen.getWidth(); } if (!screenAvailableWidth_) { screenAvailableWidth_ = CB_Screen.getWidth(); } var screenAvailableHeight_ = CB_Screen.getAvailableHeight(); //if (typeof(screenAvailableHeight_) === \"undefined\" || screenAvailableHeight_ === null || screenAvailableHeight_ === 0) { screenAvailableHeight_ = CB_Screen.getHeight(); } if (!screenAvailableHeight_) { screenAvailableHeight_ = CB_Screen.getHeight(); } //Gets the previous available screen size (or the previous screen size if it's not available): var previousScreenAvailableWidth_ = CB_Screen.getAvailableWidthPrevious(); //if (typeof(previousScreenAvailableWidth_) === \"undefined\" || previousScreenAvailableWidth_ === null || previousScreenAvailableWidth_ === 0) { previousScreenAvailableWidth_ = CB_Screen.getWidthPrevious(); } if (!previousScreenAvailableWidth_) { previousScreenAvailableWidth_ = CB_Screen.getWidthPrevious(); } var previousScreenAvailableHeight_ = CB_Screen.getAvailableHeightPrevious(); //if (typeof(previousScreenAvailableHeight_) === \"undefined\" || previousScreenAvailableHeight_ === null || previousScreenAvailableHeight_ === 0) { previousScreenAvailableHeight_ = CB_Screen.getHeightPrevious(); } if (!previousScreenAvailableHeight_) { previousScreenAvailableHeight_ = CB_Screen.getHeightPrevious(); } /* //Sets an allowed margin: var allowedWidthMargin = 0.034 * CB_Screen.getWidth();//50; //Maximum width margin allowed. if (allowedWidthMargin &lt;= 0) { allowedWidthMargin = 50; } var allowedHeightMargin = 0.035 * CB_Screen.getHeight(); //42; //Maximum height margin allowed. if (allowedHeightMargin &lt;= 0) { allowedHeightMargin = 42; } */ //Determine whether zoom affects screen available size or not: var zoomAffectsScreenSize = false; //If the page has not been zoomed yet: if (CB_Screen.getZoomPrevious() === 0) { zoomAffectsScreenSize = false; } //...otherwise, if has already been zoomed: else { //If screen available size changed form last time, zoom affects it: if (screenAvailableWidth_ !== previousScreenAvailableWidth_)// &amp;&amp; previousScreenAvailableWidth_ !== CB_Screen._storedScreenAvailableWidth) { zoomAffectsScreenSize = true; } if (screenAvailableHeight_ !== previousScreenAvailableHeight_)// &amp;&amp; previousScreenAvailableHeight_ !== CB_Screen._storedScreenAvailableHeight) { zoomAffectsScreenSize = true; } } //If it's Internet Explorer, zooms will affect the screen available size: //TODO: Add more browsers here that zoom affects the screen available size (specially the ones which are not compatible with the Fullscreen API or they don't think they are in Fullscreen mode when you press F11). //if (typeof(document.attachEvent) !== \"undefined\" &amp;&amp; document.attachEvent) if (CB_Client.getBrowser() === \"Explorer\" || typeof(document.msFullscreenElement) !== \"undefined\") { zoomAffectsScreenSize = true; } if (CB_Client.getBrowser() === \"Chrome\") //Chrome versions not compatible with FullScreen API. { zoomAffectsScreenSize = false;//true; } //If the zoom affects the screen available size: if (zoomAffectsScreenSize) { //We try to calculate the real screen available size (having in mind the zoom): screenAvailableWidth_ *= currentZoom; screenAvailableHeight_ *= currentZoom; } //Sets an allowed margin: if (typeof(allowedWidthMarginPercentage) === \"undefined\" || allowedWidthMarginPercentage === null || isNaN(allowedWidthMarginPercentage) || allowedWidthMarginPercentage &lt; 0 || allowedWidthMarginPercentage &gt;= 100) { allowedWidthMarginPercentage = CB_Configuration[CB_BASE_NAME].CB_Screen_isFullScreen_ALLOWED_WIDTH_MARGIN_PERCENTAGE; } if (typeof(allowedHeightMarginPercentage) === \"undefined\" || allowedHeightMarginPercentage === null || isNaN(allowedHeightMarginPercentage) || allowedHeightMarginPercentage &lt; 0 || allowedHeightMarginPercentage &gt;= 100) { allowedHeightMarginPercentage = CB_Configuration[CB_BASE_NAME].CB_Screen_isFullScreen_ALLOWED_HEIGHT_MARGIN_PERCENTAGE; } var allowedWidthMargin = (allowedWidthMarginPercentage / 100) * screenAvailableWidth_;//50; //Maximum width margin allowed. if (allowedWidthMargin &lt;= 0) { allowedWidthMargin = 50; } var allowedHeightMargin = (allowedHeightMarginPercentage / 100) * screenAvailableHeight_; //42; //Maximum height margin allowed. if (allowedHeightMargin &lt;= 0) { allowedHeightMargin = 42; } //We get the real window size (having in mind the zoom): var windowWidth = CB_Screen.getWindowWidth() * currentZoom; var windowHeight = CB_Screen.getWindowHeight() * currentZoom; //We round the sizes having in mind that zoom can be not exact: windowWidth = Math.ceil(windowWidth); windowHeight = Math.ceil(windowHeight); screenAvailableWidth_ = Math.floor(screenAvailableWidth_); screenAvailableHeight_ = Math.floor(screenAvailableHeight_); //If it's full screen (having in mind allowed margin): if (Math.ceil(windowWidth + allowedWidthMargin) &gt;= screenAvailableWidth_ &amp;&amp; Math.ceil(windowHeight + allowedHeightMargin) &gt;= screenAvailableHeight_) { isFullScreenApplied = true; } else { isFullScreenApplied = false; } } else { isFullScreenApplied = false; } //If the web client is compatible with Fullscreen API (except the ones which are but don't detect full screen mode when we press F11), it's not in full screen mode. } //Casts the variable to boolean type: //isFullScreenApplied = (isFullScreenApplied) ? true : false; isFullScreenApplied = !!(isFullScreenApplied); //If it's not the first time and full screen mode has been changed, calls the onFullScreenChange function (if any): if (CB_Screen._isFullScreen !== null &amp;&amp; CB_Screen._isFullScreen !== isFullScreenApplied) { //If there is any defined function: if (typeof(CB_Screen._eventsHolder[\"onFullScreenChange\"]) === \"function\") { //Sets the new position (just in case the function needs it): CB_Screen._isFullScreen = isFullScreenApplied; //Executes the function: CB_Screen._eventsHolder[\"onFullScreenChange\"](); } } } //Sets the new position: CB_Screen._isFullScreen = isFullScreenApplied; return CB_Screen._isFullScreen;//isFullScreenApplied; } CB_Screen.unlockOrientation_unsetOrientation_timeout = null; /** * Alias for {@link CB_Screen.unlockOrientation}. * @function CB_Screen.unsetOrientation * @see {@link CB_Screen.unlockOrientation} */ /** * Function that unlocks the screen orientation. Using the [unlock]{@link https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation/unlock} function and fallbacks to the [unlockOrientation]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/unlockOrientation} function of the [Screen Orientation API]{@link https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation} internally. * @function * @param {function} [onError] - Callback function that will be called if the orientation has not been unlocked successfully. Unique parameter received will be an error object (probably a [DOMException]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMException}, depending on the client) with the error. * @returns {boolean} Returns the same that the [unlock]{@link https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation/unlock} function returns (undefined, normally), if available. Otherwise, returns the same boolean as the [unlockOrientation]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/unlockOrientation} function (true if the unlocking action has been performed successfully), if available. Otherwise, returns false when the [Screen Orientation API]{@link https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation} is not available. */ CB_Screen.unlockOrientation = CB_Screen.unsetOrientation = function(onError) { clearTimeout(CB_Screen.unlockOrientation_unsetOrientation_timeout); var orientationBefore = CB_Screen.getOrientation(); var onErrorCalled = false; try { var returnValue = false; orientationObject = CB_Screen.getOrientationObject(); if (orientationObject !== null &amp;&amp; typeof(orientationObject.unlock) !== \"undefined\" &amp;&amp; orientationObject.unlock !== null) { try { returnValue = orientationObject.unlock(); //Attaching an error-catch to prevent Chrome desktop exception. } catch(E) { returnValue = false; } } else if (typeof(screen) !== \"undefined\" &amp;&amp; screen !== null) { //Using IF because of Firefox bug (\"TypeError: 'mozUnlockOrientation' called on an object that does not implement interface Screen.\"): if (screen.unlockOrientation) { returnValue = screen.unlockOrientation(); } else if (screen.mozUnlockOrientation) { returnValue = screen.mozUnlockOrientation(); } else if (screen.webkitUnlockOrientation) { returnValue = screen.webkitUnlockOrientation(); } else if (screen.oUnlockOrientation) { returnValue = screen.oUnlockOrientation(); } else if (screen.msUnlockOrientation) { returnValue = screen.msUnlockOrientation(); } else if (typeof(Screen) !== \"undefined\" &amp;&amp; Screen !== null &amp;&amp; Screen.msUnlockOrientation) { returnValue = Screen.msUnlockOrientation(); } else if (screen.khtmlUnlockOrientation) { returnValue = screen.khtmlUnlockOrientation(); } /* else if (screen.orientation &amp;&amp; screen.orientation.unlock) { return screen.orientation.unlock(); } */ } if (returnValue === false &amp;&amp; typeof(onError) === \"function\") { onErrorCalled = true; onError({ message: \"Orientation mode could not be unlocked.\" }); } } catch(E) { if (!onErrorCalled &amp;&amp; typeof(onError) === \"function\") { onErrorCalled = true; onError({ message: \"Orientation mode could not be unlocked.\" }); } returnValue = false; } //If no error happened, checks after some time: if (!onErrorCalled) { CB_Screen.unlockOrientation_unsetOrientation_timeout = setTimeout ( function() { if (onErrorCalled) { return; } var orientationNow = CB_Screen.getOrientation(); if (orientationNow === orientationBefore) //Orientation is the same one. { if (typeof(onError) === \"function\") { onErrorCalled = true; onError({ message: \"Orientation did not change after trying to unlock it (it is still '\" + orientationBefore + \"').\" }); } } }, 1000 //Unlocking process can take some time so it waits a while. ); } return returnValue; } /** * Alias for {@link CB_Screen.lockOrientation}. * @function CB_Screen.setOrientation * @see {@link CB_Screen.lockOrientation} */ /** * Function that forces a desired screen orientation. Using the [lock]{@link https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation/lock} function and fallbacks to the [lockOrientation]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/lockOrientation} function of the [Screen Orientation API]{@link https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation} internally. * @function * @param {'default'|'any'|'natural'|'landscape'|'portrait'|'portrait-primary'|'portrait-secondary'|'landscape-primary'|'landscape-secondary'} orientationMode - Desired orientation. Internally, \"default\" and \"natural\" will be exchanged and \"any\" will be transformed to \"default\", depending on the internal function used. Values \"default\", \"any\" and \"natural\" are not recommended because they are not supported in all web clients. * @param {function} [onSuccess] - Callback function with no parameters that will be called if the orientation has been set successfully. * @param {function} [onError] - Callback function that will be called if the orientation has not been set successfully. Unique parameter received will be an error object (probably a [DOMException]{@link https://developer.mozilla.org/en-US/docs/Web/API/DOMException}, depending on the client) with the error. * @returns {boolean} Returns the same [Promise]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise} that the [lock]{@link https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation/lock} function returns, if available. Otherwise, returns the same boolean as the [lockOrientation]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/lockOrientation} function (true if the locking action has been performed successfully), if available. Otherwise, returns false when the [Screen Orientation API]{@link https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation} is not available. * @todo Transform values of \"default\", \"any\" and \"natural\" to \"portrait\", \"landscape\", etc. when the web clients do not support it (calculating current orientation and trying to guess natural/default one, etc.). */ CB_Screen.lockOrientation = CB_Screen.setOrientation = function(orientationMode, onSuccess, onError) { clearTimeout(CB_Screen.unlockOrientation_unsetOrientation_timeout); try { var returnValue = false; orientationMode = CB_trim(orientationMode).toLowerCase(); var orientationObject = CB_Screen.getOrientationObject(); if (orientationObject !== null &amp;&amp; typeof(orientationObject.lock) !== \"undefined\" &amp;&amp; orientationObject.lock !== null) { if (orientationMode === \"default\") { orientationMode = \"natural\"; } //return orientationObject.lock(orientationMode).then(onSuccess)[\"catch\"](typeof(onError) === \"function\" ? onError : function() {}); //Attaching an error-catch to prevent Chrome desktop exception. try { returnValue = orientationObject.lock(orientationMode).then(onSuccess)[\"catch\"](typeof(onError) === \"function\" ? onError : function() {}); //Attaching an error-catch to prevent Chrome desktop exception. return returnValue; } catch(E) { try { returnValue = orientationObject.lock(orientationMode); //Attaching an error-catch to prevent Chrome desktop exception. } catch(E) { returnValue = false; } } } else if (typeof(screen) !== \"undefined\" &amp;&amp; screen !== null) { if (orientationMode === \"natural\") { orientationMode = \"default\"; } else if (orientationMode === \"any\") { orientationMode = \"default\"; } //Using IF because of Firefox bug (TypeError: 'mozLockOrientation' called on an object that does not implement interface Screen.): if (screen.lockOrientation) { returnValue = screen.lockOrientation(orientationMode); } else if (screen.mozLockOrientation) { returnValue = screen.mozLockOrientation(orientationMode); } else if (screen.webkitLockOrientation) { returnValue = screen.webkitLockOrientation(orientationMode); } else if (screen.oLockOrientation) { returnValue = screen.oLockOrientation(orientationMode); } else if (screen.msLockOrientation) { returnValue = screen.msLockOrientation(orientationMode); } else if (typeof(Screen) !== \"undefined\" &amp;&amp; Screen !== null &amp;&amp; Screen.msLockOrientation) { returnValue = Screen.msLockOrientation(orientationMode); } else if (screen.khtmlLockOrientation) { returnValue = screen.khtmlLockOrientation(orientationMode); } } if (returnValue === true &amp;&amp; typeof(onSucess) === \"function\") { onSuccess(); } else if (returnValue === false &amp;&amp; typeof(onError) === \"function\") { onError({ message: \"Orientation mode could not be locked.\" }); } return returnValue; } catch(E) { if (typeof(onError) === \"function\") { onError({ message: \"Orientation mode could not be locked.\" }); } return false; } } /** * Gets the [screen orientation object]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/orientation} of the [Screen Orientation API]{@link https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation}. * @function * @returns {Object} Returns the [screen orientation object]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/orientation} of the [Screen Orientation API]{@link https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation}. */ CB_Screen.getOrientationObject = function() { if (typeof(screen) !== \"undefined\") { var orientationObject = screen.orientation || screen.mozOrientation || screen.webkitOrientation || screen.oOrientation || screen.msOrientation || screen.khtmlOrientation || null; if (typeof(orientationObject) !== \"undefined\" &amp;&amp; orientationObject !== null) { return orientationObject; } } return null; } CB_Screen.getOrientation_map = //* Map and map implementation by Christian Maniewski from: https://github.com/chmanie/o9n/blob/master/index.js { '90': 'landscape-primary', '-90': 'landscape-secondary', '0': 'portrait-primary', '180': 'portrait-secondary' }; CB_Screen.getOrientation_getMql = function() //* Function by Christian Maniewski from: https://github.com/chmanie/o9n/blob/master/index.js { if (typeof(window.matchMedia) !== \"function\") { return {}; } return window.matchMedia('(orientation: landscape)'); }; /** * Gets the current orientation from the [screen orientation object]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/orientation} of the [Screen Orientation API]{@link https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation}. * @function * @returns {string} Returns a string with the current orientation from the [screen orientation object]{@link https://developer.mozilla.org/en-US/docs/Web/API/Screen/orientation} of the [Screen Orientation API]{@link https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation}. If cannot be found, it will return \"landscape-primary\" as default. */ CB_Screen.getOrientation = function() { var orientationObject = CB_Screen.getOrientationObject(); var orientation = \"\"; if (orientationObject !== null) { if (typeof(orientationObject) === \"string\") { orientation = orientationObject; } else if (typeof(orientationObject.type) === \"string\") { orientation = orientationObject.type; } } if (orientation === \"\") { orientation = CB_Screen.getOrientation_map[window.orientation + \"\"] || (CB_Screen.getOrientation_getMql().matches ? \"landscape-primary\" : \"portrait-primary\"); } return orientation; //TODO: Think about using CB_trim(); } /** * Sets the [Viewport]{@link https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag} meta tag dynamically with the desired options. If the [Viewport]{@link https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag} meta tag already exists, it will be updated. Otherwise, it will create a new one (and append it to the [HEAD]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head} tag, if found). * @function * @param {string|integer} [width] - Desired value for the \"width\" parameter. * @param {string|integer} [height] - Desired value for the \"height\" parameter. * @param {string|boolean} [userScalable='no'] - Desired value for the \"user-scalable\" parameter. * @param {number} [initialScale] - Desired value for the \"initial-scale\" parameter. * @param {number} [minimumScale] - Desired value for the \"minimum-scale\" parameter. * @param {number} [maximumScale] - Desired value for the \"maximum-scale\" parameter. * @param {string} [shrinkToFit] - Desired value for the \"shrink-to-fit\" parameter. * @param {string|number} [targetDensityDPI] - Desired value for the \"target-densitydpi\" parameter. * @returns {Node|null} Returns the DOM element which belongs to the [Viewport]{@link https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag} meta tag affected (it will have been just created if no one existed before). If a [Viewport]{@link https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag} meta tag could not be created or modified, returns null. */ CB_Screen.setViewport = function(width, height, userScalable, initialScale, minimumScale, maximumScale, shrinkToFit, targetDensityDPI) { //Finds the meta tag viewport (if any): var viewport = CB_Elements.id(\"viewport\"); if (typeof(viewport) === \"undefined\" || viewport === null) { //if (typeof(document.querySelector) !== \"undefined\" &amp;&amp; document.querySelector !== null &amp;&amp; document.querySelector) if (document.querySelector) { viewport = document.querySelector(\"meta[name=viewport]\"); } else { var metaTags = CB_Elements.tag(\"meta\", document, false); for (var x = metaTags.length - 1; x &gt;= 0; x--) //Finds the last one. { if (metaTags[x].name.toLowerCase() === \"viewport\") { viewport = metaTags[x]; break; } } } } //Prepare the given parameters: width = CB_trim(width); height = CB_trim(height); userScalable = CB_trim(userScalable).toLowerCase(); initialScale = CB_trim(initialScale); minimumScale = CB_trim(minimumScale); maximumScale = CB_trim(maximumScale); targetDensityDPI = CB_trim(targetDensityDPI); if (shrinkToFit === true) { shrinkToFit = \"yes\"; } else if (shrinkToFit === false) { shrinkToFit = \"no\"; } shrinkToFit = CB_trim(shrinkToFit); //Sets the content for the meta tag viewport (according to the parameters given): var viewportContent = \"\"; if (width !== \"\") { viewportContent += \"width=\" + width; } if (height !== \"\") { if (CB_trim(viewportContent) !== \"\") { viewportContent += \", \"; } viewportContent += \"height=\" + height; } if (userScalable &amp;&amp; userScalable !== \"no\" &amp;&amp; userScalable !== 0 &amp;&amp; userScalable !== \"0\") { userScalable = 1; } //userScalable = \"yes\"; } else { userScalable = 0; } //userScalable = \"no\"; } if (CB_trim(viewportContent) !== \"\") { viewportContent += \", \"; } viewportContent += \"user-scalable=\" + (userScalable === 0 ? \"no\" : \"yes\"); viewportContent += \", user-scalable=\" + userScalable; if (initialScale !== \"\") { viewportContent += \", initial-scale=\" + initialScale; } if (minimumScale !== \"\") { viewportContent += \", minimum-scale=\" + minimumScale; } if (maximumScale !== \"\") { viewportContent += \", maximum-scale=\" + maximumScale; } if (targetDensityDPI !== \"\") { viewportContent += \", target-densitydpi=\" + targetDensityDPI; } if (shrinkToFit !== \"\") { viewportContent += \", shrink-to-fit=\" + shrinkToFit; } //If the meta tag already exists, just updates it: if (typeof(viewport) !== \"undefined\" &amp;&amp; viewport !== null &amp;&amp; typeof(viewport.setAttribute) !== \"undefined\" &amp;&amp; viewport.setAttribute !== null) { viewport.setAttribute(\"content\", viewportContent); return viewport; } //...otherwise, it will create it: else { viewport = document.createElement('meta'); viewport.name = \"viewport\"; viewport.id = \"viewport\"; viewport.content = viewportContent; var headTag = CB_Elements.tag(\"head\", document, false); if (typeof(headTag) !== \"undefined\" &amp;&amp; headTag !== null &amp;&amp; typeof(headTag[0]) !== \"undefined\" &amp;&amp; headTag[0] !== null) { headTag[0].appendChild(viewport); return viewport; } } return null; } /** * Keeps the screen awake and prevents it from turning off. Uses different methods internally: [Apache Cordova's Insomnia plugin]{@link https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin}, [Standby API]{@link https://lists.w3.org/Archives/Public/public-device-apis/2014Feb/att-0001/Standby_API_Specification.pdf}, [Mozilla's Wake Lock API]{@link https://developer.mozilla.org/en-US/docs/Archive/B2G_OS/API/Wake_Lock_API}, [new W3C's Wake Lock API]{@link https://w3.org/TR/wake-lock/}, [old W3C's Wake Lock API]{@link https://w3.org/TR/2016/WD-wake-lock-20160714/}, [NoSleep.js library]{@link https://github.com/richtr/NoSleep.js?utm_source=recordnotfound.com} (it should be activated by an event fired by the user as onclick or ontouchstart, etc.)... * @function * @param {function} [callbackOk] - Function that will be called if the action has been performed successfully, without parameters. * @param {function} [callbackError] - Function that will be called if the action has not been performed successfully, without parameters. * @returns {boolean} If it uses the [new W3C's Wake Lock API]{@link https://w3.org/TR/wake-lock/} internally, it will return a [Promise]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise}. Otherwise, it will return a boolean depending on whether the internal method has been called successfully or not. The fact that the internal method has been called successfully does not mean that the action will perform successfully so it is recommended to relay on the \"callbackOk\" and \"callbackError\" functions and ignore this returning value. * @todo Pay attention since many internal functions as the [new W3C's Wake Lock API]{@link https://w3.org/TR/wake-lock/} are still experimental and not well-tested. */ CB_Screen.keepAwake = function(callbackOk, callbackError) { //Using Apache Cordova's Insomnia plugin: if (typeof(window.plugins) !== \"undefined\" &amp;&amp; typeof(window.plugins.insomnia) !== \"undefined\" &amp;&amp; typeof(window.plugins.insomnia.allowSleepAgain) !== \"undefined\") { try { window.plugins.insomnia.keepAwake(callbackOk, callbackError); return true; } catch(E) { } } //Using Standby API: if (window.navigator &amp;&amp; typeof(navigator.wakeLock) !== \"undefined\" &amp;&amp; navigator.wakeLock !== null &amp;&amp; typeof(navigator.wakeLock.request) !== \"undefined\") { try { navigator.wakeLock.request(\"display\").then(callbackOk, callbackError); //navigator.wakeLock.request(\"screen\").then(callbackOk, callbackError); return true; } catch(E) { } } //Using Mozilla's Wake Lock API: if (window.navigator &amp;&amp; typeof(window.navigator.requestWakeLock) !== \"undefined\") //So far, only works in Firefox/Firefox OS. { try { CB_Screen._screenLock = window.navigator.requestWakeLock(\"screen\"); if (typeof(callbackOk) === \"function\") { callbackOk(); } return CB_Screen._screenLock; } catch(E) { } } //Using the W3C's Wake Lock API: if (window.navigator &amp;&amp; typeof(window.navigator.getWakeLock) !== \"undefined\") { return navigator.getWakeLock(\"screen\").then ( function(wakeLock) { var request = wakeLock.createRequest(); if (typeof(callbackOk) === \"function\") { callbackOk(); } }, callbackError ); } //Using the old W3C's Wake Lock API: if (typeof(screen) !== \"undefined\" &amp;&amp; screen !== null &amp;&amp; typeof(screen.keepAwake) !== \"undefined\") { try { screen.keepAwake = true; if (typeof(callbackOk) === \"function\") { callbackOk(); } return true; } catch(E) { } } //Using NoSleep.js library (it should be activated by an event fired by the user as onclick or ontouchstart, etc.): if (typeof(NoSleep) !== \"undefined\") { //if (typeof(CB_Screen._noSleep) === \"undefined\" || CB_Screen._noSleep === null) { CB_Screen._noSleep = new NoSleep(); } if (CB_Screen._noSleep) { CB_Screen._noSleep.disable(); } //Fix. Source: https://github.com/richtr/NoSleep.js/issues/75. CB_Screen._noSleep = new NoSleep(); //Needs to create a new one to work on some iOS versions. Source: https://github.com/richtr/NoSleep.js/issues/75. //Fix for iOS (Source: https://github.com/richtr/NoSleep.js/issues/75): if (/iPad|iPhone|iPod/.test(navigator.userAgent) &amp;&amp; !window.MSStream || navigator.platform &amp;&amp; /iPad|iPhone|iPod/.test(navigator.platform)) //Checks whether it is iOS. { CB_Events.add ( document, \"visibilitychange\", function() { if (CB_Screen._noSleepEnabled === true &amp;&amp; document.visibilityState === \"visible\") { CB_Screen.keepAwake(); //CB_Screen.keepAwake(callbackOk, callbackError); } }, true, true, false ); } try { CB_Screen._noSleep.enable(); CB_Screen._noSleepEnabled = true; if (typeof(callbackOk) === \"function\") { callbackOk(); } return true; } catch(E) {} } if (typeof(callbackError) === \"function\") { callbackError(); } return false; } //Function that lets the screen sleep again (also uses Apache Cordova with insomnia plugin): /** * Lets the screen sleep again and stops preventing it from turning off. Uses different methods internally: [Apache Cordova's Insomnia plugin]{@link https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin}, [Standby API]{@link https://lists.w3.org/Archives/Public/public-device-apis/2014Feb/att-0001/Standby_API_Specification.pdf}, [Mozilla's Wake Lock API]{@link https://developer.mozilla.org/en-US/docs/Archive/B2G_OS/API/Wake_Lock_API}, [new W3C's Wake Lock API]{@link https://w3.org/TR/wake-lock/}, [old W3C's Wake Lock API]{@link https://w3.org/TR/2016/WD-wake-lock-20160714/}, [NoSleep.js library]{@link https://github.com/richtr/NoSleep.js?utm_source=recordnotfound.com} (it should be activated by an event fired by the user as onclick or ontouchstart, etc.)... * @function * @param {function} [callbackOk] - Function that will be called if the action has been performed successfully, without parameters. * @param {function} [callbackError] - Function that will be called if the action has not been performed successfully, without parameters. * @returns {boolean} If it uses the [new W3C's Wake Lock API]{@link https://w3.org/TR/wake-lock/} internally, it will return a [Promise]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise}. Otherwise, it will return a boolean depending on whether the internal method has been called successfully or not. The fact that the internal method has been called successfully does not mean that the action will perform successfully so it is recommended to relay on the \"callbackOk\" and \"callbackError\" functions and ignore this returning value. * @todo Pay attention since many internal functions as the [new W3C's Wake Lock API]{@link https://w3.org/TR/wake-lock/} are still experimental and not well-tested. */ CB_Screen.keepAwakeDisable = function(callbackOk, callbackError) { //Using Apache Cordova's Insomnia plugin: if (typeof(window.plugins) !== \"undefined\" &amp;&amp; typeof(window.plugins.insomnia) !== \"undefined\" &amp;&amp; typeof(window.plugins.insomnia.allowSleepAgain) !== \"undefined\") { try { window.plugins.insomnia.allowSleepAgain(callbackOk, callbackError); return true; } catch(E) { } } //Using Standby API: if (window.navigator &amp;&amp; typeof(navigator.wakeLock) !== \"undefined\" &amp;&amp; navigator.wakeLock !== null &amp;&amp; typeof(navigator.wakeLock.release) !== \"undefined\") { try { navigator.wakeLock.release(\"display\"); //navigator.wakeLock.release(\"screen\"); if (typeof(callbackOk) === \"function\") { callbackOk(); } return true; } catch(E) { } } //Using Mozilla's Wake Lock API: if (window.navigator &amp;&amp; typeof(window.navigator.requestWakeLock) !== \"undefined\") //So far, only works in Firefox/Firefox OS. { if (typeof(lock) === \"undefined\" || lock === null) { if (typeof(CB_Screen._screenLock) !== \"undefined\" &amp;&amp; CB_Screen._screenLock !== null) { lock = CB_Screen._screenLock; } } if (typeof(lock.unlock) !== \"undefined\") { try { if (typeof(callbackOk) === \"function\") { callbackOk(); } return lock.unlock(); } catch(E) { } } } //Using the W3C's Wake Lock API: if (window.navigator &amp;&amp; typeof(window.navigator.getWakeLock) !== \"undefined\") { navigator.getWakeLock(\"screen\").then ( function(wakeLock) { var request = wakeLock.createRequest(); request.cancel(); //setTimeout(function() { request.cancel(); }, 10); if (typeof(callbackOk) === \"function\") { callbackOk(); } }, callbackError ); } //Using the old W3C's Wake Lock API: if (typeof(screen) !== \"undefined\" &amp;&amp; screen !== null &amp;&amp; typeof(screen.keepAwake) !== \"undefined\") { try { screen.keepAwake = false; if (typeof(callbackOk) === \"function\") { callbackOk(); } return true; } catch(E) { } } //Using NoSleep.js library: if (typeof(NoSleep) !== \"undefined\") { //if (typeof(CB_Screen._noSleep) === \"undefined\" || CB_Screen._noSleep === null) { CB_Screen._noSleep = new NoSleep(); } CB_Screen._noSleep = new NoSleep(); //Needs to create a new one to work on some iOS versions. Source: https://github.com/richtr/NoSleep.js/issues/75. try { CB_Screen._noSleep.disable(); CB_Screen._noSleepEnabled = false; if (typeof(callbackOk) === \"function\") { callbackOk(); } return true; } catch(E) { } } if (typeof(callbackError) === \"function\") { callbackError(); } return false; } } //End of the static class CB_Screen. //CB_ScreenFileLoaded = true; //This file has been loaded. //CB_filesNeeded[\"screen/CB_Screen.js\"] = true; //This file has been loaded. × Search results Close "},"CrossBase_audiovisual_audio_CB_Speaker.js.html":{"id":"CrossBase_audiovisual_audio_CB_Speaker.js.html","title":"Source: CrossBase/audiovisual/audio/CB_Speaker.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/audiovisual/audio/CB_Speaker.js /** * @file Speakers management. Contains the {@link CB_Speaker} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage the speaker or speakers. It will return itself if it is tried to be instantiated. It can also use [timbre.js]{@link https://mohayonao.github.io/timbre.js/}, [Band.js]{@link https://github.com/meenie/band.js/} and [jsfx]{@link https://github.com/loov/jsfx}. * @namespace * @todo Check whether the path used to play silent sounds as a workaround (through the internal \"_playBlankFilesSilently\" method) is right or not (now it uses the {@link CB_scriptPath} variable). * @todo getCopy and filterProperties methods (similar to the ones from {@link CB_GraphicSprites} and {@link CB_GraphicSpritesScene}). */ var CB_Speaker = CB_Speakers = function() { return CB_Speaker; }; { CB_Speaker.initialized = false; //It will tells whether the object has been initialized or not. CB_Speaker._silentAudioFilePlayed = false; //Defines whether a silent audio file has already been played when the user has clicked (hack for some web clients that doesn't start playing sounds unless the first sound is played when the user has clicked). CB_Speaker._silentAudioFilePlayedWAAPI = false; //Defines whether a silent audio file has already been played using WAAPI when the user has clicked (hack for some web clients that doesn't start playing sounds unless the first sound is played when the user has clicked). CB_Speaker._volume = CB_Configuration[CB_BASE_NAME].CB_Speaker_DEFAULT_VOLUME; //Volume of the speaker. CB_Speaker._volumeBeforeMute = CB_Speaker._volume; //Stores the volume which was set before muting. CB_Speaker._audioFileSpritesPool = null; //CB_AudioFileSpritesPool object. CB_Speaker._timbreJSObject = null; //Stores the timbre.js object (if any). CB_Speaker._bandJSObject = null; //Stores the Band.js object (if any). CB_Speaker._jsfxObject = null; //Stores the jsfx object (if any). //Initializes all values: CB_Speaker.init = function() { if (CB_Speaker.initialized) { return CB_Speaker; } //Sets that the object has already been initialized: CB_Speaker.initialized = true; //Plays the blank sound silently, if able (workaround for some web clients): try { CB_Speaker._playBlankFilesSilently(); } catch(E) {} //Gets and stores the timbre.js object (if any): CB_Speaker._timbreJSObject = (typeof(T) !== \"undefined\" &amp;&amp; T !== null) ? T : null; //Gets and stores the Band.js object (if any): CB_Speaker._bandJSObject = (typeof(BandJS) !== \"undefined\" &amp;&amp; BandJS !== null) ? BandJS : null; //Gets and stores the jsfx object (if any): CB_Speaker._jsfxObject = (typeof(jsfx) !== \"undefined\" &amp;&amp; jsfx !== null) ? jsfx : null; return CB_Speaker; } //Function that plays a silent sound the first time the user clicks: CB_Speaker._playBlankFilesSilently = function() //Note: hack for some web clients that doesn't start playing sounds unless the first sound is played when the user has clicked. { var silentAudioFiles = new Array(2); silentAudioFiles[\"AAPI\"] = new Array(3); silentAudioFiles[\"WAAPI\"] = new Array(6); var destroySilentAudioFile = function(API, extension, needsLoaded) { setTimeout ( function() { if (typeof(silentAudioFiles) !== \"undefined\" &amp;&amp; typeof(silentAudioFiles[API]) !== \"undefined\" &amp;&amp; typeof(silentAudioFiles[API][extension]) !== \"undefined\" &amp;&amp; silentAudioFiles[API][extension] !== null) { if (!needsLoaded || silentAudioFiles[API][extension].getStatusString() === \"LOADED\") { silentAudioFiles[API][extension].destructor(true, false, true, false); silentAudioFiles[API][extension] = null; } } }, 100 ); }; var createSilentAudioFile = function(filePath, API, extension, dataURI) { extension = extension.toLowerCase(); silentAudioFiles[API][extension] = null; if (extension === \"mp3\" &amp;&amp; CB_AudioDetector.isAudioFormatSupported(\"audio/mpeg;\", dataURI) === \"\") { return; } if (extension === \"ogg\" &amp;&amp; CB_AudioDetector.isAudioFormatSupported(\"audio/ogg\", dataURI) === \"\") { return; } if (extension === \"wav\" &amp;&amp; CB_AudioDetector.isAudioFormatSupported(\"audio/wav\", dataURI) === \"\") { return; } API = API.toUpperCase(); silentAudioFiles[API][extension] = new CB_AudioFile ( filePath, //filePath \"CB_blank_sound_\" + API, //id { autoLoad: true, autoPlay: false,//(API === \"AAPI\"), loop: false, volume: 1 }, //options API, //API function() { destroySilentAudioFile(API, extension, true); }, //callbackOk function(error) { destroySilentAudioFile(API, extension); } //callbackError ); }; /* createSilentAudioFile(\"data:audio/mpeg;base64,/+MYxAAKK2IBQAgEdwIP//+P/9/9/o0//8jer//U/////5znO/V/U7T6Mc7aTnOedyEnDix6/nIyl/ylPLJ19Z2bn3//8q+2/+MYxBIJC2YcAABHTJcyCOjsDMyORiF3iDM4QSB0UtUNwSAIrB7NiRnrpo///Iv/XYeqPVUJ4FTLUuUTe0LEAi9Ox3/x8uue/+MYxCgMSAYuUABEAltFTREVAxMEDCpuSOUJUV3C90k6gTk9S6Eto//xd3+pOj/2fSN///pnc/fDinSZYWGVjATdhJIbRen//+MYxDEJ2AYySAhEAkaFv3Nq/L7P/Wzdf6tifb1Pdb//V2vF1lWCRy3Acql0khff///MKkIMQma8KhCvkLkL6////////kKE/+MYxEQKaAIuSAhEliEQn4UQvZjCgIEaxvCgI2pMQU1FMy45OS4zqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq/+MYxFUKU2IEIABHFaqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\", \"WAAPI\", \"mp3\", true); createSilentAudioFile(\"data:audio/ogg;base64,T2dnUwACAAAAAAAAAAA3ZwAAAAAAAFG/+m4BHgF2b3JiaXMAAAAAAoA+AAAAAAAAagQBAAAAAACpAU9nZ1MAAAAAAAAAAAAAN2cAAAEAAABzQvG4Dy3/////////////////tgN2b3JiaXMdAAAAWGlwaC5PcmcgbGliVm9yYmlzIEkgMjAwNzA2MjIAAAAAAQV2b3JiaXMhQkNWAQBAAAAYQhAqBa1jjjrIFSGMGaKgQsopxx1C0CGjJEOIOsY1xxhjR7lkikLJgdCQVQAAQAAApBxXUHJJLeecc6MYV8xx6CDnnHPlIGfMcQkl55xzjjnnknKOMeecc6MYVw5yKS3nnHOBFEeKcacY55xzpBxHinGoGOecc20xt5JyzjnnnHPmIIdScq4155xzpBhnDnILJeecc8YgZ8xx6yDnnHOMNbfUcs4555xzzjnnnHPOOeecc4wx55xzzjnnnHNuMecWc64555xzzjnnHHPOOeeccyA0ZBUAkAAAoKEoiuIoDhAasgoAyAAAEEBxFEeRFEuxHMvRJA0IDVkFAAABAAgAAKBIhqRIiqVYjmZpniZ6oiiaoiqrsmnKsizLsuu6LhAasgoASAAAUFEUxXAUBwgNWQUAZAAACGAoiqM4juRYkqVZngeEhqwCAIAAAAQAAFAMR7EUTfEkz/I8z/M8z/M8z/M8z/M8z/M8z/M8DQgNWQUAIAAAAIIoZBgDQkNWAQBAAAAIIRoZQ51SElwKFkIcEUMdQs5DqaWD4CmFJWPSU6xBCCF87z333nvvgdCQVQAAEAAAYRQ4iIHHJAghhGIUJ0RxpiAIIYTlJFjKeegkCN2DEEK4nHvLuffeeyA0ZBUAAAgAwCCEEEIIIYQQQggppJRSSCmmmGKKKcccc8wxxyCDDDLooJNOOsmkkk46yiSjjlJrKbUUU0yx5RZjrbXWnHOvQSljjDHGGGOMMcYYY4wxxhgjCA1ZBQCAAAAQBhlkkEEIIYQUUkgppphyzDHHHANCQ1YBAIAAAAIAAAAcRVIkR3IkR5IkyZIsSZM8y7M8y7M8TdRETRVV1VVt1/ZtX/Zt39Vl3/Zl29VlXZZl3bVtXdZdXdd1Xdd1Xdd1Xdd1Xdd1XdeB0JBVAIAEAICO5DiO5DiO5EiOpEgKEBqyCgCQAQAQAICjOIrjSI7kWI4lWZImaZZneZaneZqoiR4QGrIKAAAEABAAAAAAAICiKIqjOI4kWZamaZ6neqIomqqqiqapqqpqmqZpmqZpmqZpmqZpmqZpmqZpmqZpmqZpmqZpmqZpmqZpAqEhqwAACQAAHcdxHEdxHMdxJEeSJCA0ZBUAIAMAIAAAQ1EcRXIsx5I0S7M8y9NEz/RcUTZ1U1dtIDRkFQAACAAgAAAAAAAAx3M8x3M8yZM8y3M8x5M8SdM0TdM0TdM0TdM0TdM0TdM0TdM0TdM0TdM0TdM0TdM0TdM0TdM0TdM0TQNCQ1YCAGQAAJACz0IpLUYCHIiYo9h777333ntlPJKISe0x9NQxB7FnxiNmlKPYKc8cQgxi6Dx0SjGIKfVSMsYgxthjDCGUGAgNWSEAhGYAGCQJkDQNkDQNAAAAAAAAACRPAzRRBDRPBAAAAAAAAABJ8wBN9ABNFAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAkDwN8EQR0EQRAAAAAAAAADRRBERRBUTVBAAAAAAAAABNFAFPFQHRVAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAkDQP0EQR8EQRAAAAAAAAADRRBETVBDxRBQAAAAAAAABNFAHRVAFRFQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAQ4AAAEWAiFhqwIAOIEAAyOY1kAAOBIkqYBAIAjSZoGAACapokiAABYmiaKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAGHAAAAkwoA4WGrAQAogAADIaiaQDLAlgWQNMAmgbwPIAnAkwTAAgAAChwAAAIsEFTYnGAQkNWAgBRAAAGRZEky/I8aJqmiSI0TdNEEZ7neaIIz/M804Qoep5pQhQ9zzRhmqJomkAUTVMAAECBAwBAgA2aEosDFBqyEgAICQAwKIpleZ4oiqJpqqrrQtM8TxRF0TRV1XWhaZ4niqJomqrquvA8TzRF0zRNVXVdeJ4omqZpqqrqui48TxRN0zRV1XVdF54niqZpmqrqurIMURRF0zRNVXVdWQaiaJqmqaquK8tAFE1TVV3XdWUZiKJpqqrruq4sA9NUTVV1XVmWZYBpqqrryrIsA1TVdV1Xlm0boKqu67qybNsA13VdWZZl2wbgurIsy7YtAADgwAEAIMAIOsmosggbTbjwABQasiIAiAIAAIxRSjGlDGMSSimhYUxKSaVUUlJKqZRKQkoplVJJSSmlUjJKKaXWUiUllZJSqqSUVFJKBQCAHTgAgB1YCIWGrAQA8gAACEKQYowx56SUSjHmnHNSSqUYc845KSVjjDnnnJSSMcacc05KyZhzzjknpWTMOeeck1I655xzEEoppXTOOQillFJC6ByEUkopnXMOQgEAQAUOAAABNopsTjASVGjISgAgFQDA4DiWpWma5nmiaEmS5nmi54miqVqS5Hmi6Hmiaao8zxNFURRNU1WJouiJoiiapqqSZVE0TdNUVddly6Jomqapqq4L0xRFVXVd2YVpiqJpuq4sQ7ZVU1VdV7Zh26apqq4ry8B1XVeWbR24ruvKsq0LAABPcAAAKrBhdYSTorHAQkNWAgAZAAAEIQgppRBSSiGklEJIKYWQAACAAQcAgAATykChISsBgFQAAABCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGE0DnnnHPOOeecc84555xzzjnnnHPOOeecc84555xzzjnnnHPOOeecc84555xzzjnnnHPOOeecc04AIHaFA8BOhA2rI5wUjQUWGrISAAgHAACMMcY5i7XWWmullFISaq211lozhZSS0GKMMcYYMwYhpRZjjDHGmDHnqMUYY4wxxtZKiS3GGGOMMbZWSowxxhhjjDHG2GKLMcYYY4wxxhZjjDHGGGOMMcYYY4wxxhhjjDHGFmOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjC3GGGOMMcYYY4wxxhhjjAUAmDw4AEAl2DjDStJZ4WhwoSErAYDcAADAGKUYc8w5CCGUUkIpqbXOOQchhFJKKSmVllJMGXPOOQihlFJCKSm1lDrnHIRSSkkppZRSS611DkIIoZRSSkkppZRaCiGEUkpJJaWUUmqttRRCCKWUklJKKaWUWmsxlBJSKaWklFIqqaXWUksllJJKSimllFJqLbXWSimppJRSSimllFpsLYVSUioppZZSSqm1GFsspZWUUkoppdRaiq21FltKKaXUUksppdZiS62llFJqKaXUUmqpxdhaaymllFpKLbWUUoqttRZTSq2llFpqraUWW0qtpZZSai21lFJrrcUWW2stpZZSSim11mJLMbaWWkkppZZaS63F1mJrrbXUWkstpdRiizHG2GJsLaaUUmoptVQAANCBAwBAgBGVFmKnGVcegSMKGSagQkNWAgBkAAAEMk0yJyk1wiSnGJTSnHNKKaWUhsiSDFIMqiOTMScpZ4g0hhSkninymFIMYghJhU4xh60mH0voINagjBEupRgAAABBAICAkAAAAwQFMwDA4ABh5ECgI4DAoQ0AMBAhM4FBITQ4yASAB4gIqQAgMUFRutAFIUSQLoIsHrhw4sYTN5zQoQ0EAAAAAAAEAD4AABIKICAimrkKiwuMDI0Njg6PDxABAAAAAAACgA8AgCQECIiIZq7C4gIjQ2ODo8PjAyQAABBAAAAAAAAEEICAgAAAAAAAQAAAAICAT2dnUwAEDwkAAAAAAAA3ZwAAAgAAAEwW7hoGL1ZMVFNKBK13s5KD1btZaQCACKlDa/uped/er1NrjA5L/p035k7vI9Z8WJl/md3aOsn43Qrat/pI/QAMkOtjfaR+ADbIAxBVoqqwKKP5sl5vP3zbnfeeM90tX0dP/5nSPnrktBxk1diqs1FLYOo6PxtS+5e/L7E0PIwYHsaR+D8+rodbNe999Lb7B973+kj9AAxAn+sj9QMwAABUiapyQ89A/5b2iI3GO+ypcWTO5kbAIK40ufM/x3+Pxq39827Kw9/+OlIaxHkx3zzPV1J2PW45vNc9DxHel3pM/QAs0NC3eiz9AGyQByCqqipUiuaRKr185Uv6/Tkuu0aT8vxqdrRzqSyKduKQKR7Gc8vyTO0Vb0PMzKaMMBf/MtMf2f7c/DtdS8qPWvemJALex3rs/AAUkOhrPZZ+ABbIAxCiqnKF1ayx6fTzPvz9vf1b/7f5WuevW0udiwni8oyHVc5z68bZyr3LnrHuu6aOFK5t8Wzr8bvx/+VjmqpBTaHUAd5Xejs/AAVE+1KPnR+ABgBAlApRFb0dvfXgEI+/DrPs6tWvEuQd5z/n0ic/h07Hs5PvG76ms6e+prM59p9cs8PJ3s/W7fBlF70B\", \"WAAPI\", \"ogg\", true); createSilentAudioFile(\"data:audio/wav;base64,UklGRuwgAABXQVZFZm10IBAAAAABAAIAgD4AAAD6AAAEABAAZGF0YcggAAAAAAEAAAD+/wEAAgD+////AgAAAP7/AQACAP////8AAAAAAQAAAP//AAABAAAA//8AAAEAAAD/////AAACAAIA/v/8/wEABQAAAPv///8EAAIA/f/+/wMAAQD9////AgABAP//AAAAAAAAAQAAAAAA///+/wEAAwAAAPz/AAAFAP///P8CAAMA/v/9/wIAAgD+////AgABAP7///8CAAEA/v///wEAAQABAP7//v8DAAIA/f/+/wIAAQAAAAAA/v8AAAMA///+/wIAAQD+////AgABAP3///8EAAIA/P/+/wQAAAD9/wIAAQD9/wEABAD+//z/AgACAP//AAAAAP//AQACAP///v///wEAAwD///3/AQACAAAA/////wAAAgAAAP7/AQAAAP//AQAAAP//AQABAP7/AAADAP7//f8DAAIA/f///wIAAAD//wEAAAD//wEAAQD/////AQABAP////8BAAEA/////wEAAQAAAP///v8CAAMA/f/+/wIAAQAAAP////8AAAIAAQD+//7/AQADAAAA/f8AAAIAAAD//wAAAAD//wAAAQABAAAA/v8AAAMAAAD8////BAABAP3/AAACAP////8CAAAA/v8AAAEAAQAAAP7/AAACAP///v8CAAIA/f///wMA///+/wIAAgD+//7/AgACAP///f///wQAAgD8////BAAAAPz/AAADAAEA///+////AwADAPz/+/8DAAYA/v/6/wEABQAAAP3///8BAAEAAAD//wAAAAD//wIAAgD9//7/AwACAP3//v8DAAIA/f/9/wMABAD+//z/AQAEAAAA/f/+/wIAAgD9////BAAAAPz/AgAFAPz/+/8EAAMA/P///wQA///9/wMAAgD8//7/AwACAP///v8AAAMAAAD9/wAAAgAAAP///////wIAAwD///3/AAACAAAA//8AAAAA//8BAAIA/v///wIA///+/wMAAgD8//7/BAABAPz/AQADAP7///8BAP//AAACAP///v8CAAEA//8AAP//AAACAP///v8CAAEA/f8BAAMA/v///wIA///+/wIAAgD+//7/AQADAAEA/P/+/wUAAgD7////BAD///z/AgAEAP7//f8CAAIA///+////AgACAP7//v8CAAEA//8AAAAA//8AAAEAAAABAP///f8DAAMA/f/9/wIAAwD+////AQD//wAAAgAAAP3/AAADAP///v8BAAEA//8AAAIA///+/wEAAgD///3/AgADAP3//v8DAAIA/f///wMAAAD+/wAAAQAAAP////8CAAIA/f/+/wMAAgD+////AQD//wAAAgD///7/AQABAAEAAQD9////BAAAAPz/AQADAP7//v8DAAEA/f8AAAIAAAD//wAAAAAAAAEA/////wIAAAD+/wEAAgD///7/AAACAAEA/v///wIAAQD+/wAAAQD//wAAAQD/////AgABAP7/AAABAP//AAABAP//AAABAP//AAABAAAA//8AAAEA//8AAAIA///+/wIAAgD9////BAD///v/AgAEAP7//v8DAAEA/P8AAAQA///9/wEAAQD//wAAAQAAAP//AQACAP///f8AAAMAAAD9/wAAAwABAP3//v8DAAIA/f/+/wMAAwD9//z/AgAEAP7//P8CAAMA/////wEAAAD+/wEAAgD+//7/AQABAAAAAQAAAP7/AAACAAAA/v///wEAAQAAAP//AAABAP////8CAAIA/v/9/wEAAwAAAP7///8BAAIAAAD///////8CAAIA/v/+/wIAAQD+/wEAAQD9/wAABAAAAP3/AAABAP//AAACAP///v8CAAIA///+/wAAAQAAAAAAAAAAAP//AAADAAAA/P8AAAQAAAD8/wAAAwAAAP7/AAACAAAA/v8AAAIAAQD+//7/AQACAAAA//8AAAAAAAAAAAAAAAAAAP//AAADAAAA/f///wEAAgD///7/AQACAAAA/v8BAAEA/f8AAAMAAAD9/wAABAAAAP3/AAABAAAA//8AAAEAAAAAAAEA///9/wIABAD9//3/AwACAP7//v8AAAIAAgD9//7/BAABAP3/AAABAP7/AAAEAAAA/P///wMAAgD///7///8BAAEA//8AAAIA///9/wIABAD+//z/AQACAAAAAAAAAP////8CAAEA/v///wEAAgAAAP7///8CAAEA/f8AAAMAAAD9/wAABAAAAP3///8BAAEAAAAAAP//AAACAAAA/v8AAAEA//8AAAIAAAD//wAA//8AAAMAAAD7////BgACAPv///8DAAAA//8BAAAA/f8AAAQAAAD9/wAAAwAAAP3/AAABAAAAAQD/////AwABAPv///8GAAEA+v///wUAAQD8/wAAAwD///7/AgABAP3/AAADAP////8CAAAA/v///wEAAgAAAP3///8EAAIA/P/+/wMAAgD+//7/AQACAAAA/v///wMAAQD9////AgAAAP7/AQACAAAA/////wEAAAD//wAAAQAAAP7/AAACAAEA///+/wEAAgAAAP///v///wMAAgD+////AQAAAAAAAQD+////BAAAAPz/AQADAP7//v8DAAAA/v8CAAAA/v8BAAIA/f/+/wUAAAD7/wIABAD+//3/AgABAP7/AQABAP7///8CAAMA/v/8/wIABAD+//z/AwADAPz///8EAAEA/P///wQAAQD9//7/AgADAP///v8AAAEAAQAAAP////8AAAAAAAACAAAA/f8BAAMA/v/+/wMAAAD8/wEAAwAAAP////8AAAEAAAAAAAAA//8AAAEAAAABAAAA/v///wIAAQD+/wAAAQD//wAAAQAAAP////8AAAIAAQD+////AgABAP7/AAABAP7/AAADAAAA/P8AAAUAAAD8/wEAAgD//wAAAAD+/wAAAwAAAP3/AQACAP7///8CAAEA//8AAAAA//8BAAEA/f/+/wMAAwD///7/AAACAAAA/v8BAAEA/v///wIAAQD+/wAAAgD/////AgABAP7///8AAP//AQADAP7//f8DAAIA/v///wEAAAD//wEAAAD+/wEAAgD+////AwAAAP3/AQACAP7///8CAAAA//8BAAAA//8AAAEAAAD+/wEAAgD+////AgABAP7/AAABAP7/AAADAAAA/P///wUAAgD7//3/BAADAP7//f8AAAQAAQD7//7/BQADAPv//f8EAAMA/v/9/wEAAgD//wAAAQD///7/AQADAP///v8BAAAA//8BAAEA/v/+/wMAAwD+//7/AAAAAAEAAQD+////AgAAAP//AQAAAP7/AQADAP///v8AAAAAAAAAAAAA//8BAAIA/////wEAAAD//wEAAAD9/wEABAD///3/AQABAP//AQABAP7///8DAAEA/f///wEAAAABAAIA/v/9/wMABAD8//v/BAAEAP3//v8CAAEA//8AAAEA///+/wAAAwABAPz/AAAFAAAA+////wQAAQD9////AgACAP////8BAAAA/v8AAAMAAAD8/wAABQAAAPv/AQAEAP7//f8CAAEA//8BAAAA/v8BAAIA///+/wAAAQAAAAAAAAAAAAAA//8AAAIAAAD9/wAAAwAAAP7///8CAAEA/v8AAAEA/////wIAAgD+//7/AAACAAIA/f/9/wQAAwD9////AQD+/wAAAwD///7/AgAAAP7/AgACAP3//f8DAAMA/f/+/wMAAQD9/wAAAwD///3/AAACAAEAAAD/////AQACAP///f8AAAIAAAD//wEAAQD+/wAAAwD///3/AQABAP//AQABAP7///8DAAEA/f///wEAAgAAAP7/AAABAAAA/v8AAAMA///+/wIAAgD+//7/AQABAP////8BAAIAAAD+////AgABAP///////wEAAgAAAP7/AAACAP///v8CAAIA/f/9/wMAAwD+//7/AQABAAAAAAAAAAAA/////wEAAgD///7/AQACAAAA////////AgACAP3//v8EAAIA/P/+/wMAAgD+//3/AQAEAAAA/P8AAAMAAAD+////AQACAAAA/f8AAAMAAAD+////AgACAP7//v8BAAIA///+/wEAAQAAAAAAAAAAAP//AQACAP7//v8CAAAA/f8CAAQA/v/9/wEAAQABAAEA/f/+/wMAAgD///7/AAABAAAAAAAAAAAAAAAAAAAAAAABAAAA/v8AAAIAAAD+/wAAAwAAAPz/AAAEAAAA/f8BAAIA/v///wIAAAD+/wAAAgAAAP7/AQACAP///v8AAAIAAAD//wAA//8AAAIAAAD+/wEAAgD+////AwAAAPz/AAAEAAAA/f8AAAIAAQD+//7/AgACAP///v8AAAEAAAABAAAA/v8AAAIAAAD//wAAAAD//wEAAgD+////AgAAAP//AAABAP////8BAAEAAAD+/wAAAgAAAP////8AAAEAAQD///7/AQADAAAA/f///wIAAAD//wIAAQD9//7/AwADAP7//f8AAAIAAgAAAP7//v8BAAIAAAD///////8BAAMAAAD8////BAACAPz//f8DAAMA/v/9/wIAAwD///7///8BAAIA///9/wEABAD///3/AgABAP7/AAAAAP//AQACAP///v8BAAEA/////wAAAgAAAP7/AAACAAEA/f///wMA/////wMA///8/wIABAD+//7/AgD///7/BAABAPv/AAAEAAAA/v8AAAAA//8CAAEA/f8AAAIAAAAAAP////8CAAEA/f///wQAAQD8////BAACAPz//f8DAAIA/v8AAAEA//8AAAIAAAD9/wAAAwD///3/AgADAP7//v8CAAEA/////wAAAgAAAP3/AQAEAP7//P8CAAMA///+/wAAAQAAAAAAAAAAAP//AAACAAAA/v///wIAAQD+/wAAAQD//wAAAgAAAP3/AAACAAAAAAAAAP//AAABAAAA/////wAAAwABAPz///8EAAEA/P/+/wMAAwD///3/AAADAAAA/f8AAAIAAQD///7/AAACAAEA/v/+/wMAAgD9////AwAAAPz/AAADAAAAAAAAAP7/AAADAAEA/f///wEAAAABAAAA/v8BAAMA///9/wEAAgD///7/AAACAAEA/////wAAAQABAP7//v8DAAIA/f/+/wIAAgD/////AAAAAAEAAAD+////AwACAPz///8FAAAA+/8AAAQAAAD+/wAAAAABAAIA///9/wEABAD///v/AAAFAAIA+//9/wUABAD8//z/AgADAP///v8AAAEAAQAAAP//AAAAAAAAAQAAAP//AAAAAAAAAgAAAPz/AAAFAAAA/P8BAAIA/v8AAAIA/////wEAAAD//wEAAQD//wAAAAD//wEAAgD///3/AQADAP///f8BAAQA/v/7/wMABgD9//v/AwACAP3/AQADAP7//f8CAAIA/////wAAAQAAAP//AgABAPz///8EAAAA/f8BAAIA///+/wEAAgD///7/AQACAP7///8DAP///f8CAAMA/v/9/wEAAwABAP3//v8CAAMA///9/wAAAgACAP///f8AAAIAAQD//wAAAAAAAAEA/////wIAAAD8/wEABgD+//r/AgAFAP///f8BAAEA//8AAAAA//8BAAEA/v8AAAMAAAD9/wAAAwAAAP3/AAACAAAA//8AAAAAAQABAP7//v8CAAMA/v/8/wIABAD///z/AAAEAAAA/P///wQAAQD8/wAABAAAAPz/AAAEAAAA/P///wMAAgD+//7/AgACAP7//v8BAAIAAAD///////8BAAIA///+/wEAAgAAAP////8AAAEA/////wIAAQD+/wAAAQD//wEAAQD9/wAAAwD///7/AgABAP7/AAABAP//AAABAP////8CAAEA/v8AAAIAAAD+////AQABAAAA//8AAAEAAAABAAAA/v///wEAAgD///7/AQACAP///v8CAAEA/f8AAAIAAAAAAAAA/////wIAAgD9//7/AwABAP7/AAACAP///v8CAAIA/f/+/wIAAgD///7/AQABAP////8AAAIAAQD+////AQABAAAA/////wEAAQD//wAAAQD/////AQAAAAAAAQD///7/AgADAP7//f8AAAIAAgD+//3/AQAEAAEA+//+/wUAAwD7//z/BQADAPz///8CAP//AAADAP///P8BAAMA///+/wEAAgAAAP////8AAAEAAAD/////AQADAP///P8BAAUA///7/wEABAD///3/AAACAAEA/////wEAAgD///3/AQACAP////8BAAEA/////wEAAgAAAP3///8CAAEA//8AAAEA//8AAAEA/////wEAAQD//wAAAQAAAAEA///9/wEABAD///v/AQAFAAAA/P8AAAQAAAD8////AwABAP7/AAABAAAAAQABAP7//f8BAAMAAAD///////8CAAMA/v/8/wEAAgAAAAEA///9/wEAAwD///7/AQABAAAAAAD//wAAAQD/////AQABAP////8CAAEA/v///wIAAQD+////AQABAAAA/////wIAAgD9//7/AwACAP7//v8AAAIAAgD+//3/AQADAAAA//8AAP//AAABAAEAAAD+////AgACAP7//v8CAAEA//8AAAEA///+/wEAAgAAAP7///8DAAEA/f///wIAAAD+/wEAAQD//wEAAAD+/wIAAgD9//7/AwABAP3/AAADAAAA/v8AAAEAAAAAAAAA//8AAAEAAAAAAAAAAAAAAP//AAACAAEA/f/+/wQAAQD9/wAAAQAAAAAAAAD//wAAAgD/////AgAAAP////8AAAEAAAAAAAAAAQABAP7///8BAAEA/////wEAAAAAAAEA/////wIAAQD+////AAAAAAEAAAD//wEAAQD//wAAAQAAAP///v8AAAQAAQD8////AgAAAAAAAQD/////AQABAP///v8BAAIA/////wEAAAD//wEAAQD+////AgABAP////8AAAEAAQD///7/AQADAP///f8CAAIA/f8AAAIA/////wEAAQD//wAAAQD//wAAAAAAAAAA//8BAAEA//8AAAAA//8BAAIA/v/9/wIAAwD///3/AAADAAEA/f///wMAAAD9/wAAAgABAP////8BAAEA/////wAA//8AAAMAAAD+/wEAAQD//wAAAAD//wAAAAAAAAMAAAD7/wEABQD+//3/AgABAP7///8CAAEA////////AQACAAAA/f/+/wMAAwD+//3/AgADAP7//f8BAAIAAAD/////AAACAAEA/////wAAAAAAAAEAAQD+//7/AgADAP///f8AAAIAAQD/////AQABAP////8BAAAA//8BAAEA/////wEAAQD/////AAABAAEA/////wEAAAD//wEAAAD+/wEAAwD///3/AQACAP////8BAAEA///+/wIAAwD9//3/AgADAAAA/v///wAAAgABAP3///8DAAEA/f8AAAMA///+/wEAAQD/////AQABAP////8BAAIA///9/wEAAgD/////AQABAP////8BAAEA/////wAAAQABAP///v8AAAMAAQD9/wAAAgAAAP//AAAAAP//AQAAAP//AQABAP////8BAAEAAAD///7/AgACAP3//v8DAAIA/f///wMAAAD+/wEAAQD+////AgABAP////8BAAIA///9/wAAAwABAP7//v8BAAQA///7/wEAAwD//wAAAgD+//3/AgADAP///f8AAAMAAQD+////AAAAAAEAAQD/////AQAAAAAAAgD///3/AQADAP///v8BAAAA//8BAAIA///9/wEAAwD///7/AQABAP////8AAAEAAQAAAP////8AAAEAAgD+//z/AgAEAAAA/f/+/wEAAwABAPz//v8EAAIA/f/+/wEAAQABAAAA/v8AAAMAAAD8/wAAAwAAAP//AQAAAP7/AQACAP7//v8CAAIA/////wEAAAD+/wAAAgAAAP//AAAAAAAAAQAAAP//AAAAAAAAAQABAP7//v8DAAIA/f/+/wIAAgAAAAAA/v///wMAAAD9/wAAAgAAAP//AgABAP7//v8AAAMAAQD8////BQABAPv/AAAEAP///f8CAAIA/v///wIAAgD+//3/AQACAAEA///+/wAAAgACAP///f8AAAIAAQD///7/AAACAAAA//8AAAAAAAABAAAA//8AAAAAAAABAAAA/v///wIAAgD///7/AAACAAEA///+/wAAAgABAP7//v8CAAMA///9/wAAAwAAAP3/AAACAAAA/v8AAAMAAAD9/wAAAgAAAP//AQAAAP7/AQABAP7/AAACAAAA//8AAAEAAAD//wAAAQAAAP//AAABAAAAAAD/////AwACAPz//f8FAAMA+//+/wMAAgD///7/AAABAAEA/////wEAAAAAAAEA///+/wEAAgAAAP//AAAAAAAAAgAAAPz///8EAAIA/P///wMAAAD//wEAAAD+/wAAAgAAAP//AAAAAAAAAQAAAP//AAABAAAA//8BAAAA//8BAAAA//8BAAEA/////wAAAAABAAEA///+/wAAAgABAP////8AAAAAAQAAAP7/AAADAAAA/f8BAAIA/////wAAAQAAAP//AQABAP7//v8EAAIA+////wUAAQD8////AgD//wAAAgD///7/AQACAP////8BAP////8CAAAA/v8BAAIA/v/+/wMAAgD9////AgAAAP//AQAAAP//AQABAP7///8DAAAA/P8BAAUA///7/wEAAwD/////AAAAAAEAAAD//wEAAQD9////BAABAPz///8EAAEA/f///wIAAAD+/wIAAQD9/wEAAwD+//3/AgACAP7///8CAAAA/v8AAAIAAQD9////AwAAAP7/AAABAP////8CAAEA/////wAAAgAAAP3/AAACAAAAAAAAAP7/AAAEAAAA+/8AAAQAAAD+/wAAAAD//wEAAgD///7/AAABAAAAAAABAP7//v8DAAMA///8//7/BAADAP3//f8CAAIA//8AAAAA//8BAAEA/////wAAAQABAP////8BAAAA//8BAAIA/v/9/wMAAwD9//3/AgADAP7//v8CAAEA/v///wIAAQD//wAA/////wIAAQD+////AgABAP////8AAAEAAQD/////AgAAAP3/AQADAP///f8BAAMAAAD+//7/AQACAP////8BAAEAAAD/////AQABAP7///8CAAEA/////wEAAQD/////AAABAAAA/////wAAAwABAP3//v8BAAMAAAD9/wAAAgD/////AwAAAPv/AQAFAP///P8BAAMA/v/+/wMAAQD9////AwAAAP3/AQADAP7//f8EAAMA+//9/wQAAwD9//7/AgAAAAAAAQD/////AQAAAP//AgACAPz//v8FAAEA+v///wUAAgD9//7/AgADAP///P8AAAMA/////wIA///+/wMAAQD9/wAAAQD//wEAAgD+//3/AQAEAAAA+/8AAAUAAAD8/wEAAwD+//7/AQABAAAAAAAAAP//AAABAAAA//8AAAEAAAAAAP////8BAAEA///+/wEABAABAPv//f8FAAMA/P/9/wMAAwD9//7/AwACAP3//v8DAAEA/v8AAAEA/////wIAAQD9////BAAAAPz/AgAEAP3//P8CAAMAAAD+////AgABAP7///8CAAEA/f8AAAMA/////wIA///9/wIAAwD+//7/AQABAAEA///9/wEABAAAAPz///8EAAEA/P///wMAAQD+////AgACAP7//f8BAAMAAAD+/wAAAAAAAAIAAQD9//3/BAAFAPz/+v8DAAYA/v/7/wEABAAAAP3/AAABAAAAAQAAAP7/AAADAAAA/P8AAAQAAAD9/wEAAgD//wAAAAD+/wAAAwAAAP3/AQACAP7/AAADAP///P8BAAQA///8/wAAAwABAP7///8CAAAA/v8BAAEA/////wEAAQD//wAAAQAAAP7///8EAAEA+////wUAAQD8/wAAAgD/////AgABAP3///8DAAEA/v///wEAAQAAAP////8BAAIA///+/wEAAQAAAAAAAAD//wAAAQD//wAAAgD///7/AgABAP7/AQACAP7///8CAAAA//8BAAAA/v8BAAMA/v/9/wIAAwD+//7/AwAAAP3/AgACAPz///8FAP//+/8DAAUA/P/7/wMABAD///3///8DAAIA/f/+/wMAAQD8/wAABAD///7/AgABAP3///8DAAEA/f///wMAAQD+/wAAAQD/////AQABAAAA/v///wMAAQD9////AwABAP3///8DAAEA/f///wIAAQD/////AAABAAIA///9/wEAAwAAAP3///8CAAEAAAD/////AQACAP///f8BAAIA/////wEAAQD//wAAAQD+////AgAAAP//AQAAAP7/AgAEAPv/+/8GAAQA+//+/wQAAAD9/wIAAQD9/wAAAwAAAP7/AAABAAAAAAAAAP//AAACAAAA/f///wMAAgD9//7/AwACAP7//v8BAAIAAAD9////BAABAPz/AAADAAAA//8AAP7/AAAEAAAA/P8AAAMAAAD+/wAAAAD//wIAAgD9//7/BAACAPz//v8CAAAAAAACAP///v8CAAEA/f8AAAQA///7/wEABgAAAPr///8FAAEA/P8AAAQA///8/wEABAD///z/AQADAP////8BAAAAAAAAAP7/AQADAP3//f8DAAIA//8AAAAA/v8AAAMAAQD+//3/AQAEAP7//f8DAAIA/P///wYAAQD6////BAAAAP7/AQAAAP//AQABAP////8BAAEAAAD+/wAABAD///v/AQAFAAAA+////wQAAgD+//7/AAABAAEAAQD+//3/AwAEAP7//P8AAAMAAQD///7///8DAAIA/f/+/wIAAgD///7/AQACAP///v8AAAEAAAAAAAAA//8BAAIA///+/wAAAgAAAP7/AAABAAAAAAABAAAA/v8AAAMAAAD8/wAAAwAAAP//AAAAAAAAAQAAAP//AQD///7/AwADAP3//P8DAAQA/v/9/wAAAgABAP//AAABAAAA//8AAAAA//8BAAEA/v8AAAMAAQD9//7/AgABAP7///8CAAEA//8AAAAAAAAAAP////8CAAEA/f8AAAQAAAD7/wAABQAAAPz///8DAAIA/v/+/wEA\", \"WAAPI\", \"wav\", true); */ var silentAudioFilePlay = function() { if (!CB_Speaker._silentAudioFilePlayed) { CB_Speaker._silentAudioFilePlayed = true; /////CB_Speaker.playFileBase(CB_scriptPath + CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/audio/sounds/blank\"); if (CB_AudioDetector.isAPISupported(\"AAPI\", false)) { createSilentAudioFile(CB_scriptPath + CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/audio/sounds/blank.mp3\", \"AAPI\", \"mp3\"); createSilentAudioFile(CB_scriptPath + CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/audio/sounds/blank.mp3\", \"AAPI\", \"ogg\"); createSilentAudioFile(CB_scriptPath + CB_Configuration[CB_BASE_NAME].SCRIPT_PATH + \"audiovisual/audio/sounds/blank.mp3\", \"AAPI\", \"wav\"); } } if (!CB_Speaker._silentAudioFilePlayedWAAPI &amp;&amp; CB_AudioDetector.isAPISupported(\"WAAPI\", false)) { createSilentAudioFile(\"data:audio/mpeg;base64,/+MYxAAKK2IBQAgEdwIP//+P/9/9/o0//8jer//U/////5znO/V/U7T6Mc7aTnOedyEnDix6/nIyl/ylPLJ19Z2bn3//8q+2/+MYxBIJC2YcAABHTJcyCOjsDMyORiF3iDM4QSB0UtUNwSAIrB7NiRnrpo///Iv/XYeqPVUJ4FTLUuUTe0LEAi9Ox3/x8uue/+MYxCgMSAYuUABEAltFTREVAxMEDCpuSOUJUV3C90k6gTk9S6Eto//xd3+pOj/2fSN///pnc/fDinSZYWGVjATdhJIbRen//+MYxDEJ2AYySAhEAkaFv3Nq/L7P/Wzdf6tifb1Pdb//V2vF1lWCRy3Acql0khff///MKkIMQma8KhCvkLkL6////////kKE/+MYxEQKaAIuSAhEliEQn4UQvZjCgIEaxvCgI2pMQU1FMy45OS4zqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq/+MYxFUKU2IEIABHFaqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\", \"WAAPI\", \"mp3\", true); createSilentAudioFile(\"data:audio/ogg;base64,T2dnUwACAAAAAAAAAAA3ZwAAAAAAAFG/+m4BHgF2b3JiaXMAAAAAAoA+AAAAAAAAagQBAAAAAACpAU9nZ1MAAAAAAAAAAAAAN2cAAAEAAABzQvG4Dy3/////////////////tgN2b3JiaXMdAAAAWGlwaC5PcmcgbGliVm9yYmlzIEkgMjAwNzA2MjIAAAAAAQV2b3JiaXMhQkNWAQBAAAAYQhAqBa1jjjrIFSGMGaKgQsopxx1C0CGjJEOIOsY1xxhjR7lkikLJgdCQVQAAQAAApBxXUHJJLeecc6MYV8xx6CDnnHPlIGfMcQkl55xzjjnnknKOMeecc6MYVw5yKS3nnHOBFEeKcacY55xzpBxHinGoGOecc20xt5JyzjnnnHPmIIdScq4155xzpBhnDnILJeecc8YgZ8xx6yDnnHOMNbfUcs4555xzzjnnnHPOOeecc4wx55xzzjnnnHNuMecWc64555xzzjnnHHPOOeeccyA0ZBUAkAAAoKEoiuIoDhAasgoAyAAAEEBxFEeRFEuxHMvRJA0IDVkFAAABAAgAAKBIhqRIiqVYjmZpniZ6oiiaoiqrsmnKsizLsuu6LhAasgoASAAAUFEUxXAUBwgNWQUAZAAACGAoiqM4juRYkqVZngeEhqwCAIAAAAQAAFAMR7EUTfEkz/I8z/M8z/M8z/M8z/M8z/M8z/M8DQgNWQUAIAAAAIIoZBgDQkNWAQBAAAAIIRoZQ51SElwKFkIcEUMdQs5DqaWD4CmFJWPSU6xBCCF87z333nvvgdCQVQAAEAAAYRQ4iIHHJAghhGIUJ0RxpiAIIYTlJFjKeegkCN2DEEK4nHvLuffeeyA0ZBUAAAgAwCCEEEIIIYQQQggppJRSSCmmmGKKKcccc8wxxyCDDDLooJNOOsmkkk46yiSjjlJrKbUUU0yx5RZjrbXWnHOvQSljjDHGGGOMMcYYY4wxxhgjCA1ZBQCAAAAQBhlkkEEIIYQUUkgppphyzDHHHANCQ1YBAIAAAAIAAAAcRVIkR3IkR5IkyZIsSZM8y7M8y7M8TdRETRVV1VVt1/ZtX/Zt39Vl3/Zl29VlXZZl3bVtXdZdXdd1Xdd1Xdd1Xdd1Xdd1XdeB0JBVAIAEAICO5DiO5DiO5EiOpEgKEBqyCgCQAQAQAICjOIrjSI7kWI4lWZImaZZneZaneZqoiR4QGrIKAAAEABAAAAAAAICiKIqjOI4kWZamaZ6neqIomqqqiqapqqpqmqZpmqZpmqZpmqZpmqZpmqZpmqZpmqZpmqZpmqZpmqZpAqEhqwAACQAAHcdxHEdxHMdxJEeSJCA0ZBUAIAMAIAAAQ1EcRXIsx5I0S7M8y9NEz/RcUTZ1U1dtIDRkFQAACAAgAAAAAAAAx3M8x3M8yZM8y3M8x5M8SdM0TdM0TdM0TdM0TdM0TdM0TdM0TdM0TdM0TdM0TdM0TdM0TdM0TdM0TQNCQ1YCAGQAAJACz0IpLUYCHIiYo9h777333ntlPJKISe0x9NQxB7FnxiNmlKPYKc8cQgxi6Dx0SjGIKfVSMsYgxthjDCGUGAgNWSEAhGYAGCQJkDQNkDQNAAAAAAAAACRPAzRRBDRPBAAAAAAAAABJ8wBN9ABNFAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAkDwN8EQR0EQRAAAAAAAAADRRBERRBUTVBAAAAAAAAABNFAFPFQHRVAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAkDQP0EQR8EQRAAAAAAAAADRRBETVBDxRBQAAAAAAAABNFAHRVAFRFQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAQ4AAAEWAiFhqwIAOIEAAyOY1kAAOBIkqYBAIAjSZoGAACapokiAABYmiaKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAGHAAAAkwoA4WGrAQAogAADIaiaQDLAlgWQNMAmgbwPIAnAkwTAAgAAChwAAAIsEFTYnGAQkNWAgBRAAAGRZEky/I8aJqmiSI0TdNEEZ7neaIIz/M804Qoep5pQhQ9zzRhmqJomkAUTVMAAECBAwBAgA2aEosDFBqyEgAICQAwKIpleZ4oiqJpqqrrQtM8TxRF0TRV1XWhaZ4niqJomqrquvA8TzRF0zRNVXVdeJ4omqZpqqrqui48TxRN0zRV1XVdF54niqZpmqrqurIMURRF0zRNVXVdWQaiaJqmqaquK8tAFE1TVV3XdWUZiKJpqqrruq4sA9NUTVV1XVmWZYBpqqrryrIsA1TVdV1Xlm0boKqu67qybNsA13VdWZZl2wbgurIsy7YtAADgwAEAIMAIOsmosggbTbjwABQasiIAiAIAAIxRSjGlDGMSSimhYUxKSaVUUlJKqZRKQkoplVJJSSmlUjJKKaXWUiUllZJSqqSUVFJKBQCAHTgAgB1YCIWGrAQA8gAACEKQYowx56SUSjHmnHNSSqUYc845KSVjjDnnnJSSMcacc05KyZhzzjknpWTMOeeck1I655xzEEoppXTOOQillFJC6ByEUkopnXMOQgEAQAUOAAABNopsTjASVGjISgAgFQDA4DiWpWma5nmiaEmS5nmi54miqVqS5Hmi6Hmiaao8zxNFURRNU1WJouiJoiiapqqSZVE0TdNUVddly6Jomqapqq4L0xRFVXVd2YVpiqJpuq4sQ7ZVU1VdV7Zh26apqq4ry8B1XVeWbR24ruvKsq0LAABPcAAAKrBhdYSTorHAQkNWAgAZAAAEIQgppRBSSiGklEJIKYWQAACAAQcAgAATykChISsBgFQAAABCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGE0DnnnHPOOeecc84555xzzjnnnHPOOeecc84555xzzjnnnHPOOeecc84555xzzjnnnHPOOeecc04AIHaFA8BOhA2rI5wUjQUWGrISAAgHAACMMcY5i7XWWmullFISaq211lozhZSS0GKMMcYYMwYhpRZjjDHGmDHnqMUYY4wxxtZKiS3GGGOMMbZWSowxxhhjjDHG2GKLMcYYY4wxxhZjjDHGGGOMMcYYY4wxxhhjjDHGFmOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjC3GGGOMMcYYY4wxxhhjjAUAmDw4AEAl2DjDStJZ4WhwoSErAYDcAADAGKUYc8w5CCGUUkIpqbXOOQchhFJKKSmVllJMGXPOOQihlFJCKSm1lDrnHIRSSkkppZRSS611DkIIoZRSSkkppZRaCiGEUkpJJaWUUmqttRRCCKWUklJKKaWUWmsxlBJSKaWklFIqqaXWUksllJJKSimllFJqLbXWSimppJRSSimllFpsLYVSUioppZZSSqm1GFsspZWUUkoppdRaiq21FltKKaXUUksppdZiS62llFJqKaXUUmqpxdhaaymllFpKLbWUUoqttRZTSq2llFpqraUWW0qtpZZSai21lFJrrcUWW2stpZZSSim11mJLMbaWWkkppZZaS63F1mJrrbXUWkstpdRiizHG2GJsLaaUUmoptVQAANCBAwBAgBGVFmKnGVcegSMKGSagQkNWAgBkAAAEMk0yJyk1wiSnGJTSnHNKKaWUhsiSDFIMqiOTMScpZ4g0hhSkninymFIMYghJhU4xh60mH0voINagjBEupRgAAABBAICAkAAAAwQFMwDA4ABh5ECgI4DAoQ0AMBAhM4FBITQ4yASAB4gIqQAgMUFRutAFIUSQLoIsHrhw4sYTN5zQoQ0EAAAAAAAEAD4AABIKICAimrkKiwuMDI0Njg6PDxABAAAAAAACgA8AgCQECIiIZq7C4gIjQ2ODo8PjAyQAABBAAAAAAAAEEICAgAAAAAAAQAAAAICAT2dnUwAEDwkAAAAAAAA3ZwAAAgAAAEwW7hoGL1ZMVFNKBK13s5KD1btZaQCACKlDa/uped/er1NrjA5L/p035k7vI9Z8WJl/md3aOsn43Qrat/pI/QAMkOtjfaR+ADbIAxBVoqqwKKP5sl5vP3zbnfeeM90tX0dP/5nSPnrktBxk1diqs1FLYOo6PxtS+5e/L7E0PIwYHsaR+D8+rodbNe999Lb7B973+kj9AAxAn+sj9QMwAABUiapyQ89A/5b2iI3GO+ypcWTO5kbAIK40ufM/x3+Pxq39827Kw9/+OlIaxHkx3zzPV1J2PW45vNc9DxHel3pM/QAs0NC3eiz9AGyQByCqqipUiuaRKr185Uv6/Tkuu0aT8vxqdrRzqSyKduKQKR7Gc8vyTO0Vb0PMzKaMMBf/MtMf2f7c/DtdS8qPWvemJALex3rs/AAUkOhrPZZ+ABbIAxCiqnKF1ayx6fTzPvz9vf1b/7f5WuevW0udiwni8oyHVc5z68bZyr3LnrHuu6aOFK5t8Wzr8bvx/+VjmqpBTaHUAd5Xejs/AAVE+1KPnR+ABgBAlApRFb0dvfXgEI+/DrPs6tWvEuQd5z/n0ic/h07Hs5PvG76ms6e+prM59p9cs8PJ3s/W7fBlF70B\", \"WAAPI\", \"ogg\", true); createSilentAudioFile(\"data:audio/wav;base64,UklGRuwgAABXQVZFZm10IBAAAAABAAIAgD4AAAD6AAAEABAAZGF0YcggAAAAAAEAAAD+/wEAAgD+////AgAAAP7/AQACAP////8AAAAAAQAAAP//AAABAAAA//8AAAEAAAD/////AAACAAIA/v/8/wEABQAAAPv///8EAAIA/f/+/wMAAQD9////AgABAP//AAAAAAAAAQAAAAAA///+/wEAAwAAAPz/AAAFAP///P8CAAMA/v/9/wIAAgD+////AgABAP7///8CAAEA/v///wEAAQABAP7//v8DAAIA/f/+/wIAAQAAAAAA/v8AAAMA///+/wIAAQD+////AgABAP3///8EAAIA/P/+/wQAAAD9/wIAAQD9/wEABAD+//z/AgACAP//AAAAAP//AQACAP///v///wEAAwD///3/AQACAAAA/////wAAAgAAAP7/AQAAAP//AQAAAP//AQABAP7/AAADAP7//f8DAAIA/f///wIAAAD//wEAAAD//wEAAQD/////AQABAP////8BAAEA/////wEAAQAAAP///v8CAAMA/f/+/wIAAQAAAP////8AAAIAAQD+//7/AQADAAAA/f8AAAIAAAD//wAAAAD//wAAAQABAAAA/v8AAAMAAAD8////BAABAP3/AAACAP////8CAAAA/v8AAAEAAQAAAP7/AAACAP///v8CAAIA/f///wMA///+/wIAAgD+//7/AgACAP///f///wQAAgD8////BAAAAPz/AAADAAEA///+////AwADAPz/+/8DAAYA/v/6/wEABQAAAP3///8BAAEAAAD//wAAAAD//wIAAgD9//7/AwACAP3//v8DAAIA/f/9/wMABAD+//z/AQAEAAAA/f/+/wIAAgD9////BAAAAPz/AgAFAPz/+/8EAAMA/P///wQA///9/wMAAgD8//7/AwACAP///v8AAAMAAAD9/wAAAgAAAP///////wIAAwD///3/AAACAAAA//8AAAAA//8BAAIA/v///wIA///+/wMAAgD8//7/BAABAPz/AQADAP7///8BAP//AAACAP///v8CAAEA//8AAP//AAACAP///v8CAAEA/f8BAAMA/v///wIA///+/wIAAgD+//7/AQADAAEA/P/+/wUAAgD7////BAD///z/AgAEAP7//f8CAAIA///+////AgACAP7//v8CAAEA//8AAAAA//8AAAEAAAABAP///f8DAAMA/f/9/wIAAwD+////AQD//wAAAgAAAP3/AAADAP///v8BAAEA//8AAAIA///+/wEAAgD///3/AgADAP3//v8DAAIA/f///wMAAAD+/wAAAQAAAP////8CAAIA/f/+/wMAAgD+////AQD//wAAAgD///7/AQABAAEAAQD9////BAAAAPz/AQADAP7//v8DAAEA/f8AAAIAAAD//wAAAAAAAAEA/////wIAAAD+/wEAAgD///7/AAACAAEA/v///wIAAQD+/wAAAQD//wAAAQD/////AgABAP7/AAABAP//AAABAP//AAABAP//AAABAAAA//8AAAEA//8AAAIA///+/wIAAgD9////BAD///v/AgAEAP7//v8DAAEA/P8AAAQA///9/wEAAQD//wAAAQAAAP//AQACAP///f8AAAMAAAD9/wAAAwABAP3//v8DAAIA/f/+/wMAAwD9//z/AgAEAP7//P8CAAMA/////wEAAAD+/wEAAgD+//7/AQABAAAAAQAAAP7/AAACAAAA/v///wEAAQAAAP//AAABAP////8CAAIA/v/9/wEAAwAAAP7///8BAAIAAAD///////8CAAIA/v/+/wIAAQD+/wEAAQD9/wAABAAAAP3/AAABAP//AAACAP///v8CAAIA///+/wAAAQAAAAAAAAAAAP//AAADAAAA/P8AAAQAAAD8/wAAAwAAAP7/AAACAAAA/v8AAAIAAQD+//7/AQACAAAA//8AAAAAAAAAAAAAAAAAAP//AAADAAAA/f///wEAAgD///7/AQACAAAA/v8BAAEA/f8AAAMAAAD9/wAABAAAAP3/AAABAAAA//8AAAEAAAAAAAEA///9/wIABAD9//3/AwACAP7//v8AAAIAAgD9//7/BAABAP3/AAABAP7/AAAEAAAA/P///wMAAgD///7///8BAAEA//8AAAIA///9/wIABAD+//z/AQACAAAAAAAAAP////8CAAEA/v///wEAAgAAAP7///8CAAEA/f8AAAMAAAD9/wAABAAAAP3///8BAAEAAAAAAP//AAACAAAA/v8AAAEA//8AAAIAAAD//wAA//8AAAMAAAD7////BgACAPv///8DAAAA//8BAAAA/f8AAAQAAAD9/wAAAwAAAP3/AAABAAAAAQD/////AwABAPv///8GAAEA+v///wUAAQD8/wAAAwD///7/AgABAP3/AAADAP////8CAAAA/v///wEAAgAAAP3///8EAAIA/P/+/wMAAgD+//7/AQACAAAA/v///wMAAQD9////AgAAAP7/AQACAAAA/////wEAAAD//wAAAQAAAP7/AAACAAEA///+/wEAAgAAAP///v///wMAAgD+////AQAAAAAAAQD+////BAAAAPz/AQADAP7//v8DAAAA/v8CAAAA/v8BAAIA/f/+/wUAAAD7/wIABAD+//3/AgABAP7/AQABAP7///8CAAMA/v/8/wIABAD+//z/AwADAPz///8EAAEA/P///wQAAQD9//7/AgADAP///v8AAAEAAQAAAP////8AAAAAAAACAAAA/f8BAAMA/v/+/wMAAAD8/wEAAwAAAP////8AAAEAAAAAAAAA//8AAAEAAAABAAAA/v///wIAAQD+/wAAAQD//wAAAQAAAP////8AAAIAAQD+////AgABAP7/AAABAP7/AAADAAAA/P8AAAUAAAD8/wEAAgD//wAAAAD+/wAAAwAAAP3/AQACAP7///8CAAEA//8AAAAA//8BAAEA/f/+/wMAAwD///7/AAACAAAA/v8BAAEA/v///wIAAQD+/wAAAgD/////AgABAP7///8AAP//AQADAP7//f8DAAIA/v///wEAAAD//wEAAAD+/wEAAgD+////AwAAAP3/AQACAP7///8CAAAA//8BAAAA//8AAAEAAAD+/wEAAgD+////AgABAP7/AAABAP7/AAADAAAA/P///wUAAgD7//3/BAADAP7//f8AAAQAAQD7//7/BQADAPv//f8EAAMA/v/9/wEAAgD//wAAAQD///7/AQADAP///v8BAAAA//8BAAEA/v/+/wMAAwD+//7/AAAAAAEAAQD+////AgAAAP//AQAAAP7/AQADAP///v8AAAAAAAAAAAAA//8BAAIA/////wEAAAD//wEAAAD9/wEABAD///3/AQABAP//AQABAP7///8DAAEA/f///wEAAAABAAIA/v/9/wMABAD8//v/BAAEAP3//v8CAAEA//8AAAEA///+/wAAAwABAPz/AAAFAAAA+////wQAAQD9////AgACAP////8BAAAA/v8AAAMAAAD8/wAABQAAAPv/AQAEAP7//f8CAAEA//8BAAAA/v8BAAIA///+/wAAAQAAAAAAAAAAAAAA//8AAAIAAAD9/wAAAwAAAP7///8CAAEA/v8AAAEA/////wIAAgD+//7/AAACAAIA/f/9/wQAAwD9////AQD+/wAAAwD///7/AgAAAP7/AgACAP3//f8DAAMA/f/+/wMAAQD9/wAAAwD///3/AAACAAEAAAD/////AQACAP///f8AAAIAAAD//wEAAQD+/wAAAwD///3/AQABAP//AQABAP7///8DAAEA/f///wEAAgAAAP7/AAABAAAA/v8AAAMA///+/wIAAgD+//7/AQABAP////8BAAIAAAD+////AgABAP///////wEAAgAAAP7/AAACAP///v8CAAIA/f/9/wMAAwD+//7/AQABAAAAAAAAAAAA/////wEAAgD///7/AQACAAAA////////AgACAP3//v8EAAIA/P/+/wMAAgD+//3/AQAEAAAA/P8AAAMAAAD+////AQACAAAA/f8AAAMAAAD+////AgACAP7//v8BAAIA///+/wEAAQAAAAAAAAAAAP//AQACAP7//v8CAAAA/f8CAAQA/v/9/wEAAQABAAEA/f/+/wMAAgD///7/AAABAAAAAAAAAAAAAAAAAAAAAAABAAAA/v8AAAIAAAD+/wAAAwAAAPz/AAAEAAAA/f8BAAIA/v///wIAAAD+/wAAAgAAAP7/AQACAP///v8AAAIAAAD//wAA//8AAAIAAAD+/wEAAgD+////AwAAAPz/AAAEAAAA/f8AAAIAAQD+//7/AgACAP///v8AAAEAAAABAAAA/v8AAAIAAAD//wAAAAD//wEAAgD+////AgAAAP//AAABAP////8BAAEAAAD+/wAAAgAAAP////8AAAEAAQD///7/AQADAAAA/f///wIAAAD//wIAAQD9//7/AwADAP7//f8AAAIAAgAAAP7//v8BAAIAAAD///////8BAAMAAAD8////BAACAPz//f8DAAMA/v/9/wIAAwD///7///8BAAIA///9/wEABAD///3/AgABAP7/AAAAAP//AQACAP///v8BAAEA/////wAAAgAAAP7/AAACAAEA/f///wMA/////wMA///8/wIABAD+//7/AgD///7/BAABAPv/AAAEAAAA/v8AAAAA//8CAAEA/f8AAAIAAAAAAP////8CAAEA/f///wQAAQD8////BAACAPz//f8DAAIA/v8AAAEA//8AAAIAAAD9/wAAAwD///3/AgADAP7//v8CAAEA/////wAAAgAAAP3/AQAEAP7//P8CAAMA///+/wAAAQAAAAAAAAAAAP//AAACAAAA/v///wIAAQD+/wAAAQD//wAAAgAAAP3/AAACAAAAAAAAAP//AAABAAAA/////wAAAwABAPz///8EAAEA/P/+/wMAAwD///3/AAADAAAA/f8AAAIAAQD///7/AAACAAEA/v/+/wMAAgD9////AwAAAPz/AAADAAAAAAAAAP7/AAADAAEA/f///wEAAAABAAAA/v8BAAMA///9/wEAAgD///7/AAACAAEA/////wAAAQABAP7//v8DAAIA/f/+/wIAAgD/////AAAAAAEAAAD+////AwACAPz///8FAAAA+/8AAAQAAAD+/wAAAAABAAIA///9/wEABAD///v/AAAFAAIA+//9/wUABAD8//z/AgADAP///v8AAAEAAQAAAP//AAAAAAAAAQAAAP//AAAAAAAAAgAAAPz/AAAFAAAA/P8BAAIA/v8AAAIA/////wEAAAD//wEAAQD//wAAAAD//wEAAgD///3/AQADAP///f8BAAQA/v/7/wMABgD9//v/AwACAP3/AQADAP7//f8CAAIA/////wAAAQAAAP//AgABAPz///8EAAAA/f8BAAIA///+/wEAAgD///7/AQACAP7///8DAP///f8CAAMA/v/9/wEAAwABAP3//v8CAAMA///9/wAAAgACAP///f8AAAIAAQD//wAAAAAAAAEA/////wIAAAD8/wEABgD+//r/AgAFAP///f8BAAEA//8AAAAA//8BAAEA/v8AAAMAAAD9/wAAAwAAAP3/AAACAAAA//8AAAAAAQABAP7//v8CAAMA/v/8/wIABAD///z/AAAEAAAA/P///wQAAQD8/wAABAAAAPz/AAAEAAAA/P///wMAAgD+//7/AgACAP7//v8BAAIAAAD///////8BAAIA///+/wEAAgAAAP////8AAAEA/////wIAAQD+/wAAAQD//wEAAQD9/wAAAwD///7/AgABAP7/AAABAP//AAABAP////8CAAEA/v8AAAIAAAD+////AQABAAAA//8AAAEAAAABAAAA/v///wEAAgD///7/AQACAP///v8CAAEA/f8AAAIAAAAAAAAA/////wIAAgD9//7/AwABAP7/AAACAP///v8CAAIA/f/+/wIAAgD///7/AQABAP////8AAAIAAQD+////AQABAAAA/////wEAAQD//wAAAQD/////AQAAAAAAAQD///7/AgADAP7//f8AAAIAAgD+//3/AQAEAAEA+//+/wUAAwD7//z/BQADAPz///8CAP//AAADAP///P8BAAMA///+/wEAAgAAAP////8AAAEAAAD/////AQADAP///P8BAAUA///7/wEABAD///3/AAACAAEA/////wEAAgD///3/AQACAP////8BAAEA/////wEAAgAAAP3///8CAAEA//8AAAEA//8AAAEA/////wEAAQD//wAAAQAAAAEA///9/wEABAD///v/AQAFAAAA/P8AAAQAAAD8////AwABAP7/AAABAAAAAQABAP7//f8BAAMAAAD///////8CAAMA/v/8/wEAAgAAAAEA///9/wEAAwD///7/AQABAAAAAAD//wAAAQD/////AQABAP////8CAAEA/v///wIAAQD+////AQABAAAA/////wIAAgD9//7/AwACAP7//v8AAAIAAgD+//3/AQADAAAA//8AAP//AAABAAEAAAD+////AgACAP7//v8CAAEA//8AAAEA///+/wEAAgAAAP7///8DAAEA/f///wIAAAD+/wEAAQD//wEAAAD+/wIAAgD9//7/AwABAP3/AAADAAAA/v8AAAEAAAAAAAAA//8AAAEAAAAAAAAAAAAAAP//AAACAAEA/f/+/wQAAQD9/wAAAQAAAAAAAAD//wAAAgD/////AgAAAP////8AAAEAAAAAAAAAAQABAP7///8BAAEA/////wEAAAAAAAEA/////wIAAQD+////AAAAAAEAAAD//wEAAQD//wAAAQAAAP///v8AAAQAAQD8////AgAAAAAAAQD/////AQABAP///v8BAAIA/////wEAAAD//wEAAQD+////AgABAP////8AAAEAAQD///7/AQADAP///f8CAAIA/f8AAAIA/////wEAAQD//wAAAQD//wAAAAAAAAAA//8BAAEA//8AAAAA//8BAAIA/v/9/wIAAwD///3/AAADAAEA/f///wMAAAD9/wAAAgABAP////8BAAEA/////wAA//8AAAMAAAD+/wEAAQD//wAAAAD//wAAAAAAAAMAAAD7/wEABQD+//3/AgABAP7///8CAAEA////////AQACAAAA/f/+/wMAAwD+//3/AgADAP7//f8BAAIAAAD/////AAACAAEA/////wAAAAAAAAEAAQD+//7/AgADAP///f8AAAIAAQD/////AQABAP////8BAAAA//8BAAEA/////wEAAQD/////AAABAAEA/////wEAAAD//wEAAAD+/wEAAwD///3/AQACAP////8BAAEA///+/wIAAwD9//3/AgADAAAA/v///wAAAgABAP3///8DAAEA/f8AAAMA///+/wEAAQD/////AQABAP////8BAAIA///9/wEAAgD/////AQABAP////8BAAEA/////wAAAQABAP///v8AAAMAAQD9/wAAAgAAAP//AAAAAP//AQAAAP//AQABAP////8BAAEAAAD///7/AgACAP3//v8DAAIA/f///wMAAAD+/wEAAQD+////AgABAP////8BAAIA///9/wAAAwABAP7//v8BAAQA///7/wEAAwD//wAAAgD+//3/AgADAP///f8AAAMAAQD+////AAAAAAEAAQD/////AQAAAAAAAgD///3/AQADAP///v8BAAAA//8BAAIA///9/wEAAwD///7/AQABAP////8AAAEAAQAAAP////8AAAEAAgD+//z/AgAEAAAA/f/+/wEAAwABAPz//v8EAAIA/f/+/wEAAQABAAAA/v8AAAMAAAD8/wAAAwAAAP//AQAAAP7/AQACAP7//v8CAAIA/////wEAAAD+/wAAAgAAAP//AAAAAAAAAQAAAP//AAAAAAAAAQABAP7//v8DAAIA/f/+/wIAAgAAAAAA/v///wMAAAD9/wAAAgAAAP//AgABAP7//v8AAAMAAQD8////BQABAPv/AAAEAP///f8CAAIA/v///wIAAgD+//3/AQACAAEA///+/wAAAgACAP///f8AAAIAAQD///7/AAACAAAA//8AAAAAAAABAAAA//8AAAAAAAABAAAA/v///wIAAgD///7/AAACAAEA///+/wAAAgABAP7//v8CAAMA///9/wAAAwAAAP3/AAACAAAA/v8AAAMAAAD9/wAAAgAAAP//AQAAAP7/AQABAP7/AAACAAAA//8AAAEAAAD//wAAAQAAAP//AAABAAAAAAD/////AwACAPz//f8FAAMA+//+/wMAAgD///7/AAABAAEA/////wEAAAAAAAEA///+/wEAAgAAAP//AAAAAAAAAgAAAPz///8EAAIA/P///wMAAAD//wEAAAD+/wAAAgAAAP//AAAAAAAAAQAAAP//AAABAAAA//8BAAAA//8BAAAA//8BAAEA/////wAAAAABAAEA///+/wAAAgABAP////8AAAAAAQAAAP7/AAADAAAA/f8BAAIA/////wAAAQAAAP//AQABAP7//v8EAAIA+////wUAAQD8////AgD//wAAAgD///7/AQACAP////8BAP////8CAAAA/v8BAAIA/v/+/wMAAgD9////AgAAAP//AQAAAP//AQABAP7///8DAAAA/P8BAAUA///7/wEAAwD/////AAAAAAEAAAD//wEAAQD9////BAABAPz///8EAAEA/f///wIAAAD+/wIAAQD9/wEAAwD+//3/AgACAP7///8CAAAA/v8AAAIAAQD9////AwAAAP7/AAABAP////8CAAEA/////wAAAgAAAP3/AAACAAAAAAAAAP7/AAAEAAAA+/8AAAQAAAD+/wAAAAD//wEAAgD///7/AAABAAAAAAABAP7//v8DAAMA///8//7/BAADAP3//f8CAAIA//8AAAAA//8BAAEA/////wAAAQABAP////8BAAAA//8BAAIA/v/9/wMAAwD9//3/AgADAP7//v8CAAEA/v///wIAAQD//wAA/////wIAAQD+////AgABAP////8AAAEAAQD/////AgAAAP3/AQADAP///f8BAAMAAAD+//7/AQACAP////8BAAEAAAD/////AQABAP7///8CAAEA/////wEAAQD/////AAABAAAA/////wAAAwABAP3//v8BAAMAAAD9/wAAAgD/////AwAAAPv/AQAFAP///P8BAAMA/v/+/wMAAQD9////AwAAAP3/AQADAP7//f8EAAMA+//9/wQAAwD9//7/AgAAAAAAAQD/////AQAAAP//AgACAPz//v8FAAEA+v///wUAAgD9//7/AgADAP///P8AAAMA/////wIA///+/wMAAQD9/wAAAQD//wEAAgD+//3/AQAEAAAA+/8AAAUAAAD8/wEAAwD+//7/AQABAAAAAAAAAP//AAABAAAA//8AAAEAAAAAAP////8BAAEA///+/wEABAABAPv//f8FAAMA/P/9/wMAAwD9//7/AwACAP3//v8DAAEA/v8AAAEA/////wIAAQD9////BAAAAPz/AgAEAP3//P8CAAMAAAD+////AgABAP7///8CAAEA/f8AAAMA/////wIA///9/wIAAwD+//7/AQABAAEA///9/wEABAAAAPz///8EAAEA/P///wMAAQD+////AgACAP7//f8BAAMAAAD+/wAAAAAAAAIAAQD9//3/BAAFAPz/+v8DAAYA/v/7/wEABAAAAP3/AAABAAAAAQAAAP7/AAADAAAA/P8AAAQAAAD9/wEAAgD//wAAAAD+/wAAAwAAAP3/AQACAP7/AAADAP///P8BAAQA///8/wAAAwABAP7///8CAAAA/v8BAAEA/////wEAAQD//wAAAQAAAP7///8EAAEA+////wUAAQD8/wAAAgD/////AgABAP3///8DAAEA/v///wEAAQAAAP////8BAAIA///+/wEAAQAAAAAAAAD//wAAAQD//wAAAgD///7/AgABAP7/AQACAP7///8CAAAA//8BAAAA/v8BAAMA/v/9/wIAAwD+//7/AwAAAP3/AgACAPz///8FAP//+/8DAAUA/P/7/wMABAD///3///8DAAIA/f/+/wMAAQD8/wAABAD///7/AgABAP3///8DAAEA/f///wMAAQD+/wAAAQD/////AQABAAAA/v///wMAAQD9////AwABAP3///8DAAEA/f///wIAAQD/////AAABAAIA///9/wEAAwAAAP3///8CAAEAAAD/////AQACAP///f8BAAIA/////wEAAQD//wAAAQD+////AgAAAP//AQAAAP7/AgAEAPv/+/8GAAQA+//+/wQAAAD9/wIAAQD9/wAAAwAAAP7/AAABAAAAAAAAAP//AAACAAAA/f///wMAAgD9//7/AwACAP7//v8BAAIAAAD9////BAABAPz/AAADAAAA//8AAP7/AAAEAAAA/P8AAAMAAAD+/wAAAAD//wIAAgD9//7/BAACAPz//v8CAAAAAAACAP///v8CAAEA/f8AAAQA///7/wEABgAAAPr///8FAAEA/P8AAAQA///8/wEABAD///z/AQADAP////8BAAAAAAAAAP7/AQADAP3//f8DAAIA//8AAAAA/v8AAAMAAQD+//3/AQAEAP7//f8DAAIA/P///wYAAQD6////BAAAAP7/AQAAAP//AQABAP////8BAAEAAAD+/wAABAD///v/AQAFAAAA+////wQAAgD+//7/AAABAAEAAQD+//3/AwAEAP7//P8AAAMAAQD///7///8DAAIA/f/+/wIAAgD///7/AQACAP///v8AAAEAAAAAAAAA//8BAAIA///+/wAAAgAAAP7/AAABAAAAAAABAAAA/v8AAAMAAAD8/wAAAwAAAP//AAAAAAAAAQAAAP//AQD///7/AwADAP3//P8DAAQA/v/9/wAAAgABAP//AAABAAAA//8AAAAA//8BAAEA/v8AAAMAAQD9//7/AgABAP7///8CAAEA//8AAAAAAAAAAP////8CAAEA/f8AAAQAAAD7/wAABQAAAPz///8DAAIA/v/+/wEA\", \"WAAPI\", \"wav\", true); if (typeof(CB_AudioFile_API[\"WAAPI\"].audioContext) === \"undefined\" || CB_AudioFile_API[\"WAAPI\"].audioContext === null) { if (typeof(window.AudioContext) !== \"undefined\" || typeof(window.webkitAudioContext) !== \"undefined\") { CB_AudioFile_API[\"WAAPI\"].audioContext = new (window.AudioContext || window.webkitAudioContext)(); //Hack (source: https://stackoverflow.com/questions/56768576/safari-audiocontext-suspended-even-with-onclick-creation/56770254#56770254): try { CB_AudioFile_API[\"WAAPI\"].audioContext.createGain(); } catch (createGainError) { CB_console(\"Error creating a GainNode for the AudioContext: \" + createGainError); } try { CB_AudioFile_API[\"WAAPI\"].audioContext.resume(); } catch (audioContextResumeError) { CB_console(\"Error resuming AudioContext: \" + audioContextResumeError); } if (!CB_AudioFile_API[\"WAAPI\"].audioContext) { return null; } } } var extensions = [ \"mp3\", \"ogg\", \"wav\" ]; var allNull = true; for (var x = 0; x &lt; 3; x++) { if (silentAudioFiles[\"WAAPI\"][extensions[x]] !== null) { allNull = false; if (silentAudioFiles[\"WAAPI\"][extensions[x]].getStatusString() === \"UNCHECKED\") { new function(x) { var finishedChecking = function(error, checkedFine) { silentAudioFiles[\"WAAPI\"][extensions[x]].destructor(true, false, true, false); silentAudioFiles[\"WAAPI\"][extensions[x]] = null; }; silentAudioFiles[\"WAAPI\"][extensions[x]].checkPlaying(function() { finishedChecking(\"\", true); }, finishedChecking, false, true, false); }(x); } } } //If all objects are null it means all have either played or failed: if (allNull) { CB_Speaker._silentAudioFilePlayedWAAPI = true; } } //If not done before, initializes the jsfx library: if (typeof(jsfx) === \"undefined\" &amp;&amp; typeof(_jsfxInitializer) === \"function\") { //Initializes the jsfx library: _jsfxInitializer(CB_this[\"jsfx\"] = {}); _jsfxInitializer = null; //Prevents executing it more than once. //Gets and stores the jsfx object (if any): CB_Speaker._jsfxObject = (typeof(jsfx) !== \"undefined\" &amp;&amp; jsfx !== null) ? jsfx : null; } //If not done before, initializes the timbre.js library: if (typeof(T) === \"undefined\" &amp;&amp; typeof(_timbreJSInitializer) === \"function\") { _timbreJSInitializer.call(CB_this); _timbreJSInitializer = null; //Prevents executing it more than once. //Gets and stores the timbre.js object (if any): CB_Speaker._timbreJSObject = (typeof(T) !== \"undefined\" &amp;&amp; T !== null) ? T : null; } //TODO: Think about initializing Band.js library here too (the same as with jsfx and timbre.js libraries). }; CB_Events.add(document, \"click\", silentAudioFilePlay, true, true, false); //CB_Events.add(document, \"touchstart\", silentAudioFilePlay, true, true, false); } //Applies the current volume to all objects: CB_Speaker._applyVolume = function(volume, isMuteOrUnmute, forceSetVolumeProperty, functionToExecute, audioFiles, avoidSanitize) { //If there is no sprites pool object, just exits: if (typeof(CB_Speaker._audioFileSpritesPool) === \"undefined\" || CB_Speaker._audioFileSpritesPool === null) { return; } if (!avoidSanitize) { volume = CB_Speaker.sanitizeVolume(volume, true); //Uses CB_Speaker._volume if the value is not valid. } //If we want either to mute or unmute: if (isMuteOrUnmute) { //If volume is zero, we want to mute: if (volume === 0) { CB_Speaker._audioFileSpritesPool.muteAll(functionToExecute, audioFiles); } //...otherwise, we want to unmute: else { CB_Speaker._audioFileSpritesPool.unmuteAll(functionToExecute, audioFiles); } } //...otherwise, we just set the volume given: else { CB_Speaker._audioFileSpritesPool.setVolumeAll(volume, forceSetVolumeProperty, functionToExecute, audioFiles); } } /** * Sanitizes the volume (it does not allow values greater than 100 or lower than 0). * @function * @param {number} [volume=CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME|CB_Speaker._volume] - The desired volume to be sanitized. If not given, it will use the current volume if the \"useSpeakerVolumeIfNaN\" parameter is set to true or the default volume otherwise. * @param {boolean} [useSpeakerVolumeIfNaN=false] - If it is set to true and no valid volume is received in the \"volume\" parameter, it will use the current volume ({@link CB_Speaker._volume}). Otherwise, if it is set to false and no valid volume is received in the \"volume\" parameter, it will use the default volume which is set in the {@link CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME} constant. * @returns {number} Returns the volume sanitized (it does not allow values greater than 100 or lower than 0). */ CB_Speaker.sanitizeVolume = function(volume, useSpeakerVolumeIfNaN) { volume = parseInt(volume); if (isNaN(volume)) { volume = useSpeakerVolumeIfNaN ? CB_Speaker._volume : CB_Configuration[CB_BASE_NAME].CB_Speaker_DEFAULT_VOLUME; } //Sets the volume within their limits if it is beyond them: if (volume &gt; 100) { volume = 100; } else if (volume &lt; 0) { volume = 0; } return volume; } /** * Sets the given volume. * @function * @param {number} [volume=CB_Speaker._volume] - The desired volume to be used (it will be sanitized internally by calling the {@link CB_Speaker.sanitizeVolume} function with the volume as the unique parameter). If not given, it will use the current volume. If the \"avoidApplyingVolume\" is set to false and the \"isMuteOrUnmute\" parameter is false, it will also be used as a parameter to call the {@link CB_AudioFileSpritesPool#setVolumeAll} method of the internal {@link CB_AudioFileSpritesPool} object defined in {@link CB_Speaker._audioFileSpritesPool} (if any). * @param {boolean} [avoidApplyingVolume=false] - If it is set to true, the volume will not be applied (by calling the {@link CB_Speaker._applyVolume} internal function, which will also use the internal {@link CB_AudioFileSpritesPool} object defined in {@link CB_Speaker._audioFileSpritesPool}, if any) and just the {@link CB_Speaker._volume} internal property will be set. * @param {boolean} [forceSetVolumeProperty=false] - If the \"avoidApplyingVolume\" is set to false and the \"isMuteOrUnmute\" parameter is false, it will be used as a parameter to call the {@link CB_AudioFileSpritesPool#setVolumeAll} method of the internal {@link CB_AudioFileSpritesPool} object defined in {@link CB_Speaker._audioFileSpritesPool} (if any). * @param {function} [functionToExecute] - A callback function. If the \"avoidApplyingVolume\" is set to false and the \"isMuteOrUnmute\" parameter is false, it will be used as the \"onSetVolume\" parameter to call the {@link CB_AudioFileSpritesPool#setVolumeAll} method of the internal {@link CB_AudioFileSpritesPool} object defined in {@link CB_Speaker._audioFileSpritesPool} (if any). If the \"avoidApplyingVolume\" is set to false and the \"isMuteOrUnmute\" parameter is true, it will be used as the \"onMute\" parameter to call the {@link CB_AudioFileSpritesPool#muteAll} method or as the \"onUnmute\" parameter to call the {@link CB_AudioFileSpritesPool#unmuteAll} method of the internal {@link CB_AudioFileSpritesPool} object defined in {@link CB_Speaker._audioFileSpritesPool} (if any). * @param {array} [audioFiles] - An array containing the CB_AudioFile objects that we want to affect (if not set and the \"avoidApplyingVolume\" is set to false, it will affect all the CB_AudioFile objects of the internal {@link CB_AudioFileSpritesPool} object defined in {@link CB_Speaker._audioFileSpritesPool}, if any). If the \"avoidApplyingVolume\" is set to false and the \"isMuteOrUnmute\" parameter is false, it will be used as the \"audioFiles\" parameter to call the {@link CB_AudioFileSpritesPool#setVolumeAll} method of the internal {@link CB_AudioFileSpritesPool} object defined in {@link CB_Speaker._audioFileSpritesPool} (if any). If the \"avoidApplyingVolume\" is set to false and the \"isMuteOrUnmute\" parameter is true, it will be used as the \"audioFiles\" parameter to call the {@link CB_AudioFileSpritesPool#muteAll} method or as the \"audioFiles\" parameter to call the {@link CB_AudioFileSpritesPool#unmuteAll} method of the internal {@link CB_AudioFileSpritesPool} object defined in {@link CB_Speaker._audioFileSpritesPool} (if any). * @param {boolean} [saveForUnmute=false] - If it is set to true, the given volume will be saved to be restored later when the {@link CB_Speaker.unmute} method is called. * @param {boolean} [isMuteOrUnmute=false] - If it is set to true and the volume given is zero, the action performed internally will be muting (by calling the {@link CB_AudioFileSpritesPool#muteAll} method of the internal {@link CB_AudioFileSpritesPool} object defined in {@link CB_Speaker._audioFileSpritesPool}, if any). Otherwise, if it is set to true and the volume given is not zero, the action performed internally will be unmuting (by calling the {@link CB_AudioFileSpritesPool#unmuteAll} method of the internal {@link CB_AudioFileSpritesPool} object defined in {@link CB_Speaker._audioFileSpritesPool}, if any). If it is set to false, the action performed will be set the volume given (by calling the {@link CB_AudioFileSpritesPool#setVolumeAll} method of the internal {@link CB_AudioFileSpritesPool} object defined in {@link CB_Speaker._audioFileSpritesPool}, if any). * @returns {number} Returns the current volume being used after setting it. * @todo Also affect BandJS, jsfx and timbre.js. */ CB_Speaker.setVolume = function(volume, avoidApplyingVolume, forceSetVolumeProperty, functionToExecute, audioFiles, saveForUnmute, isMuteOrUnmute) { volume = CB_Speaker.sanitizeVolume(volume); if ((saveForUnmute || volume === 0) &amp;&amp; CB_Speaker._volume &gt; 0) { CB_Speaker._volumeBeforeMute = CB_Speaker._volume; } //Only saves it if the current volume is more than zero. CB_Speaker._volume = volume; if (!avoidApplyingVolume) { CB_Speaker._applyVolume(volume, isMuteOrUnmute, forceSetVolumeProperty, functionToExecute, audioFiles, true); } return CB_Speaker._volume; } /** * Mutes the speaker. Calls the {@link CB_Speaker.setVolume} function internally, with 0 (zero) as the \"volume\" parmeter, null as the \"forceSetVolumeProperty\" parameter and true for both \"saveForUnmute\" and \"isMuteOrUnmute\" parameters. * @function * @param {boolean} [avoidApplyingVolume=false] - Used as a parameter to call the {@link CB_Speaker.setVolume} function internally. * @param {function} [onMute] - Used as as the \"functionToExecute\" parameter to call the {@link CB_Speaker.setVolume} function internally. * @param {array} [audioFiles] - Used as a parameter to call the {@link CB_Speaker.setVolume} function internally. * @returns {number} Returns the result of the internal call to the {@link CB_Speaker.setVolume} function. * @todo Also affect BandJS, jsfx and timbre.js. */ CB_Speaker.mute = function(avoidApplyingVolume, onMute, audioFiles) { return CB_Speaker.setVolume(0, avoidApplyingVolume, null, onMute, audioFiles, true, true); } /** * Restores the audio volume after muting it. If the current volume is 0 (zero, muted) or the \"ignoreVolume\" parameter is set to true, calls the {@link CB_Speaker.setVolume} function internally, with the previously-saved volume before muting it as the \"volume\" parmeter, null as the \"forceSetVolumeProperty\" parameter, false for the \"saveForUnmute\" parameter and true for the \"isMuteOrUnmute\" parameter. * @function * @param {boolean} [avoidApplyingVolume=false] - Used as a parameter to call the {@link CB_Speaker.setVolume} function internally, if the \"ignoreVolume\" parameter is set to true. * @param {function} [onUnmute] - Used as as the \"functionToExecute\" parameter to call the {@link CB_Speaker.setVolume} function internally, if the \"ignoreVolume\" parameter is set to true. * @param {array} [audioFiles] - Used as a parameter to call the {@link CB_Speaker.setVolume} function internally, if the \"ignoreVolume\" parameter is set to true. * @param {boolean} [ignoreVolume=false] - If set to true, it will try to perform the muting action even when the current volume is not 0 (zero, muted). * @returns {number} Returns the current volume. * @todo Also affect BandJS, jsfx and timbre.js. */ CB_Speaker.unmute = function(avoidApplyingVolume, onUnmute, audioFiles, ignoreVolume) { if (CB_Speaker._volume === 0 || ignoreVolume) { CB_Speaker.setVolume(CB_Speaker._volumeBeforeMute, avoidApplyingVolume, null, onUnmute, audioFiles, false, true); } return CB_Speaker._volume; } /** * Tells the current volume. * @function * @param {boolean} [avoidSanitize=false] - If set to true, it will not call the {@link CB_Speaker.sanitizeVolume} function internally before returning the volume. * @returns {number} Returns the current volume. */ CB_Speaker.getVolume = function(avoidSanitize) { if (!avoidSanitize) { CB_Speaker._volume = CB_Speaker.sanitizeVolume(CB_Speaker._volume); } return CB_Speaker._volume; } /** * Sets the desired {@link CB_AudioFileSpritesPool} object. * @function * @param {CB_AudioFileSpritesPool} audioFileSpritesPool - The desired {@link CB_AudioFileSpritesPool} object to manage all audio files. * @returns {CB_AudioFileSpritesPool|null} Returns the current {@link CB_AudioFileSpritesPool} object after setting it (if any) or null otherwise. */ CB_Speaker.setAudioFileSpritesPool = function(audioFileSpritesPool) { //if (typeof(audioFileSpritesPool) !== \"undefined\" &amp;&amp; audioFileSpritesPool !== null &amp;&amp; audioFileSpritesPool instanceof CB_AudioFileSpritesPool) if (audioFileSpritesPool instanceof CB_AudioFileSpritesPool) { CB_Speaker._audioFileSpritesPool = audioFileSpritesPool; } return CB_Speaker._audioFileSpritesPool; } /** * Returns the current {@link CB_AudioFileSpritesPool} object (if any). * @function * @returns {CB_AudioFileSpritesPool|null} Returns the current {@link CB_AudioFileSpritesPool} object (if any) or null otherwise. */ CB_Speaker.getAudioFileSpritesPool = function() { return CB_Speaker._audioFileSpritesPool || null; } /** * Returns the [timbre.js]{@link https://mohayonao.github.io/timbre.js/} object (if any). Useful for functional processing and synthesizing audio. * @function * @returns {Object|null} Returns the current [timbre.js]{@link https://mohayonao.github.io/timbre.js/} object (if any) or null otherwise. * @todo timbre.js should have into account the CB_Speaker._volume */ CB_Speaker.getTimbreJSObject = function() { return CB_Speaker._timbreJSObject || null; } /** * Returns a new [Band.js]{@link https://github.com/meenie/band.js/} object (if possible). Useful for managing music composition. * @function * @returns {Object|null} Returns a new [Band.js]{@link https://github.com/meenie/band.js/} object (if possible) or null otherwise. * @todo Band.js should have into account the CB_Speaker._volume */ CB_Speaker.getBandJSObject = function() { return CB_Speaker._bandJSObject ? new CB_Speaker._bandJSObject() : null; } /** * Returns the [jsfx]{@link https://github.com/loov/jsfx} object (if any). Useful for managing sound effects generation. * @function * @returns {Object|null} Returns the current [jsfx]{@link https://github.com/loov/jsfx} object (if any) or null otherwise. * @todo jsfx should have into account the CB_Speaker._volume */ CB_Speaker.getJsfxObject = function() { return CB_Speaker._jsfxObject || null; } } //End of the static class CB_Speaker. × Search results Close "},"CrossBase_general_CB_others.js.html":{"id":"CrossBase_general_CB_others.js.html","title":"Source: CrossBase/general/CB_others.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/general/CB_others.js /** * @file Miscellaneous code. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. * @todo Think about a 'CB_symmetricInterval' function, similar to {@link CB_symmetricCall} but calling the callback function automatically. */ /** * Callback that is called by {@link CB_symmetricCall}. * @callback CB_symmetricCall_CALLBACK * @param {integer} expectedCallingTime - The timestamp in milliseconds that represents when the callback should have been called (it will be more or less accurate depending on many factors as the platform used, code performance, etc.). */ var CB_symmetricCallLastTimes = {}; //Array that stores the last times of every function. /** * Calls the given function once through the native [setTimeout]{@link https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function internally but having in mind the time taken when the function was called previously so it can be called multiple times and respect a symmetric interval between each call (simulates [requestAnimationFrame]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame}). * @function * @param {CB_symmetricCall_CALLBACK} callbackFunction - Function that will be called every time, receiving as the unique parameter the time (timestamp in milliseconds returned by the [performance.now]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance/now} method, which could have been polyfilled automatically by CrossBrowdy) when it is called, being \"this\" the same \"this\" of the scope where it was called. * @param {integer} timeMs - Milliseconds between one call to the function and the next one. The accuracy will depend on many factors as the platform used, code performance, etc. * @param {string} [id=callbackFunction.toString()] - String that will identify this symmetric interval. Recommended to avoid possible problems. * @returns {number|null} Returns a numeric identifier generated by an internal call to the native [setTimeout]{@link https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout} function (can be cleared/cancelled with [clearTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout}). Returns null if the given \"callbackFunction\" is not a valid function. */ //* Source: Based on requestAnimationFrame polyfill by Erik Möller. function CB_symmetricCall(callbackFunction, timeMs, id) { if (typeof(callbackFunction) !== \"function\") { return null; } var now = window.performance.now(); //Can be polyfilled (https://gist.github.com/jalbam/cc805ac3cfe14004ecdf323159ecf40e) id = id || callbackFunction; if (typeof(CB_symmetricCallLastTimes[id]) === \"undefined\" || CB_symmetricCallLastTimes[id] === null) { var nextTime = now + timeMs; //First time, it lasts the given milliseconds. CB_symmetricCallLastTimes[id] = 0; } else { //var lastTime = CB_symmetricCallLastTimes[id]; /* var timeToCall = Math.max(lastTime + timeMs, now);//Math.max(0, timeMs - (now - lastTime)); var id = setTimeout(callbackFunction, timeToCall - now);//, timeToCall); lastTime = timeToCall;//now + timeToCall; */ //var timeToCall = Math.max(0, timeMs - (now - lastTime)); //var timeToCall = Math.max(0, timeMs - (now - CB_symmetricCallLastTimes[id])); var nextTime = Math.max(CB_symmetricCallLastTimes[id] + timeMs, now); } var that = this; return setTimeout ( function() { //callbackFunction.call(that, CB_symmetricCallLastTimes[id] = now + timeToCall); callbackFunction.call(that, CB_symmetricCallLastTimes[id] = nextTime); }, //timeToCall nextTime - now ); } /** * Clears the stored last time used by {@link CB_symmetricCall} for a given symmetric interval identifier. * @function * @param {string} id - String that identifies this symmetric interval. * @returns {boolean|null} Returns null if the given \"id\" is not a valid string. Returns false if the stored time did not exist for the given \"id\" or it was cleared already. Returns true otherwise, after clearing it. */ function CB_symmetricCallClear(id) { id = id + \"\"; if (id === \"\") { return null; } if (typeof(CB_symmetricCallLastTimes[id]) === \"undefined\" || CB_symmetricCallLastTimes[id] === null) { return false; } CB_symmetricCallLastTimes[id] = null; return true; } × Search results Close "},"CrossBase_input_CB_Touch.js.html":{"id":"CrossBase_input_CB_Touch.js.html","title":"Source: CrossBase/input/CB_Touch.js","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Source: CrossBase/input/CB_Touch.js /** * @file Touch events management. Contains the {@link CB_Touch} static class. * @author Joan Alba Maldonado &lt;workindalian@gmail.com&gt; * @license Creative Commons Attribution 4.0 International. See more at {@link https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license}. */ /** * Static class to manage the [touch events]{@link https://developer.mozilla.org/en-US/docs/Web/API/Touch_events}. It will return itself if it is tried to be instantiated. It can also use [Pressure.js]{@link https://pressurejs.com/} and [Hammer.js]{@link https://hammerjs.github.io/}. * @namespace */ var CB_Touch = function() { return CB_Touch; }; { CB_Touch._data = null; //Stores the information about the touch points. CB_Touch._force = null; //Stores the force of the touch point (just one, using Pressure.js). /** * Default value for the force attribute if no one is detected. * @var * @readonly * @type {number} * @default */ CB_Touch.DEFAULT_FORCE = 1; //Default value for the force attribute if no one is detected. CB_Touch._hammerJSObject = null; //Stores the Hammer.js object (if any). CB_Touch._pressureJSObject = null; //Stores the Pressure.js object (if any). CB_Touch.initialized = false; //It will tells whether the object has been initialized or not. //Initializes all values: CB_Touch.init = function() { if (CB_Touch.initialized) { return CB_Touch; } //The object has been initialized: CB_Touch.initialized = true; //Gets the touch data constantly: CB_Events.add(document, \"touchstart\", function(e) { CB_Touch._data = CB_Touch.normalizeEvent(e) || null; }, true, true, false); CB_Events.add(document, \"touchenter\", function(e) { CB_Touch._data = CB_Touch.normalizeEvent(e) || null; }, true, true, false); CB_Events.add(document, \"touchmove\", function(e) { CB_Touch._data = CB_Touch.normalizeEvent(e) || null; }, true, true, false); CB_Events.add(document, \"touchend\", function(e) { CB_Touch._force = 0; CB_Touch._data = null; }, true, true, false); CB_Events.add(document, \"touchleave\", function(e) { CB_Touch._force = 0; CB_Touch._data = null; }, true, true, false); //Gets and stores the Hammer.js object (if any): CB_Touch._hammerJSObject = (typeof(Hammer) !== \"undefined\" &amp;&amp; Hammer !== null) ? Hammer : null; if (typeof(Hammer) !== \"undefined\" &amp;&amp; Hammer !== null &amp;&amp; Hammer.defaults) { //Chromium workaround (Chrome, Opera...) for Android thanks to Desiderius77, found on https://github.com/hammerjs/hammer.js/issues/1130#issuecomment-378851243. Hammer.defaults.inputClass = ((CB_Client.get() === \"Chrome\" || CB_Client.get() === \"Opera\") &amp;&amp; Hammer.SUPPORT_POINTER_EVENTS) ? Hammer.PointerEventInput : Hammer.TouchInput; } //Gets and stores the Pressure.js object (if any): CB_Touch._pressureJSObject = (typeof(Pressure) !== \"undefined\" &amp;&amp; Pressure !== null) ? Pressure : null; //Gets the touch force (using pressure.js) constantly: if (CB_Touch._pressureJSObject !== null &amp;&amp; typeof(CB_Touch._pressureJSObject.set) === \"function\") { CB_Touch._pressureJSObject.set ( document, { //start: function(event) { }, end: function() { CB_Touch._force = 0; }, //startDeepPress: function(event) { }, //endDeepPress: function() { }, change: function(force, event) { CB_Touch._force = typeof(force) !== \"undefined\" &amp;&amp; !isNaN(force) ? force : null; }//, //unsupported: function() { } } ); } return CB_Touch; } //Allows for interpolating a value from one range of values to another: //* Source: Pressure.js by Stuart Yamartino and Arduino documentation: https://www.arduino.cc/en/Reference/Map CB_Touch._map = function _map(x, in_min, in_max, out_min, out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; }; /** * Normalizes the given \"force\" property value across different clients. The new attached methods and properties may include polyfills, etc. This function is called by {@link CB_Touch.normalizePoint} automatically. * @function * @param {number} force - Force value to be normalized. * @returns {Event} Returns the force value normalized. * @todo Not all web clients are the same, so not all should be normalized. */ //* Source: Pressure.js by Stuart Yamartino. CB_Touch.normalizeForce = function(force) { //TODO: not all web clients are the same! so not all should normalize. if (typeof(force) === \"undefined\" || force === null || isNaN(force)) { return CB_Touch.DEFAULT_FORCE; } force = CB_Touch._map(force, 1, 3, 0, 1); force = force &gt; 0.999 ? 1 : force; force = Math.abs(force); return force; } /** * Tries to return the [touch event]{@link https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent} object with some properties normalized (since different clients can use different values), when possible. It also calls the {@link CB_Events.normalize} and {@link CB_Touch.normalizePoints} functions internally. Some properties affected could be [targetTouches]{@link https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/targetTouches}, [touches]{@link https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches}, [changedTouches]{@link https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/changedTouches}, etc. * @function * @param {Event} e - [Touch event]{@link https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent} object. If not provided, it will use the value of \"event\", \"window.event\", \"Event\" or an empty object (\"{}\"). * @returns {Event} Returns the [touch event]{@link https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent} object normalized. * @todo Add more properties and methods to normalize (if needed) */ CB_Touch.normalizeEvent = function(e) { e = CB_Events.normalize(e); //TODO: add more properties and methods to normalize (if needed). //Normalize the points: e.targetTouches = CB_Touch.normalizePoints(e.targetTouches); e.touches = CB_Touch.normalizePoints(e.touches); e.changedTouches = CB_Touch.normalizePoints(e.changedTouches); return e; } /** * Normalizes a given list of points. Calls {@link CB_Touch.normalizePoint} internally. This function is called by {@link CB_Touch.normalizeEvent} automatically. * @function * @param {TouchList|array} points - [TouchList]{@link https://developer.mozilla.org/en-US/docs/Web/API/TouchList} or array with the points ([Touch objects]{@link https://developer.mozilla.org/en-US/docs/Web/API/Touch}) to be normalized. * @returns {TouchList|array} Returns the given points normalized. */ CB_Touch.normalizePoints = function(points) { if (typeof(points) === \"undefined\" || points === null || typeof(points) === \"undefined\" || points === null) { return []; } for (var x = 0; x &lt; points.length; x++) { points[x] = CB_Touch.normalizePoint(points[x]); } return points; } /** * Normalizes a given point. Calls {@link CB_Touch.normalizeForce} internally. This function is called by {@link CB_Touch.normalizePoints} automatically. * @function * @param {Touch} point - [Touch object]{@link https://developer.mozilla.org/en-US/docs/Web/API/Touch} to be normalized. * @returns {Touch} Returns the given point normalized. */ CB_Touch.normalizePoint = function(point) { if (typeof(point) !== \"undefined\" &amp;&amp; point !== null) { if (typeof(point.force) === \"undefined\" || point.force === null || isNaN(point.force)) { if (typeof(point.webkitForce) !== \"undefined\" &amp;&amp; point.webkitForce !== null &amp;&amp; !isNaN(point.webkitForce)) { point.force = point.webkitForce; } else if (CB_Touch._force !== null) { point.force = CB_Touch._force; } //Uses force detected by Pressure.js. else { e.force = CB_Touch.DEFAULT_FORCE; } } point.force = CB_Touch.normalizeForce(point.force); } return point; } /** * Returns the last [touch event]{@link https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent} object (if any), processed by {@link CB_Touch.normalizeEvent} internally, which was used in the last touch event fired, if that touch event was [touchstart]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/touchstart_event}, [touchenter]{@link https://w3.org/TR/2011/WD-touch-events-20110505/#the-touchenter-event} or [touchmove]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/touchmove_event}. The [touchend]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/touchend_event} and [touchleave]{@link https://w3.org/TR/2011/WD-touch-events-20110505/#the-touchleave-event} events set it to \"null\". * @function * @returns {Event|null} Returns the last [touch event]{@link https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent} affected, if any. */ CB_Touch.getData = function() { return CB_Touch._data; } /** * Returns the maximum of touch points supported by the device (if possible). * @function * @returns {integer|null} Maximum touch points supported by the device (if possible). If it cannot be detected, returns null. */ CB_Touch.getMaxTouchPoints = function() { if (window.navigator) { if (window.navigator.maxTouchPoints) { return window.navigator.maxTouchPoints; } else if (window.navigator.msMaxTouchPoints) { return window.navigator.msMaxTouchPoints; } } return null; } /** * Sets a function to execute when the [onTouchStart]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/touchstart_event} event is fired or removes it. More information: [Touch events]{@link https://developer.mozilla.org/en-US/docs/DOM/Touch_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Touch.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Touch.onStart = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Touch._setEvent(\"touchstart\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when the [onTouchEnd]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/touchend_event} event is fired or removes it. More information: [Touch events]{@link https://developer.mozilla.org/en-US/docs/DOM/Touch_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Touch.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Touch.onEnd = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Touch._setEvent(\"touchend\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when the [onTouchCancel]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/touchcancel_event} event is fired or removes it. More information: [Touch events]{@link https://developer.mozilla.org/en-US/docs/DOM/Touch_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Touch.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Touch.onCancel = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Touch._setEvent(\"touchcancel\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when the [onTouchEnter]{@link https://w3.org/TR/2011/WD-touch-events-20110505/#the-touchenter-event} event is fired or removes it. More information: [Touch events]{@link https://developer.mozilla.org/en-US/docs/DOM/Touch_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Touch.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Touch.onEnter = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Touch._setEvent(\"touchenter\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when the [onTouchLeave]{@link https://w3.org/TR/2011/WD-touch-events-20110505/#the-touchleave-event} event is fired or removes it. More information: [Touch events]{@link https://developer.mozilla.org/en-US/docs/DOM/Touch_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Touch.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Touch.onLeave = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Touch._setEvent(\"touchleave\", callbackFunction, keepOldFunction, useCapture, target); } /** * Sets a function to execute when the [onTouchMove]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/touchmove_event} event is fired or removes it. More information: [Touch events]{@link https://developer.mozilla.org/en-US/docs/DOM/Touch_events}. * @function * @param {function|null} callbackFunction - The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the {@link CB_Touch.normalizeEvent} function). If a null value is used, the event will be removed. * @param {boolean} [keepOldFunction=true] - Defines whether we want to keep any possible previous event listener for the same target and event name or not. * @param {boolean} [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. * @param {Object} [target=document] - The target where we want to attach the event listener. */ CB_Touch.onMove = function(callbackFunction, keepOldFunction, useCapture, target) { return CB_Touch._setEvent(\"touchmove\", callbackFunction, keepOldFunction, useCapture, target); } //Sets a function to execute when a touch event happens: CB_Touch._setEvent = function(eventName, eventFunction, keepOldFunction, useCapture, target) { //If they are not set, use default values for optional parameters: if (typeof(keepOldFunction) === \"undefined\" || keepOldFunction === null) { keepOldFunction = true; } //If not set, it keeps old function by default. if (typeof(target) === \"undefined\" || target === null) { target = document; } //If a function has been sent: if (typeof(eventFunction) === \"function\") { //If able, adds the function given to the event: CB_Events.add ( target, eventName, function(e) { e = CB_Touch.normalizeEvent(e); //TODO. if (typeof(eventFunction) === \"function\") { return eventFunction(e); } return true; }, useCapture, keepOldFunction, true ); } //...but if the function given is null, it will cancel the event: else if (eventFunction === null)// &amp;&amp; eventFunctionHolder !== null) { CB_Events.removeByName(target, eventName); } } /** * Returns the [Hammer.js]{@link https://hammerjs.github.io/} object (if any). Useful for managing touch gestures. * @function * @returns {Object} Returns the [Hammer.js]{@link https://hammerjs.github.io/} object (if any). */ CB_Touch.getHammerJSObject = function() { return CB_Touch._hammerJSObject; } /** * Returns the [Pressure.js]{@link https://pressurejs.com/} object (if any). Useful for managing [Force Touch/3D Touch]{@link https://en.wikipedia.org/wiki/Force_Touch} and [Pointer Pressure]{@link https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure} features. * @function * @returns {Object} Returns the [Pressure.js]{@link https://pressurejs.com/} object (if any). */ CB_Touch.getPressureJSObject = function() { return CB_Touch._pressureJSObject; } CB_Touch._delayTimeout = {}; CB_Touch._delayPerforming = {}; CB_Touch._delayMsDefault = 200; /** * First time, this function will return true. Next calls, with same index, returns false during the previously-defined time set in the previous call and true after that delay. After the first call, next calls of this function with same index will be ignored (returning always false) until the delay provided expires. If it is called after a previous call with the same index and the delay of the previous call already expired, it will act as it was the first call again. Useful, for example, to prevent the [onTouchStart]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/touchstart_event} event to fire twice or more when a layer (container) is closed and behind there is another one with also the [onTouchStart]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/touchstart_event} event. * @function * @param {integer} [delayMs=CB_Touch._delayMsDefault] - Delay desired in milliseconds. For same indexes, this parameter will be ignored if there was a previous call to this function whose delay did not expire yet. * @param {integer|string} [index=0] - Desired index to identify the process. * @returns {boolean} First time, this function will return true. Next calls with the same index, returns false during the given time and true after that delay. After the first call, next calls with same index of this function will be ignored (returning always false) until the delay provided expires. If it is called after a previous call with the same index and the delay of the previous call already expired, it will act as it was the first call again. */ CB_Touch.delay = function(delayMs, index) { if (!index) { index = 0; } if (CB_Touch._delayPerforming[index]) { return false; } clearTimeout(CB_Touch._delayTimeout[index]); CB_Touch._delayPerforming[index] = true; if (typeof(delayMs) === \"undefined\" || delayMs === null || isNaN(delayMs)) { delayMs = CB_Touch._delayMsDefault; } CB_Touch._delayTimeout[index] = setTimeout(function() { CB_Touch._delayPerforming[index] = false; }, delayMs); return true; } } × Search results Close "},"global.html":{"id":"global.html","title":"Global","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Global Members &lt;constant&gt; CB_BASE_NAME :string Keeps the name of the CrossBase module. Type: string Default Value: CrossBase Source: CrossBase/CrossBase.js, line 50 &lt;readonly&gt; CB_CREDITS_DEFAULT :string Default credits. Type: string Source: CrossBrowdy.js, line 299 &lt;constant&gt; CB_NAME :string Keeps the name of the script (the main script will use this name with the \".js\" extension). Case sensitive. Type: string Default Value: CrossBrowdy Source: CrossBrowdy.js, line 18 &lt;constant&gt; CB_OPTIONS :Object Two-dimensional object defined by the user with the desired options for CrossBrowdy and its modules. The options supported are the ones used by the CB_Configuration object. First-level indexes should belong to the module name (or to \"CrossBrowdy\", for general options) and second-level indexes should belong to the option name. Example: { CrossBrowdy: { CB_console_ALLOW_ALERTS: false }, CrossBase: { SLCANVAS_LOAD : true, FLASHCANVAS_LOAD : true } } Type: Object Default Value: undefined Source: CrossBrowdy.js, line 34 &lt;readonly&gt; CB_scriptPath :string It will contain the CrossBrowdy path when it finally loads. Type: string Default Value: CB_scriptPathCalculate(); Source: CrossBrowdy.js, line 145 &lt;constant&gt; CB_this :Object Keeps the CrossBrowdy \"this\" context. Type: Object Source: CrossBrowdy.js, line 32 &lt;constant&gt; CB_VERSION :string CrossBrowdy version. Type: string Source: CrossBrowdy.js, line 25 Methods CB_addCredits(credits) → {string} Attaches the given credits to the default ones (to CB_CREDITS_DEFAULT). Parameters: Name Type Description credits string Path to the JS file. Source: CrossBrowdy.js, line 313 Returns: Returns the default credits after attaching the given ones. Type string CB_baseToBase(number [, baseSymbolsOrigin] [, baseSymbolsDestiny] [, unsigned] [, minusSymbolOrigin] [, minusSymbolDestiny] [, prefixOrigin] [, prefixDestiny]) → {string} Converts a given number which is already in a desired base into another chosen base. Note: Uses CB_baseToInt and CB_intToBase internally. Parameters: Name Type Argument Default Description number string A string containing the number which is already in the desired base and that we want to convert into the another chosen base. Used as the \"number\" parameter for calling both CB_intToBase and CB_baseToInt functions internally. baseSymbolsOrigin array | integer &lt;optional&gt; CB_baseSymbols.66 Used as the \"baseSymbols\" parameter when calling the CB_baseToInt function internally. baseSymbolsDestiny array | integer &lt;optional&gt; CB_baseSymbols.66 Used as the \"baseSymbols\" parameter when calling the CB_intToBase function internally. unsigned boolean &lt;optional&gt; false Determines whether to treat the input and output numbers as unsigned or not. Used as the \"unsigned\" parameter for calling both CB_intToBase and CB_baseToInt functions internally. minusSymbolOrigin string &lt;optional&gt; '-'|'0' Used as the \"minusSymbol\" parameter when calling the CB_baseToInt function internally. minusSymbolDestiny string &lt;optional&gt; '-'|'0' Used as the \"minusSymbol\" parameter when calling the CB_intToBase function internally. prefixOrigin prefix &lt;optional&gt; '0'|'0x'|'' Used as the \"prefix\" parameter when calling the CB_baseToInt function internally. prefixDestiny prefix &lt;optional&gt; '0'|'0x'|'' Used as the \"prefix\" parameter when calling the CB_intToBase function internally. Source: CrossBase/general/CB_data.js, line 1421 To Do: Think about accepting a decimal symbol to separate decimals and support float numbers. Returns: Returns the returning value of the internal call to the CB_intToBase function. Type string CB_baseToInt(number [, baseSymbols] [, unsigned] [, minusSymbol] [, prefix]) → {integer} Converts a given number which is already in a desired base into an integer (decimal base). Note: It can return wrong values when the value exceeds the maximum allowed by a number in the client's JavaScript engine. It can also depend on the \"baseSymbols\" used. Parameters: Name Type Argument Default Description number string A string containing the number which is already in the desired base and that we want to convert to an integer. baseSymbols array | integer &lt;optional&gt; CB_baseSymbols.66 Array with the desired symbols, using only one per index (their value will correspond to their index). The base (radix) will be the total number of indexes. It should be the base which is already being used by the given number. If an integer greater or equal than 2 is provided, it will try to use it as an index of the CB_baseSymbols object and use it if found or use it as a parameter to call the CB_baseSymbols.get function otherwise. If not provided or the integer is lower than 2, it will use base 66 (defined in the CB_baseSymbols._66 property of the CB_baseSymbols object). It is recommended not to exceed 4096 (or even lower, depending on the client, although some clients could support up to 63988 or even more). The properties of the CB_baseSymbols object or the CB_baseSymbols.get function can be used for this parameter. unsigned boolean &lt;optional&gt; false Determines whether to treat the input and output numbers as unsigned or not. minusSymbol string &lt;optional&gt; '-'|'0' Determines the minus symbol or string for the input, to mark negative numbers. If not provided, it will be '-' for bases equal or lower than 16 (hexadecimal) or '0' (zero character) otherwise. This parameter is ignored if the \"unsigned\" parameter is set to true. prefix prefix &lt;optional&gt; '0'|'0x'|'' Determines the prefix for the input. If not provided, it will be '0' (zero character) for base 8 (octal), '0x' for base 16 (hexadecimal) or nothing (empty string) for all the others. Use an empty string to avoid using anything. Source: CrossBase/general/CB_data.js, line 1349 To Do: Think about allowing to return a string, for bigger numbers (to exceed the limit for integers). Internally, it would need to perform operations comparisons, multiplications with strings, etc. Think about allowing to specify the base for the integer. Think about accepting a decimal symbol to separate decimals and support float numbers. Returns: Returns the integer number in decimal base. Type integer CB_br2nl(string) → {string} Changes &lt;br /&gt;'s, &lt;br/&gt;'s and &lt;br&gt;'s for new lines (\\n) in a given string. Parameters: Name Type Description string string The string we want to modify. Source: CrossBase/general/CB_data.js, line 442 Returns: Returns the string with all the occurrences replaced or an empty string if the element given was not a string. Type string CB_brToNl() Alias for CB_br2nl. Source: CrossBase/general/CB_data.js, line 431 See: CB_br2nl CB_combineArraysOrObjects( [arrayOrObjectA] [, arrayOrObjectB], avoidDuplicatedValuesInArray [, modifyArrayOrObjectA]) → {array|Object} Returns a combined array or object from two arrays or objects. Using the following rules: If they both are arrays (numeric indexes), it will keep all elements (attaching the elements of the second array after the elements of the first one). Otherwise, if either of them is not an array (it should be an associative array which is an object in JavaScript), it will merge the elements (overwritting those whose index is the same and keeping the ones from the second array/object): Parameters: Name Type Argument Default Description arrayOrObjectA array | Object | string | null | undefined &lt;optional&gt; []|{} One of the arrays (numeric indexes) or associative arrays (object) that we want to combine. If a string is provided, it will try to convert it into a new object (the string should be a JSON-valid string). It can be optional if \"arrayOrObjectB\" is a valid value and neither null nor undefined. If not provided but the \"arrayOrObjectB\" is provided, it will be a new empty array if the \"arrayOrObjectB\" is an array or it will be an empty object otherwise. arrayOrObjectB array | Object | string | null | undefined &lt;optional&gt; []|{} One of the arrays (numeric indexes) or associative arrays (object) that we want to combine. If a string is provided, it will try to convert it into a new object (the string should be a JSON-valid string). It can be optional if \"arrayOrObjectA\" is a valid value and neither null nor undefined. If not provided but the \"arrayOrObjectA\" is provided, it will be a new empty array if the \"arrayOrObjectA\" is an array or it will be an empty object otherwise. avoidDuplicatedValuesInArray boolean Tells whether to avoid or allow items with duplicated values in the returned array or not. Only applies when both arrays to combine are numeric arrays. modifyArrayOrObjectA boolean &lt;optional&gt; false Parameter that will be used in the case that CB_combineJSON or CB_combineArraysOrObjects is called. If set to true, it will modify the original \"arrayOrObjectA\" array or object. Source: CrossBase/general/CB_data.js, line 1007 Returns: Type array | Object CB_combineAutomatically( [a] [, b] [, avoidDuplicatedValuesInArray] [, modifyArrayOrObjectA]) → {*} Tries to combine two given values guessing the best way to do it and returns their combination. Using the following rules: If both values are either undefined or null, returns null. Otherwise, if both values are boolean, returns the AND operation for the two of them (a &amp;&amp; b). Otherwise, if either of the two is a string (not empty) and is not JSON valid, combines them as URL (GET) parameters using CB_combineURIParameters. Otherwise, if either of them is JSON valid, combines them as JSON using CB_combineJSON (passing the received avoidDuplicatedValuesInArray value as a parameter). Otherwise, combines them as arrays or objects using CB_combineArraysOrObjects (passing the received \"avoidDuplicatedValuesInArray\" value as a parameter). Parameters: Name Type Argument Default Description a * &lt;optional&gt; null|[]|{} First value. It can be optional if \"b\" is a valid value, defined and not null. b * &lt;optional&gt; null|[]|{} Second value. It can be optional if \"a\" is a valid value, defined and not null. avoidDuplicatedValuesInArray boolean &lt;optional&gt; false Parameter that will be used in the case that CB_combineJSON or CB_combineArraysOrObjects is called. modifyArrayOrObjectA boolean &lt;optional&gt; false Parameter that will be used in the case that CB_combineJSON or CB_combineArraysOrObjects is called. If set to true, it will modify the original \"a\" array or object. Source: CrossBase/general/CB_data.js, line 952 Returns: Type * CB_combineJSON() Alias for CB_combineArraysOrObjects. Source: CrossBase/general/CB_data.js, line 1089 See: CB_combineArraysOrObjects CB_combineURIParameters(parametersA, parametersB) → {string} Combines two strings as URL (GET) parameters. If either \"parametersA\" or \"parametersB\" is not a string, internally it will use the native JSON.stringify method if available or otherwise it will use JSON 3 instead. Parameters: Name Type Description parametersA string String with the desired parameter or parameters. It can be optional if \"parametersB\" is a valid string. It will trim any \"&amp;\" and \"?\" character at the beginning and at the end, and finally use \"&amp;\" to concatenate the two strings (if needed). parametersB string String with the desired parameter or parameters. It can be optional if \"parametersA\" is a valid string. It will trim any \"&amp;\" and \"?\" character at the beginning and at the end, and finally use \"&amp;\" to concatenate the two strings (if needed). Source: CrossBase/general/CB_data.js, line 981 Returns: For example, if parametersA is \"parameter1=value1&amp;parameter2=value2\" and parametersB is \"parameter3=value3&amp;what=ever\" then it will return \"parameter1=value1&amp;parameter2=value2&amp;parameter3=value3&amp;what=ever\". Type string CB_combineURLParameters() Alias for CB_combineURIParameters. Source: CrossBase/general/CB_data.js, line 969 See: CB_combineURIParameters CB_console(message) Alias for the \"console\" function which fallbacks to a DOM element with \"CB_console\" id (its CSS \"style\" attribute will be modified if needed, which means that its \"display\" property will be set to \"block\" if it is \"none\" and its \"visibility\" property to \"visible\" regardless its previous value) or even to an alert when it is not available (\"alert\" will only be used as a fallback in the case that the CB_console_ALLOW_ALERTS parameter is set to true). Parameters: Name Type Description message string Message to display Source: CrossBrowdy.js, line 325 To Do: When \"console\" is not available and it gets polyfilled, allow more parameters (use \"arguments\"). CB_copyObject(element [, onlyOwn]) → {object} Returns an object copied from the given one. Parameters: Name Type Argument Default Description element object The element whose properties and values we want to copy. It should be an object. onlyOwn boolean &lt;optional&gt; false If the \"element\" given is not an object, this parameter will be ignored. Otherwise, if it is set to true, it will only have into account the properties which the object has as their own property and have not been inherited (using the Object.hasOwnProperty method). Source: CrossBase/general/CB_data.js, line 837 Returns: Returns an object copied from the given one. Returns an empty object if the given \"element\" was not an object. Type object CB_countDecimalDigits() Alias for CB_countDecimalPart. Source: CrossBase/general/CB_data.js, line 598 See: CB_countDecimalPart CB_countDecimalPart(number) → {integer} Returns the number of decimals of the given number. It also works with numbers in exponential notation (as for example '1e-13' which would be 0.0000000000001). Parameters: Name Type Description number integer | float | string The number whose decimals we want to count. It can be a string. Source: CrossBase/general/CB_data.js, line 619 Returns: Returns zero in the case a non-valid number has been provided. Otherwise, it returns the number of decimals counted. Type integer CB_countDecimals() Alias for CB_countDecimalPart. Source: CrossBase/general/CB_data.js, line 593 See: CB_countDecimalPart CB_countIntegerDigits() Alias for CB_countIntegerPart. Source: CrossBase/general/CB_data.js, line 644 See: CB_countIntegerPart CB_countIntegerPart(number) → {integer} Returns the number of integer digits (the number of digits that belong to the integer part) of the given number. It also works with numbers in exponential notation (as for example '1e-13' which would be 0.0000000000001). Parameters: Name Type Description number integer | float | string The number whose integer digits (the digits that belong to the integer part) we want to count. It can be a string. Source: CrossBase/general/CB_data.js, line 655 Returns: Returns zero in the case a non-valid number has been provided. Otherwise, it returns the number of integer digits (the number of digits that belong to the integer part) counted. Type integer CB_credits( [credits] [, html] [, showPrefix]) → {string} Returns the credits with the desired format. Parameters: Name Type Argument Default Description credits string &lt;optional&gt; CB_CREDITS_DEFAULT Desired credits to be shown. html boolean &lt;optional&gt; true Strips all HTML tags (if any) when it is false. showPrefix boolean &lt;optional&gt; true Defines whether to show the \"[CB]\" prefix for every line or not (it will remove all \"[CB]\" occurrences if it is false). Source: CrossBrowdy.js, line 1122 Returns: Type string CB_forceString(element) → {string} Returns back the given element if it is a string or an empty string otherwise. Parameters: Name Type Description element * The element that will be checked. Source: CrossBase/general/CB_data.js, line 238 Returns: Type string CB_forEach(array, callback [, thisArg] [, extendedDOM]) → {array|undefined} Implementation of the Array.forEach method for browsers that do not support it natively. Executes a function for each element of a given array. Parameters: Name Type Argument Default Description array array Desired array. callback function Function that will be executed for each element of the given array. Following the same rules as the native Array.forEach method, it will receive three arguments: currentValue, currentIndex and the array given. thisArg * &lt;optional&gt; Value that will be passed as \"this\" every time the function is called. extendedDOM boolean &lt;optional&gt; false Defines whether the function is being called by a native function which was extended. Internal usage recommended only. Source: CrossBase/general/CB_data.js, line 136 Returns: If the \"extendedDOM\" parameter is set to false, returns the given \"array\" again. Otherwise, returns undefined. Type array | undefined CB_getBase64StringObject() → {Object} Returns the \"Base64String\" object (used by the base64-string library included in lz-string), if any. Useful for compressing/decompressing base64 code. Source: CrossBase/general/CB_data.js, line 1495 Returns: Returns the \"Base64String\" object (used by the base64-string library included in lz-string) if available or null otherwise. Type Object CB_getCookie(index) → {string|null} Returns, from its index, a previous stored cookie. Parameters: Name Type Description index string The index whose value we want to retrieve. Source: CrossBase/general/CB_data.js, line 809 Returns: Returns null when the value cannot be found. Type string | null CB_getDatum(index [, forceCookie] [, unescapeIndex]) → {string|null} Gets, from its index, a previous value stored. It will try to get it using Web Storage API (localStorage). It can use localStorage as a fallback or cookies instead. Parameters: Name Type Argument Default Description index string The index whose value we want to retrieve. forceCookie boolean &lt;optional&gt; false Forces to use cookies instead of Web Storage API (localStorage). unescapeIndex boolean &lt;optional&gt; false Applies the unescape function to the value before returning it. Only applies when cookies are used. Source: CrossBase/general/CB_data.js, line 778 Returns: Returns null when the value cannot be found. Type string | null CB_getJSONPropertyValue(JSONObject, property [, returnValueOnFail]) → {*} Gets the value of a desired property of a given JSON object. Uses the CB_getValueIndex function internally. Parameters: Name Type Argument Description JSONObject Object | string The JSON object from which we want to get the value. If it is a string, it will try to parse it to create a real object from it. Used as the \"object\" parameter when calling the CB_getValueIndex function internally. property string The property whose value we want to retrieve. If not provided, the given object will be returned again. Used as the \"index\" parameter when calling the CB_getValueIndex function internally. returnValueOnFail * &lt;optional&gt; The value we want it to return in the case it cannot be parsed. If not provided, undefined will be returned. Used as the \"returnValueOnFail\" parameter when calling the CB_getValueIndex function internally. Source: CrossBase/general/CB_data.js, line 857 Returns: Returns the given \"JSONObject\" again (after trying to parse it if it was a string, if possible) if the \"property\" value was not given. Returns the value from the given object which belongs to the desired property or the value of \"returnValueOnFail\" otherwise if it cannot be found. Type * CB_getLZStringObject() → {Object} Returns the \"LZString\" object (used by the lz-string library), if any. Useful for compressing/decompressing strings. Source: CrossBase/general/CB_data.js, line 1484 Returns: Returns the \"LZString\" object (used by the lz-string library) if available or null otherwise. Type Object CB_getValueIndex(object, index [, returnValueOnFail]) → {*} Gets the value from a given object which belongs to the desired index or returns the value of \"returnValueOnFail\" if it cannot be found. Parameters: Name Type Argument Description object Object The object from which we want to get the value. index string The index whose value we want to retrieve. returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that the property cannot be found. If not provided, undefined will be returned. Source: CrossBase/general/CB_data.js, line 823 Returns: Returns the value from a given object which belongs to the desired index or the value of \"returnValueOnFail\" otherwise if it cannot be found. Type * CB_getValuePath(object, path [, splitString]) → {*} Returns the value of a desired path in an object or an empty string if it cannot be found. Parameters: Name Type Argument Default Description object Object The object where we want to find the path. path string The path that will be search in the given object to retrieve the value. It should use the string defined in the \"splitString\" parameter to separate items. If it is empty or not provided, it will just return the given \"object\" again. splitString string &lt;optional&gt; \".\" The string that will be used to separate one item from another one. By default, it will be a dot (\".\") so, for example, a given \"path\" with a value of \"hello.world\" will indicate the \"object.hello.world\" path. Source: CrossBase/general/CB_data.js, line 684 Returns: Returns the value of a desired path in an object or an empty string if it cannot be found. If the \"path\" parameter is empty or not provided, it will just return the given \"object\" again. Type * CB_includeJSFile(filepath [, callbackOk] [, callbackError] [, timeoutMs] [, asynchronously] [, fileId] [, fileRequires] [, notMandatory]) → {Object|null|false} Includes a JavaScript file to the current document. Parameters: Name Type Argument Default Description filepath string Path to the JS file. callbackOk CB_includeJSFile_CALLBACK &lt;optional&gt; Callback for when the file is included successfully. callbackError CB_includeJSFile_CALLBACK &lt;optional&gt; Callback for when there is any error including the file or it cannot be included after the defined timeout. timeoutMs integer &lt;optional&gt; CB_Configuration.CrossBrowdy.CB_includeJSFile_TIMEOUT_MS_DEFAULT Timeout in milliseconds to consider that the inclusion of the file has failed. asynchronously boolean &lt;optional&gt; true Defines whether to load the file asynchronously or not. fileId string &lt;optional&gt; Internal usage recommended only. fileRequires array &lt;optional&gt; Internal usage recommended only. notMandatory boolean &lt;optional&gt; false Internal usage recommended only. Source: CrossBrowdy.js, line 383 Returns: Returns null when the script file cannot be loaded yet as some required file has still not been loaded. Returns false when neither the 'HEAD' tag nor the document body can be found. Otherwise, returns an object whose two properties are 'scriptElement' (with the SCRIPT element just created) and 'timeoutFailure' (with the setTimeout ID created to check whether the file cannot be loaded after the given time). Type Object | null | false CB_indexOf(array, searchElement [, fromIndex] [, extendedDOM]) → {integer} Implementation of Array.indexOf method for arrays in browsers that do not support it natively. Returns the first index of a given element that exists in an array (starting from a certain index if desired) or -1 if not found. Parameters: Name Type Argument Default Description array array Desired array. searchElement * Element we want to search. Note that it is type sensitive. fromIndex integer &lt;optional&gt; 0 First index of the given array where the search will start. extendedDOM boolean &lt;optional&gt; false Defines whether the function is being called by a native function which was extended. Internal usage recommended only. Source: CrossBase/general/CB_data.js, line 87 Returns: Type integer CB_init( [mainFunction] [, scriptPath] [, onErrorLoadingFile] [, showSplashScreen]) Starts CrossBrowdy. Parameters: Name Type Argument Default Description mainFunction CB_init_CALLBACK &lt;optional&gt; Callback for when CrossBrowdy is loaded successfully. Recommended. scriptPath string &lt;optional&gt; CB_scriptPathCalculate() Path where the main script is located. If not provided (it is undefined or null), it will try to calculate it calling the CB_scriptPathCalculate function internally. onErrorLoadingFile CB_includeRequiredFileErrorCallback &lt;optional&gt; Function to call when any of the required files fails to load (because of an error or because its timeout was fired). It could be called more than once, for each file which failed loading. If a function is provided, it will be stored in the global 'CB_initOnErrorLoadingFile' variable. showSplashScreen boolean &lt;optional&gt; CB_Configuration.CrossBrowdy.SHOW_SPLASH_SCREEN_DEFAULT Defines whether to show the splash screen or not. Source: CrossBrowdy.js, line 1048 CB_intToBase(number [, baseSymbols] [, unsigned] [, minusSymbol] [, prefix]) → {string} Converts a given integer into a desired base. Parameters: Name Type Argument Default Description number integer | string The integer that we want to convert to the desired base. For bigger numbers (up to 999999999999999934464 or even lower, depending on the client and the \"baseSymbols\" used), it is recommended to use a string which will allow to accept a slightly bigger number (up to 999999999999999999999999 or lower, depending on the client and the \"baseSymbols\" used). Really big numbers will not be codified properly even when passed as a string due to the limitations of JavaScript engines and maximum number allowed to be stored in a variable. baseSymbols array | integer &lt;optional&gt; CB_baseSymbols.66 Array with the desired symbols, using only one per index (their value will correspond to their index). The base (radix) will be the total number of indexes. If an integer greater or equal than 2 is provided, it will try to use it as an index of the CB_baseSymbols object and use it if found or use it as a parameter to call the CB_baseSymbols.get function otherwise. If not provided or the integer is lower than 2, it will use base 66 (defined in the CB_baseSymbols._66 property of the CB_baseSymbols object). It is recommended not to exceed 4096 (or even lower, depending on the client, although some clients could support up to 63988 or even more). The properties of the CB_baseSymbols object or the CB_baseSymbols.get function can be used for this parameter. unsigned boolean &lt;optional&gt; false Determines whether to treat the input and output numbers as unsigned or not. minusSymbol string &lt;optional&gt; '-'|'0' Determines the minus symbol or string for the output, to mark negative numbers. If not provided, it will be '-' for bases equal or lower than 16 (hexadecimal) or '0' (zero character) otherwise. This parameter is ignored if the \"unsigned\" parameter is set to true. prefix prefix &lt;optional&gt; '0'|'0x'|'' Determines the prefix for the output. If not provided, it will be '0' (zero character) for base 8 (octal), '0x' for base 16 (hexadecimal) or nothing (empty string) for all the others. Use an empty string to avoid using anything. Source: CrossBase/general/CB_data.js, line 1288 To Do: Think about allowing the \"number\" parameter to be a very long string, for bigger numbers (to exceed the limit for integers). Internally, it would need to perform operations comparisons, divisions, remainder calculation with strings, etc. Think about allowing to specify the base for the integer (now it is 16 if it begins with \"0x\", 8 if it begins with \"0\" and it is not a string or 10 otherwise, and newer clients can support '0b' for binaries, '0o' for octals, ). Think about accepting a decimal symbol to separate decimals and support float numbers. Returns: Returns an empty string in the case that the given number cannot be parsed as an integer. Otherwise, returns the given number in the desired base as a string. Type string CB_isArray(element [, extendedDOM]) → {boolean} Implementation of Array.isArray method for browsers that do not support it natively. Returns whether a given element is an array or not. Parameters: Name Type Argument Default Description element * The element we want to check. extendedDOM boolean &lt;optional&gt; false Defines whether the function is being called by a native function which was extended. Internal usage recommended only. Source: CrossBase/general/CB_data.js, line 172 To Do: Think about a parameter to check whether the given array is a typed array (for example, 'Uint8Array') or not. Returns: Type boolean CB_isEmail(email) → {boolean} Tells whether a given email is valid or not. Not really precise. Parameters: Name Type Description email string Possible email that we want to validate. Source: CrossBase/general/CB_data.js, line 552 Returns: Type boolean CB_isFileLocal(filePath) → {boolean} Tries to guess whether a given file path (absolute or relative) is a local address or not. It will be assumed as local if the path uses the \"file:\" protocol or the current script is running locally and the path does not use the \"http:\", \"https:\" or \"ftp:\" protocols. Parameters: Name Type Description filePath string The file path we want to check. Source: CrossBase/general/CB_data.js, line 466 Returns: Returns whether the given file path is a local address or not. Type boolean CB_isString(element) → {boolean} Returns whether a given element is a string or not. Parameters: Name Type Description element * The element we want to check. Source: CrossBase/general/CB_data.js, line 226 Returns: Type boolean CB_lastIndexOf(array, searchElement [, fromIndex] [, extendedDOM]) → {integer} Implementation of Array.lastIndexOf method for browsers that do not support it natively. Returns the last index of a given element that exists in an array (starting from a certain index if desired) or -1 if not found. Parameters: Name Type Argument Default Description array array Desired array. searchElement * Element we want to search. Note that it is type sensitive. fromIndex integer &lt;optional&gt; array.length - 1 First index of the given array where the search will start. extendedDOM boolean &lt;optional&gt; false Defines whether the function is being called by a native function which was extended. Internal usage recommended only. Source: CrossBase/general/CB_data.js, line 38 To Do: Implement the \"fromIndex\" in the polyfill. Returns: Type integer CB_ltrim(element [, undesiredStrings]) → {string|array} Trims the left side of a given string or array of strings (modifying the given array), taking off the desired strings or otherwise trimming spaces, tabs (\"\\t\"), new lines (\"\\n\") and carriage returns (\"\\r\"). Case sensitive. Parameters: Name Type Argument Default Description element string | array The element that will be trimmed. It should be either a string or an array of strings. undesiredStrings string | array &lt;optional&gt; [ \" \", \"\\n\", \"\\r\", \"\\t\" ] String or an array with the strings that we want to trim off the given element. Source: CrossBase/general/CB_data.js, line 362 To Do: Accept a \"recursive\" parameter (boolean) to affect multiple levels (array of arrays of strings, etc.). Consider accepting objects instead of arrays in the \"element\" parameter. Think about optimizing (using a counter for the number of occurrences in the loop and trim all the occurrences when finished). Returns: Returns the given element again if it was an string, a number (it will be casted to a string) or an array of strings, trimmed if it has been possible. If it was another type, returns an empty string. Type string | array CB_nl2br(string) → {string} Changes new lines (\\n) for &lt;br /&gt;'s in a given string. Parameters: Name Type Description string string The string we want to modify. Source: CrossBase/general/CB_data.js, line 416 Returns: Returns the string with all the occurrences replaced or an empty string if the element given was not a string. Type string CB_nlToBr() Alias for CB_nl2br. Source: CrossBase/general/CB_data.js, line 405 See: CB_nl2br CB_numberFormat(number [, decimals] [, stringify]) → {integer|float|string} Returns the given number with the desired decimals and make it a string if we want to (so it will be able to have trailing zeros). Uses decimal numeral system only. It will perform ceiling round automatically if needed. Parameters: Name Type Argument Default Description number integer | float | string The number that we want to format. It can be a string. decimals integer &lt;optional&gt; 2 The number of decimals we want to allow. stringify boolean &lt;optional&gt; false Set to true if we want it to return a string (filled with trailing zeros to reach the desired number of decimals). Source: CrossBase/general/CB_data.js, line 567 To Do: Allow to define a minimum length for the integer part of the \"number\" parameter, so it will fill with leading zeros if needed (when \"stringify\" is set to true). Think about allowing to define a maximum too. Returns: Returns zero in the case a non-valid number has been provided. Type integer | float | string CB_numberOfDecimalDigits() Alias for CB_countDecimalPart. Source: CrossBase/general/CB_data.js, line 608 See: CB_countDecimalPart CB_numberOfDecimals() Alias for CB_countDecimalPart. Source: CrossBase/general/CB_data.js, line 603 See: CB_countDecimalPart CB_numberOfIntegerDigits() Alias for CB_countIntegerPart. Source: CrossBase/general/CB_data.js, line 639 See: CB_countIntegerPart CB_parseJSON(objectString [, reviver] [, returnValueOnFail] [, acceptUndefinedOrNull] [, onError]) → {*} Tries to parse a given string to convert it into a JSON object. Internally it will use the native JSON.parse method or otherwise use JSON 3 instead. Parameters: Name Type Argument Default Description objectString string The JSON object we want to parse, in string format. First parameter when calling the JSON.parse method (or equivalent) reviver function &lt;optional&gt; Second parameter when calling the JSON.parse method (or equivalent). returnValueOnFail * &lt;optional&gt; The value we want it to return in the case it cannot be parsed. If not provided, undefined will be returned. acceptUndefinedOrNull boolean &lt;optional&gt; false If it is set to true and the given objectString is undefined or null, an empty object ({}) will be used as the objectString. onError function &lt;optional&gt; Callback which will be called if it failed to be parsed (it will receive the \"objectString\" as the unique parameter). Source: CrossBase/general/CB_data.js, line 889 Returns: Returns the object parsed from the given string or the value of \"returnValueOnFail\" otherwise (which will be undefined if not provided). Type * CB_parseString(element) → {string} Returns back the given element as a string if it could be parsed or an empty string otherwise. Parameters: Name Type Description element * The element that will be checked. Source: CrossBase/general/CB_data.js, line 251 Returns: Type string CB_regularExpressionString(string [, allOccurrences] [, caseInsensitive]) → {RegExp} Returns a desired regular expression (escaping the string) using the native JavaScript's RegExp from a given string. Parameters: Name Type Argument Default Description string string The string (not a regular expression) that we want to use (special characters will be escaped). allOccurrences boolean &lt;optional&gt; false Defines whether we want the regular expression returned to match all occurrences of the given string or only first found. caseInsensitive boolean &lt;optional&gt; false Defines whether we want the regular expression returned to be case insensitive or not. Source: CrossBase/general/CB_data.js, line 1470 Returns: Returns the desired regular expression (escaping the string) using the native JavaScript's RegExp from a given string. Type RegExp CB_renderString(str [, JSONObject] [, forceVanilla] [, depthLevelMax]) → {str} Processes a given string as a template and returns it rendered (if possible) with the values of the given JSON object. Tries to use Handlebars as the first choice but if is is not available it will just replace all occurrences with vanilla JavaScript. Parameters: Name Type Argument Default Description str string The string we want to render. JSONObject Object &lt;optional&gt; CB_JSONData The JSON object which contains the values. If not provided, it will try to use the global CB_JSONData object in the case it exists. forceVanilla boolean &lt;optional&gt; false Forces vanilla JavaScript rendering instead of using Handlebars. depthLevelMax integer &lt;optional&gt; 10 Maximum depth level allowed to read the object to render the string. Only applies when it is rendered by vanilla JavaScript. For performance purposes. Source: CrossBase/general/CB_data.js, line 495 Returns: Type str CB_replaceAll(stringOrArray, stringOrArrayFind [, stringReplace] [, caseInsensitive]) → {string|array} Returns the string or array of strings with all the desired occurrences replaced. Calls itself recursively and calls the CB_regularExpressionString function internally. Parameters: Name Type Argument Default Description stringOrArray string | array An string or an array of strings whose content we want to replace. It can also be an array of arrays of strings (as many levels as you wish). If an array is given, it will not be modified and a copy from it will be generated and returned with the occurrences replaced. stringOrArrayFind string | array An string or an array of strings (not a regular expressions) that we want to find to be replaced (special characters will be escaped). stringReplace string &lt;optional&gt; \"\" The string that will replace \"stringFind\". If not provided, it will be replaced as an empty string (it will just remove the occurrences found). caseInsensitive boolean &lt;optional&gt; false Defines whether we want to be case insensitive or not. Source: CrossBase/general/CB_data.js, line 1437 Returns: Returns the \"stringOrArray\" given with occurrences replaced. If the \"stringOrArray\" given was neither a string nor an array, it will be returned without being modified. Type string | array CB_rtrim(element [, undesiredStrings]) → {string|array} Trims the right side of a given string or array of strings (modifying the given array), taking off the desired strings or otherwise trimming spaces, tabs (\"\\t\"), new lines (\"\\n\") and carriage returns (\"\\r\"). Case sensitive. Parameters: Name Type Argument Default Description element string | array The element that will be trimmed. It should be either a string or an array of strings. undesiredStrings string | array &lt;optional&gt; [ \" \", \"\\n\", \"\\r\", \"\\t\" ] String or an array with the strings that we want to trim off the given element. Source: CrossBase/general/CB_data.js, line 309 To Do: Accept a \"recursive\" parameter (boolean) to affect multiple levels (array of arrays of strings, etc.). Consider accepting objects instead of arrays in the \"element\" parameter. Think about optimizing (using a counter for the number of occurrences in the loop and trim all the occurrences when finished). Returns: Returns the given element again if it was an string, a number (it will be casted to a string) or an array of strings, trimmed if it has been possible. If it was another type, returns an empty string. Type string | array CB_scriptPathCalculate() → {string} Tries to calculate and returns the path where the script is located. Source: CrossBrowdy.js, line 1004 Returns: If it cannot be calculated, it will returns the value of CB_Configuration[CB_NAME].SCRIPT_PATH_DEFAULT. Type string CB_setCookie(index, value [, days] [, path]) → {boolean} Stores a cookie. Parameters: Name Type Argument Description index string | number The index where the value given will be stored. value string | number The value we want to store. It should be a string or a number. days integer &lt;optional&gt; The number of days after which the cookie will expire. It belongs to the \"expires=\" parameter of the cookie. If not provided, the parameter will not be used at all. path string &lt;optional&gt; The path where the cookie will be stored. It belongs to the \"path=\" parameter of the cookie. If not provided, the parameter will not be used at all. Source: CrossBase/general/CB_data.js, line 764 Returns: Returns true if the value has been stored successfully (not totally reliable, it should be checked with CB_getCookie after a while). Type boolean CB_setDatum(index, value [, days] [, path] [, forceCookie]) → {boolean} Stores a value using Web Storage API (localStorage). It can use localStorage as a fallback or cookies instead. Parameters: Name Type Argument Default Description index string | number The index where the value given will be stored. value string | number The value we want to store. It should be a string or a number. days integer &lt;optional&gt; The number of days after which the cookie will expire (in the case that cookies are used). It belongs to the \"expires=\" parameter of the cookie. If not provided, the parameter will not be used at all. path string &lt;optional&gt; The path where the cookie will be stored (in the case that cookies are used). It belongs to the \"path=\" parameter of the cookie. If not provided, the parameter will not be used at all. forceCookie boolean &lt;optional&gt; false Forces to use cookies instead of Web Storage API (localStorage). Source: CrossBase/general/CB_data.js, line 718 Returns: Returns true if the value has been stored successfully (not totally reliable, it should be checked with CB_getDatum after a while). Type boolean CB_sizeof() Alias for CB_sizeOf. Source: CrossBase/general/CB_data.js, line 195 See: CB_sizeOf CB_sizeOf(element [, onlyOwn]) → {integer} Returns the size of an object or array. Parameters: Name Type Argument Default Description element Object | array The element whose size we want to know. It should be an object or an array. onlyOwn boolean &lt;optional&gt; false If the \"element\" given is not an object, this parameter will be ignored. Otherwise, if it is set to true, it will only have into account the properties which the object has as their own property and have not been inherited (using the Object.hasOwnProperty method). Source: CrossBase/general/CB_data.js, line 207 Returns: If an object is provided, the size will be the number of its properties. Otherwise, if an array is given, the size will be the numbers of its indexes (Array.length property). Type integer CB_stringifyJSON(objectOrValue [, replacer] [, space] [, returnValueOnFail] [, failIfUndefinedOrNull] [, onError]) → {string} Tries to create a JSON valid string from a given JSON object or value. Internally it will use the native JSON.stringify method or otherwise use JSON 3 instead. Parameters: Name Type Argument Default Description objectOrValue * The object or value that we want to stringify. First parameter when calling the JSON.stringify method (or equivalent). replacer function &lt;optional&gt; Second parameter when calling the JSON.stringify method (or equivalent). space string | integer &lt;optional&gt; Third parameter when calling the JSON.stringify method (or equivalent). returnValueOnFail * &lt;optional&gt; The value we want it to return in the case it cannot be stringify. If not provided, undefined will be returned. failIfUndefinedOrNull boolean &lt;optional&gt; false If it is set to true and the returning value is undefined or null, the value of \"returnValueOnFail\" will be returned. onError function &lt;optional&gt; Callback which will be called if it failed to be stringified (it will receive the \"objectOrValue\" as the unique parameter). Source: CrossBase/general/CB_data.js, line 917 Returns: Returns the object stringified from the given object or value if possible or the value of \"returnValueOnFail\" otherwise (which will be undefined if not provided). Avoids returning undefined or null if \"failIfUndefinedOrNull\" is set to true, returning the value of \"returnValueOnFail\" instead. Type string CB_symmetricCall(callbackFunction, timeMs [, id]) → {number|null} Calls the given function once through the native setTimeout function internally but having in mind the time taken when the function was called previously so it can be called multiple times and respect a symmetric interval between each call (simulates requestAnimationFrame). Parameters: Name Type Argument Default Description callbackFunction CB_symmetricCall_CALLBACK Function that will be called every time, receiving as the unique parameter the time (timestamp in milliseconds returned by the performance.now method, which could have been polyfilled automatically by CrossBrowdy) when it is called, being \"this\" the same \"this\" of the scope where it was called. timeMs integer Milliseconds between one call to the function and the next one. The accuracy will depend on many factors as the platform used, code performance, etc. id string &lt;optional&gt; callbackFunction.toString() String that will identify this symmetric interval. Recommended to avoid possible problems. Source: CrossBase/general/CB_others.js, line 25 Returns: Returns a numeric identifier generated by an internal call to the native setTimeout function (can be cleared/cancelled with clearTimeout). Returns null if the given \"callbackFunction\" is not a valid function. Type number | null CB_symmetricCallClear(id) → {boolean|null} Clears the stored last time used by CB_symmetricCall for a given symmetric interval identifier. Parameters: Name Type Description id string String that identifies this symmetric interval. Source: CrossBase/general/CB_others.js, line 73 Returns: Returns null if the given \"id\" is not a valid string. Returns false if the stored time did not exist for the given \"id\" or it was cleared already. Returns true otherwise, after clearing it. Type boolean | null CB_trim(element [, undesiredStrings]) → {string|array} Trims a given string or array of strings (modifying the given array), taking off the desired strings or otherwise trimming spaces, tabs (\"\\t\"), new lines (\"\\n\") and carriage returns (\"\\r\"). Case sensitive. Parameters: Name Type Argument Default Description element string | array The element that will be trimmed. It should be either a string or an array of strings. undesiredStrings string | array &lt;optional&gt; [ \" \", \"\\n\", \"\\r\", \"\\t\" ] String or an array with the strings that we want to trim off the given element. Source: CrossBase/general/CB_data.js, line 267 To Do: Accept a \"recursive\" parameter (boolean) to affect multiple levels (array of arrays of strings, etc.). Consider accepting objects instead of arrays in the \"element\" parameter. Returns: Returns the given element again if it was an string, a number (it will be casted to a string) or an array of strings, trimmed if it has been possible. If it was another type, returns an empty string. Type string | array Type Definitions CB_includeJSFile_CALLBACK(filepath, callbackOk, callbackError, timeoutMs, asynchronously) Callback for when the file is included successfully or fails to load. Parameters: Name Type Description filepath string The 'filepath' parameter when CB_includeJSFile was called (if any). callbackOk CB_includeJSFile_CALLBACK The 'callbackOk' parameter when CB_includeJSFile was called (if any). callbackError CB_includeJSFile_CALLBACK The 'callbackError' parameter when CB_includeJSFile was called (if any). timeoutMs integer The 'timeoutMs' parameter when CB_includeJSFile was called (if any). asynchronously boolean The 'asynchronously' parameter when CB_includeJSFile was called (if any). Source: CrossBrowdy.js, line 360 CB_includeRequiredFileErrorCallback(filepath, callbackOk, callbackError, timeoutMs, asynchronously, filesRequested, filesLoaded) Callback for when the script is loaded successfully. Without parameters. Parameters: Name Type Description filepath string The 'filepath' parameter when CB_includeJSFile was called internally (if any). callbackOk CB_includeJSFile_CALLBACK The 'callbackOk' parameter when CB_includeJSFile was called internally (if any). callbackError CB_includeJSFile_CALLBACK The 'callbackError' parameter when CB_includeJSFile was called internally (if any). timeoutMs integer The 'timeoutMs' parameter when CB_includeJSFile was called internally (if any). asynchronously boolean The 'asynchronously' parameter when CB_includeJSFile was called (if any). filesRequested object Object whose indexes are all the filepaths of the script files requested so far and the value is true when the file is still loading (or to be loaded in the future), false if it was loaded successfully (the most likely) or null if it failed to load. filesLoaded array Numeric array whose values are the filepaths of the script files loaded successfully so far. Source: CrossBrowdy.js, line 485 CB_init_CALLBACK() Callback for when the script is loaded successfully. Without parameters. Source: CrossBrowdy.js, line 1035 CB_symmetricCall_CALLBACK(expectedCallingTime) Callback that is called by CB_symmetricCall. Parameters: Name Type Description expectedCallingTime integer The timestamp in milliseconds that represents when the callback should have been called (it will be more or less accurate depending on many factors as the platform used, code performance, etc.). Source: CrossBase/general/CB_others.js, line 9 × Search results Close "},"classes.list.html":{"id":"classes.list.html","title":"Classes","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Classes Classes CB_AudioFile CB_AudioFile_API.AAPI CB_AudioFile_API.ACMP CB_AudioFile_API.SM2 CB_AudioFile_API.WAAPI CB_AudioFileCache CB_AudioFileSprites CB_AudioFileSpritesPool CB_Canvas CB_GraphicSprites CB_GraphicSpritesScene Namespaces CB_Arrays CB_AudioDetector CB_baseSymbols CB_Client CB_Collisions CB_Configuration CrossBase CrossBrowdy CB_Controllers CB_Controllers_Proprietary WII WII_U CB_Device AmbientLight Battery Location Motion Orientation Proximity Vibration CB_Elements CB_Events CB_Keyboard chars extended keys CB_Modules CB_Mouse CursorImage CB_Net Fetch REST Sockets SockJS XHR CB_Pointer CB_Screen CB_Speaker CB_Touch × Search results Close "},"namespaces.list.html":{"id":"namespaces.list.html","title":"Namespaces","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespaces Classes CB_AudioFile CB_AudioFile_API.AAPI CB_AudioFile_API.ACMP CB_AudioFile_API.SM2 CB_AudioFile_API.WAAPI CB_AudioFileCache CB_AudioFileSprites CB_AudioFileSpritesPool CB_Canvas CB_GraphicSprites CB_GraphicSpritesScene Namespaces CB_Arrays CB_AudioDetector CB_baseSymbols CB_Client CB_Collisions CB_Configuration CrossBase CrossBrowdy CB_Controllers CB_Controllers_Proprietary WII WII_U CB_Device AmbientLight Battery Location Motion Orientation Proximity Vibration CB_Elements CB_Events CB_Keyboard chars extended keys CB_Modules CB_Mouse CursorImage CB_Net Fetch REST Sockets SockJS XHR CB_Pointer CB_Screen CB_Speaker CB_Touch × Search results Close "},"index.html":{"id":"index.html","title":"Index","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION CrossBrowdy by Joan Alba Maldonado (joanalbamaldonadoNO_SPAM_PLEASE AT gmail DOT com, without NO_SPAM_PLEASE) Your cross-browser brodie! CrossBrowdy is a Multimedia JavaScript framework that can be used to create real cross-platform and hybrid game engines, games, emulators, multimedia libraries and apps. It is compatible with web browsers, desktop and laptop computers, mobile devices (phones, tablets), desktop and handheld video game consoles, TV sets, smart watches, embedded devices and many others. It is open source and free. Main web site: https://crossbrowdy.com/ About &amp; FAQVisit the About &amp; FAQ section to know more about CrossBrowdy. DownloadTo include it in your project and start using it, the most common way to download CrossBrowdy for production is through the Download section from the official web site. You can also download CrossBrowdy from the GitHub repository directly. Just download the whole content of the dist/ folder. Alternatively, from the command line (shell), you can also use one of the following commands to download CrossBrowdy while you are in your project folder: Using Yarn:yarn add crossbrowdy Using npm:npm i crossbrowdy Using Bower:bower install jalbam/crossbrowdy --save Note: Yarn, npm and Bower will also download the API documentation. HotlinkingInstead of downloading CrossBrowdy, you can hotlink it by directly pointing to a version available online. For instance this way you will be pointing to the last version: &lt;script src=\"https://crossbrowdy.com/CrossBrowdy/CrossBrowdy.js\" type=\"text/javascript\" language=\"javascript\"&gt;&lt;/script&gt;&lt;!-- \"type\" and \"language\" parameters for legacy clients. --&gt;You can find a list of some CDN providers in the Download section of the official web site. Thanks to them, you will be able to always use the last up-to-date version or even to point to a specific version you may prefer. Have in mind that including the CrossBrowdy main file from a CDN provider should never be done for production. This hotlinking method can be useful just for testing purposes. Some features might not work properly using this way and availability cannot be always guaranteed. Getting startedJust include the main JavaScript file, which is called CrossBrowdy.js, in your HTML file. The recommended place to include this main JavaScript file is inside the head section (inside the &lt;head&gt; tag) of the document. Here you have a simple example:&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /&gt; &lt;title&gt;My first CrossBrowdy project!&lt;/title&gt; &lt;script src=\"CrossBrowdy/CrossBrowdy.js\" type=\"text/javascript\" language=\"javascript\"&gt;&lt;/script&gt;&lt;!-- \"type\" and \"language\" parameters for legacy clients. --&gt; &lt;script type=\"text/javascript\" language=\"javascript\"&gt; &lt;!-- CB_init(main); //It will call the \"main\" function when ready. //This function will be called when CrossBrowdy is ready: function main() { //Now, you can start using CrossBrowdy here... CB_console(\"CrossBrowdy started!\"); } // --&gt; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- The \"CB_console\" element will be used automatically in the case that the client does not support console: --&gt; &lt;div id=\"CB_console\" style=\"display:none; visibility:hidden; overflow:scroll;\"&gt; &lt;span style=\"font-weight:bold;\"&gt;Console:&lt;/span&gt;&lt;br /&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;Visit the Getting started topic from the Basic tutorial to learn more. UsageVisit the Guides &amp; Tutorials section to get all the information you may need. LearnCheck the Basic tutorial to learn how to use it. ExamplesCheck the Examples section to see some live examples and learn through their code. API documentationFor more technical documentation, visit the API documentation section. There is also a structure diagram that can be useful to get an abstract idea about the logic structure used by CrossBrowdy. NewsVisit the News section to keep up to date. HelpCheck \"I still have a problem, doubt or suggestion. What can I do?\". Community &amp; Get InvolvedVisit the Community &amp; Get Involved section to access the CrossBrowdy community through different ways and also to get involved and contribute with its development. Please, before contributing, do not forget to read first the code of conduct and contributing documents. CreditsCrossBrowdy project was created by Joan Alba Maldonado (aka Juan Alba Maldonado).It also uses some external libraries and \"third-party\" code. The name of these libraries and the name of the authors of these libraries and that other code can be found in the source code as well as in the splash screen (if it was no disabled) and in the console when CrossBrowdy is loading. As this information may vary with each version, it is not included here. LicenseThe content from the API documentation, the content from the official web site, including tutorials, examples, etc. created by Joan Alba Maldonado (aka Juan Alba Maldonado) is licensed under a Creative Commons Attribution 4.0 International license (SPDX short identifier: \"CC BY 4.0\"). The code written by Joan Alba Maldonado (aka Juan Alba Maldonado), which genuinely belongs to the CrossBrowdy project, is licensed under the 2-Clause BSD License (aka \"Simplified BSD License\" or \"FreeBSD License\", SPDX short identifier: \"BSD-2-Clause\"). Apart from that, it is important to have into account that CrossBrowdy uses some external libraries and some code which may have their own license each. It is important to respect each license properly as the responsibility will always lie with you. See more at \"What is the CrossBrowdy's copyright and license?\". CrossBase/audiovisual/audio/CB_AudioDetector.js Audio formats and audio APIs support detection. Contains the CB_AudioDetector static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/audiovisual/audio/CB_AudioDetector.js, line 1 CrossBase/audiovisual/audio/CB_AudioFile.js Audio files management, including abstraction for different audio APIs. Possible audio APIs are \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). Contains the CB_AudioFile class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 1 CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js Audio files management using \"AAPI\" (HTML5 Audio API). Contains the CB_AudioFile_API.AAPI class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 1 CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js Audio files management using \"ACMP\" (Apache Cordova Media Plugin). Contains the CB_AudioFile_API.ACMP class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 1 CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js Audio files management using \"SM2\" (SoundManager 2). Contains the CB_AudioFile_API.SM2 class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 1 CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js Audio files management using \"WAAPI\" (HTML5 Web Audio API). Contains the CB_AudioFile_API.WAAPI class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 1 CrossBase/audiovisual/audio/CB_AudioFileCache.js Audio files cache management. Contains the CB_AudioFileCache class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1 CrossBase/audiovisual/audio/CB_AudioFileSprites.js Audio sprites management. Contains the CB_AudioFileSprites class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1 CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js Audio sprites pool management. Contains the CB_AudioFileSpritesPool class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1 CrossBase/audiovisual/audio/CB_Speaker.js Speakers management. Contains the CB_Speaker static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/audiovisual/audio/CB_Speaker.js, line 1 CrossBase/audiovisual/image/canvas/CB_Canvas.js Canvas management (including emulation fallbacks). Contains the CB_Canvas class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 1 CrossBase/audiovisual/image/CB_GraphicSprites.js Group of graphic sprites management (2D or 3D). Contains the CB_GraphicSprites class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1 CrossBase/audiovisual/image/CB_GraphicSpritesScene.js Groups of graphic sprites management (2D or 3D). Internally, it manages CB_GraphicSprites objects. Contains the CB_GraphicSpritesScene class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 1 CrossBase/audiovisual/image/CB_Screen.js Screen management. Contains the CB_Screen static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/audiovisual/image/CB_Screen.js, line 1 CrossBase/CrossBase.js Main CrossBase module file. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/CrossBase.js, line 1 CrossBase/device/CB_Device.js Device management. Contains the CB_Device static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/device/CB_Device.js, line 1 CrossBase/general/CB_Arrays.js Arrays management. Contains the CB_Arrays static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/general/CB_Arrays.js, line 1 CrossBase/general/CB_Client.js Web client (browser or engine) management. Contains the CB_Client static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/general/CB_Client.js, line 1 CrossBase/general/CB_Collisions.js Collisions management. Contains the CB_Collisions static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/general/CB_Collisions.js, line 1 CrossBase/general/CB_data.js Data and related management. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/general/CB_data.js, line 1 To Do: A function equivalent to htmlentities/htmlspecialchars (as in PHP). CrossBase/general/CB_Elements.js DOM elements management. Contains the CB_Elements static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/general/CB_Elements.js, line 1 CrossBase/general/CB_Events.js Events management. Contains the CB_Events static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/general/CB_Events.js, line 1 CrossBase/general/CB_others.js Miscellaneous code. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/general/CB_others.js, line 1 To Do: Think about a 'CB_symmetricInterval' function, similar to CB_symmetricCall but calling the callback function automatically. CrossBase/input/CB_Keyboard.js Keyboard management (and other devices which also fire keyboard events as TV remote controls, game consoles' gamepads, etc.). Contains the CB_Keyboard static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/input/CB_Keyboard.js, line 1 CrossBase/input/CB_Mouse.js Mouse and related management. Contains the CB_Mouse static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/input/CB_Mouse.js, line 1 CrossBase/input/CB_Pointer.js Pointer management. Contains the CB_Pointer static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/input/CB_Pointer.js, line 1 CrossBase/input/CB_Touch.js Touch events management. Contains the CB_Touch static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/input/CB_Touch.js, line 1 CrossBase/input/controllers/CB_Controllers.js Controllers (gamepads, joysticks, remotes, etc.) management. Contains the CB_Controllers static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/input/controllers/CB_Controllers.js, line 1 CrossBase/input/controllers/CB_Controllers_Proprietary_WII.js Nintendo Wii remotes (Wiimotes) management. Contains the CB_Controllers_Proprietary.WII static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII.js, line 1 CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js Nintendo Wii U gamepad and remotes (Wiimotes) management. Contains the CB_Controllers_Proprietary.WII_U static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js, line 1 CrossBase/net/CB_Net.js Management for things related with the net. Contains the CB_Net static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/net/CB_Net.js, line 1 CrossBase/net/fetch/CB_Net_Fetch.js Fetch API management. Contains the CB_Net.Fetch static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/net/fetch/CB_Net_Fetch.js, line 1 CrossBase/net/REST/CB_Net_REST.js REST client, services and related management. Contains the CB_Net.REST static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/net/REST/CB_Net_REST.js, line 1 CrossBase/net/sockets/CB_Net_Sockets.js Sockets and related management. Contains the CB_Net.Sockets static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/net/sockets/CB_Net_Sockets.js, line 1 CrossBase/net/XHR/CB_Net_XHR.js XMLHttpRequest (XHR, AJAX) and related management. Contains the CB_Net.XHR static class. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBase/net/XHR/CB_Net_XHR.js, line 1 CrossBrowdy.js Main CrossBrowdy file. Author: Joan Alba Maldonado License: Creative Commons Attribution 4.0 International. See more at https://crossbrowdy.com/about#what_is_the_crossbrowdy_copyright_and_license. Source: CrossBrowdy.js, line 3 To Do: Clear all timeouts before creating them (just in case). × Search results Close "},"CB_Arrays.html":{"id":"CB_Arrays.html","title":"Namespace: CB_Arrays","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Arrays CB_Arrays Static class to manage arrays. It will return itself if it is tried to be instantiated. Source: CrossBase/general/CB_Arrays.js, line 22 Methods &lt;static&gt; bsort(array [, reversed]) → {array} Sorts an array using the bubble sort (sinking sort) method. Internally, it uses the \"&gt;\" operator for comparing values as they will be treated as numbers. Parameters: Name Type Argument Default Description array array The array whose elements we want to sort. reversed boolean &lt;optional&gt; false Defines whether to sort in the reverse order or not. Source: CrossBase/general/CB_Arrays.js, line 400 To Do: Think about accepting a comparing function (as the \"sort\" method). Returns: Returns the array ordered. If another value which is not an array is given, it will be returned again. Type array &lt;static&gt; combine( [arrayOrObjectA] [, arrayOrObjectB], avoidDuplicatedValuesInArray [, modifyArrayOrObjectA]) → {array|Object} Returns a combined array or object from two arrays or objects. Using the following rules: If they both are arrays (numeric indexes), it will keep all elements (attaching the elements of the second array after the elements of the first one). Otherwise, if either of them is not an array (it should be an associative array which is an object in JavaScript), it will merge the elements (overwritting those whose index is the same and keeping the ones from the second array/object): Parameters: Name Type Argument Default Description arrayOrObjectA array | Object | string | null | undefined &lt;optional&gt; []|{} One of the arrays (numeric indexes) or associative arrays (object) that we want to combine. If a string is provided, it will try to convert it into a new object (the string should be a JSON-valid string). It can be optional if \"arrayOrObjectB\" is a valid value and neither null nor undefined. If not provided but the \"arrayOrObjectB\" is provided, it will be a new empty array if the \"arrayOrObjectB\" is an array or it will be an empty object otherwise. arrayOrObjectB array | Object | string | null | undefined &lt;optional&gt; []|{} One of the arrays (numeric indexes) or associative arrays (object) that we want to combine. If a string is provided, it will try to convert it into a new object (the string should be a JSON-valid string). It can be optional if \"arrayOrObjectA\" is a valid value and neither null nor undefined. If not provided but the \"arrayOrObjectA\" is provided, it will be a new empty array if the \"arrayOrObjectA\" is an array or it will be an empty object otherwise. avoidDuplicatedValuesInArray boolean Tells whether to avoid or allow items with duplicated values in the returned array or not. Only applies when both arrays to combine are numeric arrays. modifyArrayOrObjectA boolean &lt;optional&gt; false Parameter that will be used in the case that CB_combineJSON or CB_combineArraysOrObjects is called. If set to true, it will modify the original \"arrayOrObjectA\" array or object. Source: CrossBase/general/CB_data.js, line 1007 Returns: Type array | Object &lt;static&gt; copy(array) → {object} Returns an array copied from the given one. It will also make a copy of the arrays found in the values (if any), calling itself recursively. Parameters: Name Type Description array array The array whose values we want to copy. Source: CrossBase/general/CB_Arrays.js, line 238 Returns: Returns an array copied from the given one. Returns an empty array if the given \"array\" was not an array. Type object &lt;static&gt; count() Alias for CB_Arrays.sizeOf. Source: CrossBase/general/CB_Arrays.js, line 66 See: CB_Arrays.sizeOf &lt;static&gt; executeFunctionAll(array, functionEach [, delayBetweenEach] [, returnSetTimeoutsArray] [, delayBetweenEachAffectsFirst] [, functionFinish]) → {integer|array} Performs a desired action, using the provided function, on all the existing elements of a given array. Elements which are undefined or null will be skipped without calling the \"functionEach\" function. Parameters: Name Type Argument Default Description array array A numeric array containing the elements that we want to loop. functionEach CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK Function that will be called for each element of the given array. As the first parameter it receives the element of the \"array\" provided being looped, as the second parameter the position of this element in the \"array\" provided, the third parameter is the array being looped and the fourth parameter will be the \"delayBetweenEach\" being used, being \"this\" the element itself. delayBetweenEach number | CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK &lt;optional&gt; 0 If a value greater than zero is used, it will be used as the delay desired between each call to the \"functionEach\" function (calling them using the setTimeout function internally). If not provided or the value is 0 (zero) or lower, each call to the \"functionEach\" function will be performed immediately one after the other. If a function is provided, it will be called with the same parameters as the \"functionEach\" function and its returning value will be used as the delay (executed every loop for each item). returnSetTimeoutsArray boolean &lt;optional&gt; false Defines whether we want the method to return an integer or a numeric array with information of each setTimeout call. Returning an array with information of each setTimeout call is only useful when the setTimeout function is called internally, which happens when the \"delayBetweenEach\" parameter is greater than 0 (zero). delayBetweenEachAffectsFirst boolean &lt;optional&gt; false If set to true, the desired delay (if any) will also affect the first call to the \"functionEach\" function. functionFinish CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK &lt;optional&gt; Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. Source: CrossBase/general/CB_Arrays.js, line 168 Returns: If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the elements given in the \"array\" parameter). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a CB_Arrays.executeFunctionAll_OBJECT object for each element given. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the setTimeout function. Type integer | array &lt;static&gt; forEach(array, callback [, thisArg] [, extendedDOM]) → {array|undefined} Implementation of the Array.forEach method for browsers that do not support it natively. Executes a function for each element of a given array. Parameters: Name Type Argument Default Description array array Desired array. callback function Function that will be executed for each element of the given array. Following the same rules as the native Array.forEach method, it will receive three arguments: currentValue, currentIndex and the array given. thisArg * &lt;optional&gt; Value that will be passed as \"this\" every time the function is called. extendedDOM boolean &lt;optional&gt; false Defines whether the function is being called by a native function which was extended. Internal usage recommended only. Source: CrossBase/general/CB_data.js, line 136 Returns: If the \"extendedDOM\" parameter is set to false, returns the given \"array\" again. Otherwise, returns undefined. Type array | undefined &lt;static&gt; indexOf(array, searchElement [, fromIndex] [, extendedDOM]) → {integer} Implementation of Array.indexOf method for arrays in browsers that do not support it natively. Returns the first index of a given element that exists in an array (starting from a certain index if desired) or -1 if not found. Parameters: Name Type Argument Default Description array array Desired array. searchElement * Element we want to search. Note that it is type sensitive. fromIndex integer &lt;optional&gt; 0 First index of the given array where the search will start. extendedDOM boolean &lt;optional&gt; false Defines whether the function is being called by a native function which was extended. Internal usage recommended only. Source: CrossBase/general/CB_data.js, line 87 Returns: Type integer &lt;static&gt; insert() Alias for CB_Arrays.insertElement. Source: CrossBase/general/CB_Arrays.js, line 251 See: CB_Arrays.insertElement &lt;static&gt; insertElement(array [, index], item [, onInsert]) → {array} Inserts an element in the desired position of a given an array. Elements which are placed after it will be moved a position to the right (increasing their index). Parameters: Name Type Argument Default Description array array The array whose element we want to delete. index integer &lt;optional&gt; 0 Position of the element in the given array that we want to remove. item * Element (item) which belongs to the index which is being checked in the current iteration of the given array. onInsert CB_Arrays.removeDuplicated_PURGE_FUNCTION &lt;optional&gt; Function to call if the element is inserted, after inserting it. Source: CrossBase/general/CB_Arrays.js, line 270 Returns: Returns the new array (with the element inserted if it was possible). If no valid array is given, it will return an empty array. Type array &lt;static&gt; insertElementByPosition() Alias for CB_Arrays.insertElement. Source: CrossBase/general/CB_Arrays.js, line 256 See: CB_Arrays.insertElement &lt;static&gt; isArray(element [, extendedDOM]) → {boolean} Implementation of Array.isArray method for browsers that do not support it natively. Returns whether a given element is an array or not. Parameters: Name Type Argument Default Description element * The element we want to check. extendedDOM boolean &lt;optional&gt; false Defines whether the function is being called by a native function which was extended. Internal usage recommended only. Source: CrossBase/general/CB_data.js, line 172 To Do: Think about a parameter to check whether the given array is a typed array (for example, 'Uint8Array') or not. Returns: Type boolean &lt;static&gt; lastIndexOf(array, searchElement [, fromIndex] [, extendedDOM]) → {integer} Implementation of Array.lastIndexOf method for browsers that do not support it natively. Returns the last index of a given element that exists in an array (starting from a certain index if desired) or -1 if not found. Parameters: Name Type Argument Default Description array array Desired array. searchElement * Element we want to search. Note that it is type sensitive. fromIndex integer &lt;optional&gt; array.length - 1 First index of the given array where the search will start. extendedDOM boolean &lt;optional&gt; false Defines whether the function is being called by a native function which was extended. Internal usage recommended only. Source: CrossBase/general/CB_data.js, line 38 To Do: Implement the \"fromIndex\" in the polyfill. Returns: Type integer &lt;static&gt; ltrim(element [, undesiredStrings]) → {string|array} Trims the left side of a given string or array of strings (modifying the given array), taking off the desired strings or otherwise trimming spaces, tabs (\"\\t\"), new lines (\"\\n\") and carriage returns (\"\\r\"). Case sensitive. Parameters: Name Type Argument Default Description element string | array The element that will be trimmed. It should be either a string or an array of strings. undesiredStrings string | array &lt;optional&gt; [ \" \", \"\\n\", \"\\r\", \"\\t\" ] String or an array with the strings that we want to trim off the given element. Source: CrossBase/general/CB_data.js, line 362 To Do: Accept a \"recursive\" parameter (boolean) to affect multiple levels (array of arrays of strings, etc.). Consider accepting objects instead of arrays in the \"element\" parameter. Think about optimizing (using a counter for the number of occurrences in the loop and trim all the occurrences when finished). Returns: Returns the given element again if it was an string, a number (it will be casted to a string) or an array of strings, trimmed if it has been possible. If it was another type, returns an empty string. Type string | array &lt;static&gt; removeDuplicated(array [, purgeFunction] [, ignoreDuplicated]) → {array} Deletes duplicated and/or not desired values (with a checking function to purge) from a numeric array. Values can be of any type. Internally, loops through the given array backwards (from the last index to the first one). Parameters: Name Type Argument Default Description array array The array whose values we want to purge. purgeFunction CB_Arrays.removeDuplicated_PURGE_FUNCTION &lt;optional&gt; Callback that will be called for each item, being \"this\" the current item. It should return false when we want to keep the value or true otherwise. If the \"ignoreDuplicated\" parameter is set to true, all duplicated elements will be removed regardless of the returning value of the \"purgeFunction\" function. ignoreDuplicated boolean &lt;optional&gt; false If it is set to true, it will keep duplicated values (unless the given \"purgeFunction\" purge them). Source: CrossBase/general/CB_Arrays.js, line 301 Returns: Returns the array purged. If no valid array is given, it will return an empty array. Type array &lt;static&gt; removeElement(array [, element] [, onRemove]) → {array} Deletes a given element from an array. All occurrences will be deleted. Elements which were after a removed element will be moved a position to the left (decreasing their index). Parameters: Name Type Argument Description array array The array whose element we want to delete. element * &lt;optional&gt; The element we want to remove. All occurrences will be deleted. Note that it is type sensitive. onRemove CB_Arrays.removeDuplicated_PURGE_FUNCTION &lt;optional&gt; Function to call if the element is removed, before removing it. Source: CrossBase/general/CB_Arrays.js, line 351 Returns: Returns the new array (with the element removed if it was possible). If no valid array is given, it will return an empty array. Type array &lt;static&gt; removeElementByIndex() Alias for CB_Arrays.removeElementByPosition. Source: CrossBase/general/CB_Arrays.js, line 321 See: CB_Arrays.removeElementByPosition &lt;static&gt; removeElementByPosition(array [, index] [, onRemove]) → {array} Deletes an element from an array which is placed in the desired position. Elements which were after it will be moved a position to the left (decreasing their index). Parameters: Name Type Argument Default Description array array The array whose element we want to delete. index integer &lt;optional&gt; 0 Position of the element in the given array that we want to remove. onRemove CB_Arrays.removeDuplicated_PURGE_FUNCTION &lt;optional&gt; Function to call if the element is removed, before removing it. Source: CrossBase/general/CB_Arrays.js, line 334 Returns: Returns the new array (with the element removed if it was possible). If no valid array is given, it will return an empty array. Type array &lt;static&gt; removeElements(array, elements) → {array} Deletes the given elements from an array. All occurrences will be deleted. Elements which were after a removed element will be moved a position to the left (decreasing their index). Parameters: Name Type Description array array The array whose element we want to delete. elements array An array with the elements we want to remove. All occurrences will be deleted. Note that it is type sensitive. Source: CrossBase/general/CB_Arrays.js, line 364 Returns: Returns the new array (with the element removed if it was possible). If no valid array is given, it will return an empty array. Type array &lt;static&gt; replaceAll(stringOrArray, stringOrArrayFind [, stringReplace] [, caseInsensitive]) → {string|array} Returns the string or array of strings with all the desired occurrences replaced. Calls itself recursively and calls the CB_regularExpressionString function internally. Parameters: Name Type Argument Default Description stringOrArray string | array An string or an array of strings whose content we want to replace. It can also be an array of arrays of strings (as many levels as you wish). If an array is given, it will not be modified and a copy from it will be generated and returned with the occurrences replaced. stringOrArrayFind string | array An string or an array of strings (not a regular expressions) that we want to find to be replaced (special characters will be escaped). stringReplace string &lt;optional&gt; \"\" The string that will replace \"stringFind\". If not provided, it will be replaced as an empty string (it will just remove the occurrences found). caseInsensitive boolean &lt;optional&gt; false Defines whether we want to be case insensitive or not. Source: CrossBase/general/CB_data.js, line 1437 Returns: Returns the \"stringOrArray\" given with occurrences replaced. If the \"stringOrArray\" given was neither a string nor an array, it will be returned without being modified. Type string | array &lt;static&gt; rtrim(element [, undesiredStrings]) → {string|array} Trims the right side of a given string or array of strings (modifying the given array), taking off the desired strings or otherwise trimming spaces, tabs (\"\\t\"), new lines (\"\\n\") and carriage returns (\"\\r\"). Case sensitive. Parameters: Name Type Argument Default Description element string | array The element that will be trimmed. It should be either a string or an array of strings. undesiredStrings string | array &lt;optional&gt; [ \" \", \"\\n\", \"\\r\", \"\\t\" ] String or an array with the strings that we want to trim off the given element. Source: CrossBase/general/CB_data.js, line 309 To Do: Accept a \"recursive\" parameter (boolean) to affect multiple levels (array of arrays of strings, etc.). Consider accepting objects instead of arrays in the \"element\" parameter. Think about optimizing (using a counter for the number of occurrences in the loop and trim all the occurrences when finished). Returns: Returns the given element again if it was an string, a number (it will be casted to a string) or an array of strings, trimmed if it has been possible. If it was another type, returns an empty string. Type string | array &lt;static&gt; sizeof() Alias for CB_Arrays.sizeOf. Source: CrossBase/general/CB_Arrays.js, line 61 See: CB_Arrays.sizeOf &lt;static&gt; sizeOf(element [, onlyOwn]) → {integer} Returns the size of an object or array. Parameters: Name Type Argument Default Description element Object | array The element whose size we want to know. It should be an object or an array. onlyOwn boolean &lt;optional&gt; false If the \"element\" given is not an object, this parameter will be ignored. Otherwise, if it is set to true, it will only have into account the properties which the object has as their own property and have not been inherited (using the Object.hasOwnProperty method). Source: CrossBase/general/CB_data.js, line 207 Returns: If an object is provided, the size will be the number of its properties. Otherwise, if an array is given, the size will be the numbers of its indexes (Array.length property). Type integer &lt;static&gt; sort(array [, reversed] [, comparingFunction]) → {array} Sorts the values of an array (using the native Array.sort method). Parameters: Name Type Argument Default Description array array The array whose elements we want to sort. reversed boolean &lt;optional&gt; false Defines whether to sort in the reverse order or not. Only applies when comparingFunction is not provided. comparingFunction function &lt;optional&gt; Comparing function with the same rules as the native Array.sort method. If provided, the \"reversed\" parameter will be ignored. Source: CrossBase/general/CB_Arrays.js, line 380 Returns: Returns the array ordered. If another value which is not an array is given, it will be returned again. Type array &lt;static&gt; trim(element [, undesiredStrings]) → {string|array} Trims a given string or array of strings (modifying the given array), taking off the desired strings or otherwise trimming spaces, tabs (\"\\t\"), new lines (\"\\n\") and carriage returns (\"\\r\"). Case sensitive. Parameters: Name Type Argument Default Description element string | array The element that will be trimmed. It should be either a string or an array of strings. undesiredStrings string | array &lt;optional&gt; [ \" \", \"\\n\", \"\\r\", \"\\t\" ] String or an array with the strings that we want to trim off the given element. Source: CrossBase/general/CB_data.js, line 267 To Do: Accept a \"recursive\" parameter (boolean) to affect multiple levels (array of arrays of strings, etc.). Consider accepting objects instead of arrays in the \"element\" parameter. Returns: Returns the given element again if it was an string, a number (it will be casted to a string) or an array of strings, trimmed if it has been possible. If it was another type, returns an empty string. Type string | array executeAll() Alias for CB_Arrays#executeFunctionAll. Source: CrossBase/general/CB_Arrays.js, line 147 See: CB_Arrays#executeFunctionAll forEachDelay() Alias for CB_Arrays#executeFunctionAll. Source: CrossBase/general/CB_Arrays.js, line 152 See: CB_Arrays#executeFunctionAll Type Definitions executeFunctionAll_OBJECT Object used by the CB_Arrays#executeFunctionAll method when the \"returnSetTimeoutsArray\" parameter is set to true. Type: Object Properties: Name Type Description item * The element affected. setTimeoutReturningValue integer The returning value of calling the setTimeout internally or null if it was not called, depending on the \"delayBetweenEach\" parameter. setTimeoutDelay number The value used as the second parameter when calling the setTimeout internally or zero if it was not called, depending on the \"delayBetweenEach\" parameter. Source: CrossBase/general/CB_Arrays.js, line 138 executeFunctionAll_ON_FINISH_CALLBACK(array, itemsAffected, delayMaximum) Callback that is used when finishes all iterations after looping the array. Being \"this\" the array itself. Parameters: Name Type Description array array Whole array which was being looped. itemsAffected integer The number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null). delayMaximum integer The maximum \"delay\" used. Source: CrossBase/general/CB_Arrays.js, line 130 executeFunctionAll_ON_LOOP_CALLBACK(item, index, array, delay) → {number} Callback that is used for each iteration when looping the array. Being \"this\" the value itself. Parameters: Name Type Description item * Element (item) which belongs to the index which is being checked in the current iteration of the given array. index integer Index which is being checked in the current iteration. array array Whole array which is being looped. delay integer The \"delayBetweenEach\" used for this loop. Source: CrossBase/general/CB_Arrays.js, line 120 Returns: When used as a function to calculate the delay, it should return the delay desired as a number. Type number removeDuplicated_PURGE_FUNCTION(item, index, array) → {boolean} Callback that is used as the \"purgeFunction\" parameter of the CB_Arrays.removeDuplicated function. Being \"this\" the current element (item). It should return false when we want to keep the value or true otherwise. Parameters: Name Type Description item * Element (item) which belongs to the index which is being checked in the current iteration used in CB_Arrays.removeDuplicated. index integer Index which is being checked in the current iteration used in CB_Arrays.removeDuplicated. array array Whole array which is being checked. Source: CrossBase/general/CB_Arrays.js, line 283 Returns: It should return false when we want to keep the value or true otherwise. Type boolean × Search results Close "},"CB_AudioDetector.html":{"id":"CB_AudioDetector.html","title":"Namespace: CB_AudioDetector","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_AudioDetector CB_AudioDetector Static class to detect audio API and formats supported. Possible audio APIs are \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). It will return itself if it is tried to be instantiated. Source: CrossBase/audiovisual/audio/CB_AudioDetector.js, line 12 Methods &lt;static&gt; APIExists(audioAPI [, sanitize]) → {boolean} Returns whether a given audio API exists or not (without keeping into account whether it is supported or not). All existing ones are defined in CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS. Parameters: Name Type Argument Default Description audioAPI string The audio API that we want to check. All existing ones are defined in CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS. For example: \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). sanitize boolean &lt;optional&gt; true If set to true, the \"audioAPI\" given will be trimmed and converted to upper case. Source: CrossBase/audiovisual/audio/CB_AudioDetector.js, line 164 Returns: Returns whether the given audio API exists or not (without keeping into account whether it is supported or not). Type boolean &lt;static&gt; getPreferredAPI( [audioAPIs] [, allowEmulation] [, returnOnEmpty]) → {string|*} Calculates and returns the preferred audio API (from an array if it is given) for the current client, if any. Parameters: Name Type Argument Default Description audioAPIs array &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS An array of strings with the audio APIs that we want to check, in order of preference. All existing ones are defined in CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS. For example: \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). allowEmulation boolean &lt;optional&gt; !!CB_Configuration[CB_BASE_NAME].CB_AudioDetector_allowEmulation_DEFAULT If set to true, it will also detect as supported emulated audio APIs (as \"WAAPI\" using waapisim.js instead of supported natively). returnOnEmpty boolean &lt;optional&gt; If set to true and no audio API is supported, it will return the value of this parameter instead of null. Source: CrossBase/audiovisual/audio/CB_AudioDetector.js, line 181 Returns: Returns a string with the preferred audio API (from an array if it is given) for the current client, if any. If no audio API is supported, it will return the value set in the \"returnOnEmpty\" parameter. Type string | * &lt;static&gt; getSupportedAPIs( [audioAPIs] [, allowEmulation]) → {array} Calculates and returns an array with the audio APIs supported (from an array if it is given) for the current client, if any. Parameters: Name Type Argument Default Description audioAPIs array &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS An array of strings with the audio APIs that we want to check. All existing ones are defined in CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS. For example: \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). allowEmulation boolean &lt;optional&gt; !!CB_Configuration[CB_BASE_NAME].CB_AudioDetector_allowEmulation_DEFAULT If set to true, it will also detect as supported emulated audio APIs (as \"WAAPI\" using waapisim.js instead of supported natively). Source: CrossBase/audiovisual/audio/CB_AudioDetector.js, line 225 Returns: Returns an array with the audio APIs supported (from an array if it is given) for the current client, if any. If no audio API is supported, an empty array will be returned. Type array &lt;static&gt; getSupportedAudioFormats( [audioFormats] [, supportLevels] [, dataURI]) → {array} Returns an array of strings with the audio formats that are supported (from an array if it is given) by the current client and ordered by support level. Uses the CB_AudioDetector.isAudioFormatSupported function internally. Parameters: Name Type Argument Default Description audioFormats array &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_FORMATS An array of strings with the audio format or audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"') that we want to check. supportLevels array &lt;optional&gt; ['probably', 'maybe'] An array with the support level or support levels allowed. Two possible levels: \"probably\" and \"maybe\". The \"probably\" audio formats are more likely to be supported than the \"maybe\" ones. dataURI boolean &lt;optional&gt; false Specifies whether we want to check the support for data URI audios or just for normal audio files. Source: CrossBase/audiovisual/audio/CB_AudioDetector.js, line 40 Returns: Returns an array of strings with the audio formats that are supported (from an array if it is given) and ordered by support level. Type array &lt;static&gt; isAPISupported(audioAPI [, allowEmulation]) → {boolean} Tells whether a given audio API is supported or not by the current client. Parameters: Name Type Argument Default Description audioAPI string The audio API that we want to check. All existing ones are defined in CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS. For example: \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). allowEmulation boolean &lt;optional&gt; !!CB_Configuration[CB_BASE_NAME].CB_AudioDetector_allowEmulation_DEFAULT If set to true, it will detect as supported also emulated audio APIs (as \"WAAPI\" using waapisim.js instead of supported natively). Source: CrossBase/audiovisual/audio/CB_AudioDetector.js, line 276 To Do: Have into account allowEmulation and detect whether emulation is being used if so (for example, detect whether waapisim.js is being used). Returns: Returns whether the given audio API is supported or not. Type boolean &lt;static&gt; isAudioFormatSupported(audioFormat [, dataURI]) → {string} Returns the support level of a given audio format by the current client. Parameters: Name Type Argument Default Description audioFormat string The audio format (it can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"') that we want to check. dataURI boolean &lt;optional&gt; false Specifies whether we want to check the support for data URI audios or just for normal audio files. Source: CrossBase/audiovisual/audio/CB_AudioDetector.js, line 108 To Do: Think about using MediaSource.isTypeSupported(). Some web clients does not support data URIs for Audio element so we should take this into account. Take into account that data URIs may not be supported when WAAPI is being emulated. Returns: Returns the support level of the given audio format (it will return \"probably\", \"maybe\" or an empty string which means not supported). The \"probably\" audio formats are more likely to be supported than the \"maybe\" ones. Type string &lt;static&gt; isSM2UsingFlash() → {boolean} Tells whether SoundManager 2 is using Adobe Flash (formerly Macromedia Flash) to emulate sound or not. Source: CrossBase/audiovisual/audio/CB_AudioDetector.js, line 341 Returns: Returns whether SoundManager 2 is using Adobe Flash (formerly Macromedia Flash) to emulate sound or not. Type boolean &lt;static&gt; isWAAPIUsingEmulation() → {boolean} Tells whether \"WAAPI\" (HTML5 Web Audio API) is using emulation (through WAAPISim) or not. Source: CrossBase/audiovisual/audio/CB_AudioDetector.js, line 330 Returns: Returns whether \"WAAPI\" (HTML5 Web Audio API) is using emulation (through WAAPISim) or not. Type boolean × Search results Close "},"CB_AudioFile.html":{"id":"CB_AudioFile.html","title":"Class: CB_AudioFile","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Class: CB_AudioFile CB_AudioFile Class to manage an audio file. Internally, it uses one audio API object which belongs to the audio API being used (when the audio API is changed, it keeps the old audio API objects just in case they are needed in the future when the audio API is changed again). Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). new CB_AudioFile(filePath [, audioId] [, options] [, audioAPI] [, callbackOk] [, callbackError]) → {CB_AudioFile} The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.) if the \"autoPlay\" option is set to true, as some clients may need this at least the first time in order to be able to play the audio. Parameters: Name Type Argument Default Description filePath string The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. audioId string &lt;optional&gt; 'CB_AudioFile_' + CB_AudioFile._idUnique++ Desired identifier for the audio object (can be a different element depending on the audio API used). If not provided, an automatic unique ID will be calculated. Note that it is not case sensitive and it should be unique for each object. options CB_AudioFile.OPTIONS &lt;optional&gt; CB_AudioFile#DEFAULT_OPTIONS Object with the desired options. audioAPI string &lt;optional&gt; CB_AudioDetector.getPreferredAPI(undefined, false, null) || CB_AudioDetector.getPreferredAPI(undefined, true, null) The desired audio API to be used. If not provided, it will try to calculate the best one for the current client by calling the CB_AudioDetector.getPreferredAPI function internally. Audio API support will depend on the current client being used. All possible ones are defined in CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS. For example: \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the CB_AudioFile object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile object itself. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 24 To Do: Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). Note that the \"id\" is not case sensitive and it should be unique for each object. Send the CB_AudioFile object itself as a parameter when calling both \"callbackOk\" and \"callbackError\". Think about allowing to define 'useXHR' and 'useCache' options (used by CB_AudioFile_API.WAAPI objects). Method getCopy and static method filterProperties (similar to the ones from CB_GraphicSprites and CB_GraphicSpritesScene). Returns: Returns a new CB_AudioFile object. Type CB_AudioFile Members &lt;static, constant&gt; ABORTED :integer Status value for an audio file which has been aborted. This will happen when the audio file has been destroyed with the CB_AudioFile#destructor method. Can be used to compare the value returned by the CB_AudioFile#getStatus method. Recommended for internal usage only. Type: integer Default Value: 6 Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 254 &lt;static, constant&gt; CHECKING :integer Status value for an audio file which is being checked currently. Can be used to compare the value returned by the CB_AudioFile#getStatus method. Recommended for internal usage only. Type: integer Default Value: 3 Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 230 &lt;static, constant&gt; FAILED :integer Status value for an audio file which failed to be loaded or failed for any other reason. Can be used to compare the value returned by the CB_AudioFile#getStatus method. Recommended for internal usage only. Type: integer Default Value: 5 Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 246 &lt;static, constant&gt; LOADED :integer Status value for an audio file which has been loaded. Can be used to compare the value returned by the CB_AudioFile#getStatus method. Recommended for internal usage only. Type: integer Default Value: 4 Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 238 &lt;static, constant&gt; LOADING :integer Status value for an audio file which is loading. Can be used to compare the value returned by the CB_AudioFile#getStatus method. Recommended for internal usage only. Type: integer Default Value: 1 Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 214 &lt;static, constant&gt; UNCHECKED :integer Status value for an audio file which has been not checked yet. Can be used to compare the value returned by the CB_AudioFile#getStatus method. Recommended for internal usage only. Type: integer Default Value: 2 Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 222 &lt;static, constant&gt; UNLOADED :integer Status value for an audio file which is unloaded. Can be used to compare the value returned by the CB_AudioFile#getStatus method. Recommended for internal usage only. Type: integer Default Value: 0 Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 206 &lt;readonly&gt; audioAPI :string Defines the Audio API used for this audio file. Audio API support will depend on the current client being used. All possible ones are defined in CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS. For example: \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). Type: string Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 91 audioFileObject :CB_AudioFile_API.WAAPI|CB_AudioFile_API.SM2|CB_AudioFile_API.ACMP|CB_AudioFile_API.AAPI|Object It will store the current audio file object for the current audio API. The CB_AudioFile#load method will set the value of this property only after the audio file object (stored in its value) is loaded properly. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). When no audio API object is being set, it will contain a fake object with same methods and properties (defined in CB_AudioFile._audioFileObject_prototype). Recommended for internal usage only. Type: CB_AudioFile_API.WAAPI | CB_AudioFile_API.SM2 | CB_AudioFile_API.ACMP | CB_AudioFile_API.AAPI | Object Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 162 audioFileObjectLast :CB_AudioFile_API.WAAPI|CB_AudioFile_API.SM2|CB_AudioFile_API.ACMP|CB_AudioFile_API.AAPI|Object Stores the last audio file object created or reused, for the current API being used. The CB_AudioFile#load method will set the value of this property before knowing whether the audio file object (stored in its value) will be loaded properly or not. Used by the CB_AudioFile#load and CB_AudioFile#getProgress methods. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). When no audio API object is being set, it will contain a fake object with same methods and properties (defined in CB_AudioFile._audioFileObject_prototype). Recommended for internal usage only. Type: CB_AudioFile_API.WAAPI | CB_AudioFile_API.SM2 | CB_AudioFile_API.ACMP | CB_AudioFile_API.AAPI | Object Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 170 audioFileObjects :Object It will store the created audio file objects for the different audio APIs (for optimization purposes, to avoid creating more than one per API). Being each index the name of the audio API (\"WAAPI\", \"AAPI\", \"SM2\" or \"ACMP\"), their value will be an object which can be CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Recommended for internal usage only. Type: Object Default Value: {} Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 153 &lt;constant&gt; DEFAULT_OPTIONS :CB_AudioFile.OPTIONS Keeps the default options when an object is created. Format: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. Type: CB_AudioFile.OPTIONS Default Value: { autoLoad: true, autoPlay: false, loop: false, volume: CB_AudioFile.prototype.DEFAULT_VOLUME } Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 44 &lt;constant&gt; DEFAULT_VOLUME :number Keeps the default volume. If the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT property is true, this will keep the result of calling the CB_Speaker.getVolume function. Otherwise, it will use the value of the CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME variable. Type: number Default Value: CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 36 &lt;readonly&gt; filePath :string Stores the path of the audio file or the data URI. NOTE: Only some clients with some audio APIs will support data URIs. Type: string Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 82 &lt;readonly&gt; id :string Stores the identifier for the audio file. Type: string Default Value: 'CB_AudioFile_' + CB_AudioFile._idUnique++ Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 73 &lt;readonly&gt; loop :boolean Defines whether the file loops by default when the audio is played or not. Its value will be modified automatically whenever the CB_AudioFile#play method is called, getting the value from the \"loop\" parameter (but only if contains a boolean). Type: boolean Default Value: CB_AudioFile.prototype.DEFAULT_OPTIONS.loop Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 55 &lt;readonly&gt; volume :number Stores the volume of this audio. Accepted values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is false or otherwise MAX_VOLUME is the returning value of the CB_Speaker.getVolume function. Type: number Default Value: CB_AudioFile.prototype.DEFAULT_OPTIONS.volume Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 64 Methods checkPlaying( [callbackOk] [, callbackError] [, ignoreStatus] [, ignoreQueue] [, useCache]) → {boolean} Checks whether the audio can be played or not. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Also recommended to use before calling the CB_AudioFile#play method the first time. Internally, uses the \"checkPlaying\" method of the used audio API object. The checking action will only be performed if the value of the \"status\" property of the used audio API object belongs to the CB_AudioFile.UNCHECKED or to the CB_AudioFile.CHECKING value. After checking, if the audio can be played, the \"status\" property of the used audio API object will get the value of CB_AudioFile.LOADED. Otherwise, if it cannot be played, the \"status\" property of the used audio API object will get the value of {CB_AudioFile.FAILED}. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Parameters: Name Type Argument Default Description callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been checked successfully, being \"this\" the CB_AudioFile object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been checked successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile object itself. ignoreStatus boolean &lt;optional&gt; false If set to false and the audio status is neither \"UNCHECKED\" nor \"CHECKING\", it will fail calling the \"callbackError\" function (if any). If set to true, it will try to perform the checking action regardless the status of the audio. ignoreQueue boolean &lt;optional&gt; false If set to false and there is already the maximum number of audio files being checked (defined internally, depending on the audio API), the function will exit and it will call itself automatically again and again until the checking process can be performed (when its queue turn has been reached). This is done for performance purposes. Some audio APIs will ignore this parameter as they do not use checking queues. useCache boolean &lt;optional&gt; false If set to true (not recommended) and the same audio file was checked previously, it will not perform the checking process again and it will do the same as the previous call. Some audio APIs will ignore this parameter as they do not use cache. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 576 Returns: Returns false if the checking could not be performed and failed. If it returns true, it can mean either the checking has been processed successfully or it will fail in the future, so it is recommended to ignore the returning value and use the callback functions instead. Type boolean destructor( [stopSound] [, keepStoppedUnaltered] [, avoidOnStop] [, forceOnStop]) Destroys the audio file object and frees memory. Sets its current status to ABORTED (CB_AudioFile.ABORTED value). Parameters: Name Type Argument Default Description stopSound boolean &lt;optional&gt; false If set to true, it will also call the \"stop\" method of the internal audio file object for the current API (stored in the CB_AudioFile#audioFileObject property). This method has the same parameters as the CB_AudioFile#stop method. keepStoppedUnaltered boolean &lt;optional&gt; false Used internally as the \"keepStoppedUnaltered\" parameter to call the \"stop\" method of the internal audio file object for the current API (stored in the CB_AudioFile#audioFileObject property). This method has the same parameters as the CB_AudioFile#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. avoidOnStop boolean &lt;optional&gt; false Used internally as the \"avoidOnStop\" parameter to call the \"stop\" method of the internal audio file object for the current API (stored in the CB_AudioFile#audioFileObject property). This method has the same parameters as the CB_AudioFile#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. forceOnStop boolean &lt;optional&gt; false Used internally as the \"forceOnStop\" parameter to call the \"stop\" method of the internal audio file object for the current API (stored in the CB_AudioFile#audioFileObject property). This method has the same parameters as the CB_AudioFile#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 300 getCurrentTime() → {number} Gets the current time (in milliseconds) which belongs to the position where the audio is currently playing or where it has been paused. Note that some audio APIs and clients could give wrong values. Internally, uses the \"getCurrentTime\" method of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 789 Returns: Returns the current time (in milliseconds). Note that some audio APIs and clients could give wrong values. Type number getDuration() → {number} Tells the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. Internally, uses the \"getDuration\" method of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 595 Returns: Returns the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. Type number getProgress() → {number} Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Internally, uses the \"getProgress\" method of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 945 Returns: Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Type number getStartAt( [numeric]) → {number|*} Tells the last \"startAt\" parameter value used by the CB_AudioFile#play or the CB_AudioFile#resume method (or used by the equivalents methods of the same name from the used audio API object). Internally, uses the \"lastStartAt\" property of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Parameters: Name Type Argument Default Description numeric boolean &lt;optional&gt; false If set to true, it will sanitize the returning value by returning zero instead of undefined, null or any other non-numeric value. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 916 Returns: Returns the last \"startAt\" value used by the CB_AudioFile#play or the CB_AudioFile#resume method (or used by the equivalents methods of the same name from the used audio API object). If we want it to be numeric always, the \"numeric\" parameter should be set to true. Type number | * getStatus( [realStatus]) → {number} Gets the current status of the audio file. Parameters: Name Type Argument Default Description realStatus boolean &lt;optional&gt; false If set to true, it will return the \"status\" property of the used audio API object instead of the \"status\" property of the current CB_AudioFile object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 801 Returns: Returns the current status of the audio file. It is a number, which should match the value of the CB_AudioFile.UNLOADED (still unloaded), CB_AudioFile.LOADING (loading), CB_AudioFile.UNCHECKED (not checked by calling the \"checkPlaying\" method yet), CB_AudioFile.CHECKING (being checked by the \"checkPlaying\" method), CB_AudioFile.LOADED (loaded), CB_AudioFile.FAILED (failed loading or failed to play or by any other reason) or CB_AudioFile.ABORTED (aborted because it was destroyed with the \"destructor\" method) property. Type number getStatusString( [realStatus]) → {string} Gets the current status of the audio file, as a string. Parameters: Name Type Argument Default Description realStatus boolean &lt;optional&gt; false If set to true, it will have in mind the \"status\" property of the used audio API object instead of the \"status\" property of the current CB_AudioFile object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 814 Returns: Returns the current status of the audio file, as a string. Possible return values are \"UNLOADED\", \"LOADING\", \"UNCHECKED\", \"CHECKING\", \"LOADED\", \"FAILED\", \"ABORTED\" or \"UNKNOWN (UNKNOWN_STATUS)\" (where \"UNKNOWN_STATUS\" will be a value from the \"status\" property not recognized as any possible status). Type string getStopAt( [numeric]) → {number|*} Tells the last \"stopAt\" parameter value used by the CB_AudioFile#play or the CB_AudioFile#resume method (or used by the equivalents methods of the same name from the used audio API object). Internally, uses the \"lastStopAt\" property of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Parameters: Name Type Argument Default Description numeric boolean &lt;optional&gt; false If set to true, it will sanitize the returning value by returning zero instead of undefined, null or any other non-numeric value. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 931 Returns: Returns the last \"stopAt\" value used by the CB_AudioFile#play or the CB_AudioFile#resume method (or used by the equivalents methods of the same name from the used audio API object). If we want it to be numeric always, the \"numeric\" parameter should be set to true. Type number | * getVolume() → {number} Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Internally, uses the \"volume\" property of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 733 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Type number getVolumeBeforeMute() → {number} Returns the volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise) that was set before the audio was muted. Internally, uses the \"volumeBeforeMute\" property of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 722 Returns: Returns the volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise) that was set before the audio was muted. If the audio was not muted before, it will contain the default volume used in the \"volume\" property of the used audio API object. Type number isPaused() → {boolean} Tells whether the audio is paused or not. Internally, uses the \"paused\" property of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 839 Returns: Returns whether the audio is paused or not. Type boolean isPlaying() → {boolean} Tells whether the audio file is playing or not. Internally, uses the CB_AudioFile#isStopped and CB_AudioFile#isPaused methods. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 828 Returns: Returns whether the audio file is playing or not. Type boolean isStopped() → {boolean} Tells whether the audio file is stopped or not. Internally, uses the \"stopped\" property of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 850 Returns: Returns whether the audio file is stopped or not. Type boolean load( [filePath] [, audioAPI] [, autoPlay] [, callbackOk] [, callbackError] [, ignoreOldValues] [, forceReload]) → {CB_AudioFile_API.WAAPI|CB_AudioFile_API.SM2|CB_AudioFile_API.ACMP|CB_AudioFile_API.AAPI|null} Loads the desired audio file with the desired options. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. This method will be called automatically if the \"autoLoad\" option was set to true when calling the CB_AudioFile#setAudioAPI method. The audio API used will be stored in the CB_AudioFile#audioAPI property.When this method is called, if the \"status\" property of the audio API object already has the \"LOADED\" status (defined in the CB_AudioFile.LOADED constant) and the \"forceReload\" parameter is not set to true, it will exit calling the given \"callbackOk\" function (if any) immediately. Otherwise, regardless the status, the status will be set to \"LOADING\" (defined in the CB_AudioFile.LOADING constant). After it, it will reach the \"UNCHECKED\" (defined in the CB_AudioFile.UNCHECKED constant). If the \"autoPlay\" parameter is not set to true, this will be the final status (and it will be necessary to call the \"checkPlaying\" method of the audio API object after it). After it and only if the \"autoPlay\" is set to true, as the \"checkPlaying\" method of the audio API object will be called internally, it will have the \"CHECKING\" status (defined in the CB_AudioFile.CHECKING constant) and finally the \"LOADED\" status (defined in the CB_AudioFile.LOADED constant) if all goes well.Although it is not recommended to do so, if this method is called when the audio API object has the \"UNCHECKED\" status (defined in the CB_AudioFile.UNCHECKED constant), it will call the \"checkPlaying\" method of the audio API object internally.Internally, it can use the CB_AudioFile#audioFileObjects property as a cache. Parameters: Name Type Argument Default Description filePath string &lt;optional&gt; CB_AudioFile#filePath The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. audioAPI string &lt;optional&gt; CB_AudioFile#audioAPI The desired audio API to be used. If not provided, it will try to use the previously-set one (in the CB_AudioFile#audioAPI property). All possible ones are defined in CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS. For example: \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). autoPlay string &lt;optional&gt; false If set to true, it will start playing the audio automatically (by calling the CB_AudioFile#play method internally) unless the \"ignoreOldValues\" parameter is set to false and the previous audio was playing or paused. If set to true and the \"status\" property of the audio API object reaches to the \"UNCHECKED\" status (defined in the CB_AudioFile.UNCHECKED constant), it will also call internally the \"checkPlaying\" method of the audio API object before anything. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the CB_AudioFile object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile object itself. ignoreOldValues string &lt;optional&gt; false If set to true, it will ignore the old values of the previous used audio API object. This means that it will neither continue playing if it was playing (changing the audio API on-the-fly) nor keep the paused status if it was paused nor copy its \"loop\" property to the new audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). forceReload string &lt;optional&gt; false Used internally as the \"forceReload\" parameter when calling the \"load\" method of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 376 To Do: Think about using the \"forceReload\" just after the \"callbackError\" to match the parameter order of the \"load\" method of all the audio API objects. Returns: Returns the used audio API object or null otherwise. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Type CB_AudioFile_API.WAAPI | CB_AudioFile_API.SM2 | CB_AudioFile_API.ACMP | CB_AudioFile_API.AAPI | null mute( [onMute]) → {number} Mutes the audio file. Internally, uses the \"mute\" method of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Parameters: Name Type Argument Description onMute function &lt;optional&gt; Callback function which will be called if it has been possible to mute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the CB_AudioFile object. Used internally as the \"onMute\" parameter (with a wrapper function) to call the \"mute\" method of the audio API object. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 762 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). If all goes well, the returning value should be zero (0). Note that, even when it returns a zero (0) value, this does not always mean that the mute has been applied successfully. Type number onStop(callbackFunction [, keepOldFunction]) → {boolean} Sets a function to execute when the audio file stops playing or removes it. Internally, uses the \"onStop\" method of the used audio API object (wrapping the given function). Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. No parameters will be received, being \"this\" the CB_AudioFile object. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 878 Returns: Returns whether the event has been set or not (removed). Type boolean pause( [onPause] [, keepPausedUnaltered]) → {boolean} Pauses the audio when it is being played. Internally, uses the \"pause\" method of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Parameters: Name Type Argument Default Description onPause function &lt;optional&gt; Function without parameters to be called when the audio is paused successfully, being \"this\" the CB_AudioFile object. Used internally as the \"onPause\" parameter (with a wrapper function) to call the \"pause\" method of the audio API object. keepPausedUnaltered boolean &lt;optional&gt; false If set to true (not recommended), the \"paused\" property of the audio API object will not be set to true and it will remain with its current value. Used internally as the \"keepPausedUnaltered\" parameter to call the \"pause\" method of the audio API object. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 696 Returns: Returns the returning value of the \"pause\" method of the audio API object. It returns false if the audio is already paused or it is stopped or if it cannot be paused. Returns true otherwise. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Type boolean play( [startAt] [, stopAt] [, loop] [, avoidDelayedPlay] [, allowedRecursiveDelay] [, onPlayStart] [, onLoadError] [, isResume]) → {boolean|integer} Plays the audio. Internally, uses the \"play\" method of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Parameters: Name Type Argument Default Description startAt number &lt;optional&gt; 0 | CB_AudioFile_API.WAAPI#lastStartAt | CB_AudioFile_API.SM2#lastStartAt | CB_AudioFile_API.ACMP#lastStartAt | CB_AudioFile_API.AAPI#lastStartAt | stopAt Time in milliseconds where we want the audio to start at. If not provided or it is not a valid number, it will use zero (0) as default which belongs to the beginning of the audio. If the value provided is greater than the \"stopAt\" provided, it will use the value set in the \"lastStartAt\" property of the used audio API object (which belongs to the \"startAt\" value the last time that the \"play\" method was called). If, even using the \"lastStartAt\" value is still greather than the \"stopAt\" provided, it will use the same value as the \"stopAt\" which means it will not play and will stop immediately. Used internally as the \"startAt\" parameter to call the \"play\" method of the audio API object. stopAt number &lt;optional&gt; CB_AudioFile_API.WAAPI#getDuration() | CB_AudioFile_API.SM2#getDuration() | CB_AudioFile_API.ACMP#getDuration() | CB_AudioFile_API.AAPI#getDuration() Time in milliseconds where we want the audio to stop at. If not provided or it is not a valid number, it will use the returning value of the \"getDuration\" method of the used audio API object (which should belong to the total duration of the audio, if it was calculated correctly). Used internally as the \"stopAt\" parameter to call the \"play\" method of the audio API object. loop boolean &lt;optional&gt; CB_AudioFile#loop Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the CB_AudioFile#onStop method) will not be called. Used internally as the \"loop\" parameter to call the \"play\" method of the audio API object. avoidDelayedPlay boolean &lt;optional&gt; false If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the \"stop\" method of the used audio API object will be called immediately. Used internally as the \"avoidDelayedPlay\" parameter to call the \"play\" method of the audio API object. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the \"stop\" method of the used audio API object will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). Used internally as the \"allowedRecursiveDelay\" parameter to call the \"play\" method of the audio API object. onPlayStart function &lt;optional&gt; Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the CB_AudioFile object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. Used internally as the \"onPlayStart\" parameter to call the \"play\" method of the audio API object. onLoadError function &lt;optional&gt; Function to be called if the audio cannot be played successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile object. Used internally as the \"onLoadError\" parameter to call the \"play\" method of the audio API object. isResume boolean &lt;optional&gt; false If set to true (not recommended) and it is a looping audio, the next loop will use the value of the \"lastStartAt\" property of the audio API object as the \"startAt\" parameter when it calls the \"play\" method again automatically (internally). Recommended for internal usage only. Used internally as the \"isResume\" parameter to call the \"play\" method of the audio API object. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 614 Returns: Returns the returning value of the \"play\" method of the audio API object. It returns false if the duration is 0 (\"startAt\" and \"stopAt\" are the same number), returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Type boolean | integer resume( [loop] [, avoidDelayedPlay] [, allowedRecursiveDelay] [, onPlayStart] [, onLoadError]) → {boolean|integer} Resumes the audio (after being paused), starting from the same point it was paused previously. Internally, uses the \"resume\" method of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Parameters: Name Type Argument Default Description loop boolean &lt;optional&gt; CB_AudioFile#loop Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the CB_AudioFile#onStop method) will not be called. Used internally as the \"loop\" parameter to call the \"resume\" method of the audio API object. avoidDelayedPlay boolean &lt;optional&gt; false If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the \"stop\" method of the used audio API object will be called immediately. Used internally as the \"avoidDelayedPlay\" parameter to call the \"resume\" method of the audio API object. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the \"stop\" method of the used audio API object will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). Used internally as the \"allowedRecursiveDelay\" parameter to call the \"resume\" method of the audio API object. onPlayStart function &lt;optional&gt; Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the CB_AudioFile object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. Used internally as the \"onPlayStart\" parameter to call the \"resume\" method of the audio API object. onLoadError function &lt;optional&gt; Function to be called if the audio cannot be played successfully. It will not be called if the audio is not paused or is stopped. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile object. Used internally as the \"onLoadError\" parameter to call the \"resume\" method of the audio API object. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 657 Returns: Returns the returning value of the \"resume\" method of the audio API object. It returns false if the audio is not paused or it is stopped, returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Type boolean | integer setAudioAPI( [audioAPI] [, autoLoad] [, autoPlay] [, callbackOk] [, callbackError] [, ignoreOldValues] [, filePath] [, forceReload]) → {string} Sets the desired audio API. This method will also be called automatically by the constructor. If the \"autoLoad\" parameter is set to true, it will call the CB_AudioFile#load method internally, changing the audio API on-the-fly, and the audio will try to continue playing if it was playing at the moment of calling this method. Check the CB_AudioFile#load method documentation for more information. If the \"autoLoad\" parameter is set to true, it is recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. The audio API used will be stored in the CB_AudioFile#audioAPI property. Parameters: Name Type Argument Default Description audioAPI string &lt;optional&gt; CB_AudioDetector.getPreferredAPI(undefined, false, null) || CB_AudioDetector.getPreferredAPI(undefined, true, null) The desired audio API to be used. If not provided, it will try to calculate the best one for the current client by calling the CB_AudioDetector.getPreferredAPI function internally. Audio API support will depend on the current client being used. All possible ones are defined in CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS. For example: \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). Used internally as the \"audioAPI\" parameter when calling the CB_AudioFile#load method internally (only when the \"autoLoad\" parameter is set to true). autoLoad string &lt;optional&gt; true If set to false, it will not call the CB_AudioFile#load method internally and will only set the CB_AudioFile#audioAPI property (not recommended). autoPlay string &lt;optional&gt; false Used internally as the \"autoPlay\" parameter when calling the CB_AudioFile#load method internally (only when the \"autoLoad\" parameter is set to true). callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the CB_AudioFile object itself. Used internally as the \"callbackOk\" parameter when calling the CB_AudioFile#load method internally (only when the \"autoLoad\" parameter is set to true). callbackError function &lt;optional&gt; Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile object itself. Used internally as the \"callbackError\" parameter when calling the CB_AudioFile#load method internally (only when the \"autoLoad\" parameter is set to true). ignoreOldValues string &lt;optional&gt; false Used internally as the \"ignoreOldValues\" parameter when calling the CB_AudioFile#load method internally (only when the \"autoLoad\" parameter is set to true). filePath string &lt;optional&gt; CB_AudioFile#filePath Used internally as the \"filePath\" parameter when calling the CB_AudioFile#load method internally (only when the \"autoLoad\" parameter is set to true). forceReload string &lt;optional&gt; false Used internally as the \"forceReload\" parameter when calling the CB_AudioFile#load method internally (only when the \"autoLoad\" parameter is set to true). Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 322 To Do: Think about using the \"forceReload\" just after the \"callbackError\" to match the parameter order of the \"load\" method of all the audio API objects. Returns: Returns the desired audio API that has been tried to set, in upper case (successfully or not). Type string setVolume( [volume] [, forceSetVolumeProperty] [, onSetVolume]) → {number} Sets the desired volume for the audio file (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Internally, uses the \"setVolume\" method of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Parameters: Name Type Argument Default Description volume number &lt;optional&gt; CB_Speaker.getVolume() | CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Used internally as the \"volume\" parameter to call the \"setVolume\" method of the audio API object. forceSetVolumeProperty boolean &lt;optional&gt; false If set to true (not recommended), it will change the \"volume\" property of the used audio API object even when the volume failed to be changed. Used internally as the \"forceSetVolumeProperty\" parameter to call the \"setVolume\" method of the audio API object. onSetVolume function &lt;optional&gt; Callback function which will be called if it has been possible to set the volume (or at least it was possible to try it). It will not receive any parameters, being \"this\" the CB_AudioFile object. Used internally as the \"onSetVolume\" parameter (with a wrapper function) to call the \"setVolume\" method of the audio API object. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 748 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Type number stop( [keepStoppedUnaltered] [, avoidOnStop] [, forceOnStop]) → {boolean} Stops the audio. Internally, uses the \"stop\" method of the used audio API object. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Parameters: Name Type Argument Default Description keepStoppedUnaltered boolean &lt;optional&gt; false If set to true (not recommended), the \"stopped\" property of the audio API object will not be set to true and it will remain with its current value. Used internally as the \"keepStoppedUnaltered\" parameter to call the \"stop\" method of the audio API object. avoidOnStop boolean &lt;optional&gt; false If set to false and there is an \"onStop\" function defined (through the CB_AudioFile#onStop method), it will be called after stopping the audio (or after trying to do it, at least) but only if either the \"forceOnStop\" parameter is set to true or if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. If set to true, the \"onStop\" function (if any) will not be called at all. Used internally as the \"avoidOnStop\" parameter to call the \"stop\" method of the audio API object. forceOnStop boolean &lt;optional&gt; false If it is set to true and the \"avoidOnStop\" parameter is set to false and there is an \"onStop\" function defined (through the CB_AudioFile#onStop method), it will be called regardless the audio was stopped before or not. If set to false, the \"onStop\" function (if any) will only be called if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. This parameter will be ignored if the \"avoidOnStop\" parameter is set to true. Used internally as the \"forceOnStop\" parameter to call the \"stop\" method of the audio API object. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 711 Returns: Returns the returning value of the \"stop\" method of the audio API object. It returns false if the stopping action cannot be performed at all (this could happen with the internal audio API has not been loaded properly, for example). Returns true otherwise (this only means that it has been tried to be stopped but it could not be successfully). Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Type boolean unmute( [onUnmute]) → {number} Restores audio after muting it (unmutes it). Internally, uses the \"unmute\" method of the used audio API object which uses its own \"volumeBeforeMute\" property. Possible internal audio API objects are CB_AudioFile_API.WAAPI object for \"WAAPI\" (HTML5 Web Audio API), CB_AudioFile_API.SM2 object for \"SM2\" (SoundManager 2), CB_AudioFile_API.ACMP object for \"ACMP\" (Apache Cordova Media Plugin) or CB_AudioFile_API.AAPI object for \"AAPI\" (HTML5 Audio API). Parameters: Name Type Argument Description onUnmute function &lt;optional&gt; Callback function which will be called if it has been possible to unmute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the CB_AudioFile object. Used internally as the \"onUnmute\" parameter (with a wrapper function) to call the \"unmute\" method of the audio API object. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 776 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Type number Type Definitions OPTIONS Object with the options for an audio file. The format is the following one: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. Type: Object Properties: Name Type Argument Default Description autoLoad boolean &lt;optional&gt; CB_AudioFile#DEFAULT_OPTIONS.autoLoad Value which will be used as the \"autoLoad\" parameter when calling the CB_AudioFile#setAudioAPI method internally (when the constructor is called). autoPlay boolean &lt;optional&gt; CB_AudioFile#DEFAULT_OPTIONS.autoPlay Value which will be used as the \"autoPlay\" parameter when calling the CB_AudioFile#setAudioAPI method internally (when the constructor is called). loop boolean &lt;optional&gt; CB_AudioFile#DEFAULT_OPTIONS.loop Value that will be used for the CB_AudioFile#loop property. volume number &lt;optional&gt; CB_AudioFile#DEFAULT_OPTIONS.volume The desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise) that will be used for the CB_AudioFile#volume property. Source: CrossBase/audiovisual/audio/CB_AudioFile.js, line 186 × Search results Close "},"CB_AudioFile_API.AAPI.html":{"id":"CB_AudioFile_API.AAPI.html","title":"Class: CB_AudioFile_API.AAPI","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Class: CB_AudioFile_API.AAPI CB_AudioFile_API.AAPI Class to manage an audio file using \"AAPI\" (HTML5 Audio API). Used by the CB_AudioFile class internally and it shares most of its properties and methods. Recommended for internal usage only. new CB_AudioFile_API.AAPI(filePath [, audioId] [, options] [, callbackOk] [, callbackError]) → {CB_AudioFile_API.AAPI} The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.) if the \"autoPlay\" option is set to true, as some web clients may need this at least the first time in order to be able to play the audio. Parameters: Name Type Argument Default Description filePath string The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. audioId string &lt;optional&gt; 'CB_AUDIOFILE_AAPI_' + CB_AudioFile_API.AAPI._idUnique++ Desired identifier for the audio object. If not provided, an automatic unique ID will be calculated. Note that it is not case sensitive and it should be unique for each object. options CB_AudioFile_API.AAPI.OPTIONS &lt;optional&gt; CB_AudioFile_API.AAPI#DEFAULT_OPTIONS Object with the desired options. callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the CB_AudioFile_API.AAPI object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if could be determined), being \"this\" the CB_AudioFile_API.AAPI object itself. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 17 To Do: Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). Note that the \"id\" is not case sensitive and it should be unique for each object. Method getCopy and static method filterProperties (similar to the ones from CB_GraphicSprites and CB_GraphicSpritesScene). Returns: Returns a new CB_AudioFile_API.AAPI object. Type CB_AudioFile_API.AAPI Members &lt;readonly&gt; audioObject :HTMLAudioElement Stores the HTMLAudioElement object of the audio, used by the \"AAPI\" (HTML5 Audio API). Type: HTMLAudioElement Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 162 &lt;constant&gt; DEFAULT_OPTIONS :CB_AudioFile_API.AAPI.OPTIONS Keeps the default options when an object is created. Format: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. Type: CB_AudioFile_API.AAPI.OPTIONS Default Value: { autoLoad: true, autoPlay: false, loop: false, volume: CB_AudioFile_API.AAPI.prototype.DEFAULT_VOLUME } Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 45 &lt;constant&gt; DEFAULT_VOLUME :number Keeps the default volume. If the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT property is true, this will keep the result of calling the CB_Speaker.getVolume function. Otherwise, it will use the value of the CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME variable. Type: number Default Value: CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 37 &lt;readonly&gt; filePath :string Stores the path of the audio file or the data URI. NOTE: Only some clients with some audio APIs will support data URIs. Type: string Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 99 &lt;readonly&gt; id :string Stores the identifier for the audio file. Type: string Default Value: 'CB_AUDIOFILE_AAPI_' + CB_AudioFile_API.AAPI._idUnique++ Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 90 &lt;readonly&gt; lastStartAt :number Stores the last \"startAt\" parameter value used by the CB_AudioFile_API.AAPI#play or the CB_AudioFile_API.AAPI#resume method. Type: number Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 144 &lt;readonly&gt; lastStopAt :number Stores the last \"stopAt\" parameter value used by the CB_AudioFile_API.AAPI#play or the CB_AudioFile_API.AAPI#resume method. Type: number Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 153 &lt;readonly&gt; loop :boolean Defines whether the file loops by default when the audio is played or not. Its value will be modified automatically whenever the CB_AudioFile_API.AAPI#play method is called, getting the value from the \"loop\" parameter (but only if contains a boolean). Type: boolean Default Value: CB_AudioFile_API.AAPI.prototype.DEFAULT_OPTIONS.loop Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 63 &lt;readonly&gt; onStopFunction :function Function to call when the audio stops. Type: function Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 135 &lt;readonly&gt; paused :boolean Tells whether the audio is paused or not. Type: boolean Default Value: false Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 108 &lt;readonly&gt; pauseTime :number Stores the time (in milliseconds) when the audio has been paused. Type: number Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 117 &lt;readonly&gt; status :integer Tells whether the file is unloaded (CB_AudioFile.UNLOADED), loading (CB_AudioFile.LOADING), unchecked (CB_AudioFile.UNCHECKED), checking (CB_AudioFile.CHECKING), loaded (CB_AudioFile.LOADED), failed (CB_AudioFile.FAILED) or aborted (CB_AudioFile.ABORTED). Type: integer Default Value: CB_AudioFile.UNLOADED Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 54 &lt;readonly&gt; stopped :boolean Tells whether the audio is stopped or not. Type: boolean Default Value: true Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 126 &lt;readonly&gt; volume :number Stores the volume of this audio. Accepted values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is false or otherwise MAX_VOLUME is the returning value of the CB_Speaker.getVolume function. Type: number Default Value: CB_AudioFile_API.AAPI.prototype.DEFAULT_OPTIONS.volume Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 72 &lt;readonly&gt; volumeBeforeMute :number Stores the volume of this audio before it was muted (to restore it later). Valid values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is false or otherwise MAX_VOLUME is the returning value of the CB_Speaker.getVolume function. Type: number Default Value: CB_AudioFile_API.AAPI#volume Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 81 Methods checkPlaying( [callbackOk] [, callbackError] [, ignoreStatus] [, ignoreQueue] [, useCache]) → {boolean} Checks whether the audio can be played or not. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. Also recommended to use before calling the CB_AudioFile_API.AAPI#play method the first time. The checking action will only be performed if the value of the CB_AudioFile_API.AAPI#status property belongs to the CB_AudioFile.UNCHECKED or to the CB_AudioFile.CHECKING value. After checking, if the audio can be played, the CB_AudioFile_API.AAPI#status of the object will get the value of CB_AudioFile.LOADED. Otherwise, if it cannot be played, the CB_AudioFile_API.AAPI#status property will get the value of {CB_AudioFile.FAILED}. Parameters: Name Type Argument Default Description callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been checked successfully, being \"this\" the CB_AudioFile_API.AAPI object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been checked successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.AAPI object itself. ignoreStatus boolean &lt;optional&gt; false If set to false and the CB_AudioFile_API.AAPI#status property does not belong neither to the \"UNCHECKED\" status (defined in the CB_AudioFile.UNCHECKED constant) nor to the \"CHECKING\" status (defined in the CB_AudioFile.CHECKING constant), it will fail calling the \"callbackError\" function (if any). If set to true, it will try to perform the checking action regardless the status of the audio. ignoreQueue boolean &lt;optional&gt; false If set to false and there is already the maximum number of audio files being checked (defined internally), the function will exit and it will call itself automatically again and again until the checking process can be performed (when its queue turn has been reached). This is done for performance purposes. useCache boolean &lt;optional&gt; false This parameter will be ignored in this audio API. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 517 Returns: Returns false if the checking could not be performed and failed. If it returns true, it can mean either the checking has been processed successfully or it will fail in the future, so it is recommended to ignore the returning value and use the callback functions instead. Type boolean destructor( [stopSound] [, keepStoppedUnaltered] [, avoidOnStop] [, forceOnStop]) Destroys the audio file object and frees memory. Sets its current CB_AudioFile_API.AAPI#status property to ABORTED (CB_AudioFile.ABORTED value). Parameters: Name Type Argument Default Description stopSound boolean &lt;optional&gt; false If set to true, it will also call the CB_AudioFile_API.AAPI#stop method. keepStoppedUnaltered boolean &lt;optional&gt; false Used internally as the \"keepStoppedUnaltered\" parameter to call the CB_AudioFile_API.AAPI#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. avoidOnStop boolean &lt;optional&gt; false Used internally as the \"avoidOnStop\" parameter to call the CB_AudioFile_API.AAPI#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. forceOnStop boolean &lt;optional&gt; false Used internally as the \"forceOnStop\" parameter to call the CB_AudioFile_API.AAPI#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 255 getCurrentTime() → {number} Gets the current time (in milliseconds) which belongs to the position where the audio is currently playing or where it has been paused. Note that some audio APIs and clients could give wrong values. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 1155 Returns: Returns the current time (in milliseconds). Note that some audio APIs and clients could give wrong values. Type number getDuration() → {number} Tells the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 713 Returns: Returns the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. Type number getProgress() → {number} Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 1214 Returns: Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Type number load( [filePath] [, autoPlay] [, callbackOk] [, callbackError] [, forceReload]) → {CB_AudioFile_API.AAPI|null} Loads the desired audio file with the desired options. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. This method will be called automatically by the constructor if the \"autoLoad\" option was set to true in its given \"options\" parameter.When this method is called, if the CB_AudioFile_API.AAPI#status property already has the \"LOADED\" status (defined in the CB_AudioFile.LOADED constant) and the \"forceReload\" parameter is not set to true, it will exit calling the given \"callbackOk\" function (if any) immediately. Otherwise, regardless the status, the status will be set to \"LOADING\" (defined in the CB_AudioFile.LOADING constant). After it, it will reach the \"UNCHECKED\" (defined in the CB_AudioFile.UNCHECKED constant). If the \"autoPlay\" parameter is not set to true, this will be the final status (and it will be necessary to call the CB_AudioFile_API.AAPI#checkPlaying method after it). After it and only if the \"autoPlay\" is set to true, as the CB_AudioFile_API.AAPI#checkPlaying method will be called internally, it will have the \"CHECKING\" status (defined in the CB_AudioFile.CHECKING constant) and finally the \"LOADED\" status (defined in the CB_AudioFile.LOADED constant) if all goes well. Parameters: Name Type Argument Default Description filePath string &lt;optional&gt; CB_AudioFile_API.AAPI#filePath The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. autoPlay string &lt;optional&gt; false If set to true, it will start playing the audio automatically (by calling the CB_AudioFile_API.AAPI#play method internally). If set to true and the CB_AudioFile_API.AAPI#status property reaches to the \"UNCHECKED\" status (defined in the CB_AudioFile.UNCHECKED constant), it will also call internally the CB_AudioFile_API.AAPI#checkPlaying method. callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the CB_AudioFile_API.AAPI object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.AAPI object itself. forceReload boolean &lt;optional&gt; false If set to false, the \"filePath\" has not been changed from the previously used and the CB_AudioFile_API.AAPI#status property belongs to the \"LOADED\" status (defined in the CB_AudioFile.LOADED constant), it will exit the method without loading the audio file again (calling the \"callbackOk\" function, if any). Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 294 Returns: Returns the audio API object (if it was possible to create) or null otherwise. Type CB_AudioFile_API.AAPI | null mute( [onMute]) → {number} Mutes the audio file. Parameters: Name Type Argument Description onMute function &lt;optional&gt; Callback function which will be called if it has been possible to mute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the CB_AudioFile_API.AAPI object. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 1119 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). If all goes well, the returning value should be zero (0). Note that, even when it returns a zero (0) value, this does not always mean that the mute has been applied successfully. Type number onStop(callbackFunction [, keepOldFunction]) → {boolean} Sets a function to execute when the audio file stops playing or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. No parameters will be received, being \"this\" the CB_AudioFile_API.AAPI object. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 1177 Returns: Returns whether the event has been set or not (removed). Type boolean pause( [onPause] [, keepPausedUnaltered]) → {boolean} Pauses the audio when it is being played. Parameters: Name Type Argument Default Description onPause function &lt;optional&gt; Function without parameters to be called when the audio is paused successfully, being \"this\" the CB_AudioFile_API.AAPI object. keepPausedUnaltered boolean &lt;optional&gt; false If set to true (not recommended), the CB_AudioFile_API.AAPI#paused property will not be set to true and it will remain with its current value. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 1025 Returns: It returns false if the audio is already paused or it is stopped or if it cannot be paused. Returns true otherwise. Type boolean play( [startAt] [, stopAt] [, loop] [, avoidDelayedPlay] [, allowedRecursiveDelay] [, onPlayStart] [, onLoadError] [, isResume] [, isLooping] [, startPlayingTime]) → {boolean|integer} Plays the audio. Parameters: Name Type Argument Default Description startAt number &lt;optional&gt; 0 | CB_AudioFile_API.AAPI#lastStartAt | stopAt Time in milliseconds where we want the audio to start at. If not provided or it is not a valid number, it will use zero (0) as default which belongs to the beginning of the audio. If the value provided is greater than the \"stopAt\" provided, it will use the value set in the CB_AudioFile_API.AAPI#lastStartAt property (which belongs to the \"startAt\" value the last time that this method was called). If, even using the CB_AudioFile_API.AAPI#lastStartAt value is still greather than the \"stopAt\" provided, it will use the same value as the \"stopAt\" which means it will not play and will stop immediately. stopAt number &lt;optional&gt; CB_AudioFile_API.AAPI#getDuration() Time in milliseconds where we want the audio to stop at. If not provided or it is not a valid number, it will use the returning value of the CB_AudioFile_API.AAPI#getDuration method (which should belong to the total duration of the audio, if it was calculated correctly). loop boolean &lt;optional&gt; CB_AudioFile_API.AAPI#loop Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the CB_AudioFile_API.AAPI#onStop method) will not be called. avoidDelayedPlay boolean &lt;optional&gt; false If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the \"stop\" method will be called immediately. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the CB_AudioFile_API.AAPI#stop method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). onPlayStart function &lt;optional&gt; Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the CB_AudioFile_API.AAPI object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. onLoadError function &lt;optional&gt; Function to be called if the audio cannot be played successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.AAPI object. isResume boolean &lt;optional&gt; false If set to true (not recommended) and it is a looping audio, the next loop will use the value of the CB_AudioFile_API.AAPI#lastStartAt property as the \"startAt\" parameter when it calls this method again automatically (internally). Recommended for internal usage only. isLooping boolean &lt;optional&gt; false Used to determine whether this method was called automatically again by itself because it is looping the audio. Recommended for internal usage only. startPlayingTime integer &lt;optional&gt; Contains the time when the audio should start playing. Recommended for internal usage only. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 789 Returns: It returns false if the duration is 0 (\"startAt\" and \"stopAt\" are the same number), returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. Type boolean | integer resume( [loop] [, avoidDelayedPlay] [, allowedRecursiveDelay] [, onPlayStart] [, onLoadError]) → {boolean|integer} Resumes the audio (after being paused), starting from the same point it was paused previously. Parameters: Name Type Argument Default Description loop boolean &lt;optional&gt; CB_AudioFile_API.AAPI#loop Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the CB_AudioFile_API.AAPI#onStop method) will not be called. avoidDelayedPlay boolean &lt;optional&gt; false If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the CB_AudioFile_API.AAPI#stop method will be called immediately. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the CB_AudioFile_API.AAPI#stop method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). onPlayStart function &lt;optional&gt; Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the CB_AudioFile_API.AAPI object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. onLoadError function &lt;optional&gt; Function to be called if the audio cannot be played successfully. It will not be called if the audio is not paused or is stopped. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.AAPI object. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 998 Returns: Returns the returning value of the CB_AudioFile_API.AAPI#play method which is called internally. It returns false if the audio is not paused or it is stopped, returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. Type boolean | integer setVolume( [volume] [, forceSetVolumeProperty] [, onSetVolume] [, saveForUnmute]) → {number} Sets the desired volume for the audio file (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Parameters: Name Type Argument Default Description volume number &lt;optional&gt; CB_Speaker.getVolume() | CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). forceSetVolumeProperty boolean &lt;optional&gt; false If set to true (not recommended), it will change the CB_AudioFile_API.AAPI#volume property even when the volume failed to be changed. onSetVolume function &lt;optional&gt; Callback function which will be called if it has been possible to set the volume (or at least it was possible to try it). It will not receive any parameters, being \"this\" the CB_AudioFile_API.AAPI object. saveForUnmute boolean &lt;optional&gt; false If set to true (not recommended), it will save internally the current volume before setting it so it will restore the same volume again after calling the CB_AudioFile_API.AAPI#unmute method. Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 1081 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Type number stop( [keepStoppedUnaltered] [, avoidOnStop] [, forceOnStop]) → {boolean} Stops the audio. Parameters: Name Type Argument Default Description keepStoppedUnaltered boolean &lt;optional&gt; false If set to true (not recommended), the CB_AudioFile_API.AAPI#stopped property will not be set to true and it will remain with its current value. avoidOnStop boolean &lt;optional&gt; false If set to false and there is an \"onStop\" function defined (through the CB_AudioFile_API.AAPI#onStop method), it will be called after stopping the audio (or after trying to do it, at least) but only if either the \"forceOnStop\" parameter is set to true or if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. If set to true, the \"onStop\" function (if any) will not be called at all. forceOnStop boolean &lt;optional&gt; false If it is set to true and the \"avoidOnStop\" parameter is set to false and there is an \"onStop\" function defined (through the CB_AudioFile_API.AAPI#onStop method), it will be called regardless the audio was stopped before or not. If set to false, the \"onStop\" function (if any) will only be called if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. This parameter will be ignored if the \"avoidOnStop\" parameter is set to true. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 1051 Returns: It returns false if the stopping action cannot be performed at all (this could happen when the audio has not been loaded properly, for example). Returns true otherwise (this only means that it has been tried to be stopped but it could not be successfully). Type boolean unmute( [onUnmute]) → {number} Restores audio after muting it (unmutes it). Parameters: Name Type Argument Description onUnmute function &lt;optional&gt; Callback function which will be called if it has been possible to unmute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the CB_AudioFile_API.AAPI object. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 1137 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Type number Type Definitions OPTIONS Object with the options for an audio file. The format is the following one: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. Type: Object Properties: Name Type Argument Default Description autoLoad boolean &lt;optional&gt; CB_AudioFile_API.AAPI#DEFAULT_OPTIONS.autoLoad If set to false, it will not call the CB_AudioFile_API.AAPI#load method internally when the constructor is called (not recommended). autoPlay boolean &lt;optional&gt; CB_AudioFile_API.AAPI#DEFAULT_OPTIONS.autoPlay Value which will be used as the \"autoPlay\" parameter when calling the CB_AudioFile_API.AAPI#load method internally, only when the \"autoLoad\" is set to true (when the constructor is called). loop boolean &lt;optional&gt; CB_AudioFile_API.AAPI#DEFAULT_OPTIONS.loop Value that will be used for the CB_AudioFile_API.AAPI#loop property. volume number &lt;optional&gt; CB_AudioFile_API.AAPI#DEFAULT_OPTIONS.volume The desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise) that will be used for the CB_AudioFile_API.AAPI#volume property. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_AAPI.js, line 194 × Search results Close "},"CB_AudioFile_API.ACMP.html":{"id":"CB_AudioFile_API.ACMP.html","title":"Class: CB_AudioFile_API.ACMP","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Class: CB_AudioFile_API.ACMP CB_AudioFile_API.ACMP Class to manage an audio file using \"ACMP\" (Apache Cordova Media Plugin). Used by the CB_AudioFile class internally and it shares most of its properties and methods. Recommended for internal usage only. new CB_AudioFile_API.ACMP(filePath [, audioId] [, options] [, callbackOk] [, callbackError]) → {CB_AudioFile_API.ACMP} The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.) if the \"autoPlay\" option is set to true, as some web clients may need this at least the first time in order to be able to play the audio. Parameters: Name Type Argument Default Description filePath string The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. audioId string &lt;optional&gt; 'CB_AUDIOFILE_ACMP_' + CB_AudioFile_API.ACMP._idUnique++ Desired identifier for the audio object. If not provided, an automatic unique ID will be calculated. Note that it is not case sensitive and it should be unique for each object. options CB_AudioFile_API.ACMP.OPTIONS &lt;optional&gt; CB_AudioFile_API.ACMP#DEFAULT_OPTIONS Object with the desired options. callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the CB_AudioFile_API.ACMP object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if could be determined), being \"this\" the CB_AudioFile_API.ACMP object itself. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 10 To Do: Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). Note that the \"id\" is not case sensitive and it should be unique for each object. Method getCopy and static method filterProperties (similar to the ones from CB_GraphicSprites and CB_GraphicSpritesScene). Returns: Returns a new CB_AudioFile_API.ACMP object. Type CB_AudioFile_API.ACMP Members &lt;constant&gt; DEFAULT_OPTIONS :CB_AudioFile_API.ACMP.OPTIONS Keeps the default options when an object is created. Format: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. Type: CB_AudioFile_API.ACMP.OPTIONS Default Value: { autoLoad: true, autoPlay: false, loop: false, volume: CB_AudioFile_API.ACMP.prototype.DEFAULT_VOLUME } Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 38 &lt;constant&gt; DEFAULT_VOLUME :number Keeps the default volume. If the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT property is true, this will keep the result of calling the CB_Speaker.getVolume function. Otherwise, it will use the value of the CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME variable. Type: number Default Value: CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 30 &lt;readonly&gt; filePath :string Stores the path of the audio file or the data URI. NOTE: Only some clients with some audio APIs will support data URIs. Type: string Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 92 &lt;readonly&gt; id :string Stores the identifier for the audio file. Type: string Default Value: 'CB_AUDIOFILE_ACMP_' + CB_AudioFile_API.ACMP._idUnique++ Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 83 &lt;readonly&gt; lastStartAt :number Stores the last \"startAt\" parameter value used by the CB_AudioFile_API.ACMP#play or the CB_AudioFile_API.ACMP#resume method. Type: number Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 137 &lt;readonly&gt; lastStopAt :number Stores the last \"stopAt\" parameter value used by the CB_AudioFile_API.ACMP#play or the CB_AudioFile_API.ACMP#resume method. Type: number Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 146 &lt;readonly&gt; loop :boolean Defines whether the file loops by default when the audio is played or not. Its value will be modified automatically whenever the CB_AudioFile_API.ACMP#play method is called, getting the value from the \"loop\" parameter (but only if contains a boolean). Type: boolean Default Value: CB_AudioFile_API.ACMP.prototype.DEFAULT_OPTIONS.loop Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 56 &lt;readonly&gt; mediaObject :Object Stores the Media object of the audio, used by the \"ACMP\" (Apache Cordova Media Plugin). Type: Object Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 155 &lt;readonly&gt; onStopFunction :function Function to call when the audio stops. Type: function Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 128 &lt;readonly&gt; paused :boolean Tells whether the audio is paused or not. Type: boolean Default Value: false Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 101 &lt;readonly&gt; pauseTime :number Stores the time (in milliseconds) when the audio has been paused. Type: number Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 110 &lt;readonly&gt; position :number Stores the current position (in seconds) where the audio is playing (returned by the getCurrentPosition method), used by the \"ACMP\" (Apache Cordova Media Plugin). Type: number Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 164 &lt;readonly&gt; status :integer Tells whether the file is unloaded (CB_AudioFile.UNLOADED), loading (CB_AudioFile.LOADING), unchecked (CB_AudioFile.UNCHECKED), checking (CB_AudioFile.CHECKING), loaded (CB_AudioFile.LOADED), failed (CB_AudioFile.FAILED) or aborted (CB_AudioFile.ABORTED). Type: integer Default Value: CB_AudioFile.UNLOADED Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 47 &lt;readonly&gt; stopped :boolean Tells whether the audio is stopped or not. Type: boolean Default Value: true Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 119 &lt;readonly&gt; volume :number Stores the volume of this audio. Accepted values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is false or otherwise MAX_VOLUME is the returning value of the CB_Speaker.getVolume function. Type: number Default Value: CB_AudioFile_API.ACMP.prototype.DEFAULT_OPTIONS.volume Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 65 &lt;readonly&gt; volumeBeforeMute :number Stores the volume of this audio before it was muted (to restore it later). Valid values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is false or otherwise MAX_VOLUME is the returning value of the CB_Speaker.getVolume function. Type: number Default Value: CB_AudioFile_API.ACMP#volume Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 74 Methods checkPlaying( [callbackOk] [, callbackError] [, ignoreStatus] [, ignoreQueue] [, useCache] [, isSwapObject]) → {boolean} Checks whether the audio can be played or not. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. Also recommended to use before calling the CB_AudioFile_API.ACMP#play method the first time. The checking action will only be performed if the value of the CB_AudioFile_API.ACMP#status property belongs to the CB_AudioFile.UNCHECKED or to the CB_AudioFile.CHECKING value. After checking, if the audio can be played, the CB_AudioFile_API.ACMP#status of the object will get the value of CB_AudioFile.LOADED. Otherwise, if it cannot be played, the CB_AudioFile_API.ACMP#status property will get the value of {CB_AudioFile.FAILED}. Parameters: Name Type Argument Default Description callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been checked successfully, being \"this\" the CB_AudioFile_API.ACMP object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been checked successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.ACMP object itself. ignoreStatus boolean &lt;optional&gt; false If set to false and the CB_AudioFile_API.ACMP#status property does not belong neither to the \"UNCHECKED\" status (defined in the CB_AudioFile.UNCHECKED constant) nor to the \"CHECKING\" status (defined in the CB_AudioFile.CHECKING constant), it will fail calling the \"callbackError\" function (if any). If set to true, it will try to perform the checking action regardless the status of the audio. ignoreQueue boolean &lt;optional&gt; false This parameter will be ignored in this audio API. useCache boolean &lt;optional&gt; false This parameter will be ignored in this audio API. isSwapObject boolean &lt;optional&gt; false Defines whether the Media object to check is a swap object or the normal one (a swap object is stored internally as it is necessary due ACMP issues when looping a sprite near the end of the audio file). Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 521 Returns: Returns false if the checking could not be performed and failed. If it returns true, it can mean either the checking has been processed successfully or it will fail in the future, so it is recommended to ignore the returning value and use the callback functions instead. Type boolean destructor( [stopSound] [, keepStoppedUnaltered] [, avoidOnStop] [, forceOnStop]) Destroys the audio file object and frees memory. Sets its current CB_AudioFile_API.ACMP#status property to ABORTED (CB_AudioFile.ABORTED value). Parameters: Name Type Argument Default Description stopSound boolean &lt;optional&gt; false If set to true, it will also call the CB_AudioFile_API.ACMP#stop method. keepStoppedUnaltered boolean &lt;optional&gt; false Used internally as the \"keepStoppedUnaltered\" parameter to call the CB_AudioFile_API.ACMP#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. avoidOnStop boolean &lt;optional&gt; false Used internally as the \"avoidOnStop\" parameter to call the CB_AudioFile_API.ACMP#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. forceOnStop boolean &lt;optional&gt; false Used internally as the \"forceOnStop\" parameter to call the CB_AudioFile_API.ACMP#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 255 getCurrentTime() → {number} Gets the current time (in milliseconds) which belongs to the position where the audio is currently playing or where it has been paused. Note that some audio APIs and clients could give wrong values. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 1066 Returns: Returns the current time (in milliseconds). Note that some audio APIs and clients could give wrong values. Type number getDuration( [mediaObject]) → {number} Tells the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. Parameters: Name Type Argument Default Description mediaObject Object &lt;optional&gt; CB_AudioFile_API.ACMP#mediaObject Media object whose audio duration we want to check. Used internally to check either normal or swap Media object (a swap object is stored internally as it is necessary due ACMP issues when looping a sprite near the end of the audio file). Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 680 Returns: Returns the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. Type number getProgress() → {number} Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 1126 Returns: Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Type number load( [filePath] [, autoPlay] [, callbackOk] [, callbackError] [, forceReload]) → {CB_AudioFile_API.ACMP|null} Loads the desired audio file with the desired options. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. This method will be called automatically by the constructor if the \"autoLoad\" option was set to true in its given \"options\" parameter.When this method is called, if the CB_AudioFile_API.ACMP#status property already has the \"LOADED\" status (defined in the CB_AudioFile.LOADED constant) and the \"forceReload\" parameter is not set to true, it will exit calling the given \"callbackOk\" function (if any) immediately. Otherwise, regardless the status, the status will be set to \"LOADING\" (defined in the CB_AudioFile.LOADING constant). After it, it will reach the \"UNCHECKED\" (defined in the CB_AudioFile.UNCHECKED constant). If the \"autoPlay\" parameter is not set to true, this will be the final status (and it will be necessary to call the CB_AudioFile_API.ACMP#checkPlaying method after it). After it and only if the \"autoPlay\" is set to true, as the CB_AudioFile_API.ACMP#checkPlaying method will be called internally, it will have the \"CHECKING\" status (defined in the CB_AudioFile.CHECKING constant) and finally the \"LOADED\" status (defined in the CB_AudioFile.LOADED constant) if all goes well. Parameters: Name Type Argument Default Description filePath string &lt;optional&gt; CB_AudioFile_API.ACMP#filePath The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. autoPlay string &lt;optional&gt; false If set to true, it will start playing the audio automatically (by calling the CB_AudioFile_API.ACMP#play method internally). If set to true and the CB_AudioFile_API.ACMP#status property reaches to the \"UNCHECKED\" status (defined in the CB_AudioFile.UNCHECKED constant), it will also call internally the CB_AudioFile_API.ACMP#checkPlaying method. callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the CB_AudioFile_API.ACMP object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.ACMP object itself. forceReload boolean &lt;optional&gt; false If set to false, the \"filePath\" has not been changed from the previously used and the CB_AudioFile_API.ACMP#status property belongs to the \"LOADED\" status (defined in the CB_AudioFile.LOADED constant), it will exit the method without loading the audio file again (calling the \"callbackOk\" function, if any). Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 288 Returns: Returns the audio API object (if it was possible to create) or null otherwise. Type CB_AudioFile_API.ACMP | null mute( [onMute]) → {number} Mutes the audio file. Parameters: Name Type Argument Description onMute function &lt;optional&gt; Callback function which will be called if it has been possible to mute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the CB_AudioFile_API.ACMP object. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 1030 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). If all goes well, the returning value should be zero (0). Note that, even when it returns a zero (0) value, this does not always mean that the mute has been applied successfully. Type number onStop(callbackFunction [, keepOldFunction]) → {boolean} Sets a function to execute when the audio file stops playing or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. No parameters will be received, being \"this\" the CB_AudioFile_API.ACMP object. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 1089 Returns: Returns whether the event has been set or not (removed). Type boolean pause( [onPause] [, keepPausedUnaltered]) → {boolean} Pauses the audio when it is being played. Parameters: Name Type Argument Default Description onPause function &lt;optional&gt; Function without parameters to be called when the audio is paused successfully, being \"this\" the CB_AudioFile_API.ACMP object. keepPausedUnaltered boolean &lt;optional&gt; false If set to true (not recommended), the CB_AudioFile_API.ACMP#paused property will not be set to true and it will remain with its current value. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 931 Returns: It returns false if the audio is already paused or it is stopped or if it cannot be paused. Returns true otherwise. Type boolean play( [startAt] [, stopAt] [, loop] [, avoidDelayedPlay] [, allowedRecursiveDelay] [, onPlayStart] [, onLoadError] [, isResume] [, isLooping] [, startPlayingTime]) → {boolean|integer} Plays the audio. Parameters: Name Type Argument Default Description startAt number &lt;optional&gt; 0 | CB_AudioFile_API.ACMP#lastStartAt | stopAt Time in milliseconds where we want the audio to start at. If not provided or it is not a valid number, it will use zero (0) as default which belongs to the beginning of the audio. If the value provided is greater than the \"stopAt\" provided, it will use the value set in the CB_AudioFile_API.ACMP#lastStartAt property (which belongs to the \"startAt\" value the last time that this method was called). If, even using the CB_AudioFile_API.ACMP#lastStartAt value is still greather than the \"stopAt\" provided, it will use the same value as the \"stopAt\" which means it will not play and will stop immediately. stopAt number &lt;optional&gt; CB_AudioFile_API.ACMP#getDuration() Time in milliseconds where we want the audio to stop at. If not provided or it is not a valid number, it will use the returning value of the CB_AudioFile_API.ACMP#getDuration method (which should belong to the total duration of the audio, if it was calculated correctly). loop boolean &lt;optional&gt; CB_AudioFile_API.ACMP#loop Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the CB_AudioFile_API.ACMP#onStop method) will not be called. avoidDelayedPlay boolean &lt;optional&gt; false If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the \"stop\" method will be called immediately. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the CB_AudioFile_API.ACMP#stop method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). onPlayStart function &lt;optional&gt; Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the CB_AudioFile_API.ACMP object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. onLoadError function &lt;optional&gt; Function to be called if the audio cannot be played successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.ACMP object. isResume boolean &lt;optional&gt; false If set to true (not recommended) and it is a looping audio, the next loop will use the value of the CB_AudioFile_API.ACMP#lastStartAt property as the \"startAt\" parameter when it calls this method again automatically (internally). Recommended for internal usage only. isLooping boolean &lt;optional&gt; false Used to determine whether this method was called automatically again by itself because it is looping the audio. Recommended for internal usage only. startPlayingTime integer &lt;optional&gt; Contains the time when the audio should start playing. Recommended for internal usage only. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 703 Returns: It returns false if the duration is 0 (\"startAt\" and \"stopAt\" are the same number), returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. Type boolean | integer resume( [loop] [, avoidDelayedPlay] [, allowedRecursiveDelay] [, onPlayStart] [, onLoadError]) → {boolean|integer} Resumes the audio (after being paused), starting from the same point it was paused previously. Parameters: Name Type Argument Default Description loop boolean &lt;optional&gt; CB_AudioFile_API.ACMP#loop Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the CB_AudioFile_API.ACMP#onStop method) will not be called. avoidDelayedPlay boolean &lt;optional&gt; false If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the CB_AudioFile_API.ACMP#stop method will be called immediately. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the CB_AudioFile_API.ACMP#stop method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). onPlayStart function &lt;optional&gt; Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the CB_AudioFile_API.ACMP object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. onLoadError function &lt;optional&gt; Function to be called if the audio cannot be played successfully. It will not be called if the audio is not paused or is stopped. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.ACMP object. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 902 Returns: Returns the returning value of the CB_AudioFile_API.ACMP#play method which is called internally. It returns false if the audio is not paused or it is stopped, returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. Type boolean | integer setVolume( [volume] [, forceSetVolumeProperty] [, onSetVolume] [, saveForUnmute] [, mediaObject]) → {number} Sets the desired volume for the audio file (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Parameters: Name Type Argument Default Description volume number &lt;optional&gt; CB_Speaker.getVolume() | CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). forceSetVolumeProperty boolean &lt;optional&gt; false If set to true (not recommended), it will change the CB_AudioFile_API.ACMP#volume property even when the volume failed to be changed. onSetVolume function &lt;optional&gt; Callback function which will be called if it has been possible to set the volume (or at least it was possible to try it). It will not receive any parameters, being \"this\" the CB_AudioFile_API.ACMP object. saveForUnmute boolean &lt;optional&gt; false If set to true (not recommended), it will save internally the current volume before setting it so it will restore the same volume again after calling the CB_AudioFile_API.ACMP#unmute method. Internal usage only recommended. mediaObject Object &lt;optional&gt; CB_AudioFile_API.ACMP#mediaObject Media object whose volume we want to set. Used internally to affect either normal or swap Media object (a swap object is stored internally as it is necessary due ACMP issues when looping a sprite near the end of the audio file). Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 985 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Type number stop( [keepStoppedUnaltered] [, avoidOnStop] [, forceOnStop]) → {boolean} Stops the audio. Parameters: Name Type Argument Default Description keepStoppedUnaltered boolean &lt;optional&gt; false If set to true (not recommended), the CB_AudioFile_API.ACMP#stopped property will not be set to true and it will remain with its current value. avoidOnStop boolean &lt;optional&gt; false If set to false and there is an \"onStop\" function defined (through the CB_AudioFile_API.ACMP#onStop method), it will be called after stopping the audio (or after trying to do it, at least) but only if either the \"forceOnStop\" parameter is set to true or if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. If set to true, the \"onStop\" function (if any) will not be called at all. forceOnStop boolean &lt;optional&gt; false If it is set to true and the \"avoidOnStop\" parameter is set to false and there is an \"onStop\" function defined (through the CB_AudioFile_API.ACMP#onStop method), it will be called regardless the audio was stopped before or not. If set to false, the \"onStop\" function (if any) will only be called if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. This parameter will be ignored if the \"avoidOnStop\" parameter is set to true. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 959 Returns: It returns false if the stopping action cannot be performed at all (this could happen when the audio has not been loaded properly, for example). Returns true otherwise (this only means that it has been tried to be stopped but it could not be successfully). Type boolean unmute( [onUnmute]) → {number} Restores audio after muting it (unmutes it). Parameters: Name Type Argument Description onUnmute function &lt;optional&gt; Callback function which will be called if it has been possible to unmute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the CB_AudioFile_API.ACMP object. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 1048 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Type number Type Definitions OPTIONS Object with the options for an audio file. The format is the following one: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. Type: Object Properties: Name Type Argument Default Description autoLoad boolean &lt;optional&gt; CB_AudioFile_API.ACMP#DEFAULT_OPTIONS.autoLoad If set to false, it will not call the CB_AudioFile_API.ACMP#load method internally when the constructor is called (not recommended). autoPlay boolean &lt;optional&gt; CB_AudioFile_API.ACMP#DEFAULT_OPTIONS.autoPlay Value which will be used as the \"autoPlay\" parameter when calling the CB_AudioFile_API.ACMP#load method internally, only when the \"autoLoad\" is set to true (when the constructor is called). loop boolean &lt;optional&gt; CB_AudioFile_API.ACMP#DEFAULT_OPTIONS.loop Value that will be used for the CB_AudioFile_API.ACMP#loop property. volume number &lt;optional&gt; CB_AudioFile_API.ACMP#DEFAULT_OPTIONS.volume The desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise) that will be used for the CB_AudioFile_API.ACMP#volume property. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_ACMP.js, line 194 × Search results Close "},"CB_AudioFile_API.SM2.html":{"id":"CB_AudioFile_API.SM2.html","title":"Class: CB_AudioFile_API.SM2","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Class: CB_AudioFile_API.SM2 CB_AudioFile_API.SM2 Class to manage an audio file using \"SM2\" (SoundManager 2). Used by the CB_AudioFile class internally and it shares most of its properties and methods. Recommended for internal usage only. new CB_AudioFile_API.SM2(filePath [, audioId] [, options] [, callbackOk] [, callbackError]) → {CB_AudioFile_API.SM2} The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.) if the \"autoPlay\" option is set to true, as some web clients may need this at least the first time in order to be able to play the audio. Parameters: Name Type Argument Default Description filePath string The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. audioId string &lt;optional&gt; 'CB_AUDIOFILE_SM2_' + CB_AudioFile_API.SM2._idUnique++ Desired identifier for the audio object. If not provided, an automatic unique ID will be calculated. Note that it is not case sensitive and it should be unique for each object. options CB_AudioFile_API.SM2.OPTIONS &lt;optional&gt; CB_AudioFile_API.SM2#DEFAULT_OPTIONS Object with the desired options. callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the CB_AudioFile_API.SM2 object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if could be determined), being \"this\" the CB_AudioFile_API.SM2 object itself. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 17 To Do: Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). Note that the \"id\" is not case sensitive and it should be unique for each object. Method getCopy and static method filterProperties (similar to the ones from CB_GraphicSprites and CB_GraphicSpritesScene). Returns: Returns a new CB_AudioFile_API.SM2 object. Type CB_AudioFile_API.SM2 Members &lt;constant&gt; DEFAULT_OPTIONS :CB_AudioFile_API.SM2.OPTIONS Keeps the default options when an object is created. Format: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. Type: CB_AudioFile_API.SM2.OPTIONS Default Value: { autoLoad: true, autoPlay: false, loop: false, volume: CB_AudioFile_API.SM2.prototype.DEFAULT_VOLUME } Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 45 &lt;constant&gt; DEFAULT_VOLUME :number Keeps the default volume. If the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT property is true, this will keep the result of calling the CB_Speaker.getVolume function. Otherwise, it will use the value of the CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME variable. Type: number Default Value: CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 37 &lt;readonly&gt; filePath :string Stores the path of the audio file or the data URI. NOTE: Only some clients with some audio APIs will support data URIs. Type: string Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 99 &lt;readonly&gt; id :string Stores the identifier for the audio file. Type: string Default Value: 'CB_AUDIOFILE_SM2_' + CB_AudioFile_API.SM2._idUnique++ Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 90 &lt;readonly&gt; lastStartAt :number Stores the last \"startAt\" parameter value used by the CB_AudioFile_API.SM2#play or the CB_AudioFile_API.SM2#resume method. Type: number Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 144 &lt;readonly&gt; lastStopAt :number Stores the last \"stopAt\" parameter value used by the CB_AudioFile_API.SM2#play or the CB_AudioFile_API.SM2#resume method. Type: number Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 153 &lt;readonly&gt; loop :boolean Defines whether the file loops by default when the audio is played or not. Its value will be modified automatically whenever the CB_AudioFile_API.SM2#play method is called, getting the value from the \"loop\" parameter (but only if contains a boolean). Type: boolean Default Value: CB_AudioFile_API.SM2.prototype.DEFAULT_OPTIONS.loop Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 63 &lt;readonly&gt; onStopFunction :function Function to call when the audio stops. Type: function Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 135 &lt;readonly&gt; paused :boolean Tells whether the audio is paused or not. Type: boolean Default Value: false Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 108 &lt;readonly&gt; pauseTime :number Stores the time (in milliseconds) when the audio has been paused. Type: number Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 117 &lt;readonly&gt; soundObject :Object Stores the \"SMSound\" object (returned by the createSound method) of the audio, used by the \"SM2\" (SoundManager 2). Type: Object Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 162 &lt;readonly&gt; status :integer Tells whether the file is unloaded (CB_AudioFile.UNLOADED), loading (CB_AudioFile.LOADING), unchecked (CB_AudioFile.UNCHECKED), checking (CB_AudioFile.CHECKING), loaded (CB_AudioFile.LOADED), failed (CB_AudioFile.FAILED) or aborted (CB_AudioFile.ABORTED). Type: integer Default Value: CB_AudioFile.UNLOADED Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 54 &lt;readonly&gt; stopped :boolean Tells whether the audio is stopped or not. Type: boolean Default Value: true Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 126 &lt;readonly&gt; volume :number Stores the volume of this audio. Accepted values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is false or otherwise MAX_VOLUME is the returning value of the CB_Speaker.getVolume function. Type: number Default Value: CB_AudioFile_API.SM2.prototype.DEFAULT_OPTIONS.volume Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 72 &lt;readonly&gt; volumeBeforeMute :number Stores the volume of this audio before it was muted (to restore it later). Valid values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is false or otherwise MAX_VOLUME is the returning value of the CB_Speaker.getVolume function. Type: number Default Value: CB_AudioFile_API.SM2#volume Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 81 Methods checkPlaying( [callbackOk] [, callbackError] [, ignoreStatus] [, ignoreQueue] [, useCache]) → {boolean} Checks whether the audio can be played or not. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. Also recommended to use before calling the CB_AudioFile_API.SM2#play method the first time. The checking action will only be performed if the value of the CB_AudioFile_API.SM2#status property belongs to the CB_AudioFile.UNCHECKED or to the CB_AudioFile.CHECKING value. After checking, if the audio can be played, the CB_AudioFile_API.SM2#status of the object will get the value of CB_AudioFile.LOADED. Otherwise, if it cannot be played, the CB_AudioFile_API.SM2#status property will get the value of {CB_AudioFile.FAILED}. Parameters: Name Type Argument Default Description callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been checked successfully, being \"this\" the CB_AudioFile_API.SM2 object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been checked successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.SM2 object itself. ignoreStatus boolean &lt;optional&gt; false If set to false and the CB_AudioFile_API.SM2#status property does not belong neither to the \"UNCHECKED\" status (defined in the CB_AudioFile.UNCHECKED constant) nor to the \"CHECKING\" status (defined in the CB_AudioFile.CHECKING constant), it will fail calling the \"callbackError\" function (if any). If set to true, it will try to perform the checking action regardless the status of the audio. ignoreQueue boolean &lt;optional&gt; false If set to false and there is already the maximum number of audio files being checked (defined internally), the function will exit and it will call itself automatically again and again until the checking process can be performed (when its queue turn has been reached). This is done for performance purposes. useCache boolean &lt;optional&gt; false This parameter will be ignored in this audio API. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 515 Returns: Returns false if the checking could not be performed and failed. If it returns true, it can mean either the checking has been processed successfully or it will fail in the future, so it is recommended to ignore the returning value and use the callback functions instead. Type boolean destructor( [stopSound] [, keepStoppedUnaltered] [, avoidOnStop] [, forceOnStop]) Destroys the audio file object and frees memory. Sets its current CB_AudioFile_API.SM2#status property to ABORTED (CB_AudioFile.ABORTED value). Parameters: Name Type Argument Default Description stopSound boolean &lt;optional&gt; false If set to true, it will also call the CB_AudioFile_API.SM2#stop method. keepStoppedUnaltered boolean &lt;optional&gt; false Used internally as the \"keepStoppedUnaltered\" parameter to call the CB_AudioFile_API.SM2#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. avoidOnStop boolean &lt;optional&gt; false Used internally as the \"avoidOnStop\" parameter to call the CB_AudioFile_API.SM2#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. forceOnStop boolean &lt;optional&gt; false Used internally as the \"forceOnStop\" parameter to call the CB_AudioFile_API.SM2#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 260 getCurrentTime() → {number} Gets the current time (in milliseconds) which belongs to the position where the audio is currently playing or where it has been paused. Note that some audio APIs and clients could give wrong values. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 1141 Returns: Returns the current time (in milliseconds). Note that some audio APIs and clients could give wrong values. Type number getDuration() → {number} Tells the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 699 Returns: Returns the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. Type number getProgress() → {number} Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 1234 Returns: Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Type number load( [filePath] [, autoPlay] [, callbackOk] [, callbackError] [, forceReload]) → {CB_AudioFile_API.SM2|null} Loads the desired audio file with the desired options. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. This method will be called automatically by the constructor if the \"autoLoad\" option was set to true in its given \"options\" parameter.When this method is called, if the CB_AudioFile_API.SM2#status property already has the \"LOADED\" status (defined in the CB_AudioFile.LOADED constant) and the \"forceReload\" parameter is not set to true, it will exit calling the given \"callbackOk\" function (if any) immediately. Otherwise, regardless the status, the status will be set to \"LOADING\" (defined in the CB_AudioFile.LOADING constant). After it, it will reach the \"UNCHECKED\" (defined in the CB_AudioFile.UNCHECKED constant). If the \"autoPlay\" parameter is not set to true, this will be the final status (and it will be necessary to call the CB_AudioFile_API.SM2#checkPlaying method after it). After it and only if the \"autoPlay\" is set to true, as the CB_AudioFile_API.SM2#checkPlaying method will be called internally, it will have the \"CHECKING\" status (defined in the CB_AudioFile.CHECKING constant) and finally the \"LOADED\" status (defined in the CB_AudioFile.LOADED constant) if all goes well. Parameters: Name Type Argument Default Description filePath string &lt;optional&gt; CB_AudioFile_API.SM2#filePath The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. autoPlay string &lt;optional&gt; false If set to true, it will start playing the audio automatically (by calling the CB_AudioFile_API.SM2#play method internally). If set to true and the CB_AudioFile_API.SM2#status property reaches to the \"UNCHECKED\" status (defined in the CB_AudioFile.UNCHECKED constant), it will also call internally the CB_AudioFile_API.SM2#checkPlaying method. callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the CB_AudioFile_API.SM2 object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.SM2 object itself. forceReload boolean &lt;optional&gt; false If set to false, the \"filePath\" has not been changed from the previously used and the CB_AudioFile_API.SM2#status property belongs to the \"LOADED\" status (defined in the CB_AudioFile.LOADED constant), it will exit the method without loading the audio file again (calling the \"callbackOk\" function, if any). Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 300 Returns: Returns the audio API object (if it was possible to create) or null otherwise. Type CB_AudioFile_API.SM2 | null mute( [onMute]) → {number} Mutes the audio file. Parameters: Name Type Argument Description onMute function &lt;optional&gt; Callback function which will be called if it has been possible to mute the audio file (or at least it was possible to try it). Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 1105 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). If all goes well, the returning value should be zero (0). Note that, even when it returns a zero (0) value, this does not always mean that the mute has been applied successfully. Type number onStop(callbackFunction [, keepOldFunction]) → {boolean} Sets a function to execute when the audio file stops playing or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. No parameters will be received, being \"this\" the CB_AudioFile_API.SM2 object. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 1197 Returns: Returns whether the event has been set or not (removed). Type boolean pause( [onPause] [, keepPausedUnaltered]) → {boolean} Pauses the audio when it is being played. Parameters: Name Type Argument Default Description onPause function &lt;optional&gt; Function without parameters to be called when the audio is paused successfully, being \"this\" the CB_AudioFile_API.SM2 object. keepPausedUnaltered boolean &lt;optional&gt; false If set to true (not recommended), the CB_AudioFile_API.SM2#paused property will not be set to true and it will remain with its current value. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 996 Returns: It returns false if the audio is already paused or it is stopped or if it cannot be paused. Returns true otherwise. Type boolean play( [startAt] [, stopAt] [, loop] [, avoidDelayedPlay] [, allowedRecursiveDelay] [, onPlayStart] [, onLoadError] [, isResume] [, isLooping] [, startPlayingTime]) → {boolean|integer} Plays the audio. Parameters: Name Type Argument Default Description startAt number &lt;optional&gt; 0 | CB_AudioFile_API.SM2#lastStartAt | stopAt Time in milliseconds where we want the audio to start at. If not provided or it is not a valid number, it will use zero (0) as default which belongs to the beginning of the audio. If the value provided is greater than the \"stopAt\" provided, it will use the value set in the CB_AudioFile_API.SM2#lastStartAt property (which belongs to the \"startAt\" value the last time that this method was called). If, even using the CB_AudioFile_API.SM2#lastStartAt value is still greather than the \"stopAt\" provided, it will use the same value as the \"stopAt\" which means it will not play and will stop immediately. stopAt number &lt;optional&gt; CB_AudioFile_API.SM2#getDuration() Time in milliseconds where we want the audio to stop at. If not provided or it is not a valid number, it will use the returning value of the CB_AudioFile_API.SM2#getDuration method (which should belong to the total duration of the audio, if it was calculated correctly). loop boolean &lt;optional&gt; CB_AudioFile_API.SM2#loop Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the CB_AudioFile_API.SM2#onStop method) will not be called. avoidDelayedPlay boolean &lt;optional&gt; false If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the \"stop\" method will be called immediately. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the CB_AudioFile_API.SM2#stop method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). onPlayStart function &lt;optional&gt; Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the CB_AudioFile_API.SM2 object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. onLoadError function &lt;optional&gt; Function to be called if the audio cannot be played successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.SM2 object. isResume boolean &lt;optional&gt; false If set to true (not recommended) and it is a looping audio, the next loop will use the value of the CB_AudioFile_API.SM2#lastStartAt property as the \"startAt\" parameter when it calls this method again automatically (internally). Recommended for internal usage only. isLooping boolean &lt;optional&gt; false Used to determine whether this method was called automatically again by itself because it is looping the audio. Recommended for internal usage only. startPlayingTime integer &lt;optional&gt; Contains the time when the audio should start playing. Recommended for internal usage only. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 773 Returns: It returns false if the duration is 0 (\"startAt\" and \"stopAt\" are the same number), returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. Type boolean | integer resume( [loop] [, avoidDelayedPlay] [, allowedRecursiveDelay] [, onPlayStart] [, onLoadError]) → {boolean|integer} Resumes the audio (after being paused), starting from the same point it was paused previously. Parameters: Name Type Argument Default Description loop boolean &lt;optional&gt; CB_AudioFile_API.SM2#loop Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the CB_AudioFile_API.SM2#onStop method) will not be called. avoidDelayedPlay boolean &lt;optional&gt; false If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the CB_AudioFile_API.SM2#stop method will be called immediately. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the CB_AudioFile_API.SM2#stop method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). onPlayStart function &lt;optional&gt; Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the CB_AudioFile_API.SM2 object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. onLoadError function &lt;optional&gt; Function to be called if the audio cannot be played successfully. It will not be called if the audio is not paused or is stopped. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.SM2 object. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 967 Returns: Returns the returning value of the CB_AudioFile_API.SM2#play method which is called internally. It returns false if the audio is not paused or it is stopped, returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. Type boolean | integer setVolume( [volume] [, forceSetVolumeProperty] [, onSetVolume] [, saveForUnmute]) → {number} Sets the desired volume for the audio file (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Parameters: Name Type Argument Default Description volume number &lt;optional&gt; CB_Speaker.getVolume() | CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). forceSetVolumeProperty boolean &lt;optional&gt; false If set to true (not recommended), it will change the CB_AudioFile_API.SM2#volume property even when the volume failed to be changed. onSetVolume function &lt;optional&gt; Callback function which will be called if it has been possible to set the volume (or at least it was possible to try it). It will not receive any parameters, being \"this\" the CB_AudioFile_API.SM2 object. saveForUnmute boolean &lt;optional&gt; false If set to true (not recommended), it will save internally the current volume before setting it so it will restore the same volume again after calling the CB_AudioFile_API.SM2#unmute method. Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 1067 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Type number stop( [keepStoppedUnaltered] [, avoidOnStop] [, forceOnStop]) → {boolean} Stops the audio. Parameters: Name Type Argument Default Description keepStoppedUnaltered boolean &lt;optional&gt; false If set to true (not recommended), the CB_AudioFile_API.SM2#stopped property will not be set to true and it will remain with its current value. avoidOnStop boolean &lt;optional&gt; false If set to false and there is an \"onStop\" function defined (through the CB_AudioFile_API.SM2#onStop method), it will be called after stopping the audio (or after trying to do it, at least) but only if either the \"forceOnStop\" parameter is set to true or if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. If set to true, the \"onStop\" function (if any) will not be called at all. forceOnStop boolean &lt;optional&gt; false If it is set to true and the \"avoidOnStop\" parameter is set to false and there is an \"onStop\" function defined (through the CB_AudioFile_API.SM2#onStop method), it will be called regardless the audio was stopped before or not. If set to false, the \"onStop\" function (if any) will only be called if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. This parameter will be ignored if the \"avoidOnStop\" parameter is set to true. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 1037 Returns: It returns false if the stopping action cannot be performed at all (this could happen when the audio has not been loaded properly, for example). Returns true otherwise (this only means that it has been tried to be stopped but it could not be successfully). Type boolean unmute( [onUnmute]) → {number} Restores audio after muting it (unmutes it). Parameters: Name Type Argument Description onUnmute function &lt;optional&gt; Callback function which will be called if it has been possible to unmute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the CB_AudioFile_API.SM2 object. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 1123 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Type number Type Definitions OPTIONS Object with the options for an audio file. The format is the following one: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. Type: Object Properties: Name Type Argument Default Description autoLoad boolean &lt;optional&gt; CB_AudioFile_API.SM2#DEFAULT_OPTIONS.autoLoad If set to false, it will not call the CB_AudioFile_API.SM2#load method internally when the constructor is called (not recommended). autoPlay boolean &lt;optional&gt; CB_AudioFile_API.SM2#DEFAULT_OPTIONS.autoPlay Value which will be used as the \"autoPlay\" parameter when calling the CB_AudioFile_API.SM2#load method internally, only when the \"autoLoad\" is set to true (when the constructor is called). loop boolean &lt;optional&gt; CB_AudioFile_API.SM2#DEFAULT_OPTIONS.loop Value that will be used for the CB_AudioFile_API.SM2#loop property. volume number &lt;optional&gt; CB_AudioFile_API.SM2#DEFAULT_OPTIONS.volume The desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise) that will be used for the CB_AudioFile_API.SM2#volume property. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_SM2.js, line 199 × Search results Close "},"CB_AudioFile_API.WAAPI.html":{"id":"CB_AudioFile_API.WAAPI.html","title":"Class: CB_AudioFile_API.WAAPI","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Class: CB_AudioFile_API.WAAPI CB_AudioFile_API.WAAPI Class to manage an audio file using \"WAAPI\" (HTML5 Web Audio API). Used by the CB_AudioFile class internally and it shares most of its properties and methods. Recommended for internal usage only. Uses Base64Binary internally. Some old clients can use this audio API thanks to AudioContext-MonkeyPatch and WAAPISim. new CB_AudioFile_API.WAAPI(filePath [, audioId] [, options] [, callbackOk] [, callbackError]) → {CB_AudioFile_API.WAAPI} The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.) if the \"autoPlay\" option is set to true, as some web clients may need this at least the first time in order to be able to play the audio. Parameters: Name Type Argument Default Description filePath string The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. audioId string &lt;optional&gt; 'CB_AUDIOFILE_WAAPI_' + CB_AudioFile_API.WAAPI._idUnique++ Desired identifier for the audio object. If not provided, an automatic unique ID will be calculated. Note that it is not case sensitive and it should be unique for each object. options CB_AudioFile_API.WAAPI.OPTIONS &lt;optional&gt; CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS Object with the desired options. callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the CB_AudioFile_API.WAAPI object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if could be determined), being \"this\" the CB_AudioFile_API.WAAPI object itself. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 22 To Do: Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). Note that the \"id\" is not case sensitive and it should be unique for each object. Method getCopy and static method filterProperties (similar to the ones from CB_GraphicSprites and CB_GraphicSpritesScene). Returns: Returns a new CB_AudioFile_API.WAAPI object. Type CB_AudioFile_API.WAAPI Members &lt;readonly&gt; buffer :AudioBuffer Stores the \"buffer\" (AudioBuffer object) of the audio, used by the \"WAAPI\" (HTML5 Web Audio API). Type: AudioBuffer Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 176 &lt;constant&gt; DEFAULT_OPTIONS :CB_AudioFile_API.WAAPI.OPTIONS Keeps the default options when an object is created. Format: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. Type: CB_AudioFile_API.WAAPI.OPTIONS Default Value: { autoLoad: true, autoPlay: false, loop: false, volume: CB_AudioFile_API.WAAPI.prototype.DEFAULT_VOLUME } Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 50 &lt;constant&gt; DEFAULT_VOLUME :number Keeps the default volume. If the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT property is true, this will keep the result of calling the CB_Speaker.getVolume function. Otherwise, it will use the value of the CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME variable. Type: number Default Value: CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 42 &lt;readonly&gt; filePath :string Stores the path of the audio file or the data URI. NOTE: Only some clients with some audio APIs will support data URIs. Type: string Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 104 &lt;readonly&gt; gainNode :GainNode Stores the \"gain node\" (GainNode object created with the createGain method) of the audio, used by the \"WAAPI\" (HTML5 Web Audio API). Type: GainNode Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 186 &lt;readonly&gt; id :string Stores the identifier for the audio file. Type: string Default Value: 'CB_AUDIOFILE_WAAPI_' + CB_AudioFile_API.WAAPI._idUnique++ Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 95 &lt;readonly&gt; lastStartAt :number Stores the last \"startAt\" parameter value used by the CB_AudioFile_API.WAAPI#play or the CB_AudioFile_API.WAAPI#resume method. Type: number Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 149 &lt;readonly&gt; lastStopAt :number Stores the last \"stopAt\" parameter value used by the CB_AudioFile_API.WAAPI#play or the CB_AudioFile_API.WAAPI#resume method. Type: number Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 158 &lt;readonly&gt; loop :boolean Defines whether the file loops by default when the audio is played or not. Its value will be modified automatically whenever the CB_AudioFile_API.WAAPI#play method is called, getting the value from the \"loop\" parameter (but only if contains a boolean). Type: boolean Default Value: CB_AudioFile_API.WAAPI.prototype.DEFAULT_OPTIONS.loop Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 68 &lt;readonly&gt; onStopFunction :function Function to call when the audio stops. Type: function Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 140 &lt;readonly&gt; paused :boolean Tells whether the audio is paused or not. Type: boolean Default Value: false Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 113 &lt;readonly&gt; pauseTime :number Stores the time (in milliseconds) when the audio has been paused. Type: number Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 122 &lt;readonly&gt; progressDownloading :number Progress of the loading process (or downloading through XHR) the audio data, used by the \"WAAPI\" (HTML5 Web Audio API). Internal usage only recommended (use the CB_AudioFile_API.WAAPI#getProgress method instead to know the progress). Type: number Default Value: 0 Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 195 &lt;readonly&gt; source :AudioBufferSourceNode Stores the \"source\" (AudioBufferSourceNode object) of the audio, used by the \"WAAPI\" (HTML5 Web Audio API). Type: AudioBufferSourceNode Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 167 &lt;readonly&gt; status :integer Tells whether the file is unloaded (CB_AudioFile.UNLOADED), loading (CB_AudioFile.LOADING), unchecked (CB_AudioFile.UNCHECKED), checking (CB_AudioFile.CHECKING), loaded (CB_AudioFile.LOADED), failed (CB_AudioFile.FAILED) or aborted (CB_AudioFile.ABORTED). Type: integer Default Value: CB_AudioFile.UNLOADED Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 59 &lt;readonly&gt; stopped :boolean Tells whether the audio is stopped or not. Type: boolean Default Value: true Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 131 &lt;readonly&gt; volume :number Stores the volume of this audio. Accepted values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is false or otherwise MAX_VOLUME is the returning value of the CB_Speaker.getVolume function. Type: number Default Value: CB_AudioFile_API.WAAPI.prototype.DEFAULT_OPTIONS.volume Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 77 &lt;readonly&gt; volumeBeforeMute :number Stores the volume of this audio before it was muted (to restore it later). Valid values go from 0 to MAX_VOLUME, where MAX_VOLUME is 100 if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is false or otherwise MAX_VOLUME is the returning value of the CB_Speaker.getVolume function. Type: number Default Value: CB_AudioFile_API.WAAPI#volume Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 86 Methods checkPlaying( [callbackOk] [, callbackError] [, ignoreStatus] [, ignoreQueue] [, useCache]) → {boolean} Checks whether the audio can be played or not. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. Also recommended to use before calling the CB_AudioFile_API.WAAPI#play method the first time. The checking action will only be performed if the value of the CB_AudioFile_API.WAAPI#status property belongs to the CB_AudioFile.UNCHECKED or to the CB_AudioFile.CHECKING value. After checking, if the audio can be played, the CB_AudioFile_API.WAAPI#status of the object will get the value of CB_AudioFile.LOADED. Otherwise, if it cannot be played, the CB_AudioFile_API.WAAPI#status property will get the value of {CB_AudioFile.FAILED}. Parameters: Name Type Argument Default Description callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been checked successfully, being \"this\" the CB_AudioFile_API.WAAPI object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been checked successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.WAAPI object itself. ignoreStatus boolean &lt;optional&gt; false If set to false and the CB_AudioFile_API.WAAPI#status property does not belong neither to the \"UNCHECKED\" status (defined in the CB_AudioFile.UNCHECKED constant) nor to the \"CHECKING\" status (defined in the CB_AudioFile.CHECKING constant), it will fail calling the \"callbackError\" function (if any). If set to true, it will try to perform the checking action regardless the status of the audio. ignoreQueue boolean &lt;optional&gt; false If set to false and there is already the maximum number of audio files being checked (defined internally), the function will exit and it will call itself automatically again and again until the checking process can be performed (when its queue turn has been reached). This is done for performance purposes. useCache boolean &lt;optional&gt; false If set to true (not recommended) and the same audio file was checked previously, it will not perform the checking process again and it will do the same as the previous call. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 721 Returns: Returns false if the checking could not be performed and failed. If it returns true, it can mean either the checking has been processed successfully or it will fail in the future, so it is recommended to ignore the returning value and use the callback functions instead. Type boolean decodeAudioData(binaryData [, callbackOk] [, callbackError]) → {undefined|Promise} Decodes binary audio data given. Internal usage only recommended. Parameters: Name Type Argument Description binaryData ArrayBuffer ArrayBuffer with the audio data to be decoded. callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio data has been decoded successfully, being \"this\" the CB_AudioFile_API.WAAPI object itself. callbackError function &lt;optional&gt; Function to be called if the audio data has not been decoded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.WAAPI object itself. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 666 Returns: Returns the returning value of calling the BaseAudioContext.decodeAudioData function, which returns void (undefined) or a Promise (whose methods \"then\" and \"catch\" will have already been used internally by this function). Type undefined | Promise destructor( [stopSound] [, keepStoppedUnaltered] [, avoidOnStop] [, forceOnStop]) Destroys the audio file object and frees memory. Sets its current CB_AudioFile_API.WAAPI#status property to ABORTED (CB_AudioFile.ABORTED value). Parameters: Name Type Argument Default Description stopSound boolean &lt;optional&gt; false If set to true, it will also call the CB_AudioFile_API.WAAPI#stop method. keepStoppedUnaltered boolean &lt;optional&gt; false Used internally as the \"keepStoppedUnaltered\" parameter to call the CB_AudioFile_API.WAAPI#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. avoidOnStop boolean &lt;optional&gt; false Used internally as the \"avoidOnStop\" parameter to call the CB_AudioFile_API.WAAPI#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. forceOnStop boolean &lt;optional&gt; false Used internally as the \"forceOnStop\" parameter to call the CB_AudioFile_API.WAAPI#stop method. If the \"stopSound\" parameter is not set to true, this parameter will be ignored as the \"stop\" method will not be called. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 289 getCurrentTime() → {number} Gets the current time (in milliseconds) which belongs to the position where the audio is currently playing or where it has been paused. Note that some audio APIs and clients could give wrong values. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 1277 Returns: Returns the current time (in milliseconds). Note that some audio APIs and clients could give wrong values. Type number getDuration() → {number} Tells the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 890 Returns: Returns the duration of the audio (in milliseconds). Note that some clients might not calculate the duration correctly and, in this case, a zero (0) value would be returned. Type number getProgress() → {number} Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 1353 Returns: Returns a number representing the percentage of the loading progress for the audio file (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Type number load( [filePath] [, autoPlay] [, callbackOk] [, callbackError] [, forceReload] [, useXHR] [, useCache]) → {CB_AudioFile_API.WAAPI|null} Loads the desired audio file with the desired options. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some web clients may need this at least the first time in order to be able to play the audio. Uses Base64Binary internally. This method will be called automatically by the constructor if the \"autoLoad\" option was set to true in its given \"options\" parameter.When this method is called, if the CB_AudioFile_API.WAAPI#status property already has the \"LOADED\" status (defined in the CB_AudioFile.LOADED constant) and the \"forceReload\" parameter is not set to true, it will exit calling the given \"callbackOk\" function (if any) immediately. Otherwise, regardless the status, the status will be set to \"LOADING\" (defined in the CB_AudioFile.LOADING constant). After it, it will reach the \"UNCHECKED\" (defined in the CB_AudioFile.UNCHECKED constant). If the \"autoPlay\" parameter is not set to true, this will be the final status (and it will be necessary to call the CB_AudioFile_API.WAAPI#checkPlaying method after it). After it and only if the \"autoPlay\" is set to true, as the CB_AudioFile_API.WAAPI#checkPlaying method will be called internally, it will have the \"CHECKING\" status (defined in the CB_AudioFile.CHECKING constant) and finally the \"LOADED\" status (defined in the CB_AudioFile.LOADED constant) if all goes well. Parameters: Name Type Argument Default Description filePath string &lt;optional&gt; CB_AudioFile_API.WAAPI#filePath The path of the audio file or a data URI. NOTE: Only some clients with some audio APIs will support data URIs. autoPlay string &lt;optional&gt; false If set to true, it will start playing the audio automatically (by calling the CB_AudioFile_API.WAAPI#play method internally). If set to true and the CB_AudioFile_API.WAAPI#status property reaches the \"UNCHECKED\" status (defined in the CB_AudioFile.UNCHECKED constant), it will also call internally the CB_AudioFile_API.WAAPI#checkPlaying method. callbackOk function &lt;optional&gt; Function with no parameters to be called when the audio has been loaded successfully, being \"this\" the CB_AudioFile_API.WAAPI object itself. callbackError function &lt;optional&gt; Function to be called if the audio has not been loaded successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.WAAPI object itself. forceReload boolean &lt;optional&gt; false If set to false, the \"filePath\" has not been changed from the previously used and the CB_AudioFile_API.WAAPI#status property belongs to the \"LOADED\" status (defined in the CB_AudioFile.LOADED constant), it will exit the method without loading the audio file again (calling the \"callbackOk\" function, if any). useXHR boolean &lt;optional&gt; CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS.useXHR Defines whether to use or not XHR (AJAX) to load the audio file. useCache boolean &lt;optional&gt; CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS.useCache Defines whether to try to use or not a cache for performance purposes. If set to true and the audio file was loaded before, it will try to use the cache (if possible) to accelerate the loading process. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 356 Returns: Returns the audio API object (if it was possible to create) or null otherwise. Type CB_AudioFile_API.WAAPI | null mute( [onMute]) → {number} Mutes the audio file. Parameters: Name Type Argument Description onMute function &lt;optional&gt; Callback function which will be called if it has been possible to mute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the CB_AudioFile_API.WAAPI object. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 1241 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). If all goes well, the returning value should be zero (0). Note that, even when it returns a zero (0) value, this does not always mean that the mute has been applied successfully. Type number onStop(callbackFunction [, keepOldFunction]) → {boolean} Sets a function to execute when the audio file stops playing or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. No parameters will be received, being \"this\" the CB_AudioFile_API.WAAPI object. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 1316 Returns: Returns whether the event has been set or not (removed). Type boolean pause( [onPause] [, keepPausedUnaltered]) → {boolean} Pauses the audio when it is being played. Parameters: Name Type Argument Default Description onPause function &lt;optional&gt; Function without parameters to be called when the audio is paused successfully, being \"this\" the CB_AudioFile_API.WAAPI object. keepPausedUnaltered boolean &lt;optional&gt; false If set to true (not recommended), the CB_AudioFile_API.WAAPI#paused property will not be set to true and it will remain with its current value. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 1140 Returns: It returns false if the audio is already paused or it is stopped or if it cannot be paused. Returns true otherwise. Type boolean play( [startAt] [, stopAt] [, loop] [, avoidDelayedPlay] [, allowedRecursiveDelay] [, onPlayStart] [, onLoadError] [, isResume] [, isLooping] [, startPlayingTime]) → {boolean|integer} Plays the audio. Parameters: Name Type Argument Default Description startAt number &lt;optional&gt; 0 | CB_AudioFile_API.WAAPI#lastStartAt | stopAt Time in milliseconds where we want the audio to start at. If not provided or it is not a valid number, it will use zero (0) as default which belongs to the beginning of the audio. If the value provided is greater than the \"stopAt\" provided, it will use the value set in the CB_AudioFile_API.WAAPI#lastStartAt property (which belongs to the \"startAt\" value the last time that this method was called). If, even using the CB_AudioFile_API.WAAPI#lastStartAt value is still greather than the \"stopAt\" provided, it will use the same value as the \"stopAt\" which means it will not play and will stop immediately. stopAt number &lt;optional&gt; CB_AudioFile_API.WAAPI#getDuration() Time in milliseconds where we want the audio to stop at. If not provided or it is not a valid number, it will use the returning value of the CB_AudioFile_API.WAAPI#getDuration method (which should belong to the total duration of the audio, if it was calculated correctly). loop boolean &lt;optional&gt; CB_AudioFile_API.WAAPI#loop Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the CB_AudioFile_API.WAAPI#onStop method) will not be called. avoidDelayedPlay boolean &lt;optional&gt; false If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the \"stop\" method will be called immediately. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the CB_AudioFile_API.WAAPI#stop method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). onPlayStart function &lt;optional&gt; Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the CB_AudioFile_API.WAAPI object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. onLoadError function &lt;optional&gt; Function to be called if the audio cannot be played successfully. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.WAAPI object. isResume boolean &lt;optional&gt; false If set to true (not recommended) and it is a looping audio, the next loop will use the value of the CB_AudioFile_API.WAAPI#lastStartAt property as the \"startAt\" parameter when it calls this method again automatically (internally). Recommended for internal usage only. isLooping boolean &lt;optional&gt; false Used to determine whether this method was called automatically again by itself because it is looping the audio. Recommended for internal usage only. startPlayingTime integer &lt;optional&gt; Contains the time when the audio should start playing. Recommended for internal usage only. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 910 Returns: It returns false if the duration is 0 (\"startAt\" and \"stopAt\" are the same number), returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. Type boolean | integer resume( [loop] [, avoidDelayedPlay] [, allowedRecursiveDelay] [, onPlayStart] [, onLoadError]) → {boolean|integer} Resumes the audio (after being paused), starting from the same point it was paused previously. Parameters: Name Type Argument Default Description loop boolean &lt;optional&gt; CB_AudioFile_API.WAAPI#loop Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined (through the CB_AudioFile_API.WAAPI#onStop method) will not be called. avoidDelayedPlay boolean &lt;optional&gt; false If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the CB_AudioFile_API.WAAPI#stop method will be called immediately. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the CB_AudioFile_API.WAAPI#stop method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). onPlayStart function &lt;optional&gt; Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the CB_AudioFile_API.WAAPI object. If the audio is looping, this will be called only once when the audio starts playing the first time and it will not be called next loops. onLoadError function &lt;optional&gt; Function to be called if the audio cannot be played successfully. It will not be called if the audio is not paused or is stopped. The first and unique parameter will be a string describing the error found (if it could be determined), being \"this\" the CB_AudioFile_API.WAAPI object. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 1112 Returns: Returns the returning value of the CB_AudioFile_API.WAAPI#play method which is called internally. It returns false if the audio is not paused or it is stopped, returns \"-1\" if the audio cannot be played and an error is detected or returns true otherwise. Note that even when it returns true there can be a non-detectable error and maybe the audio is not played. Type boolean | integer setVolume( [volume] [, forceSetVolumeProperty] [, onSetVolume] [, saveForUnmute]) → {number} Sets the desired volume for the audio file (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Parameters: Name Type Argument Default Description volume number &lt;optional&gt; CB_Speaker.getVolume() | CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). forceSetVolumeProperty boolean &lt;optional&gt; false If set to true (not recommended), it will change the CB_AudioFile_API.WAAPI#volume property even when the volume failed to be changed. onSetVolume function &lt;optional&gt; Callback function which will be called if it has been possible to set the volume (or at least it was possible to try it). It will not receive any parameters, being \"this\" the CB_AudioFile_API.WAAPI object. saveForUnmute boolean &lt;optional&gt; false If set to true (not recommended), it will save internally the current volume before setting it so it will restore the same volume again after calling the CB_AudioFile_API.WAAPI#unmute method. Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 1202 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Type number stop( [keepStoppedUnaltered] [, avoidOnStop] [, forceOnStop]) → {boolean} Stops the audio. Parameters: Name Type Argument Default Description keepStoppedUnaltered boolean &lt;optional&gt; false If set to true (not recommended), the CB_AudioFile_API.WAAPI#stopped property will not be set to true and it will remain with its current value. avoidOnStop boolean &lt;optional&gt; false If set to false and there is an \"onStop\" function defined (through the CB_AudioFile_API.WAAPI#onStop method), it will be called after stopping the audio (or after trying to do it, at least) but only if either the \"forceOnStop\" parameter is set to true or if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. If set to true, the \"onStop\" function (if any) will not be called at all. forceOnStop boolean &lt;optional&gt; false If it is set to true and the \"avoidOnStop\" parameter is set to false and there is an \"onStop\" function defined (through the CB_AudioFile_API.WAAPI#onStop method), it will be called regardless the audio was stopped before or not. If set to false, the \"onStop\" function (if any) will only be called if the \"keepStoppedUnaltered\" parameter is set to false and the audio was not already stopped before. This parameter will be ignored if the \"avoidOnStop\" parameter is set to true. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 1173 Returns: It returns false if the stopping action cannot be performed at all (this could happen when the audio has not been loaded properly, for example). Returns true otherwise (this only means that it has been tried to be stopped but it could not be successfully). Type boolean unmute( [onUnmute]) → {number} Restores audio after muting it (unmutes it). Parameters: Name Type Argument Description onUnmute function &lt;optional&gt; Callback function which will be called if it has been possible to unmute the audio file (or at least it was possible to try it). It will not receive any parameters, being \"this\" the CB_AudioFile_API.WAAPI object. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 1259 Returns: Returns the current volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Type number Type Definitions OPTIONS Object with the options for an audio file. The format is the following one: { autoLoad: boolean, autoPlay: boolean, loop: boolean, volume: number }. Type: Object Properties: Name Type Argument Default Description autoLoad boolean &lt;optional&gt; CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS.autoLoad If set to false, it will not call the CB_AudioFile_API.WAAPI#load method internally when the constructor is called (not recommended). autoPlay boolean &lt;optional&gt; CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS.autoPlay Value which will be used as the \"autoPlay\" parameter when calling the CB_AudioFile_API.WAAPI#load method internally, only when the \"autoLoad\" is set to true (when the constructor is called). loop boolean &lt;optional&gt; CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS.loop Value that will be used for the CB_AudioFile_API.WAAPI#loop property. volume number &lt;optional&gt; CB_AudioFile_API.WAAPI#DEFAULT_OPTIONS.volume The desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise) that will be used for the CB_AudioFile_API.WAAPI#volume property. Source: CrossBase/audiovisual/audio/CB_AudioFile_API_WAAPI.js, line 224 × Search results Close "},"CB_AudioFileCache.html":{"id":"CB_AudioFileCache.html","title":"Class: CB_AudioFileCache","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Class: CB_AudioFileCache CB_AudioFileCache Class to manage a cache with multiple CB_AudioFile objects (they should be the same sound although they can be in different formats). This is not only useful for performance purposes but also for being able to play the same sound simultaneously and multiple times in different audio APIs and clients. new CB_AudioFileCache( [dataObject]) → {CB_AudioFileCache} The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Parameters: Name Type Argument Description dataObject CB_AudioFileCache.DATA_OBJECT &lt;optional&gt; Object with the desired data and options for the audio files cache. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 56 To Do: Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). Method getCopy and static method filterProperties (similar to the ones from CB_GraphicSprites and CB_GraphicSpritesScene). Returns: Returns a new CB_AudioFileCache object. Type CB_AudioFileCache Members &lt;static, constant&gt; ABORTED :integer Status value for an audio file cache which has been aborted. This will happen when the audio file cache has been destroyed with the CB_AudioFileCache#destructor method. Can be used to compare the value returned by the CB_AudioFileCache#getStatus method. Recommended for internal usage only. Type: integer Default Value: 6 Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 355 &lt;static, constant&gt; CHECKING :integer Status value for an audio file cache which is being checked currently. Can be used to compare the value returned by the CB_AudioFileCache#getStatus method. Recommended for internal usage only. Type: integer Default Value: 3 Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 331 &lt;static, constant&gt; checkManually_DEFAULT :boolean Default value for the CB_AudioFileCache#checkManually property. Type: boolean Default Value: false Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 387 &lt;static, constant&gt; checkManuallyOnCheckingFailed_DEFAULT :boolean Default value for the CB_AudioFileCache#checkManuallyOnCheckingFailed property. Type: boolean Default Value: false Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 411 &lt;static, constant&gt; checkManuallyOnNeededCreated_DEFAULT :boolean Default value for the CB_AudioFileCache#checkManuallyOnNeededCreated property. Type: boolean Default Value: false Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 395 &lt;static, constant&gt; checkManuallyOnPlayingFailed_DEFAULT :boolean Default value for the CB_AudioFileCache#checkManuallyOnPlayingFailed property. Type: boolean Default Value: false Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 403 &lt;static, constant&gt; FAILED :integer Status value for an audio file cache which failed to be loaded or failed for any other reason. Can be used to compare the value returned by the CB_AudioFileCache#getStatus method. Recommended for internal usage only. Type: integer Default Value: 5 Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 347 &lt;static, constant&gt; LOADED :integer Status value for an audio file cache which has been loaded. Can be used to compare the value returned by the CB_AudioFileCache#getStatus method. Recommended for internal usage only. Type: integer Default Value: 4 Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 339 &lt;static, constant&gt; LOADING :integer Status value for an audio file cache which is loading. Can be used to compare the value returned by the CB_AudioFileCache#getStatus method. Recommended for internal usage only. Type: integer Default Value: 1 Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 315 &lt;static, constant&gt; maximumAudioFiles_DEFAULT :integer|null Default value for the CB_AudioFileCache#maximumAudioFiles property. Type: integer | null Default Value: null Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 371 &lt;static, constant&gt; minimumAudioFiles_DEFAULT :integer Default value for the CB_AudioFileCache#minimumAudioFiles property. Type: integer Default Value: 2 Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 363 &lt;static, constant&gt; retries_DEFAULT :integer Default value for the CB_AudioFileCache#retries property. Type: integer Default Value: 1 Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 379 &lt;static, constant&gt; UNCHECKED :integer Status value for an audio file cache which has not been checked yet. Can be used to compare the value returned by the CB_AudioFileCache#getStatus method. Recommended for internal usage only. Type: integer Default Value: 2 Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 323 &lt;static, constant&gt; UNLOADED :integer Status value for audio file cache which is unloaded. Can be used to compare the value returned by the CB_AudioFileCache#getStatus method. Recommended for internal usage only. Type: integer Default Value: 0 Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 307 &lt;readonly&gt; audioFiles :array Numeric array containing all the CB_AudioFile objects created internally. Internal usage only recommended. Type: array Default Value: [] Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 221 &lt;readonly&gt; audioFilesCreated :integer Total number of CB_AudioFile objects created internally (optimization purposes, to avoid using CB_AudioFileCache#audioFiles.length). Internal usage only recommended. Type: integer Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 230 &lt;readonly&gt; audioFilesFree :array Stack that stores the indexes (belonged to the CB_AudioFileCache#audioFiles array) of the free CB_AudioFile objects. Internal usage only recommended. Type: array Default Value: [] Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 239 &lt;readonly&gt; audioFilesFreePointer :integer Pointer for the CB_AudioFileCache#audioFilesFree stack (for optimization purposes). Internal usage only recommended. Type: integer Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 248 &lt;readonly&gt; checkManually :boolean Tells whether the CB_AudioFile objects must be checked automatically or not (manually). Internal usage only recommended. Type: boolean Default Value: CB_AudioFileCache.checkManually_DEFAULT Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 167 &lt;readonly&gt; checkManuallyOnCheckingFailed :boolean Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when checking one has failed and tries to reload it. Internal usage only recommended. Type: boolean Default Value: CB_AudioFileCache.checkManuallyOnCheckingFailed_DEFAULT Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 194 &lt;readonly&gt; checkManuallyOnNeededCreated :boolean Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when creates a new CB_AudioFile object needed. Internal usage only recommended. Type: boolean Default Value: CB_AudioFileCache.checkManuallyOnNeededCreated_DEFAULT Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 176 &lt;readonly&gt; checkManuallyOnPlayingFailed :boolean Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when playing one has failed and tries to reload it. Internal usage only recommended. Type: boolean Default Value: CB_AudioFileCache.checkManuallyOnPlayingFailed_DEFAULT Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 185 &lt;constant&gt; DEFAULT_VOLUME :number Keeps the default volume. If the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT property is true, this will keep the result of calling the CB_Speaker.getVolume function. Otherwise, it will use the value of the CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME variable. Type: number Default Value: CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 68 &lt;readonly&gt; duration :number Stores the minimum duration found among all the CB_AudioFile objects. Internal usage only recommended. Type: number Default Value: 0 Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 266 &lt;readonly&gt; durationMaximum :number Stores the maximum duration found among all the CB_AudioFile objects. Internal usage only recommended. Type: number Default Value: 0 Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 275 &lt;readonly&gt; id :string Stores the identifier for the audio files cache. Type: string Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 87 &lt;readonly&gt; maximumAudioFiles :integer|null Maximum CB_AudioFile objects that are to be created internally. If it is set to null, there will not be a maximum (it will be unlimited). If an integer is provided, it must be the same number or greater than the value set in the CB_AudioFileCache#minimumAudioFiles property, allowing 1 minimum. Internal usage only recommended. Type: integer | null Default Value: CB_AudioFileCache.maximumAudioFiles_DEFAULT Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 131 &lt;readonly&gt; minimumAudioFiles :integer Minimum CB_AudioFile objects to create internally. It must be an integer being 1 the minimum. Internal usage only recommended. Type: integer Default Value: CB_AudioFileCache.minimumAudioFiles_DEFAULT Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 122 &lt;readonly&gt; minimumAudioFilesFree :integer New CB_AudioFile objects will be created internally when the number of free CB_AudioFile objects reaches this limit. It must be an integer being 0 (zero) the minimum. Internal usage only recommended. Type: integer Default Value: parseInt(CB_AudioFileCache#minimumAudioFiles * 0.25 + 0.5) Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 140 &lt;readonly&gt; newAudioFilesWhenNeeded :integer Number of new CB_AudioFile objects to create internally when the minimum limit of free CB_AudioFile objects (CB_AudioFileCache#minimumAudioFilesFree) is reached. It must be an integer being 0 (zero) the minimum. Internal usage only recommended. Type: integer Default Value: Math.min(parseInt(CB_AudioFileCache#minimumAudioFiles * 0.1 + 0.5), 1) Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 149 &lt;readonly&gt; onError :function Desired function to be called when any kind of error happens. The first and unique parameter will be a string with the error description (if it could be determined), being \"this\" the current CB_AudioFileCache object. Internal usage only recommended. Type: function Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 212 &lt;readonly&gt; onLoad :function Desired function to be called once the cache has been loaded. The first and unique parameter will be an integer with the CB_AudioFile objects that still need to be checked, if any, being \"this\" the current CB_AudioFileCache object. Internal usage only recommended. Type: function Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 203 &lt;readonly&gt; preferredAPIs :array Stores an array of strings with the preferred audio API or audio APIs, in order of preference. Possible audio APIs are \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). Internal usage only recommended. Type: array Default Value: CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 96 &lt;readonly&gt; preferredFormats :array Stores an array of strings with the preferred audio format or audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"'), in order of preference. Internal usage only recommended. Type: array Default Value: CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_FORMATS Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 105 &lt;readonly&gt; retries :integer Number of retries to try to load a CB_AudioFile object internally before trying to load the next possible one internally (if any). It must be an integer being 0 the minimum. Internal usage only recommended. Type: integer Default Value: CB_AudioFileCache.retries_DEFAULT Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 158 &lt;readonly&gt; soundInstancesQueued :Object Object with sound instance identifiers (integers created by the CB_AudioFileCache#play method) which are going to play (this way we can cancel the sound before it starts playing). Each property name is the identifier of the sound instance and the value will be an object with \"cancelled\" (boolean, to know whether the sound instance was cancelled or not) and \"object\" (containing the CB_AudioFile object used) properties. Internal usage only recommended. Type: Object Default Value: {} Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 257 &lt;readonly&gt; status :integer Tells whether the cache is unloaded (CB_AudioFileCache.UNLOADED), loading (CB_AudioFileCache.LOADING), unchecked (CB_AudioFileCache.UNCHECKED), checking (CB_AudioFileCache.CHECKING), loaded (CB_AudioFileCache.LOADED), failed (CB_AudioFileCache.FAILED) or aborted (CB_AudioFileCache.ABORTED). Type: integer Default Value: CB_AudioFileCache.UNLOADED Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 71 &lt;readonly&gt; URIs :CB_AudioFileCache.URIS_OBJECT Object whose property names audio formats and their value is an array of strings with the URIs (audio file paths or audio data URIs) of the audio files in order of preference. The more audio formats and URIs provided the better, as it will help to maximize the compatibility with as many clients as possible (as some audio APIs and client just support some formats, or use absolute paths instead of relative ones, etc.). Even with different formats, all provided URIs should belong to the same audio (this means same sound or same music, with same length, etc.). NOTE: Only some clients with some audio APIs will support data URIs. Internal usage only recommended. Type: CB_AudioFileCache.URIS_OBJECT Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 113 Methods cancelSoundInstance(soundInstanceId [, cancel] [, affectWithObjectAssociated]) → {boolean} Cancels (to prevent it starts playing) or enables a sound instance (created by the CB_AudioFileCache#play method), by its identifier. Parameters: Name Type Argument Default Description soundInstanceId integer The identifier (integer) of the sound instance we want to affect. cancel boolean &lt;optional&gt; false Defines whether we want to cancel it or enable it. affectWithObjectAssociated boolean &lt;optional&gt; false If set to true, it will also affect the sound instance even it has a CB_AudioFile object associated. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1643 Returns: Returns true if the sound instance has been modified or false otherwise. Type boolean cancelSoundInstances( [cancel] [, affectWithObjectAssociated]) → {integer} Cancels (to prevent they start playing) or enables all sound instances (created by the CB_AudioFileCache#play method). Parameters: Name Type Argument Default Description cancel boolean &lt;optional&gt; false Defines whether we want to cancel them or enable them. affectWithObjectAssociated boolean &lt;optional&gt; false If set to true, it will also affect the sound instances which have a CB_AudioFile object associated. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1624 Returns: Returns the number of sound instances modified. Type integer checkPlayingAll( [callbackOk] [, callbackError] [, ignoreQueue]) → {integer} Checks whether each CB_AudioFile object whose CB_AudioFile#getStatus method returns the \"unchecked\" value (which belongs to the value of the CB_AudioFile#UNCHECKED property) can be played or not. After checking, if the audio can be played, the status of the CB_AudioFile object will get the value of CB_AudioFile.LOADED. Otherwise, if it cannot be played, the status of the CB_AudioFile object will get the value of CB_AudioFile.FAILED. If a CB_AudioFile object cannot be played and it is determined necessary, it will try to reload it internally (by calling the CB_AudioFileCache#removeAudioFile method). It will call the CB_AudioFileCache#clearAudioFiles method internally after finishing. Recommended to be called through a user-driven event (as onClick, onTouch, etc.). Parameters: Name Type Argument Default Description callbackOk CB_AudioFileCache.checkPlayingAll_CALLBACK_OK &lt;optional&gt; A function which will be called if all the CB_AudioFile objects whose CB_AudioFile#getStatus method returned the \"unchecked\" value (which belongs to the value of the CB_AudioFile#UNCHECKED property) could finally be checked successfully and all can be played, being \"this\" the CB_AudioFileCache object itself. callbackError CB_AudioFileCache.checkPlayingAll_CALLBACK_ERROR &lt;optional&gt; A function which will be called if not all the CB_AudioFile objects whose CB_AudioFile#getStatus method returned the \"unchecked\" value (which belongs to the value of the CB_AudioFile#UNCHECKED property) could finally be checked successfully and any cannot be played, being \"this\" the CB_AudioFileCache object itself. This function will be called immediately if the method was previously called and it is still running currently. ignoreQueue boolean &lt;optional&gt; false Used internally as the \"ignoreQueue\" parameter when calling the CB_AudioFile#checkPlaying method of each CB_AudioFile object. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1990 To Do: Think about implementing an \"audioFiles\" parameter. Returns: Returns the number of CB_AudioFile objects whose status belonged to the \"unchecked\" value (the value of the CB_AudioFile#UNCHECKED property) before the execution of this method. It will return 0 (zero) if the method is tried to be executed while there is another previous call of it still running. It will also return 0 (zero) if the status of the audio file cache is not loaded (the CB_AudioFileCache#status property does not belong to the value set in the CB_AudioFileCache.LOADED property) nor unchecked (the CB_AudioFileCache#status property does not belong to the value set in the CB_AudioFileCache.UNCHECKED property). Type integer clearAudioFiles( [avoidCallingCheckCacheLoaded]) → {array} Cleans the array of the CB_AudioFile objects (taking off the undefined or null ones) which is in the CB_AudioFileCache#audioFiles property, just keeping the valid ones and clearing (destroying and removing) the others. For performance purposes. Internal usage only recommended. Parameters: Name Type Argument Default Description avoidCallingCheckCacheLoaded boolean &lt;optional&gt; false If set to false and neither the CB_AudioFileCache#checkPlayingAll nor the CB_AudioFileCache#setAudioAPIAll methods are being executed, it will call the CB_AudioFileCache#_checkCacheLoaded internal method which will call the \"onLoad\" function defined in the CB_AudioFileCache#onLoad property if the number of needed CB_AudioFile objects has been reached (after performing the cleaning process). Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1038 Returns: Returns the value of the CB_AudioFileCache#audioFiles property. Type array clearSoundInstances( [clearWithObjectAssociated]) → {integer} Clears the sound instances (created by the CB_AudioFileCache#play method) which have been cancelled. Parameters: Name Type Argument Default Description clearWithObjectAssociated boolean &lt;optional&gt; false If set to true, it will also clear the sound instances which have a CB_AudioFile object associated. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1592 Returns: Returns the number of cleared sound instances. Type integer createAudioFile( [URIs] [, preferredAPIs] [, preferredFormats] [, audioObject] [, callbackOk] [, callbackError] [, storeURIsList] [, checkAutomatically]) → {CB_AudioFile|null} Creates one internal CB_AudioFile object (inside the CB_AudioFileCache#audioFiles property). This method is already called by the CB_AudioFileCache#createAudioFiles method and other methods automatically. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Internal usage only recommended. Parameters: Name Type Argument Default Description URIs CB_AudioFileCache.URIS_OBJECT &lt;optional&gt; CB_AudioFileCache#URIs Object whose property names audio formats and their value is an array of strings with the URIs (audio file paths or audio data URIs) of the audio files in order of preference. It will try to calculate and use the best audio format for the current client and use the first working URI (audio file path or data URI). The more audio formats and URIs provided the better, as it will help to maximize the compatibility with as many clients as possible (as some audio APIs and client just support some formats, or use absolute paths instead of relative ones, etc.). Even with different formats, all provided URIs should belong to the same audio (this means same sound or same music, with same length, etc.). NOTE: Only some clients with some audio APIs will support data URIs. preferredAPIs array &lt;optional&gt; CB_AudioFileCache#preferredAPIs Array of strings with the preferred audio API or audio APIs, in order of preference. Possible audio APIs are \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). It will try to calculate and use the best one for the current client. preferredFormats array &lt;optional&gt; CB_AudioFileCache#preferredFormats Array of strings with the preferred audio format or audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"'), in order of preference. It will try to calculate and use the best one for the current client. audioObject CB_AudioFile &lt;optional&gt; A CB_AudioFile object that we want to reuse instead of creating a new one (for performance purposes). callbackOk function &lt;optional&gt; Function with no parameters that will be called once the CB_AudioFile object is created and loaded successfully (or after it has been checked successfully, depending on the desired option), being \"this\" the CB_AudioFileCache object itself. callbackError function &lt;optional&gt; Function called when any error is produced during creation, loading or checking process, etc. The unique parameter will be a string describing the error (if it was possible to be determined), being \"this\" the CB_AudioFileCache object itself. storeURIsList boolean &lt;optional&gt; false If set to true, it will store internally the valid supported \"URIs\" from the given ones (needed by the CB_AudioFileCache#setAudioAPIAll method, for example). Internal usage only recommended. checkAutomatically boolean &lt;optional&gt; false If set to true (not recommended), it will call the CB_AudioFile#checkPlaying method automatically. Otherwise, it will perform according to the value set at the CB_AudioFileCache#checkManually property. Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 665 Returns: If it fails, it returns null. Otherwise, returns the CB_AudioFile that has been created or reused. Type CB_AudioFile | null createAudioFiles(minimumAudioFiles [, setAsLoaded]) → {integer} Creates the desired number of internal CB_AudioFile objects (inside the CB_AudioFileCache#audioFiles property). This method is already called by the CB_AudioFileCache#load method automatically (unless the \"disableAutoLoad\" property has been set to true in the \"dataObject\" given). Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Parameters: Name Type Argument Default Description minimumAudioFiles integer Minimum CB_AudioFile objects to create internally. It must be an integer being 1 the minimum. If a valid value is given, this will be added to the CB_AudioFileCache#minimumAudioFiles property. setAsLoaded boolean &lt;optional&gt; false If the CB_AudioFile objects already created internally (before calling this method) does not reach the number given in the \"minimumAudioFiles\", this parameter will be ignored. Otherwise, if set to true, it will set the CB_AudioFileCache.status property as \"LOADED\" (the value of the CB_AudioFileCache#LOADED property) after reaching the desired number. If set to false, the CB_AudioFileCache.status property will be set as \"LOADED\" CB_AudioFileCache#LOADED property) if the CB_AudioFileCache#checkManually property is set to true or set as \"UNCHECKED\" if the CB_AudioFileCache#checkManually property is set to false. Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 583 Returns: Returns the number of CB_AudioFile objects which are intended to be created (they could fail). Type integer destroyAll( [stopSounds]) → {integer} Destroys all the CB_AudioFile objects and frees memory, by calling CB_AudioFile#destructor(stopSounds, false, true). Parameters: Name Type Argument Default Description stopSounds boolean &lt;optional&gt; false Used internally as the \"stopSound\" parameter when calling the CB_AudioFile#destructor method of each CB_AudioFile object. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1951 To Do: Think about implementing an \"audioFiles\" parameter. Returns: Returns the number of CB_AudioFile objects whose CB_AudioFile#destructor has been called. Type integer destructor( [stopSounds] [, preventAbortedStatus]) Destroys the audio file cache object, including all the internal CB_AudioFile objects, and frees memory. By default, unless the \"preventAbortedStatus\" is set to true, sets the current status of the audio file cache object as ABORTED (CB_AudioFileCache.ABORTED value). Parameters: Name Type Argument Default Description stopSounds boolean &lt;optional&gt; false Used as the \"stopSound\" parameter when calling internally the CB_AudioFile#destructor method for all the CB_AudioFile objects. preventAbortedStatus boolean &lt;optional&gt; false If set to true (not recommended), it will not assign the status of \"ABORTED\" (it will not assign the value of CB_AudioFileCache.ABORTED to the CB_AudioFileCache#status property). Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 457 errorFunction( [message] [, avoidFailing]) → {boolean} Calls the error function which should be set in the CB_AudioFileCache#onError property (if any), being \"this\" the CB_AudioFileCache object itself. Internal usage only recommended. Parameters: Name Type Argument Default Description message string &lt;optional&gt; The message describing the error that will be sent to the set CB_AudioFileCache#onError function (if any) as the first and unique parameter. avoidFailing boolean &lt;optional&gt; false If set to true, it will not set the CB_AudioFileCache#status property to \"FAILED\" (the value of the CB_AudioFile#FAILED property). Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2855 Returns: Returns true if the CB_AudioFileCache#onError function could be called or false otherwise. Type boolean executeAll() Alias for CB_AudioFileCache#executeFunctionAll. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1870 See: CB_AudioFileCache#executeFunctionAll executeFunctionAll(functionEach [, delayBetweenEach] [, audioFiles] [, returnSetTimeoutsArray] [, delayBetweenEachAffectsFirst] [, functionFinish]) → {integer|array} Performs a desired action, using the provided function, on all the existing CB_AudioFile objects or on the desired ones (if provided). Calls the CB_Arrays.executeFunctionAll function internally and returns its returning value. Parameters: Name Type Argument Default Description functionEach CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK Function that will be called for each CB_AudioFile object. As the first parameter it receives the CB_AudioFile object of the \"audioFiles\" being looped, as the second parameter the position of this CB_AudioFile object in the \"audioFiles\" array provided (or, if not provided, in the array of the CB_AudioFileCache#audioFiles property), the third parameter is the array being looped and the fourth parameter will be the \"delayBetweenEach\" being used, being \"this\" the CB_AudioFile object itself. delayBetweenEach number | CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK &lt;optional&gt; 0 If a value greater than zero is used, it will be used as the delay desired between each call to the \"functionEach\" function (calling them using the setTimeout function internally). If not provided or the value is 0 (zero) or lower, each call to the \"functionEach\" function will be performed immediately one after the other. If a function is provided, it will be called with the same parameters as the \"functionEach\" function and its returning value will be used as the delay (executed every loop for each CB_AudioFile object). audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles A numeric array containing the CB_AudioFile objects that we want to loop. It should contain only CB_AudioFile objects which are already in the current audio file cache. If not provided, it will use all the CB_AudioFile objects contained in the cache. returnSetTimeoutsArray boolean &lt;optional&gt; false Defines whether we want the method to return an integer or a numeric array with information of each setTimeout call. Returning an array with information of each setTimeout call is only useful when the setTimeout function is called internally, which happens when the \"delayBetweenEach\" parameter is greater than 0 (zero). delayBetweenEachAffectsFirst boolean &lt;optional&gt; false If set to true, the desired delay (if any) will also affect the first call to the \"functionEach\" function. functionFinish CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK &lt;optional&gt; Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1892 To Do: Think about only allowing CB_AudioFile objects (in the \"audioFiles\" parameter) which are already in the cache (identify them by their ID), to avoid problems. Returns: If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the CB_AudioFile objects given in the \"audioFiles\" parameter). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a CB_AudioFileCache.executeFunctionAll_OBJECT object for each CB_AudioFile given. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the setTimeout function. Type integer | array forEach() Alias for CB_AudioFileCache#executeFunctionAll. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1875 See: CB_AudioFileCache#executeFunctionAll getAudioFileBySoundInstanceId(soundInstanceId [, avoidCancelled]) → {CB_AudioFile|null} Gets the CB_AudioFile object associated to a given sound instance ID (created by the CB_AudioFileCache#play method), if any, or null otherwise. Parameters: Name Type Argument Default Description soundInstanceId integer The identifier (integer) of the sound instance we want to get. avoidCancelled boolean &lt;optional&gt; false If set to true, it will not return the CB_AudioFile object if its sound instance has been cancelled. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1666 Returns: Returns the CB_AudioFile object associated to a given sound instance ID, if any, or null otherwise. Type CB_AudioFile | null getAudioFilePosition(id) → {integer} Tells the position of a desired CB_AudioFile object (by its identifier) in the CB_AudioFileCache#audioFiles property or -1 otherwise. Parameters: Name Type Description id string The identifier of the CB_AudioFile object (belongs to its CB_AudioFile#id property) whose position we want to find. Note that the identifier is not case sensitive and it should be unique for each object. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1448 Returns: Returns the position of a desired CB_AudioFile object (by its identifier) in the CB_AudioFileCache#audioFiles property or -1 otherwise. Type integer getAudioFiles( [copy]) → {array} Gets an array with all the CB_AudioFile objects. Parameters: Name Type Argument Default Description copy boolean &lt;optional&gt; false If set to true, instead of returning the CB_AudioFileCache#audioFiles property directly, it will return a new copy of it. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2678 Returns: Returns an array with all the CB_AudioFile objects. Type array getAudioFilesBusy() → {array} Gets an array with the busy CB_AudioFile objects (the objects which are not available and ready to use). Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2724 Returns: Returns an array with the busy CB_AudioFile objects (the objects which are not available and ready to use). Type array getAudioFilesFree() → {array} Gets an array with the free CB_AudioFile objects (the objects which are available and ready to use). Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2703 Returns: Returns an array with the free CB_AudioFile objects (the objects which are available and ready to use). Type array getAudioFilesFreeNumber() → {integer} Tells the current number of free CB_AudioFile objects (the number of objects which are available and ready to use). Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2666 Returns: Returns the current number of free CB_AudioFile objects (the number of objects which are available and ready to use). Type integer getAudioFilesNumber( [real]) → {integer} Tells the number of CB_AudioFile objects created. Parameters: Name Type Argument Default Description real boolean &lt;optional&gt; false If set to true, instead of returning the value of the CB_AudioFileCache#audioFilesCreated property, it will return the value of the \"length\" property of the CB_AudioFileCache#audioFiles array which are the real number of CB_AudioFile objects used. If all went well, the returning value should be always the same regardless of this parameter. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2746 Returns: Returns the number of CB_AudioFile objects created. Type integer getDuration( [maximum]) → {number} Tells the duration (minimum or maximum) of the sound stored (in milliseconds). Although the audio file cache should always be used to cache the same sound only, the duration might not always be the same due the usage of different formats, file paths, etc. So this method returns either the minimum or the maximum duration found among all the CB_AudioFile objects. Parameters: Name Type Argument Default Description maximum boolean &lt;optional&gt; false If set to true, instead of returning the value of the CB_AudioFileCache#duration property (which belongs to the minimum duration found among all the CB_AudioFile objects), it will return the value of CB_AudioFileCache#durationMaximum property (which belongs to the maximum duration found among all the CB_AudioFile objects). Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2759 Returns: Returns the duration (minimum or maximum) of the sound stored (in milliseconds). Although the audio file cache should always be used to cache the same sound only, the duration might not always be the same due the usage of different formats, file paths, etc. So this method returns either the minimum or the maximum duration found among all the CB_AudioFile objects. Type number getFreeAudioFile( [popIt]) → {CB_AudioFileCache.getFreeAudioFile_OBJECT} Returns a free CB_AudioFile object, if any (from the CB_AudioFileCache#audioFilesFree property). Note that this will call the internal CB_AudioFileCache#_createNewAudioFilesIfNeeded method that could end creating a new CB_AudioFile object if needed. Parameters: Name Type Argument Default Description popIt boolean &lt;optional&gt; false If set to true, the CB_AudioFile object will also be \"popped\" (removed) from the CB_AudioFileCache#audioFilesFree property. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1407 Returns: Returns a CB_AudioFileCache.getFreeAudioFile_OBJECT object. Type CB_AudioFileCache.getFreeAudioFile_OBJECT getProgress( [countLoadedObjects] [, alsoUncheckedAndCheckingObjects]) → {number} Returns a number representing the percentage of the loading progress for the audio file cache (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Parameters: Name Type Argument Default Description countLoadedObjects boolean &lt;optional&gt; false If set to true, it will count the CB_AudioFile objects whose CB_AudioFile#getStatus method returns \"LOADED\" (the value of the CB_AudioFile#LOADED property), instead of just using the array's \"length\" of the CB_AudioFileCache#audioFiles property. alsoUncheckedAndCheckingObjects boolean &lt;optional&gt; false If set to true and the \"countLoadedObjects\" parameter is also true, it will also count the CB_AudioFile objects whose CB_AudioFile#getStatus method returns \"UNCHECKED\" (the value of the CB_AudioFile#UNCHECKED property) or \"CHECKING\" (the value of the CB_AudioFile#CHECKING property). If the \"countLoadedObjects\" parameter is false, this parameter will be ignored. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2774 To Do: Although it would be more accurate, it does not use the CB_AudioFile#getProgress method internally because the CB_AudioFile objects are not added to the CB_AudioFileCache#audioFiles property until they are loaded. It would be nice to code a way to be able to use it (perhaps a property where the CB_AudioFile objects loading are kept temporarily). Returns: Returns a number representing the percentage of the loading progress for the audio file cache (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Type number getStatus() → {number} Gets the current status of the audio file cache. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2828 Returns: Returns the current status of the audio file cache. It is a number, which should match the value of the CB_AudioFileCache.UNLOADED (still unloaded), CB_AudioFileCache.LOADING (loading), CB_AudioFileCache.UNCHECKED (not checked by calling the CB_AudioFileCache#checkPlayingAll method yet), CB_AudioFileCache.CHECKING (being checked by the CB_AudioFileCache#checkPlayingAll method), CB_AudioFileCache.LOADED (loaded), CB_AudioFileCache.FAILED (failed loading or failed to play or by any other reason) or CB_AudioFileCache.ABORTED (aborted because it was destroyed with the \"destructor\" method) property. Type number getStatusString() → {string} Gets the current status of the audio file cache, as a string. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2839 Returns: Returns the current status of the audio file cache, as a string. Possible return values are \"UNLOADED\", \"LOADING\", \"UNCHECKED\", \"CHECKING\", \"LOADED\", \"FAILED\", \"ABORTED\" or \"UNKNOWN (UNKNOWN_STATUS)\" (where \"UNKNOWN_STATUS\" will be a value from the CB_AudioFileCache#status property not recognized as any possible status). Type string isAudioFileFree(id) → {boolean} Tells whether a desired CB_AudioFile object is free (it is in the CB_AudioFileCache#audioFilesFree property) or not, by its identifier. A free CB_AudioFile object is an object which is not being used and it is available to be used. Parameters: Name Type Description id string The identifier of the CB_AudioFile object (belongs to its CB_AudioFile#id property) that we want to check. Note that the identifier is not case sensitive and it should be unique for each object. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1479 Returns: Returns whether a desired CB_AudioFile object is free (it is in the CB_AudioFileCache#audioFilesFree property) or not, by its identifier. A free CB_AudioFile object is an object which is not being used and it is available to be used. Type boolean isAudioFileFreeByPosition(position) → {boolean} Tells whether a given numeric position of a CB_AudioFile object in the CB_AudioFileCache#audioFiles property is stored in the CB_AudioFileCache#audioFilesFree property or not (this means that the CB_AudioFile object in that position of the CB_AudioFileCache#audioFiles property is free). A free CB_AudioFile object is an object which is not being used and it is available to be used. Parameters: Name Type Description position integer Position of the CB_AudioFile object in the CB_AudioFileCache#audioFiles property that we want to check whether it is in the CB_AudioFileCache#audioFilesFree property or not. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1493 Returns: Returns whether the given numeric position of a CB_AudioFile object in the CB_AudioFileCache#audioFiles property is stored in the CB_AudioFileCache#audioFilesFree property or not (this means that the CB_AudioFile object in that position of the CB_AudioFileCache#audioFiles property is free). A free CB_AudioFile object is an object which is not being used and it is available to be used. Type boolean isPlaying() → {boolean} Tells whether any of the CB_AudioFile objects is playing or not. It uses the CB_AudioFile#isPlaying method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2647 Returns: Returns whether any of the CB_AudioFile objects is playing or not. Type boolean load(dataObject) → {CB_AudioFileCache|null} Loads the audio file cache with the desired data given. This method is called by the constructor automatically. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Parameters: Name Type Description dataObject CB_AudioFileCache.DATA_OBJECT Object with the desired data and options for the audio files cache. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 504 Returns: If a \"dataObject\" is given, it returns the current CB_AudioFileCache object. Otherwise, it returns null. Type CB_AudioFileCache | null muteAll( [onMute] [, audioFiles]) → {integer} Mutes all the existing CB_AudioFile objects or the desired ones (if provided). It uses the CB_AudioFile#mute method internally. Parameters: Name Type Argument Default Description onMute function &lt;optional&gt; Callback function which will be called for each audio file if it has been possible to mute it (or at least it was possible to try it), being \"this\" the CB_AudioFile object. Used internally as the \"onMute\" parameter to call the CB_AudioFile#mute method. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles A numeric array containing the CB_AudioFile objects that we want to affect. It should contain only CB_AudioFile objects which are already in the current audio file cache. If not provided, it will use all the CB_AudioFile objects contained in the cache. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2304 Returns: Returns the number of calls to the CB_AudioFile#mute method that were performed (which should be the same number as the CB_AudioFile objects in the \"audioFiles\" parameter). Type integer pauseAll( [onPause] [, audioFiles]) → {integer} Tries to pause all the existing CB_AudioFile objects or the desired ones (if provided), which are being played, by calling their CB_AudioFile#pause method internally. Parameters: Name Type Argument Default Description onPause function &lt;optional&gt; Function without parameters to be called when the audio is paused successfully, being \"this\" the CB_AudioFile object. Used internally as the \"onPause\" parameter to call the CB_AudioFile#pause method of the CB_AudioFile object. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles A numeric array containing the CB_AudioFile objects that we want to affect. It should contain only CB_AudioFile objects which are already in the current audio file cache. If not provided, it will use all the CB_AudioFile objects contained in the cache. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2235 Returns: Returns the number of calls to the CB_AudioFile#pause method that were performed (which should be the same number as the CB_AudioFile objects in the \"audioFiles\" parameter). Type integer play( [startAt] [, stopAt] [, loop] [, volume] [, allowedRecursiveDelay] [, allowedRecursiveDelaySkipping] [, onPlayStart] [, onStop] [, startPlayingTime] [, startAtOriginal] [, soundInstanceId] [, _callRecursivelyIfNotTooLateCalledObject]) → {integer|null} Plays a sound of the cache (if there is any free). If a sound cannot be played, this method can call itself internally again and again (with most of the given parameters being the same, depending on the circumstances) to try to play the sound until a desired time limit is reached. If a CB_AudioFile object cannot be played and it is determined necessary, it will try to reload it internally (by calling the CB_AudioFileCache#removeAudioFile method). Parameters: Name Type Argument Default Description startAt number &lt;optional&gt; 0 | CB_AudioFile_API.WAAPI#lastStartAt | CB_AudioFile_API.SM2#lastStartAt | CB_AudioFile_API.ACMP#lastStartAt | CB_AudioFile_API.AAPI#lastStartAt | stopAt Time in milliseconds where we want the audio to start at. If not provided or it is not a valid number, it will use zero (0) as default which belongs to the beginning of the audio. If the value provided is greater than the \"stopAt\" provided, it will use the value set in the \"lastStartAt\" property of the used audio API object (which belongs to the \"startAt\" value the last time that the \"play\" method was called). If, even using the \"lastStartAt\" value is still greater than the \"stopAt\" provided, it will use the same value as the \"stopAt\" which means it will not play and will stop immediately. Used internally as the \"startAt\" parameter to call the CB_AudioFile#play method of the free CB_AudioFile object (if any). stopAt number &lt;optional&gt; CB_AudioFile_API.WAAPI#getDuration() | CB_AudioFile_API.SM2#getDuration() | CB_AudioFile_API.ACMP#getDuration() | CB_AudioFile_API.AAPI#getDuration() Time in milliseconds where we want the audio to stop at. If not provided or it is not a valid number, it will use the returning value of the \"getDuration\" method of the used audio API object (which should belong to the total duration of the audio, if it was calculated correctly). Used internally as the \"stopAt\" parameter to call the CB_AudioFile#play method of the free CB_AudioFile object (if any). loop boolean &lt;optional&gt; CB_AudioFile#loop Sets whether we want to play the audio looping (starting again and again) or just play it once. Used internally as the \"loop\" parameter to call the CB_AudioFile#play method of the free CB_AudioFile object (if any). volume number &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Desired volume to play the audio. Used internally as the \"volume\" parameter to call the CB_AudioFile#setVolume method of the free CB_AudioFile object (if any), before playing it. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all. Used only when the audio is not able to play immediately. allowedRecursiveDelaySkipping boolean &lt;optional&gt; stopAt-startAt If provided (uses milliseconds) and the time expired trying to start playing the sound without success is still inside this amount of time provided, it will try to play the sound but skipping the part of the audio which should have already been played already. In other words, it will try to start playing the sound as if the previous non-played part (which should have been playing during the time which already expired) was already being playing silently. Only used when the time set in the \"allowedRecursiveDelay\" parameter has been reached and the audio did not start playing yet. The default value is the duration of the sound that we want to play (having in mind the real value of the \"startAt\" and \"stopAt\" parameters which are calculated internally and can be different from the provided ones in the case that they had any error). onPlayStart function &lt;optional&gt; Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"soundInstanceId\" (the identifier of the sound instance used), \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the CB_AudioFile object used (if any). Used internally as the \"onPlayStart\" parameter (wrapped in another function) to call the CB_AudioFile#play method of the free CB_AudioFile object (if any). onStop function &lt;optional&gt; Function to call when the sound stops playing, with an unique parameter which belongs to the \"soundInstanceId\" (the identifier of the sound instance used), being \"this\" the CB_AudioFile object (if any). Used internally as the \"callbackFunction\" parameter (wrapped in a function) to call the CB_AudioFile#onStop method of the free CB_AudioFile object (if any), before playing it. startPlayingTime number &lt;optional&gt; CB_Device.getTiming() Used internally to calculate the amount of time (in milliseconds) expired without playing the sound. Internal usage only recommended. startAtOriginal number &lt;optional&gt; startAt Used internally to start playing the sound accurately and skipping the part which could not be played before, if the time expired without being played is still inside the amount of time provided in the \"allowedRecursiveDelaySkipping\" parameter. Internal usage only recommended. soundInstanceId integer &lt;optional&gt; CB_AudioFileCache._soundInstanceIdUnique++ The identifier of the sound instance that will be played. Used internally when the function is called recursively in the case that the sound could not be played immediately. Internal usage only recommended. _callRecursivelyIfNotTooLateCalledObject Object &lt;optional&gt; Object with just the \"called\" property (boolean). Used internally to know whether the current execution thread called already the _callRecursivelyIfNotTooLate internal method for the same sound instance or not. Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1754 Returns: Returns the sound instance ID used if there was one free or null otherwise. To get a sound instance returned does not mean necessarily that the sound started playing so it is necessary to use a callback function as the \"onPlayStart\" parameter for checking this. The sound instance created (if any), will be cancelled automatically once the sound is stopped. Type integer | null playAll( [startAt] [, stopAt] [, loop] [, volume] [, avoidDelayedPlay] [, allowedRecursiveDelay] [, onPlayStart] [, onStop] [, includingPlaying]) → {integer} Tries to play all the CB_AudioFile objects by calling their CB_AudioFile#play method internally. If a CB_AudioFile object cannot be played and it is determined necessary, it will try to reload it internally (by calling the CB_AudioFileCache#removeAudioFile method). It does not create sound instances. Parameters: Name Type Argument Default Description startAt number &lt;optional&gt; 0 | CB_AudioFile_API.WAAPI#lastStartAt | CB_AudioFile_API.SM2#lastStartAt | CB_AudioFile_API.ACMP#lastStartAt | CB_AudioFile_API.AAPI#lastStartAt | stopAt Time in milliseconds where we want the audio to start at. If not provided or it is not a valid number, it will use zero (0) as default which belongs to the beginning of the audio. If the value provided is greater than the \"stopAt\" provided, it will use the value set in the \"lastStartAt\" property of the used audio API object (which belongs to the \"startAt\" value the last time that the \"play\" method was called). If, even using the \"lastStartAt\" value is still greater than the \"stopAt\" provided, it will use the same value as the \"stopAt\" which means it will not play and will stop immediately. Used internally as the \"startAt\" parameter to call the CB_AudioFile#play method of the CB_AudioFile object. stopAt number &lt;optional&gt; CB_AudioFile_API.WAAPI#getDuration() | CB_AudioFile_API.SM2#getDuration() | CB_AudioFile_API.ACMP#getDuration() | CB_AudioFile_API.AAPI#getDuration() Time in milliseconds where we want the audio to stop at. If not provided or it is not a valid number, it will use the returning value of the \"getDuration\" method of the used audio API object (which should belong to the total duration of the audio, if it was calculated correctly). Used internally as the \"stopAt\" parameter to call the CB_AudioFile#play method of the CB_AudioFile object. loop boolean &lt;optional&gt; CB_AudioFile#loop Sets whether we want to play the audio looping (starting again and again) or just play it once. Note that at the end of each loop the \"onStop\" function defined will not be called. Used internally as the \"loop\" parameter to call the CB_AudioFile#play method of the CB_AudioFile object. volume number &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Desired volume to play the audio. Used internally as the \"volume\" parameter to call the CB_AudioFile#setVolume method of the CB_AudioFile object, before playing it. avoidDelayedPlay boolean &lt;optional&gt; false If set to false (recommended) and the audio failed previously or was aborted (destroyed), it will try to load it correctly again automatically and play it after that if possible (this can take some time so the audio could start playing after a delay). Otherwise, if set to true and the audio failed or was aborted (destroyed), the audio will not play at all and the \"stop\" method of the audio file object will be called immediately. Used internally as the \"avoidDelayedPlay\" parameter to call the CB_AudioFile#play method of the CB_AudioFile object. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT The maximum amount of time (in milliseconds) of delay that we accept before start playing the audio. If the amount of time is overcome, the audio will not play at all and the \"stop\" method will be called immediately. Used only when the \"avoidDelayedPlay\" parameter is set to false and the audio needs to be loaded because it failed previously or was aborted (destroyed). Used internally as the \"allowedRecursiveDelay\" parameter to call the CB_AudioFile#play method of the CB_AudioFile object. onPlayStart function &lt;optional&gt; Function to be called when the audio starts playing successfully. The function will be called with the following parameters (in order): \"startAt\", \"stopAt\", \"startAtNextLoop\", \"loop\", \"avoidDelayedPlay\", \"allowedRecursiveDelay\" and \"startPlayingTime\", being \"this\" the CB_AudioFile object. Used internally as the \"onPlayStart\" parameter to call the CB_AudioFile#play method of the CB_AudioFile object. onStop function &lt;optional&gt; Function that will be called each time that a CB_AudioFile object stops playing. Used internally as the \"callbackFunction\" parameter to call the CB_AudioFile#onStop method of the CB_AudioFile object, before playing it. includingPlaying boolean &lt;optional&gt; false If set to true, it will call the CB_AudioFile#play method even for those CB_AudioFile objects which are currently playing. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2145 To Do: Think about implementing an \"audioFiles\" parameter. Returns: Returns the number of CB_AudioFile objects whose CB_AudioFile#play method did not return the value of \"-1\" (this does not mean necessarily that they could be played successfully). Type integer playAndStopAll( [includingPlaying] [, delayBeforeStop]) → {integer} Plays silently and stops all CB_AudioFile objects after a desired time. It can be useful for some clients which need the CB_AudioFile#play method to be called through a user-driven event (as onClick, onTouch, etc.). Internally, it calls CB_AudioFileCache#playAll(0, null, false, 0, true, null, null, null, includingPlaying) and, after a desired delay, calls the CB_AudioFileCache#stopAll method. Parameters: Name Type Argument Default Description includingPlaying boolean &lt;optional&gt; false If set to true, it will call the CB_AudioFile#play method even for those CB_AudioFile objects which are currently playing. delayBeforeStop number &lt;optional&gt; 100 Delay (in milliseconds) before stopping the audio, that will be used as the second parameter of the setTimeout function when calling the CB_AudioFileCache#stopAll method. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2218 To Do: Think about implementing an \"audioFiles\" parameter. Returns: Returns the number of CB_AudioFile objects whose CB_AudioFile#play method did not return the value of \"-1\" (this does not mean necessarily that they could be played successfully). Type integer purge(desiredNumber [, setAsMinimumAudioFiles] [, includePlaying] [, stopSounds] [, statuses]) → {integer} Tries to purge the audio file cache until it reaches a desired number of CB_AudioFile objects internally (set in the CB_AudioFileCache#audioFiles property), by removing and destroying some of the current CB_AudioFile objects. For performance purposes. Parameters: Name Type Argument Default Description desiredNumber integer The desired number of internal CB_AudioFile objects that we want to keep in the CB_AudioFileCache#audioFiles property. It mus be 1 or greater. setAsMinimumAudioFiles boolean &lt;optional&gt; false If set to true, it will set the value of the \"desiredNumber\" parameter to the CB_AudioFileCache#minimumAudioFiles property (only when there is a maximum defined in CB_AudioFileCache#maximumAudioFiles). includePlaying boolean &lt;optional&gt; false If it is set to true and removing non-playing CB_AudioFile objects was not enough to reach the desired number (defined in the \"desiredNumber\" parameter), it will also try to remove objects which are being playing currently. stopSounds boolean &lt;optional&gt; false Used as the \"stopSound\" parameter when calling the CB_AudioFile#destructor method of each CB_AudioFile object removed. statuses array &lt;optional&gt; Array(CB_AudioFile.LOADING, CB_AudioFile.UNCHECKED, CB_AudioFile.CHECKING, CB_AudioFile.LOADED) Numeric array containing the statuses of the CB_AudioFile objects that we want this method to authorize to remove. This means that if the returning value of the CB_AudioFile#getStatus method of a CB_AudioFile object is not in this list, it will not be tried to be removed (unless they end removed by the CB_AudioFileCache#clearAudioFiles method called internally). Have in mind that this method will call the CB_AudioFileCache#clearAudioFiles method internally, which destroys the CB_AudioFile objects whose CB_AudioFile#getStatus method returns CB_AudioFile.ABORTED and CB_AudioFile.FAILED, so these two statuses need not be indicated. It will respect the order given. Possible values for this array are: CB_AudioFile.UNLOADED, CB_AudioFile.LOADING, CB_AudioFile.UNCHECKED, CB_AudioFile.CHECKING, CB_AudioFile.LOADED, CB_AudioFile.FAILED and CB_AudioFile.ABORTED. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1295 Returns: Returns the number of CB_AudioFile objects removed. Type integer removeAudioFile(audioObjectOrId [, reload] [, checkManually]) → {boolean|CB_AudioFile|null} If found, takes a given CB_AudioFile object off the CB_AudioFileCache#audioFiles property (and reloads it if we want to). NOTE: It does neither destroy nor remove the CB_AudioFile object so it can be used for other purposes (and if a CB_AudioFile object is given, it will be tried to be reused by the CB_AudioFileCache#createAudioFile method internally if it is called). Internal usage only recommended. Parameters: Name Type Argument Default Description audioObjectOrId CB_AudioFile | string The CB_AudioFile object or a string with its identifier (not case sensitive) that we want to remove from the CB_AudioFileCache#audioFiles property. If a CB_AudioFile object is given, its CB_AudioFile#id property (which should be unique always) must be set as it is used to identify the object. NOTE: It does neither destroy nor remove the CB_AudioFile object so it can be used for other purposes (and if a CB_AudioFile object is given, it will be tried to be reused by the CB_AudioFileCache#createAudioFile method internally if it is called). reload boolean &lt;optional&gt; false If it is set to true, the CB_AudioFileCache#createAudioFile method will be called automatically at the end of the process. If a CB_AudioFile object has been given (through the \"audioObjectOrId\" parameter) or found by its identifier, it will be tried to be reused by the CB_AudioFileCache#createAudioFile method (as its \"audioObject\" parameter). checkManually boolean &lt;optional&gt; false Only used when the \"reload\" parameter is set to true, to calculate the \"checkAutomatically\" parameter when calling the CB_AudioFileCache#createAudioFile method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1149 To Do: Think about calling the CB_AudioFileCache#createAudioFile method internally (when the \"reload\" parameter is set to true) only when the CB_AudioFile object has been found and removed from the CB_AudioFileCache#audioFiles property. Returns: Returns null if the given \"audioObjectOrId\" parameter is not a valid CB_AudioFile object or its CB_AudioFile#id property is not set or when the \"audioObjectOrId\" parameter is an empty string. Returns a CB_AudioFile object, the given one through the \"audioObjectOrId\" parameter of the first one removed (it should be the first and unique one removed as the ID must be unique), if the CB_AudioFileCache#createAudioFile method is called internally (it will reuse this CB_AudioFile object). Otherwise, returns true if the number of internal CB_AudioFile objects (inside the CB_AudioFileCache#audioFiles property) has decreased or false otherwise. Type boolean | CB_AudioFile | null resumeAll( [loop] [, allowedRecursiveDelay] [, allowedRecursiveDelaySkipping] [, onPlayStart] [, onStop] [, audioFiles]) → {array} Resumes all the existing CB_AudioFile objects or the desired ones (if provided), which are paused (and not stopped). It uses the CB_AudioFileCache#play method internally. Parameters: Name Type Argument Default Description loop boolean &lt;optional&gt; CB_AudioFile#loop Used internally as the \"loop\" parameter to call the CB_AudioFileCache#play method. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT Used internally as the \"allowedRecursiveDelay\" parameter to call the CB_AudioFileCache#play method. allowedRecursiveDelaySkipping boolean &lt;optional&gt; CB_AudioFile#lastStopAt-CB_AudioFile#lastStartAt Used internally as the \"allowedRecursiveDelaySkipping\" parameter to call the CB_AudioFileCache#play method. onPlayStart function &lt;optional&gt; Used internally as the \"onPlayStart\" parameter to call the CB_AudioFileCache#play method. onStop function &lt;optional&gt; Used internally as the \"onStop\" parameter to call the CB_AudioFileCache#play method. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles A numeric array containing the CB_AudioFile objects that we want to affect. It should contain only CB_AudioFile objects which are already in the current audio file cache. If not provided, it will use all the CB_AudioFile objects contained in the cache. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2252 Returns: Returns a numeric array containing all the return values of each internal call to the CB_AudioFileCache#play method. Type array setAudioAPIAll(preferredAPIs [, callbackOk] [, callbackError] [, mandatory] [, forceReload] [, audioFiles]) → {integer} Tries to change the audio API for all the existing CB_AudioFile objects or the desired ones (if provided). Uses the CB_AudioFile#setAudioAPI method internally. This method is not allowed to be called if a previous call to it did not finish yet. The function defined in the \"callbackError\" parameter, if any, will be called immediately if the method was previously called and it is still running currently. Parameters: Name Type Argument Default Description preferredAPIs array | string Array of strings with the preferred audio API or audio APIs, in order of preference. It also accepts a string with only one audio API. If more than one audio API is provided and setting an audio API fails for a CB_AudioFile object, it will try setting the next one and so on (this means that some of the CB_AudioFile objects could end with a different audio API). Possible audio APIs are \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). callbackOk CB_AudioFileCache.setAudioAPIAll_CALLBACK_OK &lt;optional&gt; Function that will be called when all the process was performed successfully, being \"this\" the CB_AudioFileCache object. callbackError CB_AudioFileCache.setAudioAPIAll_CALLBACK_ERROR &lt;optional&gt; Function that will be called when any error happened, being \"this\" the CB_AudioFileCache object. This function will be called immediately if the method was previously called and it is still running currently. mandatory boolean &lt;optional&gt; false If set to true and any CB_AudioFile object could not perform successfully any call to its CB_AudioFile#setAudioAPI method for all desired audio APIs provided in the \"preferredAPIs\" parameter (this means that, internally, all the CB_AudioFile#setAudioAPI calls, one per desired audio API, have fired an error by calling the function defined in its \"callbackError\" parameter), the audio file cache will be set as \"FAILED\" (the CB_AudioFileCache#status property will be set to the value of CB_AudioFileCache.FAILED). forceReload string &lt;optional&gt; false Used internally as the \"forceReload\" parameter when calling the CB_AudioFile#setAudioAPI method internally. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles A numeric array containing the CB_AudioFile objects that we want to affect. It should contain only CB_AudioFile objects which are already in the current audio file cache. If not provided, it will use all the CB_AudioFile objects contained in the cache. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2369 Returns: Returns the number of calls to the CB_AudioFile#setAudioAPI method that were performed (which should be the same number as the CB_AudioFile objects in the \"audioFiles\" parameter). Type integer setVolumeAll( [volume] [, forceSetVolumeProperty] [, onSetVolume] [, audioFiles]) → {integer} Sets the same volume for all the existing CB_AudioFile objects or the desired ones (if provided). It uses the CB_AudioFile#setVolume method internally. Parameters: Name Type Argument Default Description volume number &lt;optional&gt; CB_Speaker.getVolume() | CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Desired volume (from 0 to the maximum value, where the maximum value will be the returning value of calling the CB_Speaker.getVolume function if the CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM property is set to true or it will be 100 otherwise). Used internally as the \"volume\" parameter to call the CB_AudioFile#setVolume method. forceSetVolumeProperty boolean &lt;optional&gt; false If set to true (not recommended), it will change the \"volume\" property of the used audio API object even when the volume was failed to be changed. Used internally as the \"forceSetVolumeProperty\" parameter to call the CB_AudioFile#setVolume method. onSetVolume function &lt;optional&gt; Callback function which will be called if it has been possible to set the volume (or at least it was possible to try it), being \"this\" the CB_AudioFile object. Used internally as the \"onSetVolume\" parameter to call the CB_AudioFile#setVolume method. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles A numeric array containing the CB_AudioFile objects that we want to affect. It should contain only CB_AudioFile objects which are already in the current audio file cache. If not provided, it will use all the CB_AudioFile objects contained in the cache. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2332 Returns: Returns the number of calls to the CB_AudioFile#setVolume method that were performed (which should be the same number as the CB_AudioFile objects in the \"audioFiles\" parameter). Type integer stopAll( [audioFiles]) → {integer} Tries to stops all the existing CB_AudioFile objects or the desired ones (if provided), which are being played, by calling their CB_AudioFile#stop method internally. Parameters: Name Type Argument Default Description audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles A numeric array containing the CB_AudioFile objects that we want to affect. It should contain only CB_AudioFile objects which are already in the current audio file cache. If not provided, it will use all the CB_AudioFile objects contained in the cache. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2204 Returns: Returns the number of calls to the CB_AudioFile#stop method that were performed (which should be the same number as the CB_AudioFile objects in the \"audioFiles\" parameter). Type integer unmuteAll( [onUnmute] [, audioFiles]) → {integer} Unmutes all the existing CB_AudioFile objects or the desired ones (if provided). It uses the CB_AudioFile#unmute method internally. Parameters: Name Type Argument Default Description onUnmute function &lt;optional&gt; Callback function which will be called for each audio file if it has been possible to unmute it (or at least it was possible to try it), being \"this\" the CB_AudioFile object. Used internally as the \"onUnmute\" parameter to call the CB_AudioFile#unmute method. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles A numeric array containing the CB_AudioFile objects that we want to affect. It should contain only CB_AudioFile objects which are already in the current audio file cache. If not provided, it will use all the CB_AudioFile objects contained in the cache. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2317 Returns: Returns the number of calls to the CB_AudioFile#unmute method that were performed (which should be the same number as the CB_AudioFile objects in the \"audioFiles\" parameter). Type integer Type Definitions checkPlayingAll_CALLBACK_ERROR(errorMessage, performedActions, uncheckedObjects) Callback function used by the CB_AudioFileCache#checkPlayingAll method that will be called when not all was performed successfully. Parameters: Name Type Description errorMessage string A string describing the error, if it could be determined. performedActions integer The number of CB_AudioFile objects that can be played. uncheckedObjects integer | undefined The number of CB_AudioFile objects that needed to be checked before calling this method (it will be undefined if it could not be determined). Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1972 checkPlayingAll_CALLBACK_OK(performedActions, uncheckedObjects) Callback function used by the CB_AudioFileCache#checkPlayingAll method that will be called when all the process was performed successfully. Parameters: Name Type Description performedActions integer The number of CB_AudioFile objects that can be played. uncheckedObjects integer The number of CB_AudioFile objects that needed to be checked before calling this method. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1964 DATA_OBJECT Object with the desired data and options for the audio files cache. Type: Object Properties: Name Type Argument Default Description URIs CB_AudioFileCache.URIS_OBJECT Object whose property names audio formats and their value is an array of strings with the URIs (audio file paths or audio data URIs) of the audio files in order of preference. The best audio format for the current client will be tried to be calculated and it will use the first working URI (audio file path or data URI). The more audio formats and URIs provided the better, as it will help to maximize the compatibility with as many clients as possible (as some audio APIs and client just support some formats, or use absolute paths instead of relative ones, etc.). Even with different formats, all provided URIs should belong to the same audio (this means same sound or same music, with same length, etc.). NOTE: Only some clients with some audio APIs will support data URIs. If a valid value is given, this will be added to the CB_AudioFileCache#URIs property. id string &lt;optional&gt; \"\" Desired identifier for the audio files cache. Internal usage only recommended. If a valid value is given, this will be added to the CB_AudioFileCache#id property. preferredAPIs array &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS Array of strings with the preferred audio API or audio APIs, in order of preference. Possible audio APIs are \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). It will try to calculate and use the best one for the current client. If a valid value is given, this will be added to the CB_AudioFileCache#preferredAPIs property. preferredFormats array &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_FORMATS Array of strings with the preferred audio format or audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"'), in order of preference. It will try to calculate and use the best one for the current client. If a valid value is given, this will be added to the CB_AudioFileCache#preferredFormats property. minimumAudioFiles integer &lt;optional&gt; CB_AudioFileCache.minimumAudioFiles_DEFAULT Minimum CB_AudioFile objects to create internally. It must be an integer being 1 the minimum. If a valid value is given, this will be added to the CB_AudioFileCache#minimumAudioFiles property. maximumAudioFiles integer | null &lt;optional&gt; CB_AudioFileCache.maximumAudioFiles_DEFAULT Maximum CB_AudioFile objects that are allowed to be created internally. If it is set to null, there will not be a maximum (it will be unlimited). If an integer is provided, it must be the same number or greater than the value set in the CB_AudioFileCache#minimumAudioFiles property (also provided by the \"minimumAudioFiles\" of this object), allowing 1 minimum. If a valid value is given, this will be added to the CB_AudioFileCache#maximumAudioFiles property. minimumAudioFilesFree integer &lt;optional&gt; parseInt(CB_AudioFileCache#minimumAudioFiles * 0.25 + 0.5) New CB_AudioFile objects will be created internally when the number of free CB_AudioFile objects reaches this limit. If provided, it must be an integer being 0 (zero) the minimum. It will end using a 25% of the CB_AudioFileCache#minimumAudioFiles by default, rounded to ceil, allowing 0 (zero) minimum. If a valid value is given, this will be added to the CB_AudioFileCache#minimumAudioFilesFree property. newAudioFilesWhenNeeded integer &lt;optional&gt; Math.min(parseInt(CB_AudioFileCache#minimumAudioFiles * 0.1 + 0.5), 1) Number of new CB_AudioFile objects to create internally when the minimum limit of free CB_AudioFile objects (CB_AudioFileCache#minimumAudioFilesFree) is reached. If provided, it must be an integer being 0 (zero) the minimum. It will end using a 10% of the CB_AudioFileCache#minimumAudioFiles by default, rounded to ceil, allowing 1 minimum. If a valid value is given, this will be added to the CB_AudioFileCache#newAudioFilesWhenNeeded property. retries integer &lt;optional&gt; CB_AudioFileCache.retries_DEFAULT Number of retries to try to load a CB_AudioFile object internally before trying to load the next possible one (if any). It must be an integer being 0 the minimum. If a valid value is given, this will be added to the CB_AudioFileCache#retries property. checkManually boolean &lt;optional&gt; CB_AudioFileCache.checkManually_DEFAULT Tells whether the CB_AudioFile objects must be checked automatically or not (manually) by default. If a valid value is given, this will be added to the CB_AudioFileCache#checkManually property. checkManuallyOnNeededCreated boolean &lt;optional&gt; CB_AudioFileCache.checkManuallyOnNeededCreated_DEFAULT Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when creates a new CB_AudioFile object needed. If a valid value is given, this will be added to the CB_AudioFileCache#checkManuallyOnNeededCreated property. checkManuallyOnPlayingFailed boolean &lt;optional&gt; CB_AudioFileCache.checkManuallyOnPlayingFailed_DEFAULT Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when playing one has failed and tries to reload it. If a valid value is given, this will be added to the CB_AudioFileCache#checkManuallyOnPlayingFailed property. checkManuallyOnCheckingFailed boolean &lt;optional&gt; CB_AudioFileCache.checkManuallyOnCheckingFailed_DEFAULT Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when checking one has failed and tries to reload it. If a valid value is given, this will be added to the CB_AudioFileCache#checkManuallyOnCheckingFailed property. onLoad function &lt;optional&gt; Desired function to be called once the cache has been loaded. The first and unique parameter will be an integer with the CB_AudioFile objects that still need to be checked, if any, being \"this\" the current CB_AudioFileCache object. If a valid value is given, this will be added to the CB_AudioFileCache#onLoad property. onError function &lt;optional&gt; Desired function to be called when any kind of error happens. The first and unique parameter will be a string with the error description (if it could be determined), being \"this\" the current CB_AudioFileCache object. If a valid value is given, this will be added to the CB_AudioFileCache#onError property. disableAutoLoad boolean &lt;optional&gt; false If set to true, it will not create automatically the CB_AudioFile objects by calling the CB_AudioFileCache#createAudioFiles method internally. Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 24 executeFunctionAll_OBJECT Object used by the CB_AudioFileCache#executeFunctionAll method when the \"returnSetTimeoutsArray\" parameter is set to true. Type: Object Properties: Name Type Description item CB_AudioFile The CB_AudioFile affected. setTimeoutReturningValue integer The returning value of calling the setTimeout internally or null if it was not called, depending on the \"delayBetweenEach\" parameter. setTimeoutDelay number The value used as the second parameter when calling the setTimeout internally or zero if it was not called, depending on the \"delayBetweenEach\" parameter. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1861 getFreeAudioFile_OBJECT Object returned by the CB_AudioFileCache#getFreeAudioFile method. Type: Object Properties: Name Type Description object CB_AudioFile | null Contains the CB_AudioFile object if found or null otherwise. index string | integer Contains the position of the CB_AudioFile object inside the CB_AudioFileCache#audioFiles property if found or \"-1\" otherwise. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 1393 setAudioAPIAll_CALLBACK_ERROR(error, errorsHappened, objectsChangedAPI, performedActions, actionsNeeded) Callback function used by the CB_AudioFileCache#setAudioAPIAll method that will be called when any error happened. Parameters: Name Type Description error string A string describing the error, if it was possible to be determined. errorsHappened integer The number of errors that happened, which could be greater than 1 if more than one internal call to the CB_AudioFile#setAudioAPI method failed. objectsChangedAPI integer The number of CB_AudioFile objects that actually changed its audio API. performedActions integer The number of CB_AudioFile objects that ended with a desired audio API, including those ones which were already using it. actionsNeeded integer The total number of CB_AudioFile objects that were considered to perform the action (it will be undefined if it could not be determined). Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2347 setAudioAPIAll_CALLBACK_OK(objectsChangedAPI, performedActions, actionsNeeded) Callback function used by the CB_AudioFileCache#setAudioAPIAll method that will be called when all the process was performed successfully. Parameters: Name Type Description objectsChangedAPI integer The number of CB_AudioFile objects that actually changed its audio API. performedActions integer The number of CB_AudioFile objects that ended with a desired audio API, including those ones which were already using it. actionsNeeded integer The total number of CB_AudioFile objects that were considered to perform the action (it will be undefined if it could not be determined). Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 2338 URIS_OBJECT Object whose property names are audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"') and their value is an array of strings with the URIs (audio file paths or audio data URIs) of the audio files in order of preference. The best audio format for the current client will be tried to be calculated and it will use the first working URI (audio file path or data URI). The more audio formats and URIs provided the better, as it will help to maximize the compatibility with as many clients as possible (as some audio APIs and client just support some formats, or use absolute paths instead of relative ones, etc.). Even with different formats, all provided URIs should belong to the same audio (this means same sound or same music, with same length, etc.). NOTE: Only some clients with some audio APIs will support data URIs. Type: Object Properties: Name Type Description filePaths array Being the name of each property the audio format (it can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"'), the value will always be a numeric array of strings with the URIs (audio file paths or audio data URIs) of the audio files in order of preference. The best audio format for the current client will be tried to be calculated and it will use the first working URI (audio file path or data URI). The more audio formats and URIs provided the better, as it will help to maximize the compatibility with as many clients as possible (as some audio APIs and client just support some formats, or use absolute paths instead of relative ones, etc.). Even with different formats, all provided URIs should belong to the same audio (this means same sound or same music, with same length, etc.). NOTE: Only some clients with some audio APIs will support data URIs. Source: CrossBase/audiovisual/audio/CB_AudioFileCache.js, line 8 Example { \"audio/mp4\" : [ \"first/path/sound.m4a\", \"alternative/path/sound.m4a\", \"alternative/path/2/sound.mp4\", ... ], \"audio/ogg\" : [ \"first/path/sound.opus\", \"alternative/path/sound.ogg\", \"alternative/path/2/sound.ogg\", ... ], \"audio/mpeg\" : [ \"first/path/sound.mp3\", \"alternative/path/sound.mp3\", \"alternative/path/2/sound.mp3\", ... ], \"audio/wav\" : [ \"first/path/sound.wav\", \"alternative/path/sound.wav\", \"alternative/path/2/sound.wav\", ... ], ... } × Search results Close "},"CB_AudioFileSprites.html":{"id":"CB_AudioFileSprites.html","title":"Class: CB_AudioFileSprites","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Class: CB_AudioFileSprites CB_AudioFileSprites Class to manage audio sprites of a CB_AudioFileCache object (used internally). new CB_AudioFileSprites( [dataObject]) → {CB_AudioFileSprites} The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Parameters: Name Type Argument Description dataObject CB_AudioFileSprites.DATA_OBJECT &lt;optional&gt; Object with the desired data and options for the audio sprites. Although it can contain a \"sprites\" property, it will also be used as the first and unique parameter when calling the constructor of the CB_AudioFileCache object internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 68 To Do: Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). Think about using wrapper to replace \"this\" in callbacks (callbackOk, callbackError) to point to the CB_AudioFileSprites object itself. Method getCopy and static method filterProperties (similar to the ones from CB_GraphicSprites and CB_GraphicSpritesScene). Returns: Returns a new CB_AudioFileSprites object. Type CB_AudioFileSprites Members &lt;readonly&gt; audioFileCache :CB_AudioFileCache Contains the CB_AudioFileCache object. Internal usage only recommended. Type: CB_AudioFileCache Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 182 &lt;readonly&gt; id :string Stores the identifier for the audio file sprites object. Type: string Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 81 &lt;readonly&gt; sprites :CB_AudioFileSprites.SPRITES_OBJECT Object with information about the sprites. Type: CB_AudioFileSprites.SPRITES_OBJECT Default Value: {} Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 90 &lt;readonly&gt; spriteSoundInstances :Object Object whose property names are the sprite identifiers (strings), including one called \"_WITHOUT_SPRITE_ASSOCIATED\" for sound instances without a sprite associated, and their values are an array containing the sound instance identifiers (created by the CB_AudioFileSprites#play method). Internal usage only recommended. Type: Object Default Value: { \"_WITHOUT_SPRITE_ASSOCIATED\" : [] } Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 99 Methods cancelSoundInstance(soundInstanceId [, cancel] [, affectWithObjectAssociated]) → {boolean} Cancels (to prevent it starts playing) or enables a sound instance (created by the CB_AudioFileCache#play method), by its identifier. Uses the CB_AudioFileCache#cancelSoundInstance method internally and returns its returning value. Parameters: Name Type Argument Default Description soundInstanceId integer Used as the \"soundInstanceId\" parameter when calling the CB_AudioFileCache#cancelSoundInstance method internally. cancel boolean &lt;optional&gt; false Used as the \"cancel\" parameter when calling the CB_AudioFileCache#cancelSoundInstance method internally. affectWithObjectAssociated boolean &lt;optional&gt; false Used as the \"affectWithObjectAssociated\" parameter when calling the CB_AudioFileCache#cancelSoundInstance method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 975 Returns: Returns true if the sound instance has been modified or false otherwise. Type boolean cancelSoundInstances( [cancel] [, affectWithObjectAssociated]) → {integer} Cancels (to prevent they start playing) or enables all sound instances (created by the CB_AudioFileCache#play method). Uses the CB_AudioFileCache#cancelSoundInstances method internally and returns its returning value. Parameters: Name Type Argument Default Description cancel boolean &lt;optional&gt; false Used as the \"cancel\" parameter when calling the CB_AudioFileCache#cancelSoundInstances method internally. affectWithObjectAssociated boolean &lt;optional&gt; false Used as the \"affectWithObjectAssociated\" parameter when calling the CB_AudioFileCache#cancelSoundInstances method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 961 Returns: Returns the number of sound instances modified. Type integer checkPlayingAll( [callbackOk] [, callbackError] [, ignoreQueue]) → {integer} Checks whether each CB_AudioFile object whose CB_AudioFile#getStatus method returns the \"unchecked\" value (which belongs to the value of the CB_AudioFile#UNCHECKED property) can be played or not. After checking, if the audio can be played, the status of the CB_AudioFile object will get the value of CB_AudioFile.LOADED. Otherwise, if it cannot be played, the status of the CB_AudioFile object will get the value of CB_AudioFile.FAILED. If a CB_AudioFile object cannot be played and it is determined necessary, it will try to reload it internally (by calling the CB_AudioFileCache#removeAudioFile method). It will call the CB_AudioFileCache#clearAudioFiles method internally after finishing. Uses the CB_AudioFileCache#checkPlayingAll method internally and returns its returning value. Recommended to be called through a user-driven event (as onClick, onTouch, etc.). Parameters: Name Type Argument Default Description callbackOk CB_AudioFileCache.checkPlayingAll_CALLBACK_OK &lt;optional&gt; Used as the \"callbackOk\" parameter when calling the CB_AudioFileCache#checkPlayingAll method internally. callbackError CB_AudioFileCache.checkPlayingAll_CALLBACK_ERROR &lt;optional&gt; Used as the \"callbackError\" parameter when calling the CB_AudioFileCache#checkPlayingAll method internally. ignoreQueue boolean &lt;optional&gt; false Used as the \"ignoreQueue\" parameter when calling the CB_AudioFileCache#checkPlayingAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1072 Returns: Returns the number of CB_AudioFile objects whose status belonged to the \"unchecked\" value (the value of the CB_AudioFile#UNCHECKED property) before the execution of this method. It will return 0 (zero) if the method is tried to be executed while there is another previous call of it still running. It will also return 0 (zero) if the status of the audio file cache is not loaded (the CB_AudioFileCache#status property does not belong to the value set in the CB_AudioFileCache.LOADED property). Type integer clearAudioFiles( [avoidCallingCheckCacheLoaded]) → {array} Cleans the array of the CB_AudioFile objects (taking off the undefined or null ones) which is in the CB_AudioFileCache#audioFiles property, just keeping the valid ones and clearing (destroying and removing) the others. For performance purposes. Uses the CB_AudioFileCache#clearAudioFiles method internally and returns its returning value. Internal usage only recommended. Parameters: Name Type Argument Default Description avoidCallingCheckCacheLoaded boolean &lt;optional&gt; false Used as the \"avoidCallingCheckCacheLoaded\" parameter when calling the CB_AudioFileCache#clearAudioFiles method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 857 Returns: Returns the value of the CB_AudioFileCache#audioFiles property. Type array clearSoundInstances( [clearWithObjectAssociated]) → {integer} Clears the sound instances (created by the CB_AudioFileCache#play method) which have been cancelled. Uses the CB_AudioFileCache#clearSoundInstances method internally and returns its returning value. Parameters: Name Type Argument Default Description clearWithObjectAssociated boolean &lt;optional&gt; false Used as the \"clearWithObjectAssociated\" parameter when calling the CB_AudioFileCache#clearSoundInstances method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 923 Returns: Returns the number of cleared sound instances. Type integer createAudioFile( [URIs] [, preferredAPIs] [, preferredFormats] [, audioObject] [, callbackOk] [, callbackError] [, storeURIsList] [, checkAutomatically]) → {CB_AudioFile|null} Creates one internal CB_AudioFile object (inside the CB_AudioFileCache#audioFiles property). Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Uses the CB_AudioFileCache#createAudioFile method internally and returns its returning value. Internal usage only recommended. Parameters: Name Type Argument Default Description URIs CB_AudioFileCache.URIS_OBJECT &lt;optional&gt; CB_AudioFileCache#URIs Used as the \"URIs\" parameter when calling the CB_AudioFileCache#createAudioFile method internally. preferredAPIs array &lt;optional&gt; CB_AudioFileCache#preferredAPIs Used as the \"preferredAPIs\" parameter when calling the CB_AudioFileCache#createAudioFile method internally. preferredFormats array &lt;optional&gt; CB_AudioFileCache#preferredFormats Used as the \"preferredFormats\" parameter when calling the CB_AudioFileCache#createAudioFile method internally. audioObject CB_AudioFile &lt;optional&gt; Used as the \"audioObject\" parameter when calling the CB_AudioFileCache#createAudioFile method internally. callbackOk function &lt;optional&gt; Used as the \"callbackOk\" parameter when calling the CB_AudioFileCache#createAudioFile method internally. callbackError function &lt;optional&gt; Used as the \"callbackError\" parameter when calling the CB_AudioFileCache#createAudioFile method internally. storeURIsList boolean &lt;optional&gt; false Used as the \"storeURIsList\" parameter when calling the CB_AudioFileCache#createAudioFile method internally. checkAutomatically boolean &lt;optional&gt; false Used as the \"checkAutomatically\" parameter when calling the CB_AudioFileCache#createAudioFile method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 845 Returns: If it fails, it returns null. Otherwise, returns the CB_AudioFile that has been created or reused. Type CB_AudioFile | null createAudioFiles(minimumAudioFiles) → {integer} Creates the desired number of internal CB_AudioFile objects (inside the CB_AudioFileCache#audioFiles property). Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Uses the CB_AudioFileCache#createAudioFiles method internally and returns its returning value. Parameters: Name Type Description minimumAudioFiles integer Used as the \"minimumAudioFiles\" parameter when calling the CB_AudioFileCache#createAudioFiles method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 826 Returns: Returns the number of CB_AudioFile objects which are intended to be created (they could fail). Type integer destroyAll( [stopSounds]) → {integer} Destroys all the CB_AudioFile objects and frees memory, by calling CB_AudioFile#destructor(stopSounds, false, true). Uses the CB_AudioFileCache#destroyAll method internally and returns its returning value. Parameters: Name Type Argument Default Description stopSounds boolean &lt;optional&gt; false Used as the \"stopSounds\" parameter when calling the CB_AudioFileCache#destroyAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1058 Returns: Returns the number of CB_AudioFile objects whose CB_AudioFile#destructor has been called. Type integer destructor( [stopSounds] [, preventAbortedStatus]) Destroys the audio file sprites object (removing all sprites, etc.), including the internal audio file cache object, and frees memory. By default, unless the \"preventAbortedStatus\" is set to true, sets the current status of the CB_AudioFileCache object as ABORTED (CB_AudioFileCache.ABORTED value). Parameters: Name Type Argument Default Description stopSounds boolean &lt;optional&gt; false Used as the \"stopSounds\" parameter when calling internally the CB_AudioFileCache#destructor method of the CB_AudioFileCache object. preventAbortedStatus boolean &lt;optional&gt; false If set to true (not recommended), it will not assign the status of \"ABORTED\" (it will not assign the value of CB_AudioFileCache.ABORTED to the CB_AudioFileCache#status property). Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 239 executeAll() Alias for CB_AudioFileSprites#executeFunctionAll. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1025 See: CB_AudioFileSprites#executeFunctionAll executeAllSprite() Alias for CB_AudioFileSprites#executeFunctionAllSprite. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 579 See: CB_AudioFileSprites#executeFunctionAllSprite executeAllSprites() Alias for CB_AudioFileSprites#executeFunctionAllSprites. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 607 See: CB_AudioFileSprites#executeFunctionAllSprites executeFunctionAll(functionEach [, delayBetweenEach] [, audioFiles] [, returnSetTimeoutsArray] [, delayBetweenEachAffectsFirst] [, functionFinish]) → {integer|array} Performs a desired action, using the provided function, on all the existing CB_AudioFile objects or on the desired ones (if provided). Uses the CB_AudioFileCache#executeFunctionAll method internally and returns its returning value. Parameters: Name Type Argument Default Description functionEach CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK Used as the \"functionEach\" parameter when calling the CB_AudioFileSprites#executeFunctionAll method internally. delayBetweenEach number | CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK &lt;optional&gt; 0 Used as the \"delayBetweenEach\" parameter when calling the CB_AudioFileCache#executeFunctionAll method internally. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileCache#executeFunctionAll method internally. returnSetTimeoutsArray boolean &lt;optional&gt; false Used as the \"returnSetTimeoutsArray\" parameter when calling the CB_AudioFileCache#executeFunctionAll method internally. delayBetweenEachAffectsFirst boolean &lt;optional&gt; false Used as the \"delayBetweenEachAffectsFirst\" parameter when calling the CB_AudioFileCache#executeFunctionAll method internally. functionFinish CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK &lt;optional&gt; Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1046 Returns: If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the CB_AudioFile objects given in the \"audioFiles\" parameter). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a CB_AudioFileCache.executeFunctionAll_OBJECT object for each CB_AudioFile given. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the setTimeout function. Type integer | array executeFunctionAllSprite(spriteId, functionEach [, delayBetweenEach] [, avoidCancelled] [, returnSetTimeoutsArray] [, delayBetweenEachAffectsFirst] [, functionFinish]) → {integer|array} Executes a desired function for all the CB_AudioFile objects used by the sound instances currently created that belong to a given sprite (by its ID). It calls the CB_AudioFileSprites#executeFunctionAll method internally and returns its returning value. Parameters: Name Type Argument Default Description spriteId string The identifier for the sprite. functionEach CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK Used as the \"functionEach\" parameter when calling the CB_AudioFileSprites#executeFunctionAll method internally. delayBetweenEach number | CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK &lt;optional&gt; 0 Used as the \"delayBetweenEach\" parameter when calling the CB_AudioFileSprites#executeFunctionAll method internally. avoidCancelled boolean &lt;optional&gt; false If set to true, it will not affect the CB_AudioFile objects whose sound instance has been cancelled. Used as the \"avoidCancelled\" parameter when calling the CB_AudioFileSprites#getAudioFilesUsedBySpriteId method internally. returnSetTimeoutsArray boolean &lt;optional&gt; false Used as the \"returnSetTimeoutsArray\" parameter when calling the CB_AudioFileSprites#executeFunctionAll method internally. delayBetweenEachAffectsFirst boolean &lt;optional&gt; false Used as the \"delayBetweenEachAffectsFirst\" parameter when calling the CB_AudioFileSprites#executeFunctionAll method internally. functionFinish CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK &lt;optional&gt; Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 601 Returns: If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the CB_AudioFile objects used by the sound instances that belong to the given sprite identifier). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a CB_AudioFileCache.executeFunctionAll_OBJECT object for each CB_AudioFile given. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the setTimeout function. Type integer | array executeFunctionAllSprites(functionEach [, delayBetweenEach] [, includeWithoutSpriteAssociated] [, avoidCancelled] [, returnSetTimeoutsArray] [, delayBetweenEachAffectsFirst] [, functionFinish]) → {integer|array} Executes a desired function for all the CB_AudioFile objects used by all the sound instances currently created. It calls the CB_AudioFileSprites#executeFunctionAll method internally and returns its returning value. Parameters: Name Type Argument Default Description functionEach CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK Used as the \"functionEach\" parameter when calling the CB_AudioFileSprites#executeFunctionAll method internally. delayBetweenEach number | CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK &lt;optional&gt; 0 Used as the \"delayBetweenEach\" parameter when calling the CB_AudioFileSprites#executeFunctionAll method internally. includeWithoutSpriteAssociated boolean &lt;optional&gt; false If set to true, it will also affect the CB_AudioFile objects whose sound instance ID is not associated to any sprite. Used as the \"includeWithoutSpriteAssociated\" parameter when calling the CB_AudioFileSprites#getAudioFilesUsed method internally. avoidCancelled boolean &lt;optional&gt; false If set to true, it will not affect the CB_AudioFile objects whose sound instance has been cancelled. Used as the \"avoidCancelled\" parameter when calling the CB_AudioFileSprites#getAudioFilesUsed method internally. returnSetTimeoutsArray boolean &lt;optional&gt; false Used as the \"returnSetTimeoutsArray\" parameter when calling the CB_AudioFileSprites#executeFunctionAll method internally. delayBetweenEachAffectsFirst boolean &lt;optional&gt; false Used as the \"delayBetweenEachAffectsFirst\" parameter when calling the CB_AudioFileSprites#executeFunctionAll method internally. functionFinish CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK &lt;optional&gt; Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 629 Returns: If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the CB_AudioFile objects used by the sound instances that belong to the sprites). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a CB_AudioFileCache.executeFunctionAll_OBJECT object for each CB_AudioFile given. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the setTimeout function. Type integer | array forEach() Alias for CB_AudioFileSprites#executeFunctionAll. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1030 See: CB_AudioFileSprites#executeFunctionAll forEachSprite() Alias for CB_AudioFileSprites#executeFunctionAllSprites. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 612 See: CB_AudioFileSprites#executeFunctionAllSprites forEachSpriteById() Alias for CB_AudioFileSprites#executeFunctionAllSprite. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 584 See: CB_AudioFileSprites#executeFunctionAllSprite getAudioFileBySoundInstanceId(soundInstanceId [, avoidCancelled]) → {CB_AudioFile|null} Gets the CB_AudioFile object associated to a given sound instance ID (created by the CB_AudioFileCache#play method), if any, or null otherwise. Uses the CB_AudioFileCache#getAudioFileBySoundInstanceId method internally and returns its returning value. Parameters: Name Type Argument Default Description soundInstanceId integer Used as the \"soundInstanceId\" parameter when calling the CB_AudioFileCache#getAudioFileBySoundInstanceId method internally. avoidCancelled boolean &lt;optional&gt; false Used as the \"avoidCancelled\" parameter when calling the CB_AudioFileCache#getAudioFileBySoundInstanceId method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 988 Returns: Returns the CB_AudioFile object associated to a given sound instance ID, if any, or null otherwise. Type CB_AudioFile | null getAudioFiles( [copy]) → {array} Gets an array with all the CB_AudioFile objects. Uses the CB_AudioFileCache#getAudioFiles method internally and returns its returning value. Parameters: Name Type Argument Default Description copy boolean &lt;optional&gt; false Used as the \"copy\" parameter when calling the CB_AudioFileCache#getAudioFiles method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1256 Returns: Returns an array with all the CB_AudioFile objects. Type array getAudioFilesBusy() → {array} Gets an array with the busy CB_AudioFile objects (the objects which are not available and ready to use). Uses the CB_AudioFileCache#getAudioFilesBusy method internally and returns its returning value. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1278 Returns: Returns an array with the busy CB_AudioFile objects (the objects which are not available and ready to use). Type array getAudioFilesFree() → {array} Gets an array with the free CB_AudioFile objects (the objects which are available and ready to use). Uses the CB_AudioFileCache#getAudioFilesFree method internally and returns its returning value. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1267 Returns: Returns an array with the free CB_AudioFile objects (the objects which are available and ready to use). Type array getAudioFilesFreeNumber() → {integer} Tells the current number of free CB_AudioFile objects (the number of objects which are available and ready to use). Uses the CB_AudioFileCache#getAudioFilesFreeNumber method internally and returns its returning value. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1244 Returns: Returns the current number of free CB_AudioFile objects (the number of objects which are available and ready to use). Type integer getAudioFilesNumber( [real]) → {integer} Tells the number of CB_AudioFile objects created. Uses the CB_AudioFileCache#getAudioFilesNumber method internally and returns its returning value. Parameters: Name Type Argument Default Description real boolean &lt;optional&gt; false Used as the \"real\" parameter when calling the CB_AudioFileCache#getAudioFilesNumber method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1290 Returns: Returns the number of CB_AudioFile objects created. Type integer getAudioFilesUsed( [oneDimension] [, includeWithoutSpriteAssociated] [, avoidCancelled]) → {CB_AudioFileSprites.getAudioFilesUsed_OBJECT|array} Returns the CB_AudioFile objects used by all the sounds instances currently created. Parameters: Name Type Argument Default Description oneDimension boolean &lt;optional&gt; false If set to false, it will return an object whose property names are the sprite identifiers (including the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated, if the \"includeWithoutSpriteAssociated\" is set to true) and their value will be a numeric array with the CB_AudioFile objects used. Otherwise, if set to true, it will return a numeric array with the CB_AudioFile objects used (if the \"includeWithoutSpriteAssociated\" parameter is set to true, it will also contain the CB_AudioFile objects whose sound instance ID is not associated to any sprite). includeWithoutSpriteAssociated boolean &lt;optional&gt; false If set to true, it will also return the CB_AudioFile objects whose sound instance ID is not associated to any sprite. Used as the \"includeWithoutSpriteAssociated\" parameter when calling the CB_AudioFileSprites#getSprites method internally. avoidCancelled boolean &lt;optional&gt; false If set to true, it will not return the CB_AudioFile objects whose sound instance has been cancelled. Used as the \"avoidCancelled\" parameter when calling the CB_AudioFileSprites#getAudioFilesUsedBySpriteId method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 546 Returns: Returns the CB_AudioFile objects used by all the sounds instances currently created. If the \"oneDimension\" parameter is set to false, it will return a CB_AudioFileSprites.getAudioFilesUsed_OBJECT object whose property names are the sprite identifiers (including the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated, if the \"includeWithoutSpriteAssociated\" is set to true) and their value will be a numeric array with the CB_AudioFile objects used. Otherwise, if the \"oneDimension\" parameter set to true, it will return a numeric array with the CB_AudioFile objects used (if the \"includeWithoutSpriteAssociated\" parameter is set to true, it will also contain the CB_AudioFile objects whose sound instance ID is not associated to any sprite). Type CB_AudioFileSprites.getAudioFilesUsed_OBJECT | array getAudioFilesUsedBySpriteId(spriteId [, avoidCancelled]) → {array} Returns an array of the CB_AudioFile objects used by the sound instances that belong to a given sprite identifier. Parameters: Name Type Argument Default Description spriteId string The identifier for the sprite. avoidCancelled boolean &lt;optional&gt; false If set to true, it will not return the CB_AudioFile objects whose sound instance has been cancelled. Used as the \"avoidCancelled\" parameter when calling the CB_AudioFileSprites#getAudioFileBySoundInstanceId method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 513 Returns: Returns an array of the CB_AudioFile objects used by the sound instances that belong to the given sprite identifier. Type array getDuration( [maximum]) → {number} Tells the duration (minimum or maximum) of the sound stored (in milliseconds). Although the audio file cache should always be used to cache the same sound only, the duration might not always be the same due the usage of different formats, file paths, etc. So this method returns either the minimum or the maximum duration found among all the CB_AudioFile objects. Uses the CB_AudioFileCache#getDuration method internally and returns its returning value. Parameters: Name Type Argument Default Description maximum boolean &lt;optional&gt; false Used as the \"maximum\" parameter when calling the CB_AudioFileCache#getDuration method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1302 Returns: Returns the duration (minimum or maximum) of the sound stored (in milliseconds). Although the audio file cache should always be used to cache the same sound only, the duration might not always be the same due the usage of different formats, file paths, etc. So this method returns either the minimum or the maximum duration found among all the CB_AudioFile objects. Type number getFreeAudioFile( [popIt]) → {CB_AudioFileCache.getFreeAudioFile_OBJECT} Returns a free CB_AudioFile object, if any (from the CB_AudioFileCache#audioFilesFree property). Note that this will call the internal CB_AudioFileCache#_createNewAudioFilesIfNeeded method that could end creating a new CB_AudioFile object if needed. Uses the CB_AudioFileCache#getFreeAudioFile method internally and returns its returning value. Parameters: Name Type Argument Default Description popIt boolean &lt;optional&gt; false Used as the \"popIt\" parameter when calling the CB_AudioFileCache#getFreeAudioFile method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 899 Returns: Returns a CB_AudioFileCache.getFreeAudioFile_OBJECT object. Type CB_AudioFileCache.getFreeAudioFile_OBJECT getProgress( [countLoadedObjects] [, alsoUncheckedAndCheckingObjects]) → {number} Returns a number representing the percentage of the loading progress for the audio file sprites object (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Uses the CB_AudioFileCache#getProgress method internally and returns its returning value. Parameters: Name Type Argument Default Description countLoadedObjects boolean &lt;optional&gt; false Used as the \"countLoadedObjects\" parameter when calling the CB_AudioFileCache#getProgress method internally. alsoUncheckedAndCheckingObjects boolean &lt;optional&gt; false Used as the \"alsoUncheckedAndCheckingObjects\" parameter when calling the CB_AudioFileCache#getProgress method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1315 Returns: Returns a number representing the percentage of the loading progress for the audio file sprites object (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Type number getSoundInstancesId( [oneDimension] [, includeWithoutSpriteAssociated]) → {Object|array} Returns the sound instances (their ID) used (stored in the CB_AudioFileSprites#spriteSoundInstances property). Parameters: Name Type Argument Default Description oneDimension boolean &lt;optional&gt; false If set to true, it will return the CB_AudioFileSprites#spriteSoundInstances property directly (which includes the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated). Otherwise, if it is set to true, it will return a numeric array whose values are the sound instance IDs. includeWithoutSpriteAssociated boolean &lt;optional&gt; false If set to true, it will also return the sound instance identifiers which are not associated to any sprite. Used as the \"includeWithoutSpriteAssociated\" parameter when calling the CB_AudioFileSprites#getSprites method internally. Only used when the \"oneDimension\" parameter is set to true. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 478 Returns: Returns the sound instances (their ID) used (stored in the CB_AudioFileSprites#spriteSoundInstances property). If the \"oneDimension\" parameter is set to false, the property names of the returning object are the sprite identifiers (strings), including one called \"_WITHOUT_SPRITE_ASSOCIATED\" for sound instances without a sprite associated, and their values are an array containing the sound instance IDs. If the \"oneDimension\" parameter is set to true, it will return a numeric array whose values are the sound instance identifiers (if the \"includeWithoutSpriteAssociated\" parameter it set to true, it will also include the sound instances which are not associated to any sprite). Type Object | array getSoundInstancesIdBySpriteId(spriteId) → {array} Returns an array of the sound instance identifiers (created by the CB_AudioFileSprites#play method) used by the given sprite identifier. Parameters: Name Type Description spriteId string The identifier for the sprite. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 461 Returns: Returns a numeric array of the sound instances (created by the CB_AudioFileSprites#play method) used by the given sprite identifier. Type array getSprite(spriteId) → {CB_AudioFileSprites.SPRITE_OBJECT} Returns a sprite by its ID. Parameters: Name Type Description spriteId string The identifier for the sprite. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 423 Returns: Returns the desired sprite or a fake object if it was not found. The fake object will be this one: { \"startAt\" : 0, \"stopAt\" : null, \"fake\" : true }. Type CB_AudioFileSprites.SPRITE_OBJECT getSprites( [includeWithoutSpriteAssociated]) → {CB_AudioFileSprites.SPRITES_OBJECT} Returns an object with the sprites (and includes \"_WITHOUT_SPRITE_ASSOCIATED\" if we want to). Parameters: Name Type Argument Default Description includeWithoutSpriteAssociated boolean &lt;optional&gt; false If set to true, the returning object will also contain a property called \"_WITHOUT_SPRITE_ASSOCIATED\" whose value will be an empty object (unless the property existed before in the object stored in the CB_AudioFileSprites#sprites property and had a value which is not an empty object). If set to false, the returning object will not contain the \"_WITHOUT_SPRITE_ASSOCIATED\" property unless the property existed before in the object stored in the CB_AudioFileSprites#sprites property. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 439 Returns: Returns an object with the sprites (and includes \"_WITHOUT_SPRITE_ASSOCIATED\" if we want to). Type CB_AudioFileSprites.SPRITES_OBJECT getStatus() → {number} Gets the current status of the audio file sprites object. Uses the CB_AudioFileCache#getStatus method internally and returns its returning value. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1326 Returns: Returns the current status of the audio file sprites object. It is a number, which should match the value of the CB_AudioFileCache.UNLOADED (still unloaded), CB_AudioFileCache.LOADING (loading), CB_AudioFileCache.UNCHECKED (not checked by calling the CB_AudioFileCache#checkPlayingAll method yet), CB_AudioFileCache.CHECKING (being checked by the CB_AudioFileCache#checkPlayingAll method), CB_AudioFileCache.LOADED (loaded), CB_AudioFileCache.FAILED (failed loading or failed to play or by any other reason) or CB_AudioFileCache.ABORTED (aborted because it was destroyed with the \"destructor\" method) property. Type number getStatusString() → {string} Gets the current status of the audio file sprites, as a string. Uses the CB_AudioFileCache#getStatusString method internally and returns its returning value. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1337 Returns: Returns the current status of the audio file sprites, as a string. Possible return values are \"UNLOADED\", \"LOADING\", \"UNCHECKED\", \"CHECKING\", \"LOADED\", \"FAILED\", \"ABORTED\" or \"UNKNOWN (UNKNOWN_STATUS)\" (where \"UNKNOWN_STATUS\" will be a value from the CB_AudioFileCache#status property not recognized as any possible status). Type string insertSprite(sprite, spriteId) → {boolean} Inserts the given sprite. It will keep the existing ones. If a sprite identifier already existed and it is given again (not recommended), it will be replaced by the new one (but keeping its current sound instances, if any). Parameters: Name Type Description sprite CB_AudioFileSprites.SPRITE_OBJECT Object with the desired sprite. spriteId string The identifier for the sprite. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 327 Returns: Returns true if the sprite has been inserted or false otherwise. Type boolean insertSprites(sprites) → {integer} Inserts the given sprites. It will keep the existing ones. If a sprite identifier already existed and it is given again (not recommended), it will be replaced by the new one (but keeping its current sound instances, if any). Parameters: Name Type Description sprites CB_AudioFileSprites.SPRITES_OBJECT Object with the desired sprites. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 305 Returns: Returns the number of sprites inserted. Type integer isAudioFileFree(id) → {boolean} Tells whether a desired CB_AudioFile object is free (it is in the CB_AudioFileCache#audioFilesFree property) or not, by its identifier. A free CB_AudioFile object is an object which is not being used and it is available to be used. Uses the CB_AudioFileCache#isAudioFileFree method internally and returns its returning value. Parameters: Name Type Description id string Used as the \"id\" parameter when calling the CB_AudioFileCache#isAudioFileFree method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 911 Returns: Returns whether a desired CB_AudioFile object is free (it is in the CB_AudioFileCache#audioFilesFree property) or not, by its identifier. A free CB_AudioFile object is an object which is not being used and it is available to be used. Type boolean isPausedSprite(spriteId) → {boolean} Tells whether a given sprite (by its ID) is paused or not. Note that there could be more than one sound instance (with a {@CB_AudioFile} object) by each sprite with different status (paused, stopped, etc.) and this method will return true if any of them is paused. Parameters: Name Type Description spriteId string The identifier for the sprite. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 659 Returns: Returns whether a given sprite (by its ID) is paused or not. Type boolean isPlaying() → {boolean} Tells whether any of the CB_AudioFile objects is playing or not. Uses the CB_AudioFileCache#isPlaying method internally and returns its returning value. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1233 Returns: Returns whether any of the CB_AudioFile objects is playing or not. Type boolean isPlayingSprite(spriteId) → {boolean} Tells whether a given sprite (by its ID) is playing or not. Note that there could be more than one sound instance (with a {@CB_AudioFile} object) by each sprite with different status (paused, stopped, etc.) and this method will return true if any of them is playing. Parameters: Name Type Description spriteId string The identifier for the sprite. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 641 Returns: Returns whether a given sprite (by its ID) is playing or not. Type boolean isStoppedSprite(spriteId [, checkAudioFileObjects]) → {boolean} Tells whether a given sprite (by its ID) is stopped or not. Note that there could be more than one sound instance (with a {@CB_AudioFile} object) by each sprite with different status (paused, stopped, etc.) and this method will only return true if all of them are stopped. Parameters: Name Type Argument Default Description spriteId string The identifier for the sprite. checkAudioFileObjects boolean &lt;optional&gt; false If set to true, it will check all the {@CB_AudioFile} objects associated to the sprite. Doing so, as internally all stopped {@CB_AudioFile} objects are disassociated from their sound instances, this method should return false normally (unless something went wrong). Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 679 Returns: Returns whether a given sprite (by its ID) is stopped or not. As internally all stopped {@CB_AudioFile} objects are disassociated from their sound instances, this method should return false normally (unless something went wrong). Type boolean load(dataObject) → {CB_AudioFileSprites|null} Loads the audio file sprites with the desired data given. This method is called by the constructor automatically. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Parameters: Name Type Description dataObject CB_AudioFileSprites.DATA_OBJECT Object with the desired data and options for the audio file sprites. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 257 Returns: If a \"dataObject\" is given, it returns the current CB_AudioFileSprites object. Otherwise, it returns null. Type CB_AudioFileSprites | null muteAll( [onMute] [, audioFiles]) → {integer} Mutes all the existing CB_AudioFile objects or the desired ones (if provided). Uses the CB_AudioFileCache#muteAll method internally and returns its returning value. Parameters: Name Type Argument Default Description onMute function &lt;optional&gt; Used as the \"onMute\" parameter when calling the CB_AudioFileCache#muteAll method internally. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileCache#muteAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1177 Returns: Returns the number of calls to the CB_AudioFile#mute method that were performed (which should be the same number as the CB_AudioFile objects in the \"audioFiles\" parameter). Type integer muteSprite(spriteId [, onMute]) → {integer} Mutes all the CB_AudioFile objects that belong to the sound instances (created by the CB_AudioFileSprites#play or the CB_AudioFileSprites#playSprite methods) used by a given sprite identifier. Uses the CB_AudioFileSprites#muteAll method internally and returns its returning value. Parameters: Name Type Argument Description spriteId string The identifier for the sprite. onMute function &lt;optional&gt; Callback function which will be called for each audio file if it has been possible to mute it (or at least it was possible to try it), being \"this\" the CB_AudioFile object. Used internally as the \"onMute\" parameter to call the CB_AudioFileSprites#muteAll method. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 769 Returns: Returns the number of calls to the CB_AudioFile#mute method that were performed internally. Type integer pauseAll( [onPause] [, audioFiles]) → {integer} Tries to pause all the existing CB_AudioFile objects or the desired ones (if provided), which are being played, by calling their CB_AudioFile#pause method internally. Uses the CB_AudioFileCache#pauseAll method internally and returns its returning value. Parameters: Name Type Argument Default Description onPause function &lt;optional&gt; Used as the \"onPause\" parameter when calling the CB_AudioFileCache#pauseAll method internally. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileCache#pauseAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1130 Returns: Returns the number of calls to the CB_AudioFile#pause method that were performed (which should be the same number as the CB_AudioFile objects in the \"audioFiles\" parameter). Type integer pauseSprite(spriteId [, onPause]) → {integer} Pauses all the CB_AudioFile objects that belong to the sound instances (created by the CB_AudioFileSprites#play or the CB_AudioFileSprites#playSprite methods) which are playing used by a given sprite identifier. Uses the CB_AudioFileSprites#pauseAll method internally and returns its returning value. Parameters: Name Type Argument Description spriteId string The identifier for the sprite. onPause function &lt;optional&gt; Function without parameters to be called when the audio is paused successfully, being \"this\" the CB_AudioFile object. Used internally as the \"onPause\" parameter to call the CB_AudioFileSprites#pauseAll method. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 739 Returns: Returns the number of calls to the CB_AudioFile#pause method that were performed internally. Type integer play( [startAt] [, stopAt] [, loop] [, volume] [, allowedRecursiveDelay] [, allowedRecursiveDelaySkipping] [, onPlayStart] [, onStop] [, spriteId]) → {integer|null} Plays a sound of the cache (if there is any free), using a sprite if desired. If a sound cannot be played, this method can call itself internally again and again (with most of the given parameters being the same, depending on the circumstances) to try to play the sound until a desired time limit is reached. If a CB_AudioFile object cannot be played and it is determined necessary, it will try to reload it internally (by calling the CB_AudioFileCache#removeAudioFile method). Uses the CB_AudioFileCache#play method internally and returns its returning value. Internal usage only recommended. To play a sprite, better use the CB_AudioFileSprites#playSprite method instead. Parameters: Name Type Argument Default Description startAt number &lt;optional&gt; 0 | CB_AudioFile_API.WAAPI#lastStartAt | CB_AudioFile_API.SM2#lastStartAt | CB_AudioFile_API.ACMP#lastStartAt | CB_AudioFile_API.AAPI#lastStartAt | stopAt Used as the \"startAt\" parameter when calling the CB_AudioFileCache#play method internally. stopAt number &lt;optional&gt; CB_AudioFile_API.WAAPI#getDuration() | CB_AudioFile_API.SM2#getDuration() | CB_AudioFile_API.ACMP#getDuration() | CB_AudioFile_API.AAPI#getDuration() Used as the \"stopAt\" parameter when calling the CB_AudioFileCache#play method internally. loop boolean &lt;optional&gt; CB_AudioFile#loop Used as the \"loop\" parameter when calling the CB_AudioFileCache#play method internally. volume number &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Used as the \"volume\" parameter when calling the CB_AudioFileCache#play method internally. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT Used as the \"allowedRecursiveDelay\" parameter when calling the CB_AudioFileCache#play method internally. allowedRecursiveDelaySkipping boolean &lt;optional&gt; stopAt-startAt Used as the \"allowedRecursiveDelaySkipping\" parameter when calling the CB_AudioFileCache#play method internally. onPlayStart function &lt;optional&gt; Used as the \"onPlayStart\" parameter when calling the CB_AudioFileCache#play method internally. onStop function &lt;optional&gt; Used as the \"onStop\" parameter when calling the CB_AudioFileCache#play method internally. spriteId string &lt;optional&gt; '_WITHOUT_SPRITE_ASSOCIATED' The identifier for the sprite. Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1008 Returns: Returns null if a sprite identifier was given but it could not be found. Otherwise, returns the sound instance ID used if there was one free or null otherwise. To get a sound instance returned does not mean necessarily that the sound started playing so it is necessary to use a callback function as the \"onPlayStart\" parameter for checking this. The sound instance created (if any), will be cancelled automatically once the sound is stopped. Type integer | null playAll( [startAt] [, stopAt] [, loop] [, volume] [, avoidDelayedPlay] [, allowedRecursiveDelay] [, onPlayStart] [, onStop] [, includingPlaying]) → {integer} Tries to play all the CB_AudioFile objects by calling their CB_AudioFile#play method internally. If a CB_AudioFile object cannot be played and it is determined necessary, it will try to reload it internally (by calling the CB_AudioFileCache#removeAudioFile method). Uses the CB_AudioFileCache#playAll method internally and returns its returning value. Parameters: Name Type Argument Default Description startAt number &lt;optional&gt; 0 | CB_AudioFile_API.WAAPI#lastStartAt | CB_AudioFile_API.SM2#lastStartAt | CB_AudioFile_API.ACMP#lastStartAt | CB_AudioFile_API.AAPI#lastStartAt | stopAt Used as the \"startAt\" parameter when calling the CB_AudioFileCache#playAll method internally. stopAt number &lt;optional&gt; CB_AudioFile_API.WAAPI#getDuration() | CB_AudioFile_API.SM2#getDuration() | CB_AudioFile_API.ACMP#getDuration() | CB_AudioFile_API.AAPI#getDuration() Used as the \"stopAt\" parameter when calling the CB_AudioFileCache#playAll method internally. loop boolean &lt;optional&gt; CB_AudioFile#loop Used as the \"loop\" parameter when calling the CB_AudioFileCache#playAll method internally. volume number &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Used as the \"volume\" parameter when calling the CB_AudioFileCache#playAll method internally. avoidDelayedPlay boolean &lt;optional&gt; false Used as the \"avoidDelayedPlay\" parameter when calling the CB_AudioFileCache#playAll method internally. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT Used as the \"allowedRecursiveDelay\" parameter when calling the CB_AudioFileCache#playAll method internally. onPlayStart function &lt;optional&gt; Used as the \"onPlayStart\" parameter when calling the CB_AudioFileCache#playAll method internally. onStop function &lt;optional&gt; Used as the \"onStop\" parameter when calling the CB_AudioFileCache#playAll method internally. includingPlaying boolean &lt;optional&gt; false Used as the \"includingPlaying\" parameter when calling the CB_AudioFileCache#playAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1092 Returns: Returns the number of CB_AudioFile objects whose CB_AudioFile#play method did not return the value of \"-1\" (this does not mean necessarily that they could be played successfully). Type integer playAndStopAll( [includingPlaying] [, delayBeforeStop]) → {integer} Plays silently and stops all CB_AudioFile objects after a desired time. It can be useful for some clients which need the CB_AudioFile#play method to be called through a user-driven event (as onClick, onTouch, etc.). Internally, it calls CB_AudioFileCache#playAll(0, null, false, 0, true, null, null, null, includingPlaying) and, after a desired delay, calls the CB_AudioFileCache#stopAll method. Uses the CB_AudioFileCache#playAndStopAll method internally and returns its returning value. Parameters: Name Type Argument Default Description includingPlaying boolean &lt;optional&gt; false Used as the \"includingPlaying\" parameter when calling the CB_AudioFileCache#playAndStopAll method internally. delayBeforeStop number &lt;optional&gt; 100 Used as the \"delayBeforeStop\" parameter when calling the CB_AudioFileCache#playAndStopAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1117 Returns: Returns the number of CB_AudioFile objects whose CB_AudioFile#play method did not return the value of \"-1\" (this does not mean necessarily that they could be played successfully). Type integer playSprite(spriteId [, loop] [, volume] [, allowedRecursiveDelay] [, allowedRecursiveDelaySkipping] [, onPlayStart] [, onStop]) → {integer|null} Plays a sprite by its ID. If the sprite is found, uses the CB_AudioFileSprites#play method internally and returns its returning value. Parameters: Name Type Argument Default Description spriteId string The identifier for the sprite. Used as the \"spriteId\" parameter when calling the CB_AudioFileSprites#play method internally. loop boolean &lt;optional&gt; CB_AudioFile#loop Used as the \"loop\" parameter when calling the CB_AudioFileSprites#play method internally. volume number &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Used as the \"volume\" parameter when calling the CB_AudioFileSprites#play method internally. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT Used as the \"allowedRecursiveDelay\" parameter when calling the CB_AudioFileSprites#play method internally. allowedRecursiveDelaySkipping boolean &lt;optional&gt; stopAt-startAt Used as the \"allowedRecursiveDelaySkipping\" parameter when calling the CB_AudioFileSprites#play method internally. onPlayStart function &lt;optional&gt; Used as the \"onPlayStart\" parameter when calling the CB_AudioFileSprites#play method internally. onStop function &lt;optional&gt; Used as the \"onStop\" parameter when calling the CB_AudioFileSprites#play method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 712 Returns: Returns null if the sprite was not found. Otherwise, returns the sound instance ID used if there was one free or null otherwise. To get a sound instance returned does not mean necessarily that the sound started playing so it is necessary to use a callback function as the \"onPlayStart\" parameter for checking this. The sound instance created (if any), will be cancelled automatically once the sound is stopped. Type integer | null purge(desiredNumber [, setAsMinimumAudioFiles] [, includePlaying] [, stopSounds] [, statuses]) → {integer} Tries to purge the audio file cache until it reaches a desired number of CB_AudioFile objects internally (set in the CB_AudioFileCache#audioFiles property), by removing and destroying some of the current CB_AudioFile objects. For performance purposes. Uses the CB_AudioFileCache#purge method internally and returns its returning value. Parameters: Name Type Argument Default Description desiredNumber integer Used as the \"desiredNumber\" parameter when calling the CB_AudioFileCache#purge method internally. setAsMinimumAudioFiles boolean &lt;optional&gt; false Used as the \"setAsMinimumAudioFiles\" parameter when calling the CB_AudioFileCache#purge method internally. includePlaying boolean &lt;optional&gt; false Used as the \"includePlaying\" parameter when calling the CB_AudioFileCache#purge method internally. stopSounds boolean &lt;optional&gt; false Used as the \"stopSounds\" parameter when calling the CB_AudioFileCache#purge method internally. statuses array &lt;optional&gt; Array(CB_AudioFile.LOADING, CB_AudioFile.UNCHECKED, CB_AudioFile.CHECKING, CB_AudioFile.LOADED) Used as the \"statuses\" parameter when calling the CB_AudioFileCache#purge method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 887 Returns: Returns the number of CB_AudioFile objects removed. Type integer removeAudioFile(audioObjectOrId [, reload] [, checkManually]) → {boolean|CB_AudioFile|null} If found, takes a given CB_AudioFile object off the CB_AudioFileCache#audioFiles property (and reloads it if we want to). NOTE: It does neither destroy nor remove the CB_AudioFile object so it can be used for other purposes (and if a CB_AudioFile object is given, it will be tried to be reused by the CB_AudioFileCache#createAudioFile method internally if it is called). Uses the CB_AudioFileCache#removeAudioFile method internally and returns its returning value. Internal usage only recommended. Parameters: Name Type Argument Default Description audioObjectOrId CB_AudioFile | string Used as the \"audioObjectOrId\" parameter when calling the CB_AudioFileCache#removeAudioFile method internally. reload boolean &lt;optional&gt; false Used as the \"reload\" parameter when calling the CB_AudioFileCache#removeAudioFile method internally. checkManually boolean &lt;optional&gt; false Used as the \"checkManually\" parameter when calling the CB_AudioFileCache#removeAudioFile method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 871 Returns: Returns null if the given \"audioObjectOrId\" parameter is not a valid CB_AudioFile object or its CB_AudioFile#id property is not set or when the \"audioObjectOrId\" parameter is an empty string. Returns a CB_AudioFile object, the given one through the \"audioObjectOrId\" parameter of the first one removed (it should be the first and unique one removed as the ID must be unique), if the CB_AudioFileCache#createAudioFile method is called internally (it will reuse this CB_AudioFile object). Otherwise, returns true if all goes well. Type boolean | CB_AudioFile | null removeSprite(spriteId) → {boolean} Removes a sprite by its ID. Parameters: Name Type Description spriteId string The identifier for the sprite. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 395 Returns: Returns true if the sprite has been deleted or false otherwise. Type boolean removeSprites() Removes all the sprites by clearing the CB_AudioFileSprites#sprites property. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 293 removeSpritesAll() Alias for CB_AudioFileSprites#removeSprites. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 284 See: CB_AudioFileSprites#removeSprites resumeAll( [loop] [, allowedRecursiveDelay] [, allowedRecursiveDelaySkipping] [, onPlayStart] [, onStop] [, audioFiles] [, spriteId]) → {array} Resumes all the existing CB_AudioFile objects or the desired ones (if provided), which are paused (and not stopped). Can be focused on just one sprite identifier if desired. Uses the CB_AudioFileCache#resumeAll method internally and returns its returning value. Internal usage only recommended. To resume a sprite, better use the CB_AudioFileSprites#resumeSprite method instead. Parameters: Name Type Argument Default Description loop boolean &lt;optional&gt; CB_AudioFile#loop Used as the \"loop\" parameter when calling the CB_AudioFileCache#resumeAll method internally. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT Used as the \"allowedRecursiveDelay\" parameter when calling the CB_AudioFileCache#resumeAll method internally. allowedRecursiveDelaySkipping boolean &lt;optional&gt; CB_AudioFile#lastStopAt-CB_AudioFile#lastStartAt Used as the \"allowedRecursiveDelaySkipping\" parameter when calling the CB_AudioFileCache#resumeAll method internally. onPlayStart function &lt;optional&gt; Used as the \"onPlayStart\" parameter when calling the CB_AudioFileCache#resumeAll method internally. onStop function &lt;optional&gt; Used as the \"onStop\" parameter when calling the CB_AudioFileCache#resumeAll method internally. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileCache#resumeAll method internally. spriteId string &lt;optional&gt; '_WITHOUT_SPRITE_ASSOCIATED' The identifier for the sprite. Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1148 Returns: Returns null if a sprite identifier was given but it could not be found. Otherwise, returns a numeric array containing all the return values of each internal call to the CB_AudioFileCache#play method. Type array resumeSprite(spriteId [, loop] [, allowedRecursiveDelay] [, allowedRecursiveDelaySkipping] [, onPlayStart] [, onStop]) → {array} Resumes all the CB_AudioFile objects that belong to the sound instances (created by the CB_AudioFileSprites#play or the CB_AudioFileSprites#playSprite methods) used by a given sprite identifier. Uses the CB_AudioFileSprites#resumeAll method internally and returns its returning value. Parameters: Name Type Argument Default Description spriteId string Used as the \"spriteId\" parameter when calling the CB_AudioFileSprites#resumeAll method internally. loop boolean &lt;optional&gt; CB_AudioFile#loop Used as the \"loop\" parameter when calling the CB_AudioFileSprites#resumeAll method internally. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT Used as the \"allowedRecursiveDelay\" parameter when calling the CB_AudioFileSprites#resumeAll method internally. allowedRecursiveDelaySkipping boolean &lt;optional&gt; stopAt-startAt Used as the \"allowedRecursiveDelaySkipping\" parameter when calling the CB_AudioFileSprites#resumeAll method internally. onPlayStart function &lt;optional&gt; Used as the \"onPlayStart\" parameter when calling the CB_AudioFileSprites#resumeAll method internally. onStop function &lt;optional&gt; Used as the \"onStop\" parameter when calling the CB_AudioFileSprites#resumeAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 756 Returns: Returns null if the sprite identifier given could not be found. Otherwise, returns a numeric array containing all the return values of each internal call to the CB_AudioFileCache#play method (called through CB_AudioFileSprites#resumeAll). Type array setAudioAPIAll(preferredAPIs [, callbackOk] [, callbackError] [, mandatory] [, forceReload] [, audioFiles]) → {integer} Tries to change the audio API for all the existing CB_AudioFile objects or the desired ones (if provided). This method is not allowed to be called if a previous call to it did not finish yet. The function defined in the \"callbackError\" parameter, if any, will be called immediately if the method was previously called and it is still running currently. Uses the CB_AudioFileCache#setAudioAPIAll method internally and returns its returning value. Parameters: Name Type Argument Default Description preferredAPIs array | string Used as the \"preferredAPIs\" parameter when calling the CB_AudioFileCache#setAudioAPIAll method internally. callbackOk CB_AudioFileCache.setAudioAPIAll_CALLBACK_OK &lt;optional&gt; Used as the \"callbackOk\" parameter when calling the CB_AudioFileCache#setAudioAPIAll method internally. callbackError CB_AudioFileCache.setAudioAPIAll_CALLBACK_ERROR &lt;optional&gt; Used as the \"callbackError\" parameter when calling the CB_AudioFileCache#setAudioAPIAll method internally. mandatory boolean &lt;optional&gt; false Used as the \"mandatory\" parameter when calling the CB_AudioFileCache#setAudioAPIAll method internally. forceReload string &lt;optional&gt; false Used as the \"forceReload\" parameter when calling the CB_AudioFileCache#setAudioAPIAll method internally. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileCache#setAudioAPIAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1222 Returns: Returns the number of calls to the CB_AudioFile#setAudioAPI method that were performed (which should be the same number as the CB_AudioFile objects in the \"audioFiles\" parameter). Type integer setAudioAPISprite(spriteId, preferredAPIs [, callbackOk] [, callbackError] [, mandatory] [, forceReload]) → {integer} Tries to change the desired audio API of the CB_AudioFile objects that belong to the sound instances (created by the CB_AudioFileSprites#play or the CB_AudioFileSprites#playSprite methods) used by a given sprite identifier. Uses the CB_AudioFileSprites#setAudioAPIAll method internally and returns its returning value. Parameters: Name Type Argument Default Description spriteId string The identifier for the sprite. preferredAPIs array Used as the \"preferredAPIs\" parameter when calling the CB_AudioFileSprites#setAudioAPIAll method internally. callbackOk CB_AudioFileCache.setAudioAPIAll_CALLBACK_OK &lt;optional&gt; Used as the \"callbackOk\" parameter when calling the CB_AudioFileSprites#setAudioAPIAll method internally. callbackError CB_AudioFileCache.setAudioAPIAll_CALLBACK_ERROR &lt;optional&gt; Used as the \"callbackError\" parameter when calling the CB_AudioFileSprites#setAudioAPIAll method internally. mandatory boolean &lt;optional&gt; false Used as the \"mandatory\" parameter when calling the CB_AudioFileSprites#setAudioAPIAll method internally. forceReload string &lt;optional&gt; false Used as the \"forceReload\" parameter when calling the CB_AudioFileSprites#setAudioAPIAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 814 Returns: Returns the number of calls to the CB_AudioFile#setAudioAPI method that were performed internally. Type integer setStartAtSprite(spriteId, startAt) → {boolean} Sets when a sprite begins (stored in its \"startAt\" property), by sprite identifier. Parameters: Name Type Description spriteId string The identifier for the sprite. startAt number The time (in milliseconds) of the audio file where the audio sprite starts. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 352 Returns: Returns true if the sprite has been modified or false otherwise. Type boolean setStopAtSprite(spriteId, stopAt) → {boolean} Sets when a sprite ends (stored in its \"stopAt\" property), by sprite identifier. Parameters: Name Type Description spriteId string The identifier for the sprite. stopAt number The time (in milliseconds) of the audio file where the audio sprite ends. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 374 Returns: Returns true if the sprite has been modified or false otherwise. Type boolean setVolumeAll( [volume] [, forceSetVolumeProperty] [, onSetVolume] [, audioFiles]) → {integer} Sets the same volume for all the existing CB_AudioFile objects or the desired ones (if provided). Uses the CB_AudioFileCache#setVolumeAll method internally and returns its returning value. Parameters: Name Type Argument Default Description volume number &lt;optional&gt; CB_Speaker.getVolume() | CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Used as the \"volume\" parameter when calling the CB_AudioFileCache#setVolumeAll method internally. forceSetVolumeProperty boolean &lt;optional&gt; false Used as the \"forceSetVolumeProperty\" parameter when calling the CB_AudioFileCache#setVolumeAll method internally. onSetVolume function &lt;optional&gt; Used as the \"onSetVolume\" parameter when calling the CB_AudioFileCache#setVolumeAll method internally. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileCache#setVolumeAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1205 Returns: Returns the number of calls to the CB_AudioFile#setVolume method that were performed (which should be the same number as the CB_AudioFile objects in the \"audioFiles\" parameter). Type integer setVolumeSprite(spriteId [, volume] [, forceSetVolumeProperty] [, onSetVolume]) → {integer} Sets the same desired volume to all the CB_AudioFile objects that belong to the sound instances (created by the CB_AudioFileSprites#play or the CB_AudioFileSprites#playSprite methods) used by a given sprite identifier. Uses the CB_AudioFileSprites#setVolumeAll method internally and returns its returning value. Parameters: Name Type Argument Default Description spriteId string The identifier for the sprite. volume number &lt;optional&gt; CB_Speaker.getVolume() | CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Used as the \"volume\" parameter when calling the CB_AudioFileSprites#setVolumeAll method internally. forceSetVolumeProperty boolean &lt;optional&gt; false Used as the \"forceSetVolumeProperty\" parameter when calling the CB_AudioFileSprites#setVolumeAll method internally. onSetVolume function &lt;optional&gt; Used as the \"onSetVolume\" parameter when calling the CB_AudioFileSprites#setVolumeAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 797 Returns: Returns the number of calls to the CB_AudioFile#setVolume method that were performed internally. Type integer stopAll( [audioFiles]) → {integer} Tries to stops all the existing CB_AudioFile objects or the desired ones (if provided), which are being played, by calling their CB_AudioFile#stop method internally. Uses the CB_AudioFileCache#stopAll method internally and returns its returning value. Parameters: Name Type Argument Default Description audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileCache#stopAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1104 Returns: Returns the number of calls to the CB_AudioFile#stop method that were performed (which should be the same number as the CB_AudioFile objects in the \"audioFiles\" parameter). Type integer stopSprite(spriteId) → {integer} Stops all the CB_AudioFile objects that belong to the sound instances (created by the CB_AudioFileSprites#play or the CB_AudioFileSprites#playSprite methods) which are playing used by a given sprite identifier. Uses the CB_AudioFileSprites#stopAll method internally and returns its returning value. Parameters: Name Type Description spriteId string The identifier for the sprite. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 726 Returns: Returns the number of calls to the CB_AudioFile#stop method that were performed internally. Type integer unmuteAll( [onUnmute] [, audioFiles]) → {integer} Unmutes all the existing CB_AudioFile objects or the desired ones (if provided). Uses the CB_AudioFileCache#unmuteAll method internally and returns its returning value. Parameters: Name Type Argument Default Description onUnmute function &lt;optional&gt; Used as the \"onUnmute\" parameter when calling the CB_AudioFileCache#unmuteAll method internally. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileCache#unmuteAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 1190 Returns: Returns the number of calls to the CB_AudioFile#unmute method that were performed (which should be the same number as the CB_AudioFile objects in the \"audioFiles\" parameter). Type integer unmuteSprite(spriteId [, onUnmute]) → {integer} Unmutes all the CB_AudioFile objects that belong to the sound instances (created by the CB_AudioFileSprites#play or the CB_AudioFileSprites#playSprite methods) used by a given sprite identifier. Uses the CB_AudioFileSprites#unmuteAll method internally and returns its returning value. Parameters: Name Type Argument Description spriteId string The identifier for the sprite. onUnmute function &lt;optional&gt; Used internally as the \"onUnmute\" parameter to call the CB_AudioFileSprites#unmuteAll method. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 782 Returns: Returns the number of calls to the CB_AudioFile#unmute method that were performed internally. Type integer Type Definitions DATA_OBJECT Object with the desired data and options for the audio sprites. It is almost identical to the CB_AudioFileCache.DATA_OBJECT but adding a \"sprites\" property. Type: Object Properties: Name Type Argument Default Description URIs CB_AudioFileCache.URIS_OBJECT Object whose property names audio formats and their value is an array of strings with the URIs (audio file paths or audio data URIs) of the audio files in order of preference. The best audio format for the current client will be tried to be calculated and it will use the first working URI (audio file path or data URI). The more audio formats and URIs provided the better, as it will help to maximize the compatibility with as many clients as possible (as some audio APIs and client just support some formats, or use absolute paths instead of relative ones, etc.). Even with different formats, all provided URIs should belong to the same audio (this means same sound or same music, with same length, etc.). NOTE: Only some clients with some audio APIs will support data URIs. If a valid value is given, this will be added to the CB_AudioFileCache#URIs property. sprites CB_AudioFileSprites.SPRITES_OBJECT &lt;optional&gt; Object with the desired sprites. It will be used as the first parameter to call the CB_AudioFileSprites#insertSprites method internally. It will be added (after being processed) to the CB_AudioFileCache#sprites property. id string &lt;optional&gt; \"\" Desired identifier for the audio file sprites object. Internal usage only recommended. If a valid value is given, this will be added to the CB_AudioFileSprites#id property as well as to the CB_AudioFileCache#id property of the internally-created CB_AudioFileCache object. preferredAPIs array &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS Array of strings with the preferred audio API or audio APIs, in order of preference. Possible audio APIs are \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). It will try to calculate and use the best one for the current client. If a valid value is given, this will be added to the CB_AudioFileCache#preferredAPIs property. preferredFormats array &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_FORMATS Array of strings with the preferred audio format or audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"'), in order of preference. It will try to calculate and use the best one for the current client. If a valid value is given, this will be added to the CB_AudioFileCache#preferredFormats property. minimumAudioFiles integer &lt;optional&gt; CB_AudioFileCache.minimumAudioFiles_DEFAULT Minimum CB_AudioFile objects to create internally. It must be an integer being 1 the minimum. If a valid value is given, this will be added to the CB_AudioFileCache#minimumAudioFiles property. maximumAudioFiles integer &lt;optional&gt; CB_AudioFileCache.maximumAudioFiles_DEFAULT Maximum CB_AudioFile objects that are to be created internally. If it is set to null, there will not be a maximum (it will be unlimited). If an integer is provided, it must be the same number or greater than the value set in the CB_AudioFileCache#minimumAudioFiles property (also provided by the \"minimumAudioFiles\" of this object), allowing 1 minimum. If a valid value is given, this will be added to the CB_AudioFileCache#maximumAudioFiles property. minimumAudioFilesFree integer &lt;optional&gt; parseInt(CB_AudioFileCache#minimumAudioFiles * 0.25 + 0.5) New CB_AudioFile objects will be created internally when the number of free CB_AudioFile objects reaches this limit. If provided, it must be an integer being 0 (zero) the minimum. It will end using a 25% of the CB_AudioFileCache#minimumAudioFiles by default, rounded to ceil, allowing 0 (zero) minimum. If a valid value is given, this will be added to the CB_AudioFileCache#minimumAudioFilesFree property. newAudioFilesWhenNeeded integer &lt;optional&gt; Math.min(parseInt(CB_AudioFileCache#minimumAudioFiles * 0.1 + 0.5), 1) Number of new CB_AudioFile objects to create internally when the minimum limit of free CB_AudioFile objects (CB_AudioFileCache#minimumAudioFilesFree) is reached. If provided, it must be an integer being 0 (zero) the minimum. It will end using a 10% of the CB_AudioFileCache#minimumAudioFiles by default, rounded to ceil, allowing 1 minimum. If a valid value is given, this will be added to the CB_AudioFileCache#newAudioFilesWhenNeeded property. retries integer &lt;optional&gt; CB_AudioFileCache.retries_DEFAULT Number of retries to try to load a CB_AudioFile object internally before trying to load the next possible one internally (if any). It must be an integer being 0 the minimum. If a valid value is given, this will be added to the CB_AudioFileCache#retries property. checkManually boolean &lt;optional&gt; CB_AudioFileCache.checkManually_DEFAULT Tells whether the CB_AudioFile objects must be checked automatically or not (manually) by default. If a valid value is given, this will be added to the CB_AudioFileCache#checkManually property. checkManuallyOnNeededCreated boolean &lt;optional&gt; CB_AudioFileCache.checkManuallyOnNeededCreated_DEFAULT Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when creates a new CB_AudioFile object needed. If a valid value is given, this will be added to the CB_AudioFileCache#checkManuallyOnNeededCreated property. checkManuallyOnPlayingFailed boolean &lt;optional&gt; CB_AudioFileCache.checkManuallyOnPlayingFailed_DEFAULT Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when playing one has failed and tries to reload it. If a valid value is given, this will be added to the CB_AudioFileCache#checkManuallyOnPlayingFailed property. checkManuallyOnCheckingFailed boolean &lt;optional&gt; CB_AudioFileCache.checkManuallyOnCheckingFailed_DEFAULT Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when checking one has failed and tries to reload it. If a valid value is given, this will be added to the CB_AudioFileCache#checkManuallyOnCheckingFailed property. onLoad function &lt;optional&gt; Desired function to be called once the cache has been loaded. The first and unique parameter will be an integer with the CB_AudioFile objects that still need to be checked, if any, being \"this\" the current CB_AudioFileCache object. If a valid value is given, this will be added to the CB_AudioFileCache#onLoad property. onError function &lt;optional&gt; Desired function to be called when any kind of error happens. The first and unique parameter will be a string with the error description (if it could be determined), being \"this\" the current CB_AudioFileCache object. If a valid value is given, this will be added to the CB_AudioFileCache#onError property. disableAutoLoad boolean &lt;optional&gt; false If set to true, it will not create automatically the CB_AudioFile objects by calling the CB_AudioFileCache#createAudioFiles method internally. Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 34 getAudioFilesUsed_OBJECT Object returned by the CB_AudioFileSprites#getAudioFilesUsed method. Each property names will be the sprites identifiers except the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated (if we wanted to include them). Type: Object Properties: Name Type Description spriteId CB_AudioFile Each property name will be a sprite identifier (it can be \"_WITHOUT_SPRITE_ASSOCIATED\" for sound instances without a sprite associated, if we wanted to include them). The value will be a numeric array with the CB_AudioFile objects used. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 531 SPRITE_OBJECT An object representing an audio sprite which can contain, optionally, the \"startAt\" and \"stopAt\" properties with a numeric value (representing when the audio sprite starts and when it stops, respectively). If not set, the default \"startAt\" value will be 0 (zero) and the default \"stopAt\" value will be null (which means it will not stop until the end of the audio is reached unless it is paused or stopped before). The \"fake\" property should never be used as it is used internally to distinguish real sprites from fake ones (generated and returned by the CB_AudioFileSprites#getSprite method when a requested sprite is not found). Type: Object Properties: Name Type Argument Default Description startAt number &lt;optional&gt; 0 The time (in milliseconds) of the audio file where the audio sprite starts. If not provided, it will use the value of 0 (zero) which means that it will start from the beginning. stopAt number &lt;optional&gt; CB_AudioFile_API.WAAPI#getDuration() | CB_AudioFile_API.SM2#getDuration() | CB_AudioFile_API.ACMP#getDuration() | CB_AudioFile_API.AAPI#getDuration() The time (in milliseconds) of the audio file where the audio sprite stops. If not provided (not recommended), it will use the whole duration of the file (which means until it reaches its end). NOTE: Due to some possible problems between clients with different audio APIs calculating the duration of an audio file, it is recommended to always set the \"stopAt\" property even when we want it to stop at the end of the audio. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 8 Example { startAt: 10, stopAt: 20 } SPRITES_OBJECT Object whose property names the identifiers of each sprite (a case-sensitive string) and their value is a CB_AudioFileSprites.SPRITE_OBJECT object. Type: Object Properties: Name Type Description spriteInformation CB_AudioFileSprites.SPRITE_OBJECT Being the name of each property the identifier of a sprite (a string which cannot be \"_WITHOUT_SPRITE_ASSOCIATED\" as it is a reserved name), the value will always be a CB_AudioFileSprites.SPRITE_OBJECT object. Source: CrossBase/audiovisual/audio/CB_AudioFileSprites.js, line 18 Example { \"whole_audio\" : {}, \"first_sprite\" : { stopAt: 10 }, \"second_sprite\" : { startAt: 10, stopAt: 20 }, \"third_sprite\" : { startAt: 20 }, ... } × Search results Close "},"CB_AudioFileSpritesPool.html":{"id":"CB_AudioFileSpritesPool.html","title":"Class: CB_AudioFileSpritesPool","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Class: CB_AudioFileSpritesPool CB_AudioFileSpritesPool Class to manage many audio sprites stored in different groups, each with one CB_AudioFileSprites object (used internally). new CB_AudioFileSpritesPool( [dataObject]) → {CB_AudioFileSpritesPool} The constructor is recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Parameters: Name Type Argument Description dataObject CB_AudioFileSpritesPool.DATA_OBJECT &lt;optional&gt; Object with the desired data and options for the groups of audio sprites. Each group will have a CB_AudioFileSprites object. Some of its properties (\"preferredAPIs\", \"preferredFormats\", \"minimumAudioFiles\", \"maximumAudioFiles\", \"minimumAudioFilesFree\", \"newAudioFilesWhenNeeded\", \"retries\", \"checkManually\", \"checkManuallyOnNeededCreated\", \"checkManuallyOnPlayingFailed\", \"checkManuallyOnCheckingFailed\" and \"disableAutoLoad\") will be used as the default value to create internally the CB_AudioFileSprites objects when the value is not given in the CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT object (set as the value of the CB_AudioFileSpritesPool.DATA_OBJECT#spritesGroups property). Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 55 To Do: Do not allow to create one object with an \"id\" which has already been used (unless the value is undefined, null...). Method getCopy and static method filterProperties (similar to the ones from CB_GraphicSprites and CB_GraphicSpritesScene). Returns: Returns a new CB_AudioFileSpritesPool object. Type CB_AudioFileSpritesPool Members &lt;static, constant&gt; ABORTED :integer Status value for an audio file sprites pool which has been aborted. This will happen when the audio file sprites pool has been destroyed with the CB_AudioFileSpritesPool#destructor method. Can be used to compare the value returned by the CB_AudioFileSpritesPool#getStatus method. Recommended for internal usage only. Type: integer Default Value: 6 Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 277 &lt;static, constant&gt; CHECKING :integer Status value for an audio file sprites pool which is being checked currently. Can be used to compare the value returned by the CB_AudioFileSpritesPool#getStatus method. Recommended for internal usage only. Type: integer Default Value: 3 Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 253 &lt;static, constant&gt; FAILED :integer Status value for an audio file sprites pool which failed to be loaded or failed for any other reason. Can be used to compare the value returned by the CB_AudioFileSpritesPool#getStatus method. Recommended for internal usage only. Type: integer Default Value: 5 Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 269 &lt;static, constant&gt; LOADED :integer Status value for an audio file sprites pool which has been loaded. Can be used to compare the value returned by the CB_AudioFileSpritesPool#getStatus method. Recommended for internal usage only. Type: integer Default Value: 4 Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 261 &lt;static, constant&gt; LOADING :integer Status value for an audio file sprites pool which is loading. Can be used to compare the value returned by the CB_AudioFileSpritesPool#getStatus method. Recommended for internal usage only. Type: integer Default Value: 1 Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 237 &lt;static, constant&gt; UNCHECKED :integer Status value for an audio file sprites pool which has not been checked yet. Can be used to compare the value returned by the CB_AudioFileSpritesPool#getStatus method. Recommended for internal usage only. Type: integer Default Value: 2 Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 245 &lt;static, constant&gt; UNLOADED :integer Status value for audio file sprites pool which is unloaded. Can be used to compare the value returned by the CB_AudioFileSpritesPool#getStatus method. Recommended for internal usage only. Type: integer Default Value: 0 Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 229 &lt;readonly&gt; audioFileSprites :Object Stores the internally-created CB_AudioFileSprites objects, using the name of each property as their group ID and the value being the CB_AudioFileSprites object itself. Internal usage only recommended. Type: Object Default Value: {} Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 204 &lt;readonly&gt; checkManually :boolean Tells whether the CB_AudioFile objects must be checked automatically or not (manually). Internal usage only recommended. Type: boolean Default Value: CB_AudioFileCache.checkManually_DEFAULT Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 141 &lt;readonly&gt; checkManuallyOnCheckingFailed :boolean Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when checking one has failed and tries to reload it. Internal usage only recommended. Type: boolean Default Value: CB_AudioFileCache.checkManuallyOnCheckingFailed_DEFAULT Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 168 &lt;readonly&gt; checkManuallyOnNeededCreated :boolean Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when creates a new CB_AudioFile object needed. Internal usage only recommended. Type: boolean Default Value: CB_AudioFileCache.checkManuallyOnNeededCreated_DEFAULT Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 150 &lt;readonly&gt; checkManuallyOnPlayingFailed :boolean Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when playing one has failed and tries to reload it. Internal usage only recommended. Type: boolean Default Value: CB_AudioFileCache.checkManuallyOnPlayingFailed_DEFAULT Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 159 &lt;readonly&gt; disableAutoLoad :boolean If set to true, it will not create automatically the CB_AudioFile objects by calling the CB_AudioFileCache#createAudioFiles method internally. Internal usage only recommended. Type: boolean Default Value: false Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 177 &lt;readonly&gt; id :string Stores the identifier for the audio file sprites pool object. Type: string Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 68 &lt;readonly&gt; maximumAudioFiles :integer|null Maximum CB_AudioFile objects that are to be created internally for each CB_AudioFileSprites object. If it is set to null, there will not be a maximum (it will be unlimited). If an integer is provided, it must be the same number or greater than the value set in the CB_AudioFileCache#minimumAudioFiles property, allowing 1 minimum. Internal usage only recommended. Type: integer | null Default Value: CB_AudioFileCache.maximumAudioFiles_DEFAULT Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 104 &lt;readonly&gt; minimumAudioFiles :integer Minimum CB_AudioFile objects to create internally for each CB_AudioFileSprites object. It must be an integer being 1 the minimum. Internal usage only recommended. Type: integer Default Value: CB_AudioFileCache.minimumAudioFiles_DEFAULT Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 95 &lt;readonly&gt; minimumAudioFilesFree :integer New CB_AudioFile objects will be created internally for each CB_AudioFileSprites object when the number of free CB_AudioFile objects reaches this limit. It must be an integer being 0 (zero) the minimum. Internal usage only recommended. Type: integer Default Value: parseInt(CB_AudioFileCache#minimumAudioFiles * 0.25 + 0.5) Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 113 &lt;readonly&gt; newAudioFilesWhenNeeded :integer Number of new CB_AudioFile objects to create internally for each CB_AudioFileSprites object when the minimum limit of free CB_AudioFile objects (CB_AudioFileCache#minimumAudioFilesFree) is reached. It must be an integer being 0 (zero) the minimum. Internal usage only recommended. Type: integer Default Value: Math.min(parseInt(CB_AudioFileCache#minimumAudioFiles * 0.1 + 0.5), 1) Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 122 &lt;readonly&gt; onError :function Desired function to be called when any kind of error happens. The first and unique parameter will be a string with the error description (if it could be determined), being \"this\" the current CB_AudioFileSpritesPool object. If a function is set, it will always be called through the CB_AudioFileSpritesPool#errorFunction method whenever the \"onError\" event of an internally-created CB_AudioFileSprites object is fired. Type: function Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 195 &lt;readonly&gt; onLoad :function Desired function to be called once the pool has been loaded. The first and unique parameter will be an integer with the CB_AudioFile objects that still need to be checked, if any, being \"this\" the current CB_AudioFileSpritesPool object. Type: function Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 186 &lt;readonly&gt; preferredAPIs :array Stores an array of strings with the preferred audio API or audio APIs, in order of preference. Possible audio APIs are \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). Internal usage only recommended. Type: array Default Value: CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 77 &lt;readonly&gt; preferredFormats :array Stores an array of strings with the preferred audio format or audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"'), in order of preference. Internal usage only recommended. Type: array Default Value: CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_FORMATS Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 86 &lt;readonly&gt; retries :integer Number of retries to try to load a CB_AudioFile object internally before trying to load the next possible one internally (if any). It must be an integer being 0 the minimum. Internal usage only recommended. Type: integer Default Value: CB_AudioFileCache.retries_DEFAULT Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 131 Methods cancelSoundInstance(soundInstanceId [, cancel] [, affectWithObjectAssociated]) → {boolean} Cancels (to prevent it starts playing) or enables a sound instance (created by the CB_AudioFileCache#play method), by its identifier. Uses the CB_AudioFileSprites#cancelSoundInstance method internally. Parameters: Name Type Argument Default Description soundInstanceId integer Used as the \"soundInstanceId\" parameter when calling the CB_AudioFileSprites#cancelSoundInstance method internally. cancel boolean &lt;optional&gt; false Used as the \"cancel\" parameter when calling the CB_AudioFileSprites#cancelSoundInstance method internally. affectWithObjectAssociated boolean &lt;optional&gt; false Used as the \"affectWithObjectAssociated\" parameter when calling the CB_AudioFileSprites#cancelSoundInstance method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 901 Returns: Returns true if the sound instance has been modified or false otherwise. Type boolean cancelSoundInstances( [cancel] [, affectWithObjectAssociated]) → {integer} Cancels (to prevent they start playing) or enables all sound instances (created by the CB_AudioFileCache#play method). Uses the CB_AudioFileSprites#cancelSoundInstances method internally. Parameters: Name Type Argument Default Description cancel boolean &lt;optional&gt; false Used as the \"cancel\" parameter when calling the CB_AudioFileSprites#cancelSoundInstances method internally. affectWithObjectAssociated boolean &lt;optional&gt; false Used as the \"affectWithObjectAssociated\" parameter when calling the CB_AudioFileSprites#cancelSoundInstances method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 882 Returns: Returns the number of sound instances modified. Type integer checkPlayingAll( [callbackOk] [, callbackError] [, ignoreQueue] [, ignoreStatus]) → {integer} Checks whether each CB_AudioFile object whose CB_AudioFile#getStatus method returns the \"unchecked\" value (which belongs to the value of the CB_AudioFile#UNCHECKED property) can be played or not. After checking, if the audio can be played, the status of the CB_AudioFile object will get the value of CB_AudioFile.LOADED. Otherwise, if it cannot be played, the status of the CB_AudioFile object will get the value of CB_AudioFile.FAILED. If a CB_AudioFile object cannot be played and it is determined necessary, it will try to reload it internally (by calling the CB_AudioFileCache#removeAudioFile method). It will call the CB_AudioFileCache#clearAudioFiles method internally after finishing each call to the CB_AudioFileSprites#checkPlayingAll method. Uses the CB_AudioFileSprites#checkPlayingAll method internally. Recommended to be called through a user-driven event (as onClick, onTouch, etc.). Parameters: Name Type Argument Default Description callbackOk CB_AudioFileSpritesPool.checkPlayingAll_CALLBACK_OK &lt;optional&gt; A function which will be called if all the CB_AudioFile objects whose CB_AudioFile#getStatus method returned the \"unchecked\" value (which belongs to the value of the CB_AudioFile#UNCHECKED property) could finally be checked successfully and all can be played, being \"this\" the CB_AudioFileSpritesPool object itself. callbackError CB_AudioFileSpritesPool.checkPlayingAll_CALLBACK_ERROR &lt;optional&gt; A function which will be called if not all the CB_AudioFile objects whose CB_AudioFile#getStatus method returned the \"unchecked\" value (which belongs to the value of the CB_AudioFile#UNCHECKED property) could finally be checked successfully and any cannot be played, being \"this\" the CB_AudioFileSpritesPool object itself. This function will be called immediately if the method was previously called and it is still running currently. ignoreQueue boolean &lt;optional&gt; false Used as the \"ignoreQueue\" parameter when calling the CB_AudioFileSprites#checkPlayingAll method internally. ignoreStatus boolean &lt;optional&gt; false If it is set to false and the sprites pool object is loaded (the CB_AudioFileSpritesPool#getStatus method returns the value set in the CB_AudioFileSpritesPool.LOADED property), it will exit returning an error. Otherwise, if it is set to true, it will ignore the current sprites pool object status. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1039 Returns: Returns the number of CB_AudioFile objects whose status belonged to the \"unchecked\" value (the value of the CB_AudioFile#UNCHECKED property) before the execution of this method. It will return 0 (zero) if the method is tried to be executed while there is another previous call of it still running. It will also return 0 (zero) if the status of audio sprites pool is neither loaded (the CB_AudioFileSpritesPool#getStatus method does not returns the value set in the CB_AudioFileSpritesPool.LOADED property) nor unchecked (the CB_AudioFileSpritesPool#status method does not return the value set in the CB_AudioFileSpritesPool.UNCHECKED property). Type integer clearAudioFiles( [avoidCallingCheckCacheLoaded]) → {array} Cleans the arrays of the CB_AudioFile objects (taking off the undefined or null ones) which is in the CB_AudioFileCache#audioFiles property used by each CB_AudioFileSprites object, just keeping the valid ones and clearing (destroying and removing) the others. For performance purposes. Uses the CB_AudioFileSprites#clearAudioFiles method internally. Internal usage only recommended. Parameters: Name Type Argument Default Description avoidCallingCheckCacheLoaded boolean &lt;optional&gt; false Used as the \"avoidCallingCheckCacheLoaded\" parameter when calling the CB_AudioFileSprites#clearAudioFiles method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 810 Returns: Returns an object whose each property name is the sprites group ID and each value is the returning value of calling internally the CB_AudioFileSprites#clearAudioFiles method. Type array clearSoundInstances( [clearWithObjectAssociated]) → {integer} Clears the sound instances (created by the CB_AudioFileCache#play method) which have been cancelled. Uses the CB_AudioFileSprites#clearSoundInstances method internally. Parameters: Name Type Argument Default Description clearWithObjectAssociated boolean &lt;optional&gt; false Used as the \"clearWithObjectAssociated\" parameter when calling the CB_AudioFileSprites#clearSoundInstances method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 864 Returns: Returns the number of cleared sound instances. Type integer destroyAll( [stopSounds]) → {integer} Destroys all the CB_AudioFile objects and frees memory, by calling CB_AudioFile#destructor(stopSounds, false, true). Uses the CB_AudioFileSprites#destroyAll method internally. Parameters: Name Type Argument Default Description stopSounds boolean &lt;optional&gt; false Used as the \"stopSounds\" parameter when calling the CB_AudioFileSprites#destroyAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 993 Returns: Returns the number of CB_AudioFile objects whose CB_AudioFile#destructor has been called. Type integer destructor( [stopSounds] [, preventAbortedStatus]) Destroys the audio file sprites pool object (removing all sprites, etc.), including the internal audio file sprites objects, and frees memory. By default, unless the \"preventAbortedStatus\" is set to true, sets the current status of all the CB_AudioFileCache objects as ABORTED (CB_AudioFileCache.ABORTED value). Internally, calls the CB_AudioFileSprites#destructor method of all the internally-created CB_AudioFileSprites objects. Parameters: Name Type Argument Default Description stopSounds boolean &lt;optional&gt; false Used as the \"stopSounds\" parameter when calling internally the CB_AudioFileSprites#destructor method of all the internally-created CB_AudioFileSprites objects. preventAbortedStatus boolean &lt;optional&gt; false If set to true (not recommended), it will not assign the status of \"ABORTED\" (it will not set the CB_AudioFileSpritesPool#_aborted property to true}. Used as the \"preventAbortedStatus\" parameter when calling internally the CB_AudioFileSprites#destructor method of all the internally-created CB_AudioFileSprites objects. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 326 errorFunction( [message] [, ignorePreviousExecution]) → {boolean} Calls the error function which should be set in the CB_AudioFileSprites#onError property (if any), being \"this\" the CB_AudioFileSpritesPool object itself. Internal usage only recommended. Parameters: Name Type Argument Default Description message string &lt;optional&gt; The message describing the error that will be sent to the set CB_AudioFileSprites#onError function (if any) as the first and unique parameter. ignorePreviousExecution boolean &lt;optional&gt; false If it is set to false, the function set in the CB_AudioFileSprites#onError property (if any) will only be called if it was not executed previously. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1698 Returns: Returns true if the CB_AudioFileSprites#onError function could be called or false otherwise. Type boolean executeAll() Alias for CB_AudioFileSpritesPool#executeFunctionAll. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 930 See: CB_AudioFileSpritesPool#executeFunctionAll executeAllSprites() Alias for CB_AudioFileSpritesPool#executeFunctionAllSprites. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 759 See: CB_AudioFileSpritesPool#executeFunctionAllSprites executeAllSubSprites() Alias for CB_AudioFileSpritesPool#executeFunctionAllSubSprites. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1253 See: CB_AudioFileSpritesPool#executeFunctionAllSubSprites executeFunctionAll(functionEach [, delayBetweenEach] [, audioFiles] [, returnArrayOfSetTimeoutsArray] [, delayBetweenEachAffectsFirst] [, functionFinish]) → {integer|array} Performs a desired action, using the provided function, on all the existing CB_AudioFile objects or on the desired ones (if provided). Uses the CB_AudioFileSprites#executeFunctionAll method internally. Parameters: Name Type Argument Default Description functionEach CB_Arrays.CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK Used as the \"functionEach\" parameter when calling the CB_AudioFileSprites#executeFunctionAll method internally. delayBetweenEach number | CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK &lt;optional&gt; 0 Used as the \"delayBetweenEach\" parameter when calling the CB_AudioFileSprites#executeFunctionAll method internally. Note that each call to the CB_AudioFileSprites#executeFunctionAll method will be performed sequentially one after the other, without adding a delay. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileSprites#executeFunctionAll method internally. returnArrayOfSetTimeoutsArray boolean &lt;optional&gt; false If it is set to false, it will return the number of calls to the \"functionEach\" function that were performed. Otherwise, if it is set to true, it will return a numeric array and each value (which will belong to each sprites group) will be another numeric array with a CB_AudioFileCache.executeFunctionAll_OBJECT object for each CB_AudioFile of that sprites group. delayBetweenEachAffectsFirst boolean &lt;optional&gt; false Used as the \"delayBetweenEachAffectsFirst\" parameter when calling the CB_AudioFileSprites#executeFunctionAll method internally. Note that each call to the CB_AudioFileSprites#executeFunctionAll method will be performed sequentially one after the other, without adding a delay. functionFinish CB_AudioFileSpritesPool.executeFunctionAll_ON_FINISH_CALLBACK &lt;optional&gt; Function that will be called for when it has finished looping all the items. The first parameter will be the array containing all the items which were looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 952 To Do: Think about consider executing only one by one (now it will loop CB_AudioFile objects from different sprites groups simultaneously). Returns: If the \"returnArrayOfSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed. Otherwise, if the \"returnArrayOfSetTimeoutsArray\" is set to true, it will return a numeric array and each value will be another numeric array with a CB_AudioFileCache.executeFunctionAll_OBJECT object for each CB_AudioFile given. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the setTimeout function. Type integer | array executeFunctionAllSprites(functionEach [, delayBetweenEach] [, includeWithoutSpriteAssociated] [, avoidCancelled] [, delayBetweenEachAffectsFirst] [, functionFinish]) → {integer} Executes a desired function for all the CB_AudioFile objects used by all the sound instances currently created of each sprite group. It calls the CB_AudioFileSprites#executeFunctionAllSprites method internally. Parameters: Name Type Argument Default Description functionEach CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK Used as the \"functionEach\" parameter when calling the CB_AudioFileSprites#executeFunctionAllSprites method internally. delayBetweenEach number | CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK &lt;optional&gt; 0 Used as the \"delayBetweenEach\" parameter when calling the CB_AudioFileSprites#executeFunctionAllSprites method internally. Note that each call to the CB_AudioFileSprites#executeFunctionAllSprites method will be performed sequentially one after the other, without adding a delay. includeWithoutSpriteAssociated boolean &lt;optional&gt; false Used as the \"includeWithoutSpriteAssociated\" parameter when calling the CB_AudioFileSprites#executeFunctionAllSprites method internally. avoidCancelled boolean &lt;optional&gt; false Used as the \"avoidCancelled\" parameter when calling the CB_AudioFileSprites#executeFunctionAllSprites method internally. delayBetweenEachAffectsFirst boolean &lt;optional&gt; false Used as the \"delayBetweenEachAffectsFirst\" parameter when calling the CB_AudioFileSprites#executeFunctionAllSprites method internally. Internal usage only recommended. Note that each call to the CB_AudioFileSprites#executeFunctionAllSprites method will be performed sequentially one after the other, without adding a delay. functionFinish CB_AudioFileSpritesPool.executeFunctionAll_ON_FINISH_CALLBACK &lt;optional&gt; Function that will be called for when it has finished looping all the items. The first parameter will be the array containing all the items which were looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 782 To Do: Think about implementing a \"returnSetTimeoutsArray\" or similar (as in CB_AudioFileSprites#executeFunctionAllSprites). Think about consider executing only one by one (now it will loop CB_AudioFile objects from different sprites groups simultaneously). Returns: It will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the CB_AudioFile objects used by the sound instances that belong to the sprites of each sprites group). Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the setTimeout function. Type integer forEach() Alias for CB_AudioFileSpritesPool#executeFunctionAll. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 935 See: CB_AudioFileSpritesPool#executeFunctionAll forEachSprite() Alias for CB_AudioFileSpritesPool#executeFunctionAllSprites. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 764 See: CB_AudioFileSpritesPool#executeFunctionAllSprites forEachSubSprite() Alias for CB_AudioFileSpritesPool#executeFunctionAllSubSprites. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1258 See: CB_AudioFileSpritesPool#executeFunctionAllSubSprites getAudioFileBySoundInstanceId(soundInstanceId [, avoidCancelled]) → {CB_AudioFile|null} Gets the CB_AudioFile object associated to a given sound instance ID (created by the CB_AudioFileCache#play method), if any, or null otherwise. Uses the CB_AudioFileSprites#getAudioFileBySoundInstanceId method internally. Parameters: Name Type Argument Default Description soundInstanceId integer Used as the \"soundInstanceId\" parameter when calling the CB_AudioFileSprites#getAudioFileBySoundInstanceId method internally. avoidCancelled boolean &lt;optional&gt; false Used as the \"avoidCancelled\" parameter when calling the CB_AudioFileSprites#getAudioFileBySoundInstanceId method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 918 Returns: Returns the CB_AudioFile object associated to a given sound instance ID, if any, or null otherwise. Type CB_AudioFile | null getAudioFiles( [copy] [, oneDimension]) → {Object|array} Gets an object with arrays or a one-dimension array with all the CB_AudioFile objects. Uses the CB_AudioFileSprites#getAudioFiles method internally. Parameters: Name Type Argument Default Description copy boolean &lt;optional&gt; false Used as the \"copy\" parameter when calling the CB_AudioFileSprites#getAudioFiles method internally. oneDimension boolean &lt;optional&gt; false If it is set to true, the method will return an array with all the CB_AudioFile objects. Otherwise, if it is set to false, the method will return an object whose property names will be the ID of each sprites group and their value will be an array with all the CB_AudioFile objects that belong to that sprites group. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1483 Returns: If the \"oneDimension\" parameter is set to true, returns an array with all the CB_AudioFile objects. Otherwise, if the \"oneDimension\" parameter is set to false, it will return an object whose property names will be the ID of each sprites group and their value will be an array with all the CB_AudioFile objects that belong to that sprites group. Type Object | array getAudioFilesBusy( [oneDimension]) → {Object|array} Gets an object with arrays or a one-dimension array with the busy CB_AudioFile objects (the objects which are not available and ready to use). Uses the CB_AudioFileSprites#getAudioFilesBusy method internally. Parameters: Name Type Argument Default Description oneDimension boolean &lt;optional&gt; false If it is set to true, the method will return an array with the busy CB_AudioFile objects. Otherwise, if it is set to false, the method will return an object whose property names will be the ID of each sprites group and their value will be an array with the busy CB_AudioFile objects that belong to that sprites group. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1559 Returns: If the \"oneDimension\" parameter is set to true, returns an array with the busy CB_AudioFile objects. Otherwise, if the \"oneDimension\" parameter is set to false, it will return an object whose property names will be the ID of each sprites group and their value will be an array with the busy CB_AudioFile objects that belong to that sprites group. Type Object | array getAudioFilesFree( [oneDimension]) → {Object|array} Gets an object with arrays or a one-dimension array with the free CB_AudioFile objects (the objects which are available and ready to use). Uses the CB_AudioFileSprites#getAudioFilesFree method internally. Parameters: Name Type Argument Default Description oneDimension boolean &lt;optional&gt; false If it is set to true, the method will return an array with the free CB_AudioFile objects. Otherwise, if it is set to false, the method will return an object whose property names will be the ID of each sprites group and their value will be an array with the free CB_AudioFile objects that belong to that sprites group. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1521 Returns: If the \"oneDimension\" parameter is set to true, returns an array with the free CB_AudioFile objects. Otherwise, if the \"oneDimension\" parameter is set to false, it will return an object whose property names will be the ID of each sprites group and their value will be an array with the free CB_AudioFile objects that belong to that sprites group. Type Object | array getAudioFilesFreeNumber() → {integer} Tells the current number of free CB_AudioFile objects (the number of objects which are available and ready to use). Uses the CB_AudioFileSprites#getAudioFilesFreeNumber method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1465 Returns: Returns the current number of free CB_AudioFile objects (the number of objects which are available and ready to use). Type integer getAudioFilesNumber( [real]) → {integer} Tells the number of CB_AudioFile objects created. Uses the CB_AudioFileSprites#getAudioFilesNumber method internally. Parameters: Name Type Argument Default Description real boolean &lt;optional&gt; false Used as the \"real\" parameter when calling the CB_AudioFileSprites#getAudioFilesNumber method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1597 Returns: Returns the number of CB_AudioFile objects created. Type integer getAudioFilesUsed( [oneDimension] [, includeWithoutSpriteAssociated] [, avoidCancelled]) → {CB_AudioFileSprites.getAudioFilesUsed_OBJECT|array} Returns the CB_AudioFile objects used by all the sounds instances of all the sprites groups. Parameters: Name Type Argument Default Description oneDimension boolean &lt;optional&gt; false If set to false, it will return an object whose property names will be the ID of each sprites group and their value will be the an object whose property names are the sprite identifiers (including the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated, if the \"includeWithoutSpriteAssociated\" is set to true) and their value will be a numeric array with the CB_AudioFile objects used. Otherwise, if set to true, it will return a numeric array with the CB_AudioFile objects used (if the \"includeWithoutSpriteAssociated\" parameter is set to true, it will also contain the CB_AudioFile objects whose sound instance ID is not associated to any sprite). includeWithoutSpriteAssociated boolean &lt;optional&gt; false If set to true, it will also return the CB_AudioFile objects whose sound instance ID is not associated to any sprite. Used as the \"includeWithoutSpriteAssociated\" parameter when calling the CB_AudioFileSprites#getAudioFilesUsed method internally. avoidCancelled boolean &lt;optional&gt; false If set to true, it will not return the CB_AudioFile objects whose sound instance has been cancelled. Used as the \"avoidCancelled\" parameter when calling the CB_AudioFileSprites#getAudioFilesUsed method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 718 Returns: Returns the CB_AudioFile objects used by all the sounds instances of all the sprites groups. If the \"oneDimension\" parameter is set to false, it will return a CB_AudioFileSpritesPool.getAudioFilesUsed_OBJECT object whose property names will be the ID of each sprites group and their value will be a CB_AudioFileSprites.getAudioFilesUsed_OBJECT object whose property names are the sprite identifiers (including the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated, if the \"includeWithoutSpriteAssociated\" is set to true) and their value will be a numeric array with the CB_AudioFile objects used. Otherwise, if the \"oneDimension\" parameter set to true, it will return a numeric array with the CB_AudioFile objects used (if the \"includeWithoutSpriteAssociated\" parameter is set to true, it will also contain the CB_AudioFile objects whose sound instance ID is not associated to any sprite). Type CB_AudioFileSprites.getAudioFilesUsed_OBJECT | array getProgress( [countLoadedObjects] [, alsoUncheckedAndCheckingObjects]) → {number} Returns a number representing the percentage of the loading progress for the audio sprites pool object (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Uses the CB_AudioFileSprites#getProgress method internally. Parameters: Name Type Argument Default Description countLoadedObjects boolean &lt;optional&gt; false Used as the \"countLoadedObjects\" parameter when calling the CB_AudioFileSprites#getProgress method internally. alsoUncheckedAndCheckingObjects boolean &lt;optional&gt; false Used as the \"alsoUncheckedAndCheckingObjects\" parameter when calling the CB_AudioFileSprites#getProgress method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1615 Returns: Returns a number representing the percentage of the loading progress for the audio sprites pool object (from 0 to 100, being 100 a complete loading progress). The way to calculate it internally may differ from one audio API to another and it is not totally reliable. Type number getSoundInstancesId( [oneDimension] [, includeWithoutSpriteAssociated]) → {Object|array} Returns the sound instances (their ID) used (stored in the CB_AudioFileSprites#spriteSoundInstances property of each CB_AudioFileSprites object). Parameters: Name Type Argument Default Description oneDimension boolean &lt;optional&gt; false If set to false, it will return an object whose property names will be the ID of each sprites group and their value will be the CB_AudioFileSprites#spriteSoundInstances property of each CB_AudioFileSprites object (which includes the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated) which belongs to that sprites group. Otherwise, if it is set to true, it will return a numeric array whose values are the sound instance IDs. includeWithoutSpriteAssociated boolean &lt;optional&gt; false If set to true, it will also return the sound instance identifiers which are not associated to any sprite. Used as the \"includeWithoutSpriteAssociated\" parameter when calling the CB_AudioFileSprites#getSoundInstancesId method internally. Only used when the \"oneDimension\" parameter is set to true. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 671 Returns: Returns the sound instances (their ID) used (stored in the CB_AudioFileSprites#spriteSoundInstances property). If the \"oneDimension\" parameter is set to false, it will return an object whose property names will be the ID of each sprites group and their value will be the CB_AudioFileSprites#spriteSoundInstances property of each CB_AudioFileSprites object (which includes the \"_WITHOUT_SPRITE_ASSOCIATED\" property for sound instances without a sprite associated) which belongs to that sprites group. If the \"oneDimension\" parameter is set to true, it will return a numeric array whose values are the sound instance identifiers (if the \"includeWithoutSpriteAssociated\" parameter it set to true, it will also include the sound instances which are not associated to any sprite). Type Object | array getSprites( [includeWithoutSpriteAssociated] [, orderBySpritesGroup]) → {CB_AudioFileSprites.SPRITES_OBJECT|Object} Returns an object with the sprites (and includes \"_WITHOUT_SPRITE_ASSOCIATED\" if we want to). Internally, uses the CB_AudioFileSprites#getSprites method. Parameters: Name Type Argument Default Description includeWithoutSpriteAssociated boolean &lt;optional&gt; false If set to true, the returning object will also contain a property called \"_WITHOUT_SPRITE_ASSOCIATED\" whose value will be an empty object (unless the \"orderBySpritesGroup\" parameter is set to true and the property existed before in the object stored in the CB_AudioFileSprites#sprites property and had a value which is not an empty object). If set to false and the \"orderBySpritesGroup\" parameter is also set to false, the returning object will not contain the \"_WITHOUT_SPRITE_ASSOCIATED\" property. If set to false and the \"orderBySpritesGroup\" parameter is set to true, the returning object will not contain the \"_WITHOUT_SPRITE_ASSOCIATED\" property unless the property existed before in the object stored in the CB_AudioFileSprites#sprites property. orderBySpritesGroup boolean &lt;optional&gt; false If set to false, it will return a CB_AudioFileSprites.SPRITES_OBJECT object whose properties will be the ID of each sprite (each sprite ID should be unique) and their value will be a CB_AudioFileSprites.SPRITE_OBJECT object. If set to true, it will return an object whose properties will be the ID of each sprites group and the value will be a CB_AudioFileSprites.SPRITES_OBJECT object which will include its sprites. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 634 Returns: If the \"orderBySpritesGroup\" is set to false, it will return a CB_AudioFileSprites.SPRITES_OBJECT object whose properties will be the ID of each sprite (each sprite ID should be unique) and their value will be a CB_AudioFileSprites.SPRITE_OBJECT object. If the \"orderBySpritesGroup\" is set to true, it will return an object whose properties will be the ID of each sprites group and the value will be a CB_AudioFileSprites.SPRITES_OBJECT object which will include its sprites. Type CB_AudioFileSprites.SPRITES_OBJECT | Object getSpritesGroup(spritesGroupId [, withoutChecking]) → {CB_AudioFileSprites|undefined|*|null} Returns a sprites group (the CB_AudioFileSprites object) by its ID. Parameters: Name Type Argument Default Description spritesGroupId string The identifier for the sprites group. withoutChecking boolean &lt;optional&gt; false If set to true and the sprites group cannot be found, the method will return undefined (or whatever is stored by the given ID) instead of null. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 605 Returns: Returns null if the \"withoutChecking\" parameter is set to true and the sprites group cannot be found. Otherwise, it will return what is stored internally by the given ID which can be a CB_AudioFileSprites object if found or undefined (or whatever is stored by the given ID) if not found. Type CB_AudioFileSprites | undefined | * | null getSpritesGroups() → {Object} Returns an object with the sprites groups (all the internally-created CB_AudioFileSprites objects), being the name of each property their group ID and the value being the CB_AudioFileSprites object itself. Internally, it just returns the CB_AudioFileSpritesPool#audioFileSprites property. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 621 Returns: Returns an object with the sprites groups (all the internally-created CB_AudioFileSprites objects), being the name of each property their group ID and the value being the CB_AudioFileSprites object itself. Internally, it just returns the CB_AudioFileSpritesPool#audioFileSprites property. Type Object getStatus() → {number} Gets the current status of the audio file sprites pool object. Uses the CB_AudioFileSprites#getStatus method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1634 Returns: Returns the current status of the audio file sprites pool object. It is a number, affected by the returning value of the CB_AudioFileSprites#getStatus method of each CB_AudioFileSprites object used internally, which should match the value of the CB_AudioFileCache.UNLOADED (still unloaded), CB_AudioFileCache.LOADING (loading), CB_AudioFileCache.UNCHECKED (not checked by calling the CB_AudioFileCache#checkPlayingAll method yet), CB_AudioFileCache.CHECKING (being checked by the CB_AudioFileCache#checkPlayingAll method), CB_AudioFileCache.LOADED (loaded), CB_AudioFileCache.FAILED (failed loading or failed to play or by any other reason) or CB_AudioFileCache.ABORTED (aborted because it was destroyed with the \"destructor\" method) property. Type number getStatusString() → {string} Gets the current status of the audio file sprites pool object, as a string. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1682 Returns: Returns the current status of the audio file sprites pool object, as a string. Possible return values are \"UNLOADED\", \"LOADING\", \"UNCHECKED\", \"CHECKING\", \"LOADED\", \"FAILED\", \"ABORTED\" or \"UNKNOWN (UNKNOWN_STATUS)\" (where \"UNKNOWN_STATUS\" will be a returning value from the CB_AudioFileSpritesPool#getStatus method not recognized as any possible status). Type string insertSpritesGroup(spritesGroupId [, dataObject] [, avoidCheckingLoaded]) → {boolean} Inserts the given sprites group to the audio file sprites pool object. Parameters: Name Type Argument Default Description spritesGroupId string The identifier for the sprites group. dataObject CB_AudioFileSprites.DATA_OBJECT &lt;optional&gt; Object with the data of the sprites group. Optional but recommended. avoidCheckingLoaded boolean &lt;optional&gt; false If set to true, it will not check whether all sprites groups has been loaded after inserting the desired one. This is done internally by the CB_AudioFileSpritesPool#_checkSpritesGroupsLoaded method which will fire the CB_AudioFileSpritesPool#onLoad function (if any). Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 498 Returns: Returns true if the sprites group has been inserted or false otherwise. Type boolean insertSpritesGroups(sprites) → {integer} Inserts the given sprites groups. Parameters: Name Type Description sprites CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT Object with the desired sprites groups. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 470 Returns: Returns the number of sprites groups inserted. Type integer isAudioFileFree(id) → {boolean} Tells whether a desired CB_AudioFile object is free (it is in the CB_AudioFileCache#audioFilesFree property of any CB_AudioFileSprites object) or not, by its identifier. A free CB_AudioFile object is an object which is not being used and it is available to be used. Uses the CB_AudioFileSprites#isAudioFileFree method internally. Parameters: Name Type Description id string Used as the \"id\" parameter when calling the CB_AudioFileSprites#isAudioFileFree method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 848 Returns: Returns whether a desired CB_AudioFile object is free (it is in the CB_AudioFileCache#audioFilesFree property of any CB_AudioFileSprites object) or not, by its identifier. A free CB_AudioFile object is an object which is not being used and it is available to be used. Type boolean isPlaying() → {boolean} Tells whether any of the CB_AudioFile objects is playing or not. Uses the CB_AudioFileSprites#isPlaying method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1450 Returns: Returns whether any of the CB_AudioFile objects is playing or not. Type boolean load(dataObject) → {CB_AudioFileSpritesPool|null} Loads the audio file sprites pool with the desired data given. This method is called by the constructor automatically. Recommended to be called through a user-driven event (as onClick, onTouch, etc.), as some clients may need this at least the first time in order to be able to play the audio. Parameters: Name Type Description dataObject CB_AudioFileSpritesPool.DATA_OBJECT Object with the desired data and options for the audio file sprites. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 365 Returns: If a \"dataObject\" is given, it returns the current CB_AudioFileSpritesPool object. Otherwise, it returns null. Type CB_AudioFileSpritesPool | null muteAll( [onMute] [, audioFiles]) → {integer} Mutes all the existing CB_AudioFile objects or the desired ones (if provided). Uses the CB_AudioFileSprites#muteAll method internally. Parameters: Name Type Argument Default Description onMute function &lt;optional&gt; Used as the \"onMute\" parameter when calling the CB_AudioFileSprites#muteAll method internally. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileSprites#muteAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1239 Returns: Returns the number of calls to the CB_AudioFile#mute method that were performed. Type integer pauseAll( [onPause] [, audioFiles]) → {integer} Tries to pause all the existing CB_AudioFile objects or the desired ones (if provided), which are being played, by calling their CB_AudioFile#pause method internally. Uses the CB_AudioFileSprites#pauseAll method internally. Parameters: Name Type Argument Default Description onPause function &lt;optional&gt; Used as the \"onPause\" parameter when calling the CB_AudioFileSprites#pauseAll method internally. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileSprites#pauseAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1198 Returns: Returns the number of calls to the CB_AudioFile#pause method that were performed. Type integer playAll( [startAt] [, stopAt] [, loop] [, volume] [, avoidDelayedPlay] [, allowedRecursiveDelay] [, onPlayStart] [, onStop] [, includingPlaying]) → {integer} Tries to play all the CB_AudioFile objects by calling their CB_AudioFile#play method internally. If a CB_AudioFile object cannot be played and it is determined necessary, it will try to reload it internally (by calling the CB_AudioFileCache#removeAudioFile method). Uses the CB_AudioFileSprites#playAll method internally. Parameters: Name Type Argument Default Description startAt number &lt;optional&gt; 0 | CB_AudioFile_API.WAAPI#lastStartAt | CB_AudioFile_API.SM2#lastStartAt | CB_AudioFile_API.ACMP#lastStartAt | CB_AudioFile_API.AAPI#lastStartAt | stopAt Used as the \"startAt\" parameter when calling the CB_AudioFileSprites#playAll method internally. stopAt number &lt;optional&gt; CB_AudioFile_API.WAAPI#getDuration() | CB_AudioFile_API.SM2#getDuration() | CB_AudioFile_API.ACMP#getDuration() | CB_AudioFile_API.AAPI#getDuration() Used as the \"stopAt\" parameter when calling the CB_AudioFileSprites#playAll method internally. loop boolean &lt;optional&gt; CB_AudioFile#loop Used as the \"loop\" parameter when calling the CB_AudioFileSprites#playAll method internally. volume number &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT ? CB_Speaker.getVolume() : CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Used as the \"volume\" parameter when calling the CB_AudioFileSprites#playAll method internally. avoidDelayedPlay boolean &lt;optional&gt; false Used as the \"avoidDelayedPlay\" parameter when calling the CB_AudioFileSprites#playAll method internally. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT Used as the \"allowedRecursiveDelay\" parameter when calling the CB_AudioFileSprites#playAll method internally. onPlayStart function &lt;optional&gt; Used as the \"onPlayStart\" parameter when calling the CB_AudioFileSprites#playAll method internally. onStop function &lt;optional&gt; Used as the \"onStop\" parameter when calling the CB_AudioFileSprites#playAll method internally. includingPlaying boolean &lt;optional&gt; false Used as the \"includingPlaying\" parameter when calling the CB_AudioFileSprites#playAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1145 Returns: Returns the number of CB_AudioFile objects whose CB_AudioFile#play method did not return the value of \"-1\" (this does not mean necessarily that they could be played successfully). Type integer playAndStopAll( [includingPlaying] [, delayBeforeStop]) → {integer} Plays silently and stops all CB_AudioFile objects after a desired time. It can be useful for some clients which need the CB_AudioFile#play method to be called through a user-driven event (as onClick, onTouch, etc.). Internally, it calls CB_AudioFileCache#playAll(0, null, false, 0, true, null, null, null, includingPlaying) and, after a desired delay, calls the CB_AudioFileCache#stopAll method. Uses the CB_AudioFileSprites#playAndStopAll method internally. Parameters: Name Type Argument Default Description includingPlaying boolean &lt;optional&gt; false Used as the \"includingPlaying\" parameter when calling the CB_AudioFileSprites#playAndStopAll method internally. delayBeforeStop number &lt;optional&gt; 100 Used as the \"delayBeforeStop\" parameter when calling the CB_AudioFileSprites#playAndStopAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1180 Returns: Returns the number of CB_AudioFile objects whose CB_AudioFile#play method did not return the value of \"-1\" (this does not mean necessarily that they could be played successfully). Type integer purge(desiredNumber [, setAsMinimumAudioFiles] [, includePlaying] [, stopSounds] [, statuses]) → {integer} Tries to purge the audio file cache of each CB_AudioFileSprites object until it reaches a desired number of CB_AudioFile objects internally (set in the CB_AudioFileCache#audioFiles property), by removing and destroying some of the current CB_AudioFile objects. Note that the desired number is for each CB_AudioFileSprites object and not a global number. For performance purposes. Uses the CB_AudioFileSprites#purge method internally. Parameters: Name Type Argument Default Description desiredNumber integer Used as the \"desiredNumber\" parameter when calling the CB_AudioFileSprites#purge method internally. Note that the desired number is for each CB_AudioFileSprites object and not a global number. setAsMinimumAudioFiles boolean &lt;optional&gt; false Used as the \"setAsMinimumAudioFiles\" parameter when calling the CB_AudioFileSprites#purge method internally. includePlaying boolean &lt;optional&gt; false Used as the \"includePlaying\" parameter when calling the CB_AudioFileSprites#purge method internally. stopSounds boolean &lt;optional&gt; false Used as the \"stopSounds\" parameter when calling the CB_AudioFileSprites#purge method internally. statuses array &lt;optional&gt; Array(CB_AudioFile.LOADING, CB_AudioFile.UNCHECKED, CB_AudioFile.CHECKING, CB_AudioFile.LOADED) Used as the \"statuses\" parameter when calling the CB_AudioFileSprites#purge method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 831 Returns: Returns the number of CB_AudioFile objects removed. Type integer removeSpritesGroup(spritesGroupId [, destroy] [, stopSounds] [, preventAbortedStatus]) → {boolean} Removes a sprites group by its ID. Parameters: Name Type Argument Default Description spritesGroupId string The identifier for the sprites group. destroy boolean &lt;optional&gt; false If set to true, it will call the CB_AudioFileSprites#destructor method of the CB_AudioFileSprites object which belongs to the desired sprites group. stopSounds boolean &lt;optional&gt; false If the \"destroy\" parameter is set to false, this parameter will be ignored. Used as the \"stopSound\" parameter when calling internally the CB_AudioFileSprites#destructor method of the CB_AudioFileSprites object which belongs to the desired sprites group. preventAbortedStatus boolean &lt;optional&gt; false If the \"destroy\" parameter is set to false, this parameter will be ignored. Used as the \"preventAbortedStatus\" parameter when calling internally the CB_AudioFileSprites#destructor method of the CB_AudioFileSprites object which belongs to the desired sprites group. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 573 Returns: Returns true if the sprites group has been deleted or false otherwise. Type boolean removeSpritesGroups() Removes all the sprites groups (CB_AudioFileSprites objects) by clearing the CB_AudioFileSpritesPool#audioFileSprites property. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 458 resumeAll( [loop] [, allowedRecursiveDelay] [, allowedRecursiveDelaySkipping] [, onPlayStart] [, onStop] [, audioFiles] [, spriteId]) → {Object} Resumes all the existing CB_AudioFile objects or the desired ones (if provided), which are paused (and not stopped). Can be focused on just one sprite ID if desired. Uses the CB_AudioFileSprites#resumeAll method internally. Internal usage only recommended. To resume a sprite, better use the CB_AudioFileSprites#resumeSprite method instead. Parameters: Name Type Argument Default Description loop boolean &lt;optional&gt; CB_AudioFile#loop Used as the \"loop\" parameter when calling the CB_AudioFileSprites#resumeAll method internally. allowedRecursiveDelay boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT Used as the \"allowedRecursiveDelay\" parameter when calling the CB_AudioFileSprites#resumeAll method internally. allowedRecursiveDelaySkipping boolean &lt;optional&gt; stopAt-startAt Used as the \"allowedRecursiveDelaySkipping\" parameter when calling the CB_AudioFileSprites#resumeAll method internally. onPlayStart function &lt;optional&gt; Used as the \"onPlayStart\" parameter when calling the CB_AudioFileSprites#resumeAll method internally. onStop function &lt;optional&gt; Used as the \"onStop\" parameter when calling the CB_AudioFileSprites#resumeAll method internally. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileSprites#resumeAll method internally. spriteId string &lt;optional&gt; '_WITHOUT_SPRITE_ASSOCIATED' Used as the \"spriteId\" when calling the CB_AudioFileSprites#resumeAll method internally. Internal usage only recommended. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1221 Returns: Returns an object whose property names will be the ID of each sprites group and their value will be the returning value of the internal call to the CB_AudioFileSprites#resumeAll method. Type Object setAudioAPIAll(preferredAPIs [, callbackOk] [, callbackError] [, mandatory] [, forceReload] [, audioFiles]) → {integer} Tries to change the audio API for all the existing CB_AudioFile objects or the desired ones (if provided). This method is not allowed to be called if a previous call to it did not finish yet. The function defined in the \"callbackError\" parameter, if any, will be called immediately if the method was previously called and it is still running currently. Uses the CB_AudioFileSprites#setAudioAPIAll method internally. Parameters: Name Type Argument Default Description preferredAPIs array | string Used as the \"preferredAPIs\" parameter when calling the CB_AudioFileSprites#setAudioAPIAll method internally. callbackOk CB_AudioFileSpritesPool.setAudioAPIAll_CALLBACK_OK &lt;optional&gt; Function that will be called when all the process was performed successfully, being \"this\" the CB_AudioFileSpritesPool object. callbackError CB_AudioFileSpritesPool.setAudioAPIAll_CALLBACK_ERROR &lt;optional&gt; Function that will be called when any error happened, being \"this\" the CB_AudioFileSpritesPool object. This function will be called immediately if the method was previously called and it is still running currently. mandatory boolean &lt;optional&gt; false Used as the \"mandatory\" parameter when calling the CB_AudioFileSprites#setAudioAPIAll method internally. forceReload string &lt;optional&gt; false Used as the \"forceReload\" parameter when calling the CB_AudioFileSprites#setAudioAPIAll method internally. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileSprites#setAudioAPIAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1330 Returns: Returns the number of calls to the CB_AudioFile#setAudioAPI method that were performed. Type integer setVolumeAll( [volume] [, forceSetVolumeProperty] [, onSetVolume] [, audioFiles]) → {integer} Sets the same volume for all the existing CB_AudioFile objects or the desired ones (if provided). Uses the CB_AudioFileSprites#setVolumeAll method internally. Parameters: Name Type Argument Default Description volume number &lt;optional&gt; CB_Speaker.getVolume() | CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME Used as the \"volume\" parameter when calling the CB_AudioFileSprites#setVolumeAll method internally. forceSetVolumeProperty boolean &lt;optional&gt; false Used as the \"forceSetVolumeProperty\" parameter when calling the CB_AudioFileSprites#setVolumeAll method internally. onSetVolume function &lt;optional&gt; Used as the \"onSetVolume\" parameter when calling the CB_AudioFileSprites#setVolumeAll method internally. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileSprites#setVolumeAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1277 Returns: Returns the number of calls to the CB_AudioFile#setVolume method that were performed internally. Type integer stopAll( [audioFiles]) → {integer} Tries to stops all the existing CB_AudioFile objects or the desired ones (if provided), which are being played, by calling their CB_AudioFile#stop method internally. Uses the CB_AudioFileSprites#stopAll method internally. Parameters: Name Type Argument Default Description audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileSprites#stopAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1162 Returns: Returns the number of calls to the CB_AudioFile#stop method that were performed. Type integer unmuteAll( [onUnmute] [, audioFiles]) → {integer} Unmutes all the existing CB_AudioFile objects or the desired ones (if provided). Uses the CB_AudioFileSprites#unmuteAll method internally. Parameters: Name Type Argument Default Description onUnmute function &lt;optional&gt; Used as the \"onUnmute\" parameter when calling the CB_AudioFileSprites#unmuteAll method internally. audioFiles array &lt;optional&gt; CB_AudioFileCache#audioFiles Used as the \"audioFiles\" parameter when calling the CB_AudioFileSprites#unmuteAll method internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1257 Returns: Returns the number of calls to the CB_AudioFile#unmute method that were performed. Type integer Type Definitions checkPlayingAll_CALLBACK_ERROR(errorsObject, performedActions, uncheckedObjects) Callback function used by the CB_AudioFileSpritesPool#checkPlayingAll method that will be called when not all was performed successfully. Parameters: Name Type Description errorsObject Object Object whose property names are the ID of each sprites group or \"GENERAL_ERROR\" if the error is not related to any sprites group and their value will be a CB_AudioFileSpritesPool.checkPlayingAll_CALLBACK_ERROR_OBJECT object. performedActions integer The number of CB_AudioFile objects that can be played). uncheckedObjects integer | undefined The number of CB_AudioFile objects that needed to be checked before calling this method (it will be undefined if it could not be determined). Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1012 checkPlayingAll_CALLBACK_ERROR_OBJECT An object with errors, used by the CB_AudioFileSpritesPool.checkPlayingAll_CALLBACK_ERROR callback (used by the CB_AudioFileSpritesPool#checkPlayingAll method). Type: Object Properties: Name Type Description error string A string describing the error (if it was possible to be determined). checked integer The number of CB_AudioFile objects that can be played. needed integer | undefined The number of CB_AudioFile objects that needed to be checked before calling this method (it will be undefined if it could not be determined). Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1021 checkPlayingAll_CALLBACK_OK(performedActions, uncheckedObjects) Callback function used by the CB_AudioFileSpritesPool#checkPlayingAll method that will be called when all the process was performed successfully. Parameters: Name Type Description performedActions integer The number of CB_AudioFile objects that can be played. uncheckedObjects integer The number of CB_AudioFile objects that needed to be checked before calling this method. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1004 DATA_OBJECT Object with the desired data and options for the audio sprites. It is almost identical to the CB_AudioFileSprites.DATA_OBJECT but adding a \"spritesGroups\" property. Type: Object Properties: Name Type Argument Default Description spritesGroups CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT &lt;optional&gt; Object with the desired sprites groups, containing the CB_AudioFileSprites.DATA_OBJECT objects which will be used to create the CB_AudioFileSprites objects internally. Each group will have a CB_AudioFileSprites object. It will be used as the first parameter to call the CB_AudioFileSpritesPool#insertSpritesGroups method internally. Some of the missing properties (\"preferredAPIs\", \"preferredFormats\", \"minimumAudioFiles\", \"maximumAudioFiles\", \"minimumAudioFilesFree\", \"newAudioFilesWhenNeeded\", \"retries\", \"checkManually\", \"checkManuallyOnNeededCreated\", \"checkManuallyOnPlayingFailed\", \"checkManuallyOnCheckingFailed\" and \"disableAutoLoad\") of the CB_AudioFileSprites.DATA_OBJECT objects given will use the value set on the other properties of this object (if any). id string &lt;optional&gt; \"\" Desired identifier for the object. If a valid value is given, this will be added to the CB_AudioFileSpritesPool#id property. preferredAPIs array &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_APIS Array of strings with the preferred audio API or audio APIs, in order of preference. Possible audio APIs are \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). It will try to calculate and use the best one for the current client. If a valid value is given, this will be added to the CB_AudioFileSpritesPool#preferredAPIs property. If the CB_AudioFileSprites.DATA_OBJECT object (defined in the CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT object set in the \"spritesGroups\") of a certain sprites group does not contain the \"preferredAPIs\" property, it will use the value of this property instead when creating its CB_AudioFileSprites object internally. preferredFormats array &lt;optional&gt; CB_Configuration.CrossBase.CB_AudioFileCache_PREFERRED_AUDIO_FORMATS Array of strings with the preferred audio format or audio formats (they can include just the format as 'audio/ogg' or also the codec as for example 'audio/ogg; codecs=\"vorbis\"'), in order of preference. It will try to calculate and use the best one for the current client. If a valid value is given, this will be added to the CB_AudioFileSpritesPool#preferredFormats property. If the CB_AudioFileSprites.DATA_OBJECT object (defined in the CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT object set in the \"spritesGroups\") of a certain sprites group does not contain the \"preferredFormats\" property, it will use the value of this property instead when creating its CB_AudioFileSprites object internally. minimumAudioFiles integer &lt;optional&gt; CB_AudioFileCache.minimumAudioFiles_DEFAULT Minimum CB_AudioFile objects to create internally. It must be an integer being 1 the minimum. If a valid value is given, this will be added to the CB_AudioFileSpritesPool#minimumAudioFiles property. If the CB_AudioFileSprites.DATA_OBJECT object (defined in the CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT object set in the \"spritesGroups\") of a certain sprites group does not contain the \"minimumAudioFiles\" property, it will use the value of this property instead when creating its CB_AudioFileSprites object internally. maximumAudioFiles integer &lt;optional&gt; CB_AudioFileCache.maximumAudioFiles_DEFAULT Maximum CB_AudioFile objects that are to be created internally. If it is set to null, there will not be a maximum (it will be unlimited). If an integer is provided, it must be the same number or greater than the value set in the CB_AudioFileCache#minimumAudioFiles property (also provided by the \"minimumAudioFiles\" of this object), allowing 1 minimum. If a valid value is given, this will be added to the CB_AudioFileSpritesPool#maximumAudioFiles property. If the CB_AudioFileSprites.DATA_OBJECT object (defined in the CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT object set in the \"spritesGroups\") of a certain sprites group does not contain the \"maximumAudioFiles\" property, it will use the value of this property instead when creating its CB_AudioFileSprites object internally. minimumAudioFilesFree integer &lt;optional&gt; parseInt(CB_AudioFileCache#minimumAudioFiles * 0.25 + 0.5) New CB_AudioFile objects will be created internally when the number of free CB_AudioFile objects reaches this limit. If provided, it must be an integer being 0 (zero) the minimum. It will end using a 25% of the CB_AudioFileSpritesPool#minimumAudioFiles by default, rounded to ceil, allowing 0 (zero) minimum. If a valid value is given, this will be added to the CB_AudioFileSpritesPool#minimumAudioFilesFree property. If the CB_AudioFileSprites.DATA_OBJECT object (defined in the CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT object set in the \"spritesGroups\") of a certain sprites group does not contain the \"minimumAudioFilesFree\" property, it will use the value of this property instead when creating its CB_AudioFileSprites object internally. newAudioFilesWhenNeeded integer &lt;optional&gt; Math.min(parseInt(CB_AudioFileCache#minimumAudioFiles * 0.1 + 0.5), 1) Number of new CB_AudioFile objects to create internally when the minimum limit of free CB_AudioFile objects (CB_AudioFileSpritesPool#minimumAudioFilesFree) is reached. If provided, it must be an integer being 0 (zero) the minimum. It will end using a 10% of the CB_AudioFileSpritesPool#minimumAudioFiles by default, rounded to ceil, allowing 1 minimum. If a valid value is given, this will be added to the CB_AudioFileSpritesPool#newAudioFilesWhenNeeded property. If the CB_AudioFileSprites.DATA_OBJECT object (defined in the CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT object set in the \"spritesGroups\") of a certain sprites group does not contain the \"newAudioFilesWhenNeeded\" property, it will use the value of this property instead when creating its CB_AudioFileSprites object internally. retries integer &lt;optional&gt; CB_AudioFileCache.retries_DEFAULT Number of retries to try to load a CB_AudioFile object internally before trying to load the next possible one internally (if any). It must be an integer being 0 the minimum. If a valid value is given, this will be added to the CB_AudioFileSpritesPool#retries property. If the CB_AudioFileSprites.DATA_OBJECT object (defined in the CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT object set in the \"spritesGroups\") of a certain sprites group does not contain the \"retries\" property, it will use the value of this property instead when creating its CB_AudioFileSprites object internally. checkManually boolean &lt;optional&gt; CB_AudioFileCache.checkManually_DEFAULT Tells whether the CB_AudioFile objects must be checked automatically or not (manually) by default. If a valid value is given, this will be added to the CB_AudioFileSpritesPool#checkManually property. If the CB_AudioFileSprites.DATA_OBJECT object (defined in the CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT object set in the \"spritesGroups\") of a certain sprites group does not contain the \"checkManually\" property, it will use the value of this property instead when creating its CB_AudioFileSprites object internally. checkManuallyOnNeededCreated boolean &lt;optional&gt; CB_AudioFileCache.checkManuallyOnNeededCreated_DEFAULT Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when creates a new CB_AudioFile object needed. If a valid value is given, this will be added to the CB_AudioFileSpritesPool#checkManuallyOnNeededCreated property. If the CB_AudioFileSprites.DATA_OBJECT object (defined in the CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT object set in the \"spritesGroups\") of a certain sprites group does not contain the \"checkManuallyOnNeededCreated\" property, it will use the value of this property instead when creating its CB_AudioFileSprites object internally. checkManuallyOnPlayingFailed boolean &lt;optional&gt; CB_AudioFileCache.checkManuallyOnPlayingFailed_DEFAULT Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when playing one has failed and tries to reload it. If a valid value is given, this will be added to the CB_AudioFileSpritesPool#checkManuallyOnPlayingFailed property. If the CB_AudioFileSprites.DATA_OBJECT object (defined in the CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT object set in the \"spritesGroups\") of a certain sprites group does not contain the \"checkManuallyOnPlayingFailed\" property, it will use the value of this property instead when creating its CB_AudioFileSprites object internally. checkManuallyOnCheckingFailed boolean &lt;optional&gt; CB_AudioFileCache.checkManuallyOnCheckingFailed_DEFAULT Tells whether the CB_AudioFile objects must be checked automatically or not (manually) when checking one has failed and tries to reload it. If a valid value is given, this will be added to the CB_AudioFileSpritesPool#checkManuallyOnCheckingFailed property. If the CB_AudioFileSprites.DATA_OBJECT object (defined in the CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT object set in the \"spritesGroups\") of a certain sprites group does not contain the \"checkManuallyOnCheckingFailed\" property, it will use the value of this property instead when creating its CB_AudioFileSprites object internally. onLoad function &lt;optional&gt; Desired function to be called once the pool has been loaded. The first and unique parameter will be an integer with the CB_AudioFile objects that still need to be checked, if any, being \"this\" the current CB_AudioFileSpritesPool object. If a valid value is given, this will be added to the CB_AudioFileSpritesPool#onLoad property. onError function &lt;optional&gt; Desired function to be called when any kind of error happens. The first and unique parameter will be a string with the error description (if it could be determined), being \"this\" the current CB_AudioFileSpritesPool object. If a valid value is given, this will be added to the CB_AudioFileSpritesPool#onError property. If a function is set, it will always be called through the CB_AudioFileSpritesPool#errorFunction method whenever the \"onError\" event of an internally-created CB_AudioFileSprites object is fired. disableAutoLoad boolean &lt;optional&gt; false If set to true, it will not create automatically the CB_AudioFile objects by calling the CB_AudioFileCache#createAudioFiles method internally. Internal usage only recommended. If the CB_AudioFileSprites.DATA_OBJECT object (defined in the CB_AudioFileSpritesPool.SPRITES_GROUPS_OBJECT object set in the \"spritesGroups\") of a certain sprites group does not contain the \"disableAutoLoad\" property, it will use the value of this property instead when creating its CB_AudioFileSprites object internally. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 23 executeFunctionAll_ON_FINISH_CALLBACK(array, itemsAffected, delayMaximum) Callback that is used when finishes all iterations after looping through the items. Being \"this\" an array with all the items. Parameters: Name Type Description array array An array with all the items which were being looped. itemsAffected integer The number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null). delayMaximum integer The maximum \"delay\" used. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 750 getAudioFilesUsed_OBJECT Object returned by the CB_AudioFileSpritesPool#getAudioFilesUsed method. Each property names will be the the ID of each sprites group and their value will be a CB_AudioFileSprites.getAudioFilesUsed_OBJECT object. Type: Object Properties: Name Type Description spriteId CB_AudioFileSpritesPool.getAudioFilesUsed_OBJECT Each property names will be the the ID of each sprites group and their value will be a CB_AudioFileSprites.getAudioFilesUsed_OBJECT object. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 703 setAudioAPIAll_CALLBACK_ERROR(errorsObject, errorsHappened, objectsChangedAPI, performedActions, actionsNeeded) Callback function used by the CB_AudioFileCache#setAudioAPIAll method that will be called when any error happened. Parameters: Name Type Description errorsObject Object Object whose property names are the ID of each sprites group or \"GENERAL_ERROR\" if the error is not related to any sprites group and their value will be a CB_AudioFileSpritesPool.setAudioAPIAll_CALLBACK_ERROR_OBJECT object each. errorsHappened integer The number of errors that happened, which could be greater than 1 if more than one internal call to the CB_AudioFile#setAudioAPI method failed. objectsChangedAPI integer The number of CB_AudioFile objects that actually changed its audio API. performedActions integer The number of CB_AudioFile objects that ended with a desired audio API, including those ones which were already using it. actionsNeeded integer | undefined The total number of CB_AudioFile objects that were considered to perform the action (it will be undefined if it could not be determined). Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1297 setAudioAPIAll_CALLBACK_ERROR_OBJECT Object used by the CB_AudioFileSpritesPool.setAudioAPIAll_CALLBACK_ERROR callback. Unless it belongs to a general error, its information will only be regarding a certain sprites group. Type: Object Properties: Name Type Description error string A string describing the error, if it was possible to be determined. errors integer The number of errors that happened, which could be greater than 1 if more than one internal call to the CB_AudioFile#setAudioAPI method failed. changed integer The number of objects that actually changed its audio API. performed integer The number of CB_AudioFile objects that ended with a desired audio API, including those ones which were already using it. needed integer | undefined The total number of CB_AudioFile objects that were considered to perform the action (it will be undefined if it could not be determined). Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1308 setAudioAPIAll_CALLBACK_OK(objectsChangedAPI, performedActions, actionsNeeded) Callback function used by the CB_AudioFileSpritesPool#setAudioAPIAll method that will be called when all the process was performed successfully. Parameters: Name Type Description objectsChangedAPI integer The number of CB_AudioFile objects that actually changed its audio API. performedActions integer The number of CB_AudioFile objects that ended with a desired audio API, including those ones which were already using it. actionsNeeded integer The total number of CB_AudioFile objects that were considered to perform the action (it will be undefined if it could not be determined). Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 1288 SPRITES_GROUPS_OBJECT Object whose property names the identifiers of each sprite (a case-sensitive string) and their value is a CB_AudioFileSprites.DATA_OBJECT object. Type: Object Properties: Name Type Description spritesGroupId CB_AudioFileSprites.DATA_OBJECT Being the name of each property the unique identifier of a sprites group which will use a future internally-created CB_AudioFileSprites object, the value will always be the CB_AudioFileSprites.DATA_OBJECT that the CB_AudioFileSprites object will use to be created (received by its constructor). Some of the missing properties (\"preferredAPIs\", \"preferredFormats\", \"minimumAudioFiles\", \"maximumAudioFiles\", \"minimumAudioFilesFree\", \"newAudioFilesWhenNeeded\", \"retries\", \"checkManually\", \"checkManuallyOnNeededCreated\", \"checkManuallyOnPlayingFailed\", \"checkManuallyOnCheckingFailed\" and \"disableAutoLoad\") will use the value set on the properties of the main CB_AudioFileSpritesPool.DATA_OBJECT object (if any) used by the CB_AudioFileSpritesPool object. If a function in the \"onError\" parameter is given, it will always be wrapped so the main error function set on the CB_AudioFileSpritesPool#onError parameter will always be called (if any) through the CB_AudioFileSpritesPool#errorFunction method. Source: CrossBase/audiovisual/audio/CB_AudioFileSpritesPool.js, line 8 Example { \"sprites_group_id_1\" : CB_AudioFileSprites.DATA_OBJECT, \"sprites_group_id_2\" : CB_AudioFileSprites.DATA_OBJECT, \"sprites_group_id_3\" : CB_AudioFileSprites.DATA_OBJECT, ... } × Search results Close "},"CB_baseSymbols.html":{"id":"CB_baseSymbols.html","title":"Namespace: CB_baseSymbols","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_baseSymbols CB_baseSymbols Object that contains different properties and methods that can be used as the \"baseSymbols\" parameter for the CB_intToBase and CB_baseToInt functions. Each property is a numeric array of characters. Source: CrossBase/general/CB_data.js, line 1108 Members &lt;static&gt; 10 :array Numeric array of characters with 10 symbols (using 0 to 9), decimal system. These symbols will not be encoded neither by the escape function nor by the encodeURIComponent function (recommended for URI components for any client, JavaScript strings or HTML code). Includes all symbols from lower bases, respecting the same order (which is their value). Type: array Default Value: [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"] Source: CrossBase/general/CB_data.js, line 1232 &lt;static&gt; 128 :array Numeric array of characters with 128 symbols. These symbols (and also the ones from other bases with higher number) will be encoded by the escape function and also by the encodeURIComponent function and they will need to be encoded in HTML (not recommended for URI components or JavaScript strings or HTML code). Type: array Default Value: An array with each item being the result of calling the String.fromCharCode function from 0 to 127 as its unique parameter. Source: CrossBase/general/CB_data.js, line 1148 &lt;static&gt; 16 :array Numeric array of characters with 16 symbols (using 0 to 9, A to F), hexadecimal system. These symbols will not be encoded neither by the escape function nor by the encodeURIComponent function (recommended for URI components for any client, JavaScript strings or HTML code). Includes all symbols from lower bases, respecting the same order (which is their value). Type: array Default Value: [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"] Source: CrossBase/general/CB_data.js, line 1220 &lt;static&gt; 2 :array Numeric array of characters with 2 symbols (using 0 and 1), binary system. These symbols will not be encoded neither by the escape function nor by the encodeURIComponent function (recommended for URI components for any client, JavaScript strings or HTML code). Type: array Default Value: [\"0\",\"1\"] Source: CrossBase/general/CB_data.js, line 1256 &lt;static&gt; 64 :array Numeric array of characters with 64 symbols (using 0 to 9, A to Z, a to z, \".\" and \"*\"). These symbols will not be encoded neither by the escape function nor by the encodeURIComponent function (recommended for URI components for any client, JavaScript strings or HTML code in the case that we do not want to use base 66 from the CB_baseSymbols.66 property). Includes all symbols from lower bases, respecting the same order (which is their value). Type: array Default Value: [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\",\".\",\"*\"] Source: CrossBase/general/CB_data.js, line 1208 &lt;static&gt; 66 :array Numeric array of characters with 66 symbols. These symbols will not be encoded neither by the escape function nor by the encodeURIComponent function (recommended for URI components for any client, JavaScript strings or HTML code). Includes Includes all symbols from lower bases, respecting the same order (which is their value). Type: array Default Value: [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\",\".\",\"*\",\"-\",\"_\"] Source: CrossBase/general/CB_data.js, line 1196 &lt;static&gt; 71 :array Numeric array of characters with 71 symbols. These symbols will be encoded by the escape function but not by the encodeURIComponent function (not recommended for URI components in old clients, but useful for URI components in new clients with encodeURIComponent function support, for JavaScript strings or HTML code). Includes all symbols from lower bases, respecting the same order (which is their value). Type: array Default Value: [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\",\".\",\"*\",\"-\",\"_\",\"~\",\"!\",\"'\",\"(\",\")\"] Source: CrossBase/general/CB_data.js, line 1184 &lt;static&gt; 8 :array Numeric array of characters with 8 symbols (using 0 to 7), octal system. These symbols will not be encoded neither by the escape function nor by the encodeURIComponent function (recommended for URI components for any client, JavaScript strings or HTML code). Includes all symbols from lower bases, respecting the same order (which is their value). Type: array Default Value: [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\"] Source: CrossBase/general/CB_data.js, line 1244 &lt;static&gt; 87 :array Numeric array of characters with 87 symbols. These symbols will be encoded by the escape function and also by the encodeURIComponent function but they will not need to be encoded neither in JavaScript strings nor in HTML (not recommended for URI components, but useful for JavaScript strings or HTML code). Includes all symbols from lower bases, respecting the same order (which is their value). Type: array Default Value: [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\",\".\",\"*\",\"-\",\"_\",\"~\",\"!\",\"'\",\"(\",\")\",\"@\",\"/\",\"|\",\"[\",\"]\",\"{\",\"}\",\"$\",\"%\",\"=\",\"?\",\"^\",\":\",\";\",\",\",\"+\"] Source: CrossBase/general/CB_data.js, line 1172 &lt;static&gt; 88 :array Numeric array of characters with 88 symbols. These symbols will be encoded by the escape function and also by the encodeURIComponent function, but they will not need to be encoded in HTML (not recommended for URI components or JavaScript strings, but useful for HTML code). Type: array Default Value: [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\",\".\",\"~\",\"!\",\"'\",\"(\",\")\",\"*\",\"-\",\"_\",\"@\",\"\\\\\",\"/\",\"|\",\"[\",\"]\",\"{\",\"}\",\"$\",\"%\",\"=\",\"?\",\"^\",\":\",\";\",\",\",\"+\"] Source: CrossBase/general/CB_data.js, line 1160 &lt;static&gt; _8 Alias for CB_baseSymbols.8. Source: CrossBase/general/CB_data.js, line 1234 See: CB_baseSymbols.8 &lt;static&gt; _8 Alias for CB_baseSymbols.2. Source: CrossBase/general/CB_data.js, line 1246 See: CB_baseSymbols.2 &lt;static&gt; _10 Alias for CB_baseSymbols.10. Source: CrossBase/general/CB_data.js, line 1222 See: CB_baseSymbols.10 &lt;static&gt; _16 Alias for CB_baseSymbols.16. Source: CrossBase/general/CB_data.js, line 1210 See: CB_baseSymbols.16 &lt;static&gt; _64 Alias for CB_baseSymbols.64. Source: CrossBase/general/CB_data.js, line 1198 See: CB_baseSymbols.64 &lt;static&gt; _66 Alias for CB_baseSymbols.66. Source: CrossBase/general/CB_data.js, line 1186 See: CB_baseSymbols.66 &lt;static&gt; _71 Alias for CB_baseSymbols.71. Source: CrossBase/general/CB_data.js, line 1174 See: CB_baseSymbols.71 &lt;static&gt; _87 Alias for CB_baseSymbols.87. Source: CrossBase/general/CB_data.js, line 1162 See: CB_baseSymbols.87 &lt;static&gt; _88 Alias for CB_baseSymbols.88. Source: CrossBase/general/CB_data.js, line 1150 See: CB_baseSymbols.88 &lt;static&gt; _128 Alias for CB_baseSymbols.128. Source: CrossBase/general/CB_data.js, line 1137 See: CB_baseSymbols.128 Methods &lt;static&gt; get( [base]) → {array} Function that will return a numeric array of characters containing as many items as the desired base. Uses a cache internally. Parameters: Name Type Argument Default Description base integer &lt;optional&gt; 256 The desired base (number of items, each with a character, that the returning array will contain). Minimum value is 1. The maximum can differ one client to another but it is not recommended to exceed 4096 (or even lower, depending on the client, although some clients could support up to 63988 or even more). All arrays of bases lower than 87 use the symbols included also in base 87. Source: CrossBase/general/CB_data.js, line 1118 Returns: Returns a numeric array of characters containing as many items as the desired base. All arrays of bases lower than 87 use the symbols included also in base 87. When the base is greater than 87 and it is not not created by default (88 and 128), each item of the returning array will be the result of calling the String.fromCharCode function from 0 to one number less than the desired base number. Type array × Search results Close "},"CB_Canvas.html":{"id":"CB_Canvas.html","title":"Class: CB_Canvas","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Class: CB_Canvas CB_Canvas Class to manage a canvas. For clients which do not support native canvas, it provides Adobe Flash (formerly Macromedia Flash) emulation with FlashCanvas, Microsoft Silverlight emulation with SLCanvas, VML emulation with ExplorerCanvas (reinforced with canvas-text) and DHTML (DOM elements) emulation with CanBox. NOTE: To make the VML emulation work without errors (using ExplorerCanvas), it is recommended to always load FlashCanvas (which already includes ExplorerCanvas) in your HTML code (without using lazy-load, as ExplorerCanvas does not support it). This is recommended even when we are not going to use Adobe Flash (formerly Macromedia Flash) emulation with FlashCanvas. This is an example (should be placed before loading the main \"CrossBrowdy\" script): &lt;!-- Loads FlashCanvas (Flash emulation) before CrossBrowdy. Needed also to use ExplorerCanvas (VML emulation) without problems: --&gt; &lt;script type=\"text/javascript\" src=\"CrossBrowdy/CrossBase/audiovisual/image/canvas/FlashCanvas/pro/bin/flashcanvas.js\"&gt;&lt;/script&gt;&lt;!-- FlashCanvas/ExplorerCanvas do not support lazy load. --&gt; new CB_Canvas(canvasId [, contextType] [, canvasWidth] [, canvasHeight] [, onLoad] [, onError] [, canvasParent] [, alternativeCanvasEmulationPreferredOrder] [, forceFirstEmulationMethod] [, addOtherMethods] [, allowFlashCanvasLocally]) → {CB_Canvas} Class to manage a canvas. Parameters: Name Type Argument Default Description canvasId string The desired ID for the canvas. contextType '2d' | 'webgl' | 'experimental-webgl' | 'webgl2' | 'experimental-webgl2' | 'bitmaprenderer' &lt;optional&gt; '2d' The contextType desired by default. More information: HTMLCanvasElement.getContext. Note that most emulation methods will only support \"2d\". canvasWidth integer &lt;optional&gt; CB_Canvas.WIDTH_DEFAULT The desired width (horizontal size) in pixels for the canvas. canvasHeight integer &lt;optional&gt; CB_Canvas.HEIGHT_DEFAULT The desired height (vertical size) in pixels for the canvas. onLoad function &lt;optional&gt; Callback function that will be called when the canvas is finally loaded. It will not receive parameters, being \"this\" the CB_Canvas object itself. onError function &lt;optional&gt; Callback function that will be called when there is an error creating or loading the canvas. Being \"this\" the CB_Canvas object itself, the unique parameter received will be a string describing the error (if it could be determined). canvasParent Element &lt;optional&gt; document.body The parent element desired to adopt the canvas. alternativeCanvasEmulationPreferredOrder array &lt;optional&gt; CB_Configuration.CrossBase.CB_Canvas_PREFERRED_EMULATION_METHODS Numeric array listing the desired alternative emulation methods for rendering the canvas, in order of preference. Supported emulation methods: \"FLASH\", \"VML\", \"DHTML\" and \"SILVERLIGHT\". forceFirstEmulationMethod boolean &lt;optional&gt; false If set to true, it will force to use the first alternative emulation method desired (even when this alternative emulation method could be not supported and even when native canvas support could be supported). addOtherMethods boolean &lt;optional&gt; true If set to true, it will add other alternative methods (if any is missing) at the end of the desired alternative emulation methods so they will also be checked and used if the previous ones are not finally used. The order they will be added will be the one used in the CB_Configuration.CrossBase.CB_Canvas_PREFERRED_EMULATION_METHODS constant. allowFlashCanvasLocally boolean &lt;optional&gt; CB_Configuration.CrossBase.FLASHCANVAS_ALLOW_RUN_LOCALLY_DEFAULT If set to true, it will allow to use Adobe Flash (formerly Macromedia Flash) emulation (if needed) even when it is running locally. Uses the CB_Client.isRunningLocally function internally. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 30 Returns: Returns a new CB_Canvas object. Type CB_Canvas Members &lt;static, constant&gt; HEIGHT_DEFAULT :integer Default canvas height in pixels. Type: integer Default Value: 240 Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 81 &lt;static, constant&gt; WIDTH_DEFAULT :integer Default canvas width in pixels. Type: integer Default Value: 320 Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 74 Methods &lt;static&gt; bestEmulation( [preferredOrder] [, forceFirstEmulationMethod] [, addOtherMethods] [, allowFlashCanvasLocally]) → {'NONE'|'FLASH'|'SILVERLIGHT'|'VML'|'DHTML'} Calculates and returns the best alternative canvas emulation. Parameters: Name Type Argument Default Description preferredOrder array | string &lt;optional&gt; CB_Configuration.CrossBase.CB_Canvas_PREFERRED_EMULATION_METHODS Numeric array listing the desired alternative emulation methods for rendering the canvas, in order of preference. Possible emulation methods: \"FLASH\", \"VML\", \"DHTML\" and \"SILVERLIGHT\". It can also be a string with the unique desired canvas emulation method or with \"NO\" or \"NONE\" value (meaning no emulation method is desired and then the returning value will always be \"NONE\"). forceFirstEmulationMethod boolean &lt;optional&gt; false If set to true, it will force to return the first alternative emulation method desired which is detected as supported without being too strict (even when this alternative emulation method could be not really supported and even when native canvas support could be supported). addOtherMethods boolean &lt;optional&gt; true If set to true, it will add other alternative methods (if any is missing) at the end of the desired alternative emulation methods so they will also be checked and used if the previous ones are not finally used. The order they will be added will be the one used in the CB_Configuration.CrossBase.CB_Canvas_PREFERRED_EMULATION_METHODS constant. allowFlashCanvasLocally boolean &lt;optional&gt; CB_Configuration.CrossBase.FLASHCANVAS_ALLOW_RUN_LOCALLY_DEFAULT If set to true, it will allow to use Adobe Flash (formerly Macromedia Flash) emulation (if needed) even when it is running locally. Uses the CB_Client.isRunningLocally function internally. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 142 Returns: Returns \"NONE\" if no canvas emulation is needed/supported (and no emulation method is forced). Otherwise, it returns the best emulation method calculated (\"FLASH\", \"SILVERLIGHT\", \"VML\" or \"DHTML\"). Type 'NONE' | 'FLASH' | 'SILVERLIGHT' | 'VML' | 'DHTML' &lt;static&gt; needsEmulation() → {boolean} Tells whether the current client needs canvas emulation or not. Uses CB_Client.supportsCanvas internally. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 127 Returns: Returns whether the current client needs canvas emulation or not. Type boolean &lt;static&gt; supportsEmulationMethod(emulationMethod [, strictMode]) → {boolean} Tells whether the current client is compatible with a given canvas emulation method or not. Parameters: Name Type Argument Default Description emulationMethod string Emulation method we want to check. Possible emulation methods: \"FLASH\", \"VML\", \"DHTML\" and \"SILVERLIGHT\". strictMode boolean &lt;optional&gt; true If set to true, the compatibility will be checked more carefully. If set to false (not recommended), the method could return true even when sometimes the canvas emulation method is not totally supported by the current client. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 216 Returns: Returns whether the current client is compatible with the given canvas emulation method or not. Type boolean clear( [keepTransform] [, backgroundFillStyle]) → {boolean} Clear the canvas entirely. Parameters: Name Type Argument Default Description keepTransform boolean &lt;optional&gt; false If set to true, it will save and restore the current transformation. backgroundFillStyle string &lt;optional&gt; The style used (color, gradient, pattern...) to fill the canvas background. If defined, it will be used as the value for the fillStyle property of the context object, internally. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 840 Returns: Returns true if the action could be performed or false otherwise. Type boolean clearCanvas() Alias for CB_Canvas#clear. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 828 See: CB_Canvas#clear disableAntiAliasing( [performTranslate]) → {boolean} Disables anti-aliasing. Useful to work with image sprites (to avoid problems showing adjacent ones), for example. Parameters: Name Type Argument Default Description performTranslate boolean &lt;optional&gt; false If set to true, it will also call the transform method. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 889 Returns: Returns true if the action could be performed or false otherwise. Type boolean get() → {Element|null} Returns the canvas element (if any). Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 602 Returns: Returns the canvas element (if any). If not found, null will be returned. Type Element | null getContext( [contextType]) → {RenderingContext|Object} Defines and returns the canvas context. It could call the CB_Canvas#prepareContext method internally. Parameters: Name Type Argument Default Description contextType '2d' | 'webgl' | 'experimental-webgl' | 'webgl2' | 'experimental-webgl2' | 'bitmaprenderer' &lt;optional&gt; CB_Canvas#._contextType|'2d' The context type desired. More information: HTMLCanvasElement.getContext. Note that most emulation methods will only support \"2d\". Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 614 Returns: Returns the canvas context (different type if a canvas emulation method is being used). Type RenderingContext | Object getContextType() → {string} Tells the current canvas context type used. Internally, it returns the value of the CB_Canvas#._contextType property. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 668 Returns: Tells the current canvas context type used. More information: HTMLCanvasElement.getContext. Type string getHeight() → {number} Tells the canvas height (vertical size) being used in pixels. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 789 Returns: Returns the canvas height (vertical size) being used in pixels. It could return zero (0) if cannot be calculated. Type number getId() → {string} Returns the identifier (ID) of the canvas element. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 319 Returns: Returns the identifier (ID) of the canvas element. Type string getMode() → {'NONE'|'NORMAL'|'FLASH'|'SILVERLIGHT'|'VML'|'DHTML'} Tells the mode used to create the canvas. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 800 Returns: Returns the mode used to create the canvas. Returns \"NONE\" if no method is used yet (possible when no method is supported at all or when it is still loading). Returns \"NORMAL\" if native canvas is used (no canvas emulation method). Type 'NONE' | 'NORMAL' | 'FLASH' | 'SILVERLIGHT' | 'VML' | 'DHTML' getWidth() → {number} Tells the canvas width (horizontal size) being used in pixels. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 739 Returns: Returns the canvas width (horizontal size) being used in pixels. It could return zero (0) if cannot be calculated. Type number isLoading() → {boolean} Tells whether the canvas is loading or not. Some canvas emulation methods can take some time until they finish loading. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 822 Returns: Returns whether the canvas is loading or not. Type boolean isReady() → {boolean} Tells whether the canvas is ready to be used or not. Some canvas emulation methods can take some time until they are ready to be used. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 811 Returns: Returns whether the canvas is ready to be used or not. Type boolean isSupported() → {boolean} Tells whether the canvas works or not. The internal test used could be not totally reliable. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 679 Returns: Returns whether the canvas works or not. The internal test used could be not totally reliable. Type boolean normalizeContext() Alias for CB_Canvas#prepareContext. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 537 See: CB_Canvas#prepareContext prepareContext( ) → {RenderingContext|Object} Provides the canvas context with some methods and properties, in case it needs it (as some canvas emulation methods lack of some methods and properties). Since this method is called by the CB_Canvas#set method already (and this one is called by the constructor automatically), it is not needed to be called again normally. Parameters: Name Type Argument Default Description context RenderingContext | Object &lt;optional&gt; CB_Canvas#getContext() The context object that we want to prepare (different type if a canvas emulation method is being used). If not defined, calls the CB_Canvas#getContext method internally. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 549 To Do: Add more methods and properties needed by some emulation methods. Returns: Returns the canvas context (different type if a canvas emulation method is being used). Type RenderingContext | Object set(canvasId [, canvasWidth] [, canvasHeight] [, onLoad] [, onError] [, alternativeCanvasEmulation] [, forceEmulation]) Defines the canvas element. Since this method is called by the constructor already, it is not needed to be called unless the canvas element wants to be defined again. Parameters: Name Type Argument Default Description canvasId string The desired ID for the canvas. canvasWidth integer &lt;optional&gt; CB_Canvas.WIDTH_DEFAULT The desired width (horizontal size) in pixels for the canvas. canvasHeight integer &lt;optional&gt; CB_Canvas.HEIGHT_DEFAULT The desired height (vertical size) in pixels for the canvas. onLoad function &lt;optional&gt; Callback function that will be called when the canvas is finally loaded. It will not receive parameters, being \"this\" the CB_Canvas object itself. onError function &lt;optional&gt; Callback function that will be called when there is an error creating or loading the canvas. Being \"this\" the CB_Canvas object itself, the unique parameter received will be a string describing the error (if it could be determined). alternativeCanvasEmulation string &lt;optional&gt; CB_Canvas.bestEmulation() Emulation method we want to use in the case that the native canvas is not supported or if the \"forceEmulation\" parameter is set to true. Possible emulation methods: \"FLASH\", \"VML\", \"DHTML\" and \"SILVERLIGHT\". forceEmulation boolean &lt;optional&gt; false If set to true, it will force to use the emulation method defined in the \"alternativeCanvasEmulation\" parameter (even when this alternative emulation method could be not supported and even when native canvas support could be supported). Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 336 setContextType( [contextType]) → {string} Defines the desired canvas context type. Internally, it only defines the CB_Canvas#._contextType property. Parameters: Name Type Argument Default Description contextType '2d' | 'webgl' | 'experimental-webgl' | 'webgl2' | 'experimental-webgl2' | 'bitmaprenderer' &lt;optional&gt; '2d' The [context]context type desired. More information: HTMLCanvasElement.getContext. Note that most emulation methods will only support \"2d\". Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 650 Returns: Returns the context type just applied. Type string setHeight( [canvasHeight]) → {number} Defines the desired canvas height. Parameters: Name Type Argument Default Description canvasHeight integer &lt;optional&gt; CB_Canvas.HEIGHT_DEFAULT The desired height (vertical size) in pixels for the canvas. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 751 Returns: Returns the canvas height (vertical size) being used in pixels. It could return zero (0) if cannot be calculated. Type number setId(canvasId) Sets the desired identifier (ID) of the canvas element. Since this method is called by the constructor already, it is not needed to be called unless the canvas element wants to be defined again through the CB_Canvas#set method. Note that changing the ID after the canvas has been set could lead to some problems when using certain emulation methods so it is not recommended. Parameters: Name Type Description canvasId string Identifier (ID) for the canvas element. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 304 setWidth( [canvasWidth]) → {number} Defines the desired canvas width. Parameters: Name Type Argument Default Description canvasWidth integer &lt;optional&gt; CB_Canvas.WIDTH_DEFAULT The desired width (horizontal size) in pixels for the canvas. Source: CrossBase/audiovisual/image/canvas/CB_Canvas.js, line 701 Returns: Returns the canvas width (horizontal size) being used in pixels. It could return zero (0) if cannot be calculated. Type number × Search results Close "},"CB_Client.html":{"id":"CB_Client.html","title":"Namespace: CB_Client","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Client CB_Client Static class to manage the current client. It will return itself if it is tried to be instantiated. It can use BrowserDetect (source code rescued). Source: CrossBase/general/CB_Client.js, line 14 To Do: Think about implementing a getDocumentParents function (similar to CB_Client.getWindowParents). Think about implementing \"onClose\" event (to fire when app/web is going to be closed). Methods &lt;static&gt; exit( [allowWindowCloseFallback] [, allowRedirectionFallback] [, redirectionAddress]) Exits and finishes the script. In a browser, it will try to close the window or at least abandon it redirecting to an empty one (or to a desired URL). In an app (NW.js (formerly node-webkit)/Electron (Electron.js)/Apache Cordova/Adobe PhoneGap/Appcelerator Titanium SDK/Appcelerator TideSDK (Titanium Desktop)/Weixin (WeChat)/etc.), it will try to close the app. Parameters: Name Type Argument Default Description allowWindowCloseFallback boolean &lt;optional&gt; true Defines whether to allow using the window.close method as a fallback. allowRedirectionFallback boolean &lt;optional&gt; true Defines whether to redirect the current client as a fallback (to the URL defined in the \"redirectionAddress\" parameter). redirectionAddress boolean &lt;optional&gt; 'about:blank' Defines the URL where the current client will be redirected to in the case that the window cannot be closed. Only used if the \"allowRedirectionFallback\" parameter is set to true. Source: CrossBase/general/CB_Client.js, line 557 To Do: Have in mind iframes (think about it). &lt;static&gt; get() → {string} Returns the current web client (if possible) as a string. It uses BrowserDetect (source code rescued) internally. Source: CrossBase/general/CB_Client.js, line 107 Returns: Type string &lt;static&gt; getAddressWithoutFile(address [, fallbackURL] [, allowsLocal]) → {string} Returns the given address without the file (for example, if \"http://whatever.com/index.html\" is given, it will return \"http://whatever.com/\"). Parameters: Name Type Argument Default Description address string The address that we want to filter. fallbackURL string &lt;optional&gt; The address that we want it to return in the case that the given one is not allowed (used when \"allowsLocal\" does not allow a local address). If it contains a file, it will not be stripped out. allowsLocal boolean &lt;optional&gt; true Defines whether to allow returning a local address or not. If it is set to false and the address is local, it will return the \"fallbackURL\" instead (without stripping out the file, if any). Source: CrossBase/general/CB_Client.js, line 762 Returns: Type string &lt;static&gt; getBoundingClientRectMargin( [leftOrTop]) → {integer} Gets the starting pixel of top or left coordinates for getBoundingClientRect (it's not 0 in some Internet Explorer versions). Parameters: Name Type Argument Default Description leftOrTop 'left' | 'top' &lt;optional&gt; 'left' String that defines whether we want it to return the values for \"left\" or for \"top\". Source: CrossBase/general/CB_Client.js, line 798 Returns: Type integer &lt;static&gt; getBrowser() Alias for CB_Client.get. Source: CrossBase/general/CB_Client.js, line 97 See: CB_Client.get &lt;static&gt; getBrowserVersion() Alias for CB_Client.getVersion. Source: CrossBase/general/CB_Client.js, line 113 See: CB_Client.getVersion &lt;static&gt; getBrowserVersionMain() Alias for CB_Client.getVersionMain. Source: CrossBase/general/CB_Client.js, line 129 See: CB_Client.getVersionMain &lt;static&gt; getButtonsDown() Alias for CB_Client.getButtons. Source: CrossBase/input/CB_Mouse.js, line 291 See: CB_Client.getButtons &lt;static&gt; getDocument( [mindIframes]) → {Object} Returns the document object (having in mind whether the script is running in one iframe or more, if we want). Parameters: Name Type Argument Default Description mindIframes boolean &lt;optional&gt; CB_Configuration.CrossBase.MIND_IFRAMES If set to true, it will try to get and return the topmost document object. Useful in case the script is running in an iframe or more. Source: CrossBase/general/CB_Client.js, line 264 Returns: Type Object &lt;static&gt; getDocumentBase() → {Object} Returns the document object of the first parent (the topmost one). Useful in case the script is running in an iframe or more. Source: CrossBase/general/CB_Client.js, line 246 Returns: Type Object &lt;static&gt; getFlashVersion( [asString]) → {array|string} Returns the available version of Adobe Flash (formerly Macromedia Flash) plugin, if any, as either an array of strings or as a string. Parameters: Name Type Argument Default Description asString boolean &lt;optional&gt; false If set to true, returns the version as a string. Source: CrossBase/general/CB_Client.js, line 441 Returns: Type array | string &lt;static&gt; getLanguage( [allowNavigatorLanguages] [, PHPAcceptedLanguagesFirst]) → {string} Returns the most preferred language as a string. Parameters: Name Type Argument Default Description allowNavigatorLanguages boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Client_allowNavigatorLanguages_DEFAULT Defines whether to allow using the window.navigator.languages property (if not available, it will proceed normally). PHPAcceptedLanguagesFirst boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Client_PHPAcceptedLanguagesFirst_DEFAULT If it is set to true, it will try to return the accepted languages found out by PHP (if PHP is available) in $_SERVER['HTTP_ACCEPT_LANGUAGE'] or it will proceed normally otherwise. Source: CrossBase/general/CB_Client.js, line 47 To Do: Use other back-end ways to calculate the language (using Node.js, for example). Returns: Type string &lt;static&gt; getLanguages( [allowNavigatorLanguages] [, PHPAcceptedLanguagesFirst]) → {array} Returns the most preferred languages as an array of strings. Parameters: Name Type Argument Default Description allowNavigatorLanguages boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Client_allowNavigatorLanguages_DEFAULT Defines whether to allow using the window.navigator.languages property (if not available, it will proceed normally). PHPAcceptedLanguagesFirst boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Client_PHPAcceptedLanguagesFirst_DEFAULT If it is set to true, it will try to return the accepted languages found out by PHP (if PHP is available) in $_SERVER['HTTP_ACCEPT_LANGUAGE'] or it will proceed normally otherwise. Source: CrossBase/general/CB_Client.js, line 78 To Do: Use other back-end ways to calculate languages (using Node.js, for example). Returns: Type array &lt;static&gt; getLocation( [mindIframes]) → {string} Returns the current URL, if possible (having in mind whether the script is running in one iframe or more, if we want). Parameters: Name Type Argument Default Description mindIframes boolean &lt;optional&gt; CB_Configuration.CrossBase.MIND_IFRAMES If set to true, it will try to get the location of the topmost window object. Useful in case the script is running in an iframe or more. Source: CrossBase/general/CB_Client.js, line 742 Returns: Type string &lt;static&gt; getLocationWithoutFile( [fallbackURL] [, allowsLocal] [, mindIframes]) → {string} Returns the current URL without the file (for example, if \"http://whatever.com/index.html\" is the current URL, it will return \"http://whatever.com/\"), if possible (having in mind whether the script is running in one iframe or more, if we want). Parameters: Name Type Argument Default Description fallbackURL string &lt;optional&gt; The address that we want it to return in the case that the current one is not allowed (used when \"allowsLocal\" does not allow a local address). If it contains a file, it will not be stripped out. allowsLocal boolean &lt;optional&gt; true Defines whether to allow returning a local address or not. If it is set to false and the current address is local, it will return the \"fallbackURL\" instead (without stripping out the file, if any). mindIframes boolean &lt;optional&gt; CB_Configuration.CrossBase.MIND_IFRAMES If set to true, it will try to get the location of the topmost window object. Useful in case the script is running in an iframe or more. Source: CrossBase/general/CB_Client.js, line 785 Returns: Type string &lt;static&gt; getNodeJSVersion( [asString]) → {array|string} Returns the available version of Node.js (if any), as either an array of strings or as a string. Parameters: Name Type Argument Default Description asString boolean &lt;optional&gt; false If set to true, returns the version as a string. Source: CrossBase/general/CB_Client.js, line 346 Returns: Type array | string &lt;static&gt; getPHPVersion( [asString]) → {array|string} Returns the available version of PHP (if any), as either an array of strings or as a string. Parameters: Name Type Argument Default Description asString boolean &lt;optional&gt; false If set to true, returns the version as a string. Source: CrossBase/general/CB_Client.js, line 321 Returns: Type array | string &lt;static&gt; getSilverlightVersion( [asString]) → {array|string} Returns the available version of Microsoft Silverlight plugin (if any), as either an array of strings or as a string. Parameters: Name Type Argument Default Description asString boolean &lt;optional&gt; false If set to true, returns the version as a string. Source: CrossBase/general/CB_Client.js, line 387 Returns: Type array | string &lt;static&gt; getTitle() → {string} Returns the current document title. Source: CrossBase/general/CB_Client.js, line 868 Returns: Type string &lt;static&gt; getVersion() → {string} Returns the current web client version (if possible) as a string. It uses BrowserDetect (source code rescued) internally. Source: CrossBase/general/CB_Client.js, line 123 Returns: Type string &lt;static&gt; getVersionMain() → {integer} Returns the current web client main version (first number), if possible, as an integer. It uses BrowserDetect (source code rescued) internally. Source: CrossBase/general/CB_Client.js, line 139 Returns: Type integer &lt;static&gt; getWindow( [mindIframes]) → {Object} Returns the window object (having in mind whether the script is running in one iframe or more, if we want). Parameters: Name Type Argument Default Description mindIframes boolean &lt;optional&gt; CB_Configuration.CrossBase.MIND_IFRAMES If set to true, it will try to get and return the topmost window object. Useful in case the script is running in an iframe or more. Source: CrossBase/general/CB_Client.js, line 223 Returns: Type Object &lt;static&gt; getWindowBase() → {Object} Returns the window object of the first parent (the topmost one). Useful in case the script is running in an iframe or more. Source: CrossBase/general/CB_Client.js, line 186 Returns: Type Object &lt;static&gt; getWindowParents() → {array} Returns all the window objects, parents and last son (main one) in an array (with the topmost parent in the highest index). Useful in case the script is running in an iframe or more. Source: CrossBase/general/CB_Client.js, line 151 Returns: Type array &lt;static&gt; isRunningLocally( [mindIframes]) → {boolean} Tells whether the script is running locally (using \"file:\" protocol) or not. Parameters: Name Type Argument Default Description mindIframes boolean &lt;optional&gt; CB_Configuration.CrossBase.MIND_IFRAMES If set to true, it will try to check the protocol of the topmost window object. Useful in case the script is running in an iframe or more. Source: CrossBase/general/CB_Client.js, line 481 Returns: Type boolean &lt;static&gt; isRunningOnElectron() → {boolean} Tells whether the script is running on Electron (Electron.js) or not. Source: CrossBase/general/CB_Client.js, line 537 Returns: Type boolean &lt;static&gt; isRunningOnNWjs() → {boolean} Tells whether the script is running on NW.js (formerly node-webkit) or not. Source: CrossBase/general/CB_Client.js, line 518 Returns: Type boolean &lt;static&gt; onLanguageChanges(eventFunction [, keepOldFunction] [, useCapture]) Sets a function to execute when the languagechange event is fired (only for some web clients) or removes it. Parameters: Name Type Argument Default Description eventFunction function | null Function that represents the event listener that will be called when the event is fired. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether to also keep the previous listeners or remove them otherwise. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. Source: CrossBase/general/CB_Client.js, line 91 &lt;static&gt; redirectTo(address [, getData] [, mindIframes]) Redirects the current client to the desired location (having in mind whether the script is running in one iframe or more, if we want). Parameters: Name Type Argument Default Description address string The address where we want to go. getData string &lt;optional&gt; Any URL (GET) variables we want to send (as for example \"data1=value1&amp;data2=value2\"). mindIframes boolean &lt;optional&gt; CB_Configuration.CrossBase.MIND_IFRAMES If set to true, it will try to redirect the topmost window object. Useful in case the script is running in an iframe or more. Source: CrossBase/general/CB_Client.js, line 721 &lt;static&gt; setTitle(newTitle) → {string} Tries to change the document title and returns it. Parameters: Name Type Description newTitle newTitle The desired new title. Source: CrossBase/general/CB_Client.js, line 848 Returns: Type string &lt;static&gt; supportsCanvas() → {boolean} Tells whether the canvas element is supported natively or not. Source: CrossBase/general/CB_Client.js, line 280 Returns: Type boolean &lt;static&gt; supportsCSS3Transform() → {boolean} Tells whether CSS3 transform is supported natively or not. Source: CrossBase/general/CB_Client.js, line 292 Returns: Type boolean &lt;static&gt; supportsFlash() → {boolean} Function that tells whether Adobe Flash (formerly Macromedia Flash) plugin is available or not. Source: CrossBase/general/CB_Client.js, line 403 Returns: Type boolean &lt;static&gt; supportsNodeJS() → {boolean} Function that tells whether Node.js is available (checks the availability of process.versions.node) or not. Source: CrossBase/general/CB_Client.js, line 334 Returns: Type boolean &lt;static&gt; supportsPHP() → {boolean} Function that tells whether PHP is available or not. Source: CrossBase/general/CB_Client.js, line 309 Returns: Type boolean &lt;static&gt; supportsSilverlight() → {boolean} Function that tells whether Microsoft Silverlight plugin is available or not. Source: CrossBase/general/CB_Client.js, line 361 Returns: Type boolean × Search results Close "},"CB_Collisions.html":{"id":"CB_Collisions.html","title":"Namespace: CB_Collisions","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Collisions CB_Collisions Static class to manage collisions. It will return itself if it is tried to be instantiated. Source: CrossBase/general/CB_Collisions.js, line 18 To Do: Finish many functions for many more kinds of collisions. Add triangles, polygons, arcs, etc. Add support to more dimensions (at least to 3D). Add lacking \"touching\" functions, equivalent to the \"over\" ones. Add a boolean parameter and a border parameter to detect collision just when it hits the border (not when it is inside of the object without touching the border), for \"hollow\" shapes. Think about adding function aliases with reversed names (for example, \"isElementOverPoint\" that points to \"isPointOverElement\", etc.). Think about whether the aliases should or not have some parameters in reversed order. Methods &lt;static&gt; getDistancePoints(x, y, x2, y2) → {number|null} Tells the distance between two points. Parameters: Name Type Description x number The \"X\" coordinate of the first point. y number The \"Y\" coordinate of the first point. x2 number The \"X\" coordinate of the second point. y2 number The \"Y\" coordinate of the second point. Source: CrossBase/general/CB_Collisions.js, line 49 Returns: Returns the distance between the two points. In the case that it could not be calculated, returns null. Type number | null &lt;static&gt; isCircleOverCircle(centreX, centreY, radius, centreX2, centreY2, radius2) → {boolean} Tells whether a circle is over another circle. Parameters: Name Type Description centreX number The \"X\" coordinate of the center of the first circle. centreY number The \"Y\" coordinate of the center of the first circle. radius number The radius of the first circle. centreX2 number The \"X\" coordinate of the center of the second circle. centreY2 number The \"Y\" coordinate of the center of the second circle. radius2 number The radius of the second circle. Source: CrossBase/general/CB_Collisions.js, line 434 Returns: Returns whether the circle is over the other circle. Type boolean &lt;static&gt; isCircleTouchingCircle(centreX, centreY, radius, centreX2, centreY2, radius2) → {boolean} Tells whether a circle is touching (maybe over) another circle. This will also return true if they are adjacent (next to each other). Parameters: Name Type Description centreX number The \"X\" coordinate of the center of the first circle. centreY number The \"Y\" coordinate of the center of the first circle. radius number The radius of the first circle. centreX2 number The \"X\" coordinate of the center of the second circle. centreY2 number The \"Y\" coordinate of the center of the second circle. radius2 number The radius of the second circle. Source: CrossBase/general/CB_Collisions.js, line 452 Returns: Returns whether the circle is touching (maybe over) the other circle. This will also return true if they are adjacent (next to each other). Type boolean &lt;static&gt; isElementOverElement(element, element2) → {boolean} Tells whether two given DOM elements are over each other (they will be considered a rectangle). Parameters: Name Type Description element Element The first DOM element that we want to check (it will be considered a rectangle). element2 Element The second DOM element that we want to check (it will be considered a rectangle). Source: CrossBase/general/CB_Collisions.js, line 402 Returns: Returns whether the two given DOM elements are over each other (they will be considered a rectangle). Type boolean &lt;static&gt; isElementTouchingElement(element, element2) → {boolean} Tells whether two given DOM elements are touching each other, maybe over each other (they will be considered a rectangle). This will also return true if they are adjacent (next to each other). Parameters: Name Type Description element Element The first DOM element that we want to check (it will be considered a rectangle). element2 Element The second DOM element that we want to check (it will be considered a rectangle). Source: CrossBase/general/CB_Collisions.js, line 416 Returns: Returns whether the two given DOM elements are touching each other, maybe over each other (they will be considered a rectangle). This will also return true if they are adjacent (next to each other). Type boolean &lt;static&gt; isLineOverCircle(lineX1, lineY1, lineX2, lineY2, centreX, centreY, radius) → {boolean} Tells whether a line (infinite) is over a given circle. Parameters: Name Type Description lineX1 number The \"X\" coordinate of a first point of the line. lineY1 number The \"Y\" coordinate of a first point of the line. lineX2 number The \"X\" coordinate of a second point of the line. lineY2 number The \"Y\" coordinate of a second point of the line. centreX number The \"X\" coordinate of the center of the first circle. centreY number The \"Y\" coordinate of the center of the first circle. radius number The radius of the first circle. Source: CrossBase/general/CB_Collisions.js, line 536 Returns: Returns whether the line (infinite) is over the circle. Type boolean &lt;static&gt; isLineTouchingCircle(lineX1, lineY1, lineX2, lineY2, centreX, centreY, radius) → {boolean} Tells whether a line (infinite) is touching (maybe over) a given circle. Parameters: Name Type Description lineX1 number The \"X\" coordinate of a first point of the line. lineY1 number The \"Y\" coordinate of a first point of the line. lineX2 number The \"X\" coordinate of a second point of the line. lineY2 number The \"Y\" coordinate of a second point of the line. centreX number The \"X\" coordinate of the center of the first circle. centreY number The \"Y\" coordinate of the center of the first circle. radius number The radius of the first circle. Source: CrossBase/general/CB_Collisions.js, line 577 Returns: Returns whether the line (infinite) is touching (maybe over) the circle. Type boolean &lt;static&gt; isPointOverCircle(x, y, centreX, centreY, radius) → {boolean} Tells whether a point is over a circle. Parameters: Name Type Description x number The \"X\" coordinate of the point. y number The \"Y\" coordinate of the point. centreX number The \"X\" coordinate of the center of the circle. centreY number The \"Y\" coordinate of the center of the circle. radius number The radius of the circle. Source: CrossBase/general/CB_Collisions.js, line 237 Returns: Returns whether the point is over the circle. Type boolean &lt;static&gt; isPointOverElement(x, y, element) → {boolean} Tells whether a given point is over a given DOM element (it will be considered a rectangle). Parameters: Name Type Description x number The \"X\" coordinate of the point. y number The \"Y\" coordinate of the point. element Element The DOM element that we want to check (it will be considered a rectangle). Source: CrossBase/general/CB_Collisions.js, line 64 Returns: Returns whether the point is over the given DOM element (it will be considered a rectangle). Type boolean &lt;static&gt; isPointOverEllipse(x, y, centreX, centreY, radiusX, radiusY [, rotation] [, rotationUseDegrees]) → {boolean} Tells whether a point is over an ellipse. Parameters: Name Type Argument Default Description x number The \"X\" coordinate of the point. y number The \"Y\" coordinate of the point. centreX number The \"X\" coordinate of the center of the ellipse. centreY number The \"Y\" coordinate of the center of the ellipse. radiusX number The X (horizontal) radius of the ellipse. radiusY number The Y (vertical) radius of the ellipse. rotation number &lt;optional&gt; 0 The ellipse rotation. The value given will be considered either degrees or radians depending on the given \"rotationUseDegrees\" parameter (by default, it is considered radians). Not implemented yet! rotationUseDegrees boolean &lt;optional&gt; false Defines whether the \"rotation\" given should be considered degrees or not (radians). Not implemented yet! Source: CrossBase/general/CB_Collisions.js, line 277 To Do: Make the \"rotation\" parameter work (check https://math.stackexchange.com/questions/426150/what-is-the-general-equation-of-the-ellipse-that-is-not-in-the-origin-and-rotate). Returns: Returns whether the point is over the ellipse. Type boolean &lt;static&gt; isPointOverLine(x, y, lineX1, lineY1, lineX2, lineY2 [, tolerance]) → {boolean} Tells whether a point is over a line (infinite). Parameters: Name Type Argument Default Description x number The \"X\" coordinate of the point. y number The \"Y\" coordinate of the point. lineX1 number The \"X\" coordinate of a first point of the line. lineY1 number The \"Y\" coordinate of a first point of the line. lineX2 number The \"X\" coordinate of a second point of the line. lineY2 number The \"Y\" coordinate of a second point of the line. tolerance number &lt;optional&gt; 0.001 The amount of loss of precision we can tolerate to consider a collision. Source: CrossBase/general/CB_Collisions.js, line 100 To Do: Think about using a \"width\" parameter (apart from the \"tolerance\" parameter). Create a CB_Collisions.isPointTouchingLine function. Returns: Returns whether the point is over the line (infinite). Type boolean &lt;static&gt; isPointOverRectangle(x, y, rectangleX, rectangleY, rectangleWidth, rectangleHeight) → {boolean} Tells whether a point is over a rectangle. Parameters: Name Type Description x number The \"X\" coordinate of the point. y number The \"Y\" coordinate of the point. rectangleX number The \"X\" coordinate of the upper left corner of the rectangle. rectangleY number The \"Y\" coordinate of the upper left corner of the rectangle. rectangleWidth number The width of the rectangle. rectangleHeight number The height of the rectangle. Source: CrossBase/general/CB_Collisions.js, line 193 To Do: Think about using a \"rotation\" parameter to accept rotated rectangles. Returns: Returns whether the point is over the rectangle. Type boolean &lt;static&gt; isPointOverSegment(x, y, segmentX1, segmentY1, segmentX2, segmentY2 [, tolerance]) → {boolean} Tells whether a point is over a line segment. Parameters: Name Type Argument Default Description x number The \"X\" coordinate of the point. y number The \"Y\" coordinate of the point. segmentX1 number The \"X\" coordinate of the beginning point of the line. segmentY1 number The \"Y\" coordinate of the beginning point of the line. segmentX2 number The \"X\" coordinate of the end point of the line. segmentY2 number The \"Y\" coordinate of the end point of the line. tolerance number &lt;optional&gt; 0.001 The amount of loss of precision we can tolerate to consider a collision. Source: CrossBase/general/CB_Collisions.js, line 154 To Do: Think about using a \"width\" parameter (apart from the \"tolerance\" parameter). Create a CB_Collisions.isPointTouchingSegment function. Returns: Returns whether the point is over the line segment. Type boolean &lt;static&gt; isPointTouchingCircle(x, y, centreX, centreY, radius) → {boolean} Tells whether a point is touching (maybe over) a circle. This will also return true if they are adjacent (next to each other). Parameters: Name Type Description x number The \"X\" coordinate of the point. y number The \"Y\" coordinate of the point. centreX number The \"X\" coordinate of the center of the circle. centreY number The \"Y\" coordinate of the center of the circle. radius number The radius of the circle. Source: CrossBase/general/CB_Collisions.js, line 255 Returns: Returns whether the point is touching (maybe over) the circle. This will also return true if they are adjacent (next to each other). Type boolean &lt;static&gt; isPointTouchingElement(x, y, element) → {boolean} Tells whether a given point is touching (maybe over) a given DOM element (it will be considered a rectangle). This will also return true if they are adjacent (next to each other). Parameters: Name Type Description x number The \"X\" coordinate of the point. y number The \"Y\" coordinate of the point. element Element The DOM element that we want to check (it will be considered a rectangle). Source: CrossBase/general/CB_Collisions.js, line 79 Returns: Returns whether the point is touching (maybe over) the given DOM element (it will be considered a rectangle). This will also return true if they are adjacent (next to each other). Type boolean &lt;static&gt; isPointTouchingEllipse(x, y, centreX, centreY, radiusX, radiusY [, rotation] [, rotationUseDegrees]) → {boolean} Tells whether a point is touching (maybe over) a ellipse. This will also return true if they are adjacent (next to each other). Parameters: Name Type Argument Default Description x number The \"X\" coordinate of the point. y number The \"Y\" coordinate of the point. centreX number The \"X\" coordinate of the center of the ellipse. centreY number The \"Y\" coordinate of the center of the ellipse. radiusX number The X (horizontal) radius of the ellipse. radiusY number The Y (vertical) radius of the ellipse. rotation number &lt;optional&gt; 0 The ellipse rotation. The value given will be considered either degrees or radians depending on the given \"rotationUseDegrees\" parameter (by default, it is considered radians). Not implemented yet! rotationUseDegrees boolean &lt;optional&gt; false Defines whether the \"rotation\" given should be considered degrees or not (radians). Not implemented yet! Source: CrossBase/general/CB_Collisions.js, line 302 To Do: Make the \"rotation\" parameter work (check https://math.stackexchange.com/questions/426150/what-is-the-general-equation-of-the-ellipse-that-is-not-in-the-origin-and-rotate). Returns: Returns whether the point is touching (maybe over) the ellipse. This will also return true if they are adjacent (next to each other). Type boolean &lt;static&gt; isPointTouchingRectangle(x, y, rectangleX, rectangleY, rectangleWidth, rectangleHeight) → {boolean} Tells whether a point is touching (maybe over) a rectangle. This will also return true if they are adjacent (next to each other). Parameters: Name Type Description x number The \"X\" coordinate of the point. y number The \"Y\" coordinate of the point. rectangleX number The \"X\" coordinate of the upper left corner of the rectangle. rectangleY number The \"Y\" coordinate of the upper left corner of the rectangle. rectangleWidth number The width of the rectangle. rectangleHeight number The height of the rectangle. Source: CrossBase/general/CB_Collisions.js, line 211 To Do: Think about using a \"rotation\" parameter to accept rotated rectangles. Returns: Returns whether the point is touching (maybe over) the rectangle. This will also return true if they are adjacent (next to each other). Type boolean &lt;static&gt; isRectangleOverCircle(centreX, centreY, radius, rectangleX, rectangleY, rectangleWidth, rectangleHeight) → {boolean} Tells whether a circle is over a given rectangle. Parameters: Name Type Description centreX number The \"X\" coordinate of the center of the first circle. centreY number The \"Y\" coordinate of the center of the first circle. radius number The radius of the first circle. rectangleX number The \"X\" coordinate of the upper left corner of the first rectangle. rectangleY number The \"Y\" coordinate of the upper left corner of the first rectangle. rectangleWidth number The width of the first rectangle. rectangleHeight number The height of the first rectangle. Source: CrossBase/general/CB_Collisions.js, line 473 To Do: Think about using a \"rotation\" parameter to accept rotated rectangles. Returns: Returns whether the circle is over the rectangle. Type boolean &lt;static&gt; isRectangleOverElement(rectangleX, rectangleY, rectangleWidth, rectangleHeight, element) → {boolean} Tells whether a rectangle is over a given DOM element (it will be considered a rectangle). Parameters: Name Type Description rectangleX number The \"X\" coordinate of the upper left corner of the first rectangle. rectangleY number The \"Y\" coordinate of the upper left corner of the first rectangle. rectangleWidth number The width of the first rectangle. rectangleHeight number The height of the first rectangle. element Element The DOM element that we want to check (it will be considered a rectangle). Source: CrossBase/general/CB_Collisions.js, line 370 To Do: Think about using a \"rotation\" parameter to accept rotated rectangles. Returns: Returns whether the rectangle is over the given DOM element (it will be considered a rectangle). Type boolean &lt;static&gt; isRectangleOverRectangle(rectangleX, rectangleY, rectangleWidth, rectangleHeight, rectangleX2, rectangleY2, rectangleWidth2, rectangleHeight2) → {boolean} Tells whether a rectangle is over another rectangle. Parameters: Name Type Description rectangleX number The \"X\" coordinate of the upper left corner of the first rectangle. rectangleY number The \"Y\" coordinate of the upper left corner of the first rectangle. rectangleWidth number The width of the first rectangle. rectangleHeight number The height of the first rectangle. rectangleX2 number The \"X\" coordinate of the upper left corner of the second rectangle. rectangleY2 number The \"Y\" coordinate of the upper left corner of the second rectangle. rectangleWidth2 number The width of the second rectangle. rectangleHeight2 number The height of the second rectangle. Source: CrossBase/general/CB_Collisions.js, line 327 To Do: Think about using \"rotation\" and \"rotation2\" parameters to accept rotated rectangles. Returns: Returns whether the rectangle is over the other rectangle. Type boolean &lt;static&gt; isRectangleTouchingCircle(rectangleX, rectangleY, rectangleWidth, rectangleHeight, centreX, centreY, radius) → {boolean} Tells whether a circle is touching (maybe over) a given rectangle. Parameters: Name Type Description rectangleX number The \"X\" coordinate of the upper left corner of the first rectangle. rectangleY number The \"Y\" coordinate of the upper left corner of the first rectangle. rectangleWidth number The width of the first rectangle. rectangleHeight number The height of the first rectangle. centreX number The \"X\" coordinate of the center of the first circle. centreY number The \"Y\" coordinate of the center of the first circle. radius number The radius of the first circle. Source: CrossBase/general/CB_Collisions.js, line 505 To Do: Think about using a \"rotation\" parameter to accept rotated rectangles. //* Source (modified): markE at https://stackoverflow.com/questions/21089959/detecting-collision-of-rectangle-with-circle Returns: Returns whether the circle is touching (maybe over) the rectangle. This will also return true if they are adjacent (next to each other). Type boolean &lt;static&gt; isRectangleTouchingElement(rectangleX, rectangleY, rectangleWidth, rectangleHeight, element) → {boolean} Tells whether a rectangle is touching (maybe over) a given DOM element (it will be considered a rectangle). This will also return true if they are adjacent (next to each other). Parameters: Name Type Description rectangleX number The \"X\" coordinate of the upper left corner of the first rectangle. rectangleY number The \"Y\" coordinate of the upper left corner of the first rectangle. rectangleWidth number The width of the first rectangle. rectangleHeight number The height of the first rectangle. element Element The DOM element that we want to check (it will be considered a rectangle). Source: CrossBase/general/CB_Collisions.js, line 388 To Do: Think about using a \"rotation\" parameter to accept rotated rectangles. Returns: Returns whether the rectangle is touching (maybe over) the given DOM element (it will be considered a rectangle). This will also return true if they are adjacent (next to each other). Type boolean &lt;static&gt; isRectangleTouchingRectangle(rectangleX, rectangleY, rectangleWidth, rectangleHeight, rectangleX2, rectangleY2, rectangleWidth2, rectangleHeight2) → {boolean} Tells whether a rectangle is touching (maybe over) another rectangle. This will also return true if they are adjacent (next to each other). Parameters: Name Type Description rectangleX number The \"X\" coordinate of the upper left corner of the first rectangle. rectangleY number The \"Y\" coordinate of the upper left corner of the first rectangle. rectangleWidth number The width of the first rectangle. rectangleHeight number The height of the first rectangle. rectangleX2 number The \"X\" coordinate of the upper left corner of the second rectangle. rectangleY2 number The \"Y\" coordinate of the upper left corner of the second rectangle. rectangleWidth2 number The width of the second rectangle. rectangleHeight2 number The height of the second rectangle. Source: CrossBase/general/CB_Collisions.js, line 350 To Do: Think about using \"rotation\" and \"rotation2\" parameters to accept rotated rectangles. Returns: Returns whether the rectangle is touching (maybe over) the other rectangle. This will also return true if they are adjacent (next to each other). Type boolean × Search results Close "},"CB_Configuration.html":{"id":"CB_Configuration.html","title":"Namespace: CB_Configuration","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Configuration CB_Configuration Static class to manage the configuration. It will be overwritten with the values defined in CB_OPTIONS (if any). First-level indexes should belong to the module name and second-level indexes should belong to the option name. Follows the same format as CB_OPTIONS. Source: CrossBrowdy.js, line 66 Namespaces CrossBase CrossBrowdy × Search results Close "},"CB_Configuration.CrossBase.html":{"id":"CB_Configuration.CrossBase.html","title":"Namespace: CrossBase","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CrossBase CB_Configuration. CrossBase Property that contains an object with the options for the main script. Source: CrossBase/CrossBase.js, line 53 Members &lt;static, constant&gt; BANDJS_LOAD :boolean Defines whether to load or not Band.js. Type: boolean Default Value: typeof(window.AudioContext) !== \"undefined\" || typeof(window.webkitAudioContext) !== \"undefined\" Source: CrossBase/CrossBase.js, line 1166 &lt;static, constant&gt; BANDJS_PATH :string Directory that contains the Band.js files. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"audiovisual/audio/band.js/\" Source: CrossBase/CrossBase.js, line 1176 &lt;static, constant&gt; BANDJS_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.BANDJS_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1196 &lt;static, constant&gt; BANDJS_PATH_SCRIPT_FILE :string The script file path for Band.js. Type: string Default Value: CB_Configuration.CrossBase.BANDJS_PATH + \"band.min.js\" Source: CrossBase/CrossBase.js, line 1186 &lt;static, constant&gt; CANBOX_LOAD :boolean Defines whether to load or not Canbox. Type: boolean Default Value: CB_Configuration.CrossBase.needsCanbox() Source: CrossBase/CrossBase.js, line 1559 &lt;static, constant&gt; CANBOX_PATH :string Directory that contains the Canbox files. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"audiovisual/image/canvas/canbox/\" Source: CrossBase/CrossBase.js, line 1569 &lt;static, constant&gt; CANBOX_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.CANBOX_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1589 &lt;static, constant&gt; CANBOX_PATH_SCRIPT_FILE :string The script file path for Canbox. Type: string Default Value: CB_Configuration.CrossBase.CANBOX_PATH + \"canbox.0.2.1.js\" Source: CrossBase/CrossBase.js, line 1579 &lt;static, constant&gt; CANVAS_TEXT_LOAD :boolean Defines whether to load or not canvas-text. Type: boolean Default Value: CB_Configuration.CrossBase.needsCanvasText() Source: CrossBase/CrossBase.js, line 1777 &lt;static, constant&gt; CANVAS_TEXT_PATH :string Directory that contains the canvas-text files. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"audiovisual/image/canvas/excanvas_with_canvas_text/\" Source: CrossBase/CrossBase.js, line 1787 &lt;static, constant&gt; CANVAS_TEXT_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.CANVAS_TEXT_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1807 &lt;static, constant&gt; CANVAS_TEXT_PATH_SCRIPT_FILE :string The script file path for canvas-text. Type: string Default Value: CB_Configuration.CrossBase.CANVAS_TEXT_PATH + \"canvas.text.js\" Source: CrossBase/CrossBase.js, line 1797 &lt;static, constant&gt; CB_AudioDetector_allowEmulation_DEFAULT :boolean Value by default when the \"allowEmulation\" parameter is not provided in the CB_AudioDetector.getPreferredAPI, the CB_AudioDetector.getSupportedAPIs or the CB_AudioDetector.isAPISupported function. Type: boolean Source: CrossBase/CrossBase.js, line 364 &lt;static, constant&gt; CB_AudioFile_AAPI_USE_TIMEOUT_TO_DETECT_STOPAT :boolean Tells whether CB_AudioFile[\"AAPI\"] uses setTimeout (instead of timeupdate event) to detect when the given \"stopAt\" is reached. Type: boolean Default Value: true Source: CrossBase/CrossBase.js, line 296 &lt;static, constant&gt; CB_AudioFile_AudioFileCache_ALLOWED_RECURSIVE_DELAY_DEFAULT :integer Default value for maximum delay (in milliseconds) to wait for a sound to start playing or start next loop (if the time expires, the sound will never be played). Used by CB_AudioFile_API.WAAPI, CB_AudioFile_API.AAPI, CB_AudioFile_API.SM2, CB_AudioFile_API.ACMP and CB_AudioFileCache. Type: integer Default Value: 150 Source: CrossBase/CrossBase.js, line 307 &lt;static, constant&gt; CB_AudioFile_AudioFileCache_MUTE_ON_LOAD_AND_CHECKING :boolean Tells whether to mute or not the audio files when they load or are checking. Note: Audio cache does not work properly on BlackBerry PlayBook's default browser if the sounds are muted when load or are checking. Used by CB_AudioFile, CB_AudioFile_API.WAAPI, CB_AudioFile_API.AAPI, CB_AudioFile_API.SM2, CB_AudioFile_API.ACMP and CB_AudioFileCache. Type: boolean Default Value: !(navigator.userAgent.indexOf(\"PlayBook\") !== -1 &amp;&amp; navigator.userAgent.indexOf(\"Tablet OS\") !== -1) Source: CrossBase/CrossBase.js, line 318 &lt;static, constant&gt; CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_DEFAULT :boolean Defines whether to use CB_Speaker._volume as default volume. Used by CB_AudioFile, CB_AudioFile_API.WAAPI, CB_AudioFile_API.AAPI, CB_AudioFile_API.SM2, CB_AudioFile_API.ACMP and CB_AudioFileCache. Type: boolean Default Value: true Source: CrossBase/CrossBase.js, line 328 &lt;static, constant&gt; CB_AudioFile_AudioFileCache_USE_SPEAKER_VOLUME_AS_MAXIMUM :boolean Defines whether to use CB_Speaker._volume as maximum volume. Used by CB_AudioFile, CB_AudioFile_API.WAAPI, CB_AudioFile_API.AAPI, CB_AudioFile_API.SM2 and CB_AudioFile_API.ACMP. Type: boolean Source: CrossBase/CrossBase.js, line 338 &lt;static, constant&gt; CB_AudioFile_AUTOPLAY_SILENTLY_ON_LOAD_MS :integer Milliseconds that a file is played (with volume set to 0) automatically when an audio file is loaded. Needed for some web clients which cannot find out the duration otherwise. Used by CB_AudioFile. Type: integer Default Value: 500 Source: CrossBase/CrossBase.js, line 276 &lt;static, constant&gt; CB_AudioFile_ONLOAD_TIMEOUT_MS :integer Milliseconds to wait before declaring a sound as failed if it cannot be loaded before. Used by CB_AudioFile_API.SM2. Type: integer Default Value: 15000 Source: CrossBase/CrossBase.js, line 286 &lt;static, constant&gt; CB_AudioFileCache_PREFERRED_AUDIO_APIS :array Array with the default preferred audio APIs by order of preference. Used by CB_AudioFileCache and CB_AudioDetector. Possible audio APIs are \"WAAPI\" (HTML5 Web Audio API), \"SM2\" (SoundManager 2), \"ACMP\" (Apache Cordova Media Plugin) or \"AAPI\" (HTML5 Audio API). Note: since Internet Explorer 9 works better with SM2 than with AAPI, if it is detected then the default value will be: [ \"WAAPI\", \"SM2\", \"ACMP\", \"AAPI\" ] Type: array Default Value: [\"WAAPI\", \"AAPI\", \"ACMP\", \"SM2\"] Source: CrossBase/CrossBase.js, line 376 &lt;static, constant&gt; CB_AudioFileCache_PREFERRED_AUDIO_FORMATS :array Array with the default preferred audio formats by order of preference. Used by CB_AudioFileCache and CB_AudioDetector. NOTE: some web clients do not support to specify codecs so it is better to also provide strings without codecs. Type: array Default Value: [\"audio/ogg; codecs=\\\"vorbis\\\"\",\"audio/ogg; codecs=\\\"speex\\\"\",\"audio/ogg; codecs=\\\"flac\\\"\",\"audio/ogg\",\"audio/mpeg; codecs=\\\"mp3\\\"\",\"audio/mpeg\",\"audio/mp4; codecs=\\\"mp4a.40.5\\\"\",\"audio/mp4; codecs=\\\"mp4a.40.2\\\"\",\"audio/mp4; codecs=\\\"mp4a.40.05\\\"\",\"audio/mp4; codecs=\\\"mp4a.40.02\\\"\",\"audio/mp4; codecs=\\\"mp4a.69\\\"\",\"audio/mp4; codecs=\\\"mp4a.6B\\\"\",\"audio/mp4; codecs=\\\"mp4a.67\\\"\",\"audio/mp4; codecs=\\\"mp4a.a6\\\"\",\"audio/mp4; codecs=\\\"mp4a.a5\\\"\",\"audio/mp4; codecs=\\\"aac51\\\"\",\"audio/mp4; codecs=\\\"ac-3\\\"\",\"audio/mp4; codecs=\\\"ec-3\\\"\",\"audio/mp4\",\"audio/aac; codecs=\\\"aac\\\"\",\"audio/aac; codecs=\\\"mp4a.40.5\\\"\",\"audio/aac; codecs=\\\"vorbis\\\"\",\"audio/aac\",\"audio/x-aac; codecs=\\\"aac\\\"\",\"audio/x-aac\",\"audio/x-m4b; codecs=\\\"aac\\\"\",\"audio/x-m4b\",\"audio/x-m4p; codecs=\\\"aac\\\"\",\"audio/x-m4p\",\"audio/webm; codecs=\\\"vorbis\\\"\",\"audio/webm\",\"audio/3gpp; codecs=\\\"samr\\\"\",\"audio/3gpp\",\"audio/wav; codecs=\\\"1\\\"\",\"audio/wav\",\"audio/x-wav; codecs=\\\"1\\\"\",\"audio/x-wav\",\"audio/x-pn-wav; codecs=\\\"1\\\"\",\"audio/x-pn-wav\",\"audio/wave; codecs=\\\"1\\\"\",\"audio/wave\",\"audio/x-wave; codecs=\\\"1\\\"\",\"audio/x-wave\"] Source: CrossBase/CrossBase.js, line 396 &lt;static, constant&gt; CB_Canvas_PREFERRED_EMULATION_METHODS :array Array with the default desired canvas emulation methods by order of preference. Used by CB_Canvas. Type: array Default Value: [\"FLASH\",\"VML\",\"DHTML\",\"SILVERLIGHT\"] Source: CrossBase/CrossBase.js, line 348 &lt;static, constant&gt; CB_Client_allowNavigatorLanguages_DEFAULT :boolean Default value for the \"allowNavigatorLanguages\" parameter for CB_Client.getLanguage and CB_Client.getLanguages functions. Type: boolean Source: CrossBase/CrossBase.js, line 146 &lt;static, constant&gt; CB_Client_language_DEFAULT :string Default language to use for CB_Client when no language can be detected (very strange case!). Type: string Default Value: en Source: CrossBase/CrossBase.js, line 136 &lt;static, constant&gt; CB_Client_PHPAcceptedLanguagesFirst_DEFAULT :boolean Tells whether the CB_Client.getLanguage and CB_Client.getLanguages functions will use the accepted languages detected by PHP (if any) as the first option by default or not. Type: boolean Default Value: true Source: CrossBase/CrossBase.js, line 156 &lt;static, constant&gt; CB_Controllers_avoidProprietary_DEFAULT :boolean Default value for the \"avoidProprietary\" proprietary when calling different functions of the CB_Controllers static class, as the CB_Controllers.getButtonsDown, the CB_Controllers.isButtonDown and the CB_Controllers.getGamePads functions, etc. Type: boolean Source: CrossBase/CrossBase.js, line 226 &lt;static, constant&gt; CB_Device_getTime_HIGH_PRECISION :string Defines whether to use high precision in the CB_Device.getTime (returning 'window.performance.timing.navigationStart + window.performance.now()', where 'window.performance.now' could be polyfilled) or not (returning 'Date.now()', where 'Date.now' could be polyfilled). Type: string Default Value: true Source: CrossBase/CrossBase.js, line 96 &lt;static, constant&gt; CB_Elements_classes_USE_CACHE :boolean Defines whether to use cache for the function CB_Elements.classes by default. Type: boolean Default Value: true Source: CrossBase/CrossBase.js, line 126 &lt;static, constant&gt; CB_Elements_id_USE_CACHE :boolean Defines whether to use cache for the function CB_Elements.id by default. Type: boolean Default Value: true Source: CrossBase/CrossBase.js, line 106 &lt;static, constant&gt; CB_Elements_tag_USE_CACHE :boolean Defines whether to use cache for the CB_Elements.tag function by default. Type: boolean Default Value: true Source: CrossBase/CrossBase.js, line 116 &lt;static, constant&gt; CB_Keyboard_extended_PS4_allowDuplicateKeyAliases :boolean Defines whether to allow Sony Playstation 4 codes set in the CB_Keyboard.extended.PS4CB_Keyboard.extended.PS4 object to be defined in the key aliases even if they use codes which belong to other keys. Used by CB_Keyboard. Type: boolean Source: CrossBase/CrossBase.js, line 196 &lt;static, constant&gt; CB_Keyboard_extended_SAMSUNG_TV_allowDuplicateKeyAliases :boolean Defines whether to allow Samsung TV key codes (from the remote control) set in the CB_Keyboard.extended.SAMSUNG_TV object to be defined in the key aliases even if they use codes which belong to other keys. Used by CB_Keyboard. Type: boolean Source: CrossBase/CrossBase.js, line 216 &lt;static, constant&gt; CB_Keyboard_extended_VK_allowDuplicateKeyAliases :boolean Defines whether to allow Smart TV codes (from the remote control) and virtual key codes set in the CB_Keyboard.extended.VK object to be defined in the key aliases even if they use codes which belong to other keys. Used by CB_Keyboard. Type: boolean Default Value: true Source: CrossBase/CrossBase.js, line 206 &lt;static, constant&gt; CB_Keyboard_extended_WII_allowDuplicateKeyAliases :boolean Defines whether to allow Nintendo Wii codes (from the Wiimote) set in the CB_Keyboard.extended.WII object to be defined in the key aliases even if they use codes which belong to other keys. Used by CB_Keyboard. Type: boolean Default Value: true Source: CrossBase/CrossBase.js, line 186 &lt;static, constant&gt; CB_Net_Sockets_PREVENT_FIREFOX_ESC_BUG :boolean Defines whether we want to prevent the Firefox bug that affects SockJS library (see https://github.com/sockjs/sockjs-client/issues/18) or not. Used by CB_Keyboard. Type: boolean Default Value: true Source: CrossBase/CrossBase.js, line 176 &lt;static, constant&gt; CB_Net_XHR_PROXY_URL :string URL for the proxy to prevent cross-domain issues through AJAX, used by CB_Net.XHR.callProxy function. Can be relative to the main script folder or not, depending on CB_Configuration.CrossBase.CB_Net_XHR_PROXY_URL_RELATIVE. NOTE: Edit the \"CB_proxy.config.php\" file to configure the default proxy. Apart from configuring it, adding some security measures is highly recommended. Have in mind that, for safety reasons, the default proxy only allows to request the URLs defined in the \"$allowedURLs\" array in the \"CB_proxy.config.php\" file. Just edit it to allow other URLs. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"net/proxy/CB_proxy.php\" Source: CrossBase/CrossBase.js, line 458 &lt;static, constant&gt; CB_Net_XHR_PROXY_URL_RELATIVE :boolean Defines whether the URL for the proxy (defined in CB_Configuration.CrossBase.CB_Net_XHR_PROXY_URL) is relative to the main script folder or not. If it is relative, the \"onCall\" event of the CrossBase module will append the value of the \"scriptPathGiven\" parameter at the beginning. Type: boolean Default Value: true Source: CrossBase/CrossBase.js, line 166 &lt;static, constant&gt; CB_Screen_isFullScreen_ALLOWED_HEIGHT_MARGIN_PERCENTAGE :float Allowed height margin of the total screen available to consider whether it is in full screen or not. Needed by old web clients without Fullscreen API support, mainly. Used by the CB_Screen.isFullScreen function. Type: float Default Value: 3.5 Source: CrossBase/CrossBase.js, line 246 &lt;static, constant&gt; CB_Screen_isFullScreen_ALLOWED_WIDTH_MARGIN_PERCENTAGE :float Allowed width margin of the total screen available to consider whether it is in full screen or not. Needed by old web clients without Fullscreen API support, mainly. Used by the CB_Screen.isFullScreen function. Type: float Default Value: 3.9 Source: CrossBase/CrossBase.js, line 236 &lt;static, constant&gt; CB_Speaker_DEFAULT_VOLUME :integer Default volume for CB_Speaker (from 0 to 100). Type: integer Default Value: 100 Source: CrossBase/CrossBase.js, line 266 &lt;static, constant&gt; CORDOVAJS_LOAD :boolean Defines whether to try to load or not cordova.js (used by Apache Cordova). It should not be loaded together with phonegap.js, normally. If set to true, the checker defined at CB_Configuration.CrossBase.CORDOVAJS_LOAD_CHECKER will finally decide whether to load it or not. Type: boolean Default Value: !CB_Configuration.CrossBase.PHONEGAPJS_LOAD Source: CrossBase/CrossBase.js, line 931 &lt;static, constant&gt; CORDOVAJS_LOAD_CHECKER :CB_Modules.neededFile_LOAD_CHECKER Callback checker to determine whether cordova.js (used by Apache Cordova) is needed or not. Requires CB_Configuration.CrossBase.CORDOVAJS_LOAD set to true. Type: CB_Modules.neededFile_LOAD_CHECKER Default Value: function(currentPath, info) { return (typeof(window.cordova) === \"undefined\"); } Source: CrossBase/CrossBase.js, line 946 &lt;static, constant&gt; CORDOVAJS_PATH :string Directory that contains the \"cordova.js\" file (used by Apache Cordova). Type: string Source: CrossBase/CrossBase.js, line 956 &lt;static, constant&gt; CORDOVAJS_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.CORDOVAJS_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 976 &lt;static, constant&gt; CORDOVAJS_PATH_SCRIPT_FILE :string The script file path for the cordova.js file (used by Apache Cordova). Type: string Default Value: CB_Configuration.CrossBase.CORDOVAJS_PATH + \"cordova.js\" Source: CrossBase/CrossBase.js, line 966 &lt;static, constant&gt; EXCANVAS_LOAD :boolean Defines whether to load or not ExplorerCanvas. Type: boolean Default Value: CB_Configuration.CrossBase.needsExplorerCanvas() Source: CrossBase/CrossBase.js, line 1735 &lt;static, constant&gt; EXCANVAS_PATH :string Directory that contains the ExplorerCanvas files. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"audiovisual/image/canvas/excanvas_with_canvas_text/\" Source: CrossBase/CrossBase.js, line 1745 &lt;static, constant&gt; EXCANVAS_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.EXCANVAS_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1765 &lt;static, constant&gt; EXCANVAS_PATH_SCRIPT_FILE :string The script file path for ExplorerCanvas. Type: string Default Value: CB_Configuration.CrossBase.EXCANVAS_PATH + \"excanvas.js\" Source: CrossBase/CrossBase.js, line 1755 &lt;static, constant&gt; EXTEND_DOM :boolean Defines whether to allow to extend the DOM if needed or not. If set to true and some methods (as for example Array.indexOf, Array.lastIndexOf, Array.isArray, Array.forEach, NodeList.forEach, HTMLCollection.forEach, etc.) are not supported natively, they will be added. Type: boolean Source: CrossBase/CrossBase.js, line 86 &lt;static, constant&gt; FLASHCANVAS_ALLOW_RUN_LOCALLY_DEFAULT :boolean Defines whether to allow to run FlashCanvas locally or not (because the \".swf\" file folder needs to be added to 'trusted files' in Flash global configuration to work locally in some operating systems). Type: boolean Source: CrossBase/CrossBase.js, line 1611 &lt;static, constant&gt; FLASHCANVAS_DISABLE_CONTEXT_MENU :boolean Disables the context menu when the right mouse button is clicked on any canvas using FlashCanvas' SWF. Belongs to the \"disableContextMenu\" parameter of the library set on the \"window.FlashCanvasOptions\" object. More information: https://web.archive.org/web/20180604011002/http://flashcanvas.net/docs/config Type: boolean Source: CrossBase/CrossBase.js, line 1661 &lt;static, constant&gt; FLASHCANVAS_IMAGE_CACHE_SIZE :integer Maximum size for the image cache used by FlashCanvas. Belongs to the \"imageCacheSize\" parameter of the library set on the \"window.FlashCanvasOptions\" object. More information: https://web.archive.org/web/20180604011002/http://flashcanvas.net/docs/config Type: integer Source: CrossBase/CrossBase.js, line 1681 &lt;static, constant&gt; FLASHCANVAS_LOAD :boolean Defines whether to load or not FlashCanvas. Type: boolean Default Value: CB_Configuration.CrossBase.needsFlashCanvas() Source: CrossBase/CrossBase.js, line 1601 &lt;static, constant&gt; FLASHCANVAS_PATH :string Directory that contains the FlashCanvas files. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"audiovisual/image/canvas/FlashCanvas/pro/\" Source: CrossBase/CrossBase.js, line 1621 &lt;static, constant&gt; FLASHCANVAS_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.FLASHCANVAS_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1651 &lt;static, constant&gt; FLASHCANVAS_PATH_SCRIPT_FILE :string The script file path for FlashCanvas. Type: string Default Value: CB_Configuration.CrossBase.FLASHCANVAS_PATH + \"bin/flashcanvas.js\" Source: CrossBase/CrossBase.js, line 1631 &lt;static, constant&gt; FLASHCANVAS_PATH_SWF :string Directory that contains the SWF's for FlashCanvas. The value of the \"scriptPathGiven\" parameter will be attached at the beginning automatically. Belongs to the \"swfPath\" parameter of the library set on the \"window.FlashCanvasOptions\" object. More information: https://web.archive.org/web/20180604011002/http://flashcanvas.net/docs/config Type: string Default Value: CB_Configuration.CrossBase.FLASHCANVAS_PATH + \"bin/\" Source: CrossBase/CrossBase.js, line 1641 &lt;static, constant&gt; FLASHCANVAS_TURBO_MODE :boolean Uses turbo mode to speed up FlashCanvas. Belongs to the \"turbo\" parameter of the library set on the \"window.FlashCanvasOptions\" object. More information: https://web.archive.org/web/20180604011002/http://flashcanvas.net/docs/config Type: boolean Source: CrossBase/CrossBase.js, line 1671 &lt;static, constant&gt; GAMEPAD_PLUS_LOAD :boolean Defines whether to load or not gamepad-plus. Type: boolean Default Value: CB_Configuration.CrossBase.needsGamepadPlus() Source: CrossBase/CrossBase.js, line 1517 &lt;static, constant&gt; GAMEPAD_PLUS_PATH :string Directory that contains the gamepad-plus files. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"input/controllers/gamepad-plus/\" Source: CrossBase/CrossBase.js, line 1527 &lt;static, constant&gt; GAMEPAD_PLUS_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.GAMEPAD_PLUS_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1547 &lt;static, constant&gt; GAMEPAD_PLUS_PATH_SCRIPT_FILE :string The script file path for gamepad-plus. Type: string Default Value: CB_Configuration.CrossBase.GAMEPAD_PLUS_PATH + \"gamepads.js\" Source: CrossBase/CrossBase.js, line 1537 &lt;static, constant&gt; HAMMERJS_HAMMER_TIME_PATH_SCRIPT_FILE :string The script file path for Hammer Time. Type: string Default Value: CB_Configuration.CrossBase.HAMMERJS_PATH + \"hammer-time/hammer-time.min.js\" Source: CrossBase/CrossBase.js, line 1453 &lt;static, constant&gt; HAMMERJS_LOAD :boolean Defines whether to load or not Hammer.js and Hammer Time. Type: boolean Default Value: CB_Configuration.CrossBase.needsHammerJS() Source: CrossBase/CrossBase.js, line 1423 &lt;static, constant&gt; HAMMERJS_PATH :string Directory that contains the Hammer.js and Hammer Time files. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"input/hammer.js/\" Source: CrossBase/CrossBase.js, line 1433 &lt;static, constant&gt; HAMMERJS_PATH_ABSOLUTE :boolean Defines whether the paths defined in CB_Configuration.CrossBase.HAMMERJS_PATH_SCRIPT_FILE and CB_Configuration.CrossBase.HAMMERJS_HAMMER_TIME_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1463 &lt;static, constant&gt; HAMMERJS_PATH_SCRIPT_FILE :string The script file path for Hammer.js. Type: string Default Value: CB_Configuration.CrossBase.HAMMERJS_PATH + \"hammer.min.js\" Source: CrossBase/CrossBase.js, line 1443 &lt;static, constant&gt; INTELXDK_INITDEVJS_LOAD :boolean Defines whether to try to load or not init-dev.js (used by Intel XDK). If set to true, the checker defined at CB_Configuration.CrossBase.INTELXDK_INITDEVJS_LOAD_CHECKER will finally decide whether to load it or not. Type: boolean Source: CrossBase/CrossBase.js, line 836 &lt;static, constant&gt; INTELXDK_INITDEVJS_LOAD_CHECKER :CB_Modules.neededFile_LOAD_CHECKER Callback checker to determine whether init-dev.js (used by Intel XDK) is needed or not. Requires CB_Configuration.CrossBase.INTELXDK_INITDEVJS_LOAD set to true. Type: CB_Modules.neededFile_LOAD_CHECKER Default Value: false Source: CrossBase/CrossBase.js, line 847 &lt;static, constant&gt; INTELXDK_INITDEVJS_PATH :string Directory that contains the \"init-dev.js\" (used by Intel XDK). Type: string Source: CrossBase/CrossBase.js, line 857 &lt;static, constant&gt; INTELXDK_INITDEVJS_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.INTELXDK_INITDEVJS_PATH is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 877 &lt;static, constant&gt; INTELXDK_INITDEVJS_PATH_SCRIPT_FILE :string The script file path for init-dev.js file (used by Intel XDK). Type: string Default Value: CB_Configuration.CrossBase.INTELXDK_INITDEVJS_PATH + \"init-dev.js\" Source: CrossBase/CrossBase.js, line 867 &lt;static, constant&gt; INTELXDKJS_LOAD :boolean Defines whether to load or not intelxdk.js (used by Intel XDK). Type: boolean Source: CrossBase/CrossBase.js, line 796 &lt;static, constant&gt; INTELXDKJS_PATH :string Directory that contains the \"intelxdk.js\" file (used by Intel XDK). Type: string Source: CrossBase/CrossBase.js, line 806 &lt;static, constant&gt; INTELXDKJS_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.INTELXDKJS_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 826 &lt;static, constant&gt; INTELXDKJS_PATH_SCRIPT_FILE :string The script file path for intelxdk.js (used by Intel XDK). Type: string Default Value: CB_Configuration.CrossBase.INTELXDKJS_PATH + \"intelxdk.js\" Source: CrossBase/CrossBase.js, line 816 &lt;static, constant&gt; JSFX_LOAD :boolean Defines whether to load or not jsfx. Type: boolean Default Value: CB_Configuration.CrossBase.needsJsfx() Source: CrossBase/CrossBase.js, line 1297 &lt;static, constant&gt; JSFX_PATH :string Directory that contains the jsfx files. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"audiovisual/audio/jsfx/\" Source: CrossBase/CrossBase.js, line 1307 &lt;static, constant&gt; JSFX_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.JSFX_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1327 &lt;static, constant&gt; JSFX_PATH_SCRIPT_FILE :string The script file path for jsfx. Type: string Default Value: CB_Configuration.CrossBase.JSFX_PATH + \"jsfx.js\" Source: CrossBase/CrossBase.js, line 1317 &lt;static, constant&gt; LOCALSTORAGE_POLYFILL_LOAD :boolean Defines whether to load or not localStorage polyfill. Type: boolean Source: CrossBase/CrossBase.js, line 988 &lt;static, constant&gt; LOCALSTORAGE_POLYFILL_PATH :string Directory that contains the localStorage polyfill files. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"general/localStorage/\" Source: CrossBase/CrossBase.js, line 998 &lt;static, constant&gt; LOCALSTORAGE_POLYFILL_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.LOCALSTORAGE_POLYFILL_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1029 &lt;static, constant&gt; LOCALSTORAGE_POLYFILL_PATH_SCRIPT_FILE :string The script file path for localStorage polyfill. Type: string Default Value: CB_Configuration.CrossBase.LOCALSTORAGE_POLYFILL_PATH + \"localStorage.min.js?swfURL=\" + CB_Configuration[CB_BASE_NAME].LOCALSTORAGE_POLYFILL_PATH_SWF_FILE Source: CrossBase/CrossBase.js, line 1019 &lt;static, constant&gt; LOCALSTORAGE_POLYFILL_PATH_SWF :string Directory that contains the SWF for localStorage polyfill. The value of the \"scriptPathGiven\" parameter will be attached at the beginning automatically. Belongs to the \"swfURL\" parameter (URL \"GET\" parameter) of the library when the localStorage script file is attached. Type: string Default Value: CB_Configuration.CrossBase.LOCALSTORAGE_POLYFILL_PATH + \"localStorage.swf\" Source: CrossBase/CrossBase.js, line 1008 &lt;static, constant&gt; MIND_IFRAMES :boolean Defines whether to have in mind possible iframes that could contain the script or not. Used by some functions of CB_Client, CB_Events, etc. Type: boolean Default Value: true Source: CrossBase/CrossBase.js, line 76 &lt;static, constant&gt; NOSLEEP_LOAD :boolean Defines whether to load or not NoSleep.js. Type: boolean Default Value: CB_Configuration.CrossBase.needsSleepJS() Source: CrossBase/CrossBase.js, line 1339 &lt;static, constant&gt; NOSLEEP_PATH :string Directory that contains the NoSleep.js files. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"audiovisual/image/NoSleep/\" Source: CrossBase/CrossBase.js, line 1349 &lt;static, constant&gt; NOSLEEP_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.NOSLEEP_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1369 &lt;static, constant&gt; NOSLEEP_PATH_SCRIPT_FILE :string The script file path for NoSleep.js. Type: string Default Value: CB_Configuration.CrossBase.NOSLEEP_PATH + \"NoSleep.min.js\" Source: CrossBase/CrossBase.js, line 1359 &lt;static, constant&gt; PHONEGAPJS_LOAD :boolean Defines whether to load or not phonegap.js (used by Adobe PhoneGap). Type: boolean Source: CrossBase/CrossBase.js, line 889 &lt;static, constant&gt; PHONEGAPJS_PATH :string Directory that contains the \"phonegap.js\" (used by Adobe PhoneGap) file. Type: string Source: CrossBase/CrossBase.js, line 899 &lt;static, constant&gt; PHONEGAPJS_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.PHONEGAPJS_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 919 &lt;static, constant&gt; PHONEGAPJS_PATH_SCRIPT_FILE :string The script file path for phonegap.js (used by Adobe PhoneGap). Type: string Default Value: CB_Configuration.CrossBase.PHONEGAPJS_PATH + \"phonegap.js\" Source: CrossBase/CrossBase.js, line 909 &lt;static, constant&gt; PRESSUREJS_LOAD :boolean Defines whether to load or not Pressure.js. Type: boolean Default Value: CB_Configuration.CrossBase.needsPressureJS() Source: CrossBase/CrossBase.js, line 1381 &lt;static, constant&gt; PRESSUREJS_PATH :string Directory that contains the Pressure.js files. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"input/pressure.js/\" Source: CrossBase/CrossBase.js, line 1391 &lt;static, constant&gt; PRESSUREJS_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.PRESSUREJS_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1411 &lt;static, constant&gt; PRESSUREJS_PATH_SCRIPT_FILE :string The script file path for Pressure.js. Type: string Default Value: CB_Configuration.CrossBase.PRESSUREJS_PATH + \"pressure.min.js\" Source: CrossBase/CrossBase.js, line 1401 &lt;static, constant&gt; SCRIPT_PATH :string Path to the CrossBase module, relative to the CrossBrowdy folder. Type: string Default Value: CB_BASE_NAME + \"/\" Source: CrossBase/CrossBase.js, line 66 &lt;static, constant&gt; SLCANVAS_LOAD :boolean Defines whether to load or not SLCanvas. Type: boolean Default Value: CB_Configuration.CrossBase.needsSLCanvas() Source: CrossBase/CrossBase.js, line 1693 &lt;static, constant&gt; SLCANVAS_PATH :string Directory that contains the SLCanvas files. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"audiovisual/image/canvas/slcanvas/\" Source: CrossBase/CrossBase.js, line 1703 &lt;static, constant&gt; SLCANVAS_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.SLCANVAS_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1723 &lt;static, constant&gt; SLCANVAS_PATH_SCRIPT_FILE :string The script file path for SLCanvas. Type: string Default Value: CB_Configuration.CrossBase.SLCANVAS_PATH + \"slcanvas.js\" Source: CrossBase/CrossBase.js, line 1713 &lt;static, constant&gt; SM2_AUDIO_FORMATS_REQUIRED :Object Object with the required formats for SoundManager 2. If the format is required and the web client doesn't support it, SoundManager 2 will use Flash. More information: http://www.schillmania.com/projects/soundmanager2/doc/#soundmanager-audioformats Type: Object Properties: Name Type Default Description mp3 boolean false Defines MP3 format as required. mp4 boolean false Defines MP4 format as required. ogg boolean false Defines OGG format as required. opus boolean false Defines OPUS format as required. wav boolean false Defines WAV format as required. Source: CrossBase/CrossBase.js, line 1258 &lt;static, constant&gt; SM2_LOAD :boolean Defines whether to load or not SoundManager 2. Type: boolean Source: CrossBase/CrossBase.js, line 1208 &lt;static, constant&gt; SM2_PATH :string Directory that contains the SoundManager 2 files. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"audiovisual/audio/soundmanager2/\" Source: CrossBase/CrossBase.js, line 1218 &lt;static, constant&gt; SM2_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.SM2_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1248 &lt;static, constant&gt; SM2_PATH_SCRIPT_FILE :string The script file path for SoundManager 2. Type: string Default Value: CB_Configuration.CrossBase.SM2_PATH + \"script/soundmanager2-nodebug-jsmin.js\" Source: CrossBase/CrossBase.js, line 1228 &lt;static, constant&gt; SM2_PATH_SWF :string Directory that contains the SWF's for SoundManager 2. The value of the \"scriptPathGiven\" parameter will be attached at the beginning automatically. Belongs to the \"url\" parameter of the library when soundManager.setup\"&gt;www.schillmania.com/projects/soundmanager2/doc/#soundmanager-setup} function is called. More information: http://www.schillmania.com/projects/soundmanager2/doc/#soundmanager-url Type: string Default Value: CB_Configuration.CrossBase.SM2_PATH + \"swf/\" Source: CrossBase/CrossBase.js, line 1238 &lt;static, constant&gt; SM2_TIMEOUT_MS :integer Milliseconds to wait after loading SoundManager 2 to define it as not supported if there is no response. Belongs to the \"flashLoadTimeout\" parameter of the library when soundManager.setup\"&gt;www.schillmania.com/projects/soundmanager2/doc/#soundmanager-setup} function is called. More information: http://www.schillmania.com/projects/soundmanager2/doc/#soundmanager-flashloadtimeout Type: integer Source: CrossBase/CrossBase.js, line 1283 &lt;static, constant&gt; SM2_USE_HIGH_PERFORMANCE :boolean Defines whether to use or not high performance mode in SoundManager 2 (may cause a flash object to be visible). Belongs to the \"useHighPerformance\" parameter of the library when soundManager.setup\"&gt;www.schillmania.com/projects/soundmanager2/doc/#soundmanager-setup} function is called. More information: http://www.schillmania.com/projects/soundmanager2/doc/#soundmanager-highperformance Type: boolean Source: CrossBase/CrossBase.js, line 1273 &lt;static, constant&gt; SOCKJS_PATH :string Directory that contains the SockJS library files. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"net/sockets/SockJS/\" Source: CrossBase/CrossBase.js, line 770 &lt;static, constant&gt; SOCKJS_PATH_SCRIPT_FILE :string The script file path for the SockJS library. As the newer SockJS library versions do not work in old Internet Explorer versions (6, 7 or 8), if they are detected it will use the SockJS library 0.3.4 version instead. Type: string Default Value: CB_Configuration[CB_BASE_NAME].SOCKJS_PATH + SOCKJS_SCRIPT_FILE, where \"SOCKJS_SCRIPT_FILE\" is sockjs-0.3.4.min.js (SockJS 0.3.4), sockjs-1.1.1.min.js (SockJS 1.1.1) or sockjs.min.js (last version) depending on the client detected. Source: CrossBase/CrossBase.js, line 781 &lt;static, constant&gt; SUBCOLLIDERJS_LOAD :boolean Defines whether to load or not subcollider.js. Type: boolean Default Value: CB_Configuration.CrossBase.TIMBREJS_LOAD Source: CrossBase/CrossBase.js, line 1124 &lt;static, constant&gt; SUBCOLLIDERJS_PATH :string Directory that contains the subcollider.js script. Type: string Default Value: CB_Configuration.CrossBase.TIMBREJS_PATH + \"subcollider/\" Source: CrossBase/CrossBase.js, line 1134 &lt;static, constant&gt; SUBCOLLIDERJS_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.SUBCOLLIDERJS_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1154 &lt;static, constant&gt; SUBCOLLIDERJS_PATH_SCRIPT_FILE :string The script file path for subcollider.js. Type: string Default Value: CB_Configuration.CrossBase.SUBCOLLIDERJS_PATH + \"subcollider.js\" Source: CrossBase/CrossBase.js, line 1144 &lt;static, constant&gt; TIMBREJS_LOAD :boolean Defines whether to load or not timbre.js. Type: boolean Default Value: CB_Configuration.CrossBase.needsTimbreJS() Source: CrossBase/CrossBase.js, line 1084 &lt;static, constant&gt; TIMBREJS_PATH :string Directory that contains the timbre.js files (script and SWF). Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"audiovisual/audio/timbre.js/\" Source: CrossBase/CrossBase.js, line 1094 &lt;static, constant&gt; TIMBREJS_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.TIMBREJS_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1114 &lt;static, constant&gt; TIMBREJS_PATH_SCRIPT_FILE :string The script file path for timbre.js. Type: string Default Value: CB_Configuration.CrossBase.TIMBREJS_PATH + \"timbre.js\" Source: CrossBase/CrossBase.js, line 1104 &lt;static, constant&gt; WAAPI_EMULATION_ALLOWED :boolean Defines whether to allow using \"WAAPI\" (HTML5 Web Audio API) emulation (it will use WAAPISim if needed) or not. Type: boolean Default Value: true Source: CrossBase/CrossBase.js, line 256 &lt;static, constant&gt; WAAPISIM_LOAD :boolean Defines whether to load or not WAAPISim. Type: boolean Default Value: CB_Configuration.CrossBase.WAAPI_EMULATION_ALLOWED &amp;&amp; CB_Configuration.CrossBase.needsWAAPISim() Source: CrossBase/CrossBase.js, line 1041 &lt;static, constant&gt; WAAPISIM_PATH :string Directory that contains the WAAPISim files (script and SWF). Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"audiovisual/audio/WAAPISim/\" Source: CrossBase/CrossBase.js, line 1052 &lt;static, constant&gt; WAAPISIM_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.WAAPISIM_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1072 &lt;static, constant&gt; WAAPISIM_PATH_SCRIPT_FILE :string The script file path for the WAAPISim script file. Type: string Default Value: CB_Configuration.CrossBase.WAAPISIM_PATH + \"waapisim.min.js\" Source: CrossBase/CrossBase.js, line 1062 &lt;static, constant&gt; WII_JS_LOAD :boolean Defines whether to load or not wii-js. Type: boolean Source: CrossBase/CrossBase.js, line 1475 &lt;static, constant&gt; WII_JS_PATH :string Directory that contains the wii-js script. Type: string Default Value: CB_Configuration.CrossBase.SCRIPT_PATH + \"input/controllers/wii-js/\" Source: CrossBase/CrossBase.js, line 1485 &lt;static, constant&gt; WII_JS_PATH_ABSOLUTE :boolean Defines whether the path defined in CB_Configuration.CrossBase.WII_JS_PATH_SCRIPT_FILE is either absolute or relative to the CrossBrowdy script path. Type: boolean Source: CrossBase/CrossBase.js, line 1505 &lt;static, constant&gt; WII_JS_PATH_SCRIPT_FILE :string The script file path for wii-js. Type: string Default Value: CB_Configuration.CrossBase.WII_JS_PATH + \"wii.min.js\" Source: CrossBase/CrossBase.js, line 1495 Methods &lt;static&gt; needsCanbox() → {boolean} Detects whether the web client needs Canbox or not. Source: CrossBase/CrossBase.js, line 548 Returns: Type boolean &lt;static&gt; needsCanvasText() → {boolean} Detects whether the web client needs canvas-text or not. Source: CrossBase/CrossBase.js, line 642 Returns: Type boolean &lt;static&gt; needsExplorerCanvas() → {boolean} Detects whether the web client needs ExplorerCanvas or not. Source: CrossBase/CrossBase.js, line 571 Returns: Type boolean &lt;static&gt; needsFlashCanvas() → {boolean} Detects whether the web client needs FlashCanvas or not. Source: CrossBase/CrossBase.js, line 620 Returns: Type boolean &lt;static&gt; needsGamepadPlus() → {boolean} Detects whether the web client needs gamepad-plus or not. Source: CrossBase/CrossBase.js, line 740 To Do: Find a better way for this as old Firefox versions can only detect GamePad API support when the events are fired, so we cannot relay on navigator.getGamepads/navigator.webkitGetGamepads/navigator.webkitGamepads. Returns: Type boolean &lt;static&gt; needsHammerJS() → {boolean} Detects whether the web client needs Hammer.js or not. Source: CrossBase/CrossBase.js, line 726 Returns: Type boolean &lt;static&gt; needsJsfx() → {boolean} Detects whether the web client needs jsfx or not. Source: CrossBase/CrossBase.js, line 698 Returns: Type boolean &lt;static&gt; needsPressureJS() → {boolean} Detects whether the web client needs Pressure.js or not. Source: CrossBase/CrossBase.js, line 712 Returns: Type boolean &lt;static&gt; needsSLCanvas() → {boolean} Detects whether the web client needs SLCanvas or not. Source: CrossBase/CrossBase.js, line 594 Returns: Type boolean &lt;static&gt; needsSleepJS() → {boolean} Detects whether the web client needs NoSleep.js or not. Source: CrossBase/CrossBase.js, line 755 Returns: Type boolean &lt;static&gt; needsTimbreJS() → {boolean} Detects whether the web client needs timbre.js (including subcollider.js) or not. Source: CrossBase/CrossBase.js, line 684 Returns: Type boolean &lt;static&gt; needsWAAPISim() → {boolean} Detects whether the web client needs WAAPISim or not. Source: CrossBase/CrossBase.js, line 474 Returns: Type boolean × Search results Close "},"CB_Configuration.CrossBrowdy.html":{"id":"CB_Configuration.CrossBrowdy.html","title":"Namespace: CrossBrowdy","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CrossBrowdy CB_Configuration. CrossBrowdy Property that contains an object with the options for the main script. Source: CrossBrowdy.js, line 68 Members &lt;static, constant&gt; CB_console_ALLOW_ALERTS :boolean Defines whether to allow the use of alert()'s as a fallback when using CB_console and neither the console object nor a DOM element with \"CB_console\" ID are found. Type: boolean Default Value: true Source: CrossBrowdy.js, line 123 &lt;static, constant&gt; CB_includeJSFile_TIMEOUT_MS_DEFAULT :int Default milliseconds before firing the timeout callback for the CB_includeJSFile function. Type: int Default Value: 90000 Source: CrossBrowdy.js, line 133 &lt;static, constant&gt; SCRIPT_PATH_DEFAULT :string Default path of the script (path can be changed when CB_init is called) Type: string Default Value: CB_NAME + \"/\" Source: CrossBrowdy.js, line 81 &lt;static, constant&gt; SHOW_SPLASH_SCREEN_DEFAULT :boolean Defines whether to show the splash screen in the beginning by default or not. Type: boolean Default Value: true Source: CrossBrowdy.js, line 91 &lt;static, constant&gt; STATS :boolean Defines whether to register statistics or not. If it is enabled, the URL defined in CB_Configuration.CrossBrowdy.STATS_URL will be called (by including it as a JavaScript file) as soon as CrossBrowdy gets called (might not be ready yet).This parameter do not do anything else, just includes your desired URL (defined in CB_Configuration.CrossBrowdy.STATS_URL) as a JavaScript file when CrossBrowdy is called. Type: boolean Default Value: false Source: CrossBrowdy.js, line 102 &lt;static, constant&gt; STATS_URL :string URL to register the statistics if CB_Configuration.CrossBrowdy.STATS is enabled. When CB_Configuration.CrossBrowdy.STATS is enabled, this URL will be included as a JavaScript file as soon as CrossBrowdy gets called (might not be ready yet).The URL will be called (included in the document as a JavaScript file) adding three parameters: \"cb\" parameter with the CrossBrowdy version as the value, \"time\" with a timestamp which belongs to the current time of the client and \"url\" parameter with the current URL visited by the user as the value. Type: string Default Value: https://crossbrowdy.com/_stats/CB_stats.php Source: CrossBrowdy.js, line 113 × Search results Close "},"CB_Controllers.html":{"id":"CB_Controllers.html","title":"Namespace: CB_Controllers","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Controllers CB_Controllers Static class to manage different controllers (gamepads, joysticks, remotes, etc.). It will return itself if it is tried to be instantiated. It uses gamepad-plus. Source: CrossBase/input/controllers/CB_Controllers.js, line 8 To Do: Find a way to do button mapping (so we could use names as LEFT, RIGHT, etc.) and normalization for most web clients and gamepads (without forgetting proprietary ones as WII U, etc.). Consider using always a numeric index instead of the ID of the gamepad (array instead of object), which could be a string, for CB_Controllers._gamepads (for optimization purposes). Consider modifying CB_Controllers.isButtonDown function or add a new one to check whether any button (or axes) is down or not. Methods &lt;static&gt; getAxes( [gamepadId] [, gamepadIdNumeric] [, caseSensitive] [, avoidProprietary]) → {array} Gets an array with information about the status of the axes of a given gamepad (or from all if none is given). Parameters: Name Type Argument Default Description gamepadId integer | string &lt;optional&gt; \"\" If an empty string is given, all gamepads available will be checked. Otherwise, it will only check the gamepad with the given ID or index (if any). When more than one gamepad is checked, the first axes values found which are not zero (0) will have priority. gamepadIdNumeric boolean &lt;optional&gt; false|true If the \"gamepadId\" parameter is an empty string, this parameter will be ignored. Otherwise, if the \"gamepadId\" parameter is not empty and this parameter is set to true, the gamepadId parameter will be converted to integer using \"parseInt\" internally. By default, this parameter is false unless the given \"gamepadId\" is numeric. caseSensitive boolean &lt;optional&gt; false Defines whether the \"gamepadId\" given should match the ID of the gamepad being case sensitive or not. This parameter will only be considered when the \"gamepadIdNumeric\" parameter is set to false. avoidProprietary boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Controllers_avoidProprietary_DEFAULT If set to true, proprietary gamepads will not be checked (performance will be faster). Source: CrossBase/input/controllers/CB_Controllers.js, line 321 Returns: Returns an array with information about the status of the axes of a given gamepad (or from all if none is given). Type array &lt;static&gt; getAxesDown( [gamepadId] [, minimumValue] [, maximumValue] [, gamepadIdNumeric] [, caseSensitive] [, avoidProprietary]) → {Object} Gets an array with the axes pressed of a given gamepad (or from all if none is given). If more than one gamepad is pressing the same axis, it will return the value of the first one found. Parameters: Name Type Argument Default Description gamepadId integer | string &lt;optional&gt; \"\" If an empty string is given, all gamepads available will be checked. Otherwise, it will only check the gamepad with the given ID or index (if any). minimumValue float &lt;optional&gt; 0.5 The minimum value (included) that the checked axis or axes must have to consider them to be pressed. maximumValue float &lt;optional&gt; 1|-0.5 The maximum value (included) that the checked axis or axes must have to consider them to be pressed. The default value will be -0.5 if the given \"minimumValue\" is negative or zero (0) or it will be 1 otherwise. gamepadIdNumeric boolean &lt;optional&gt; false|true If the \"gamepadId\" parameter is an empty string, this parameter will be ignored. Otherwise, if the \"gamepadId\" parameter is not empty and this parameter is set to true, the gamepadId parameter will be converted to integer using \"parseInt\" internally. By default, this parameter is false unless the given \"gamepadId\" is numeric. caseSensitive boolean &lt;optional&gt; false Defines whether the \"gamepadId\" given should match the ID of the gamepad being case sensitive or not. This parameter will only be considered when the \"gamepadIdNumeric\" parameter is set to false. avoidProprietary boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Controllers_avoidProprietary_DEFAULT If set to true, proprietary gamepads will not be checked (performance will be faster). Source: CrossBase/input/controllers/CB_Controllers.js, line 379 Returns: Returns an array with the axes pressed of a given gamepad (or from all if none is given). If more than one gamepad is pressing the same axis, it will return the value of the first one found. Type Object &lt;static&gt; getButtons( [gamepadId] [, gamepadIdNumeric] [, caseSensitive] [, avoidProprietary]) → {Object} Gets an object with all the buttons of a given gamepad (or from all if none is given). Parameters: Name Type Argument Default Description gamepadId integer | string &lt;optional&gt; \"\" If an empty string is given, all gamepads available will be checked. Otherwise, it will only check the gamepad with the given ID or index (if any). gamepadIdNumeric boolean &lt;optional&gt; false|true If the \"gamepadId\" parameter is an empty string, this parameter will be ignored. Otherwise, if the \"gamepadId\" parameter is not empty and this parameter is set to true, the gamepadId parameter will be converted to integer using \"parseInt\" internally. By default, this parameter is false unless the given \"gamepadId\" is numeric. caseSensitive boolean &lt;optional&gt; false Defines whether the \"gamepadId\" given should match the ID of the gamepad being case sensitive or not. This parameter will only be considered when the \"gamepadIdNumeric\" parameter is set to false. avoidProprietary boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Controllers_avoidProprietary_DEFAULT If set to true, proprietary gamepads will not be checked (performance will be faster). Source: CrossBase/input/controllers/CB_Controllers.js, line 476 Returns: Returns an object with all the buttons of a given gamepad (or from all if none is given). The indexes will be the button code and the values will be an object with information about the button (with properties such as \"pressed\", \"value\", etc.). Type Object &lt;static&gt; getButtonsDown( [gamepadId] [, gamepadIdNumeric] [, caseSensitive] [, avoidProprietary]) → {Object} Gets an object with the buttons pressed of a given gamepad (or from all if none is given). Parameters: Name Type Argument Default Description gamepadId integer | string &lt;optional&gt; \"\" If an empty string is given, all gamepads available will be checked. Otherwise, it will only check the gamepad with the given ID or index (if any). gamepadIdNumeric boolean &lt;optional&gt; false|true If the \"gamepadId\" parameter is an empty string, this parameter will be ignored. Otherwise, if the \"gamepadId\" parameter is not empty and this parameter is set to true, the gamepadId parameter will be converted to integer using \"parseInt\" internally. By default, this parameter is false unless the given \"gamepadId\" is numeric. caseSensitive boolean &lt;optional&gt; false Defines whether the \"gamepadId\" given should match the ID of the gamepad being case sensitive or not. This parameter will only be considered when the \"gamepadIdNumeric\" parameter is set to false. avoidProprietary boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Controllers_avoidProprietary_DEFAULT If set to true, proprietary gamepads will not be checked (performance will be faster). Source: CrossBase/input/controllers/CB_Controllers.js, line 522 Returns: Returns an object with the buttons pressed of a given gamepad (or from all if none is given). Type Object &lt;static&gt; getGamePads( [avoidProprietary]) → {Object} Returns an object with the current gamepad objects, if any (using the GamePad API for non-proprietary gamepads). Parameters: Name Type Argument Default Description avoidProprietary boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Controllers_avoidProprietary_DEFAULT If set to true, proprietary gamepads which do not use the GamePad API (as WII, WI U gamepads, etc.) will not be included in the returning object and it will only include the ones detected by the GamePad API. Otherwise, if set to true, the returning object will contain one property called \"standard\" which will contain an object with the \"gamepads\" property with the gamepad objects that use the GamePad API and possibly different properties (one per each proprietary system) and inside of them an object with the \"gamepads\" property and maybe also other properties for other kind of devices which will include the status objects of those devices for each proprietary system. For gamepads that support the GamePad API, the indexes will be the identifier for each gamepad and the value its gamepad object. For proprietary gamepads, it will contain the returning value of the \"getGamePads\" function of each proprietary API. Source: CrossBase/input/controllers/CB_Controllers.js, line 582 To Do: The proprietary ones should return better-normalized values to simulate the GamePad API. Returns: Returns an object with the current gamepad objects, if any (using the GamePad API for non-proprietary gamepads). Type Object &lt;static&gt; isAxisDown(axesNumbers [, gamepadId] [, minimumValue] [, maximumValue] [, allPressed] [, gamepadIdNumeric] [, caseSensitive] [, avoidProprietary]) → {boolean} Returns whether a given axis or axes are being pressed or not (accepts one index or more than one with an array). Parameters: Name Type Argument Default Description axesNumbers integer | array Number with the index of the axis or array of numbers with the indexes of the axes that we want to check. gamepadId integer | string &lt;optional&gt; \"\" If an empty string is given, all gamepads available will be checked. Otherwise, it will only check the gamepad with the given ID or index (if any). minimumValue float &lt;optional&gt; 0.5 The minimum value (included) that the checked axis or axes must have to consider them to be pressed. maximumValue float &lt;optional&gt; 1|-0.5 The maximum value (included) that the checked axis or axes must have to consider them to be pressed. The default value will be -0.5 if the given \"minimumValue\" is negative or zero (0) or it will be 1 otherwise. allPressed boolean &lt;optional&gt; false If set to true, the function will return true only in the case that all given axes are being pressed. In the case that this parameter is set to true and the \"gamepadId\" parameter is set to an empty string, it will not have in mind whether the axes are pressed by a unique gamepad or by different ones as long as all axes are pressed. gamepadIdNumeric boolean &lt;optional&gt; false|true If the \"gamepadId\" parameter is an empty string, this parameter will be ignored. Otherwise, if the \"gamepadId\" parameter is not empty and this parameter is set to true, the gamepadId parameter will be converted to integer using \"parseInt\" internally. By default, this parameter is false unless the given \"gamepadId\" is numeric. caseSensitive boolean &lt;optional&gt; false Defines whether the \"gamepadId\" given should match the ID of the gamepad being case sensitive or not. This parameter will only be considered when the \"gamepadIdNumeric\" parameter is set to false. avoidProprietary boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Controllers_avoidProprietary_DEFAULT If set to true, proprietary gamepads will not be checked (performance will be faster). Source: CrossBase/input/controllers/CB_Controllers.js, line 399 To Do: Make it compatible with proprietary gamepads (if possible). Returns: If the \"allPressed\" parameter is false, returns true if the given code or any of the given codes is pressed. If the \"allPressed\" parameter is set to true, it will return true only in the case that all given axes are being pressed. In the case that the \"allPressed\" parameter is set to true and the gamepadId parameter is set to an empty string, it will not have in mind whether the axes are pressed by a unique gamepad or by different ones as long as all axes are pressed. Type boolean &lt;static&gt; isButtonDown(buttonCodes [, gamepadId] [, allPressed] [, gamepadIdNumeric] [, caseSensitive] [, avoidProprietary]) → {boolean} Returns whether a given button or buttons are being pressed or not (accepts one key code or more than one with an array). Parameters: Name Type Argument Default Description buttonCodes integer | array Number with the button code or array of numbers with the button codes that we want to check. gamepadId integer | string &lt;optional&gt; \"\" If an empty string is given, all gamepads available will be checked. Otherwise, it will only check the gamepad with the given ID or index (if any). allPressed boolean &lt;optional&gt; false If set to true, the function will return true only in the case that all given buttons are being pressed. In the case that this parameter is set to true and the \"gamepadId\" parameter is set to an empty string, it will not have in mind whether the buttons are pressed by a unique gamepad or by different ones as long as all buttons are pressed. gamepadIdNumeric boolean &lt;optional&gt; false|true If the \"gamepadId\" parameter is an empty string, this parameter will be ignored. Otherwise, if the \"gamepadId\" parameter is not empty and this parameter is set to true, the gamepadId parameter will be converted to integer using \"parseInt\" internally. By default, this parameter is false unless the given \"gamepadId\" is numeric. caseSensitive boolean &lt;optional&gt; false Defines whether the \"gamepadId\" given should match the ID of the gamepad being case sensitive or not. This parameter will only be considered when the \"gamepadIdNumeric\" parameter is set to false. avoidProprietary boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Controllers_avoidProprietary_DEFAULT If set to true, proprietary gamepads will not be checked (performance will be faster). Source: CrossBase/input/controllers/CB_Controllers.js, line 540 To Do: Make it compatible with proprietary gamepads (if possible). Returns: If the \"allPressed\" parameter is false, returns true if the given code or any of the given codes is pressed. If the \"allPressed\" parameter is set to true, it will return true only in the case that all given buttons are being pressed. In the case that the \"allPressed\" parameter is set to true and the gamepadId parameter is set to an empty string, it will not have in mind whether the buttons are pressed by a unique gamepad or by different ones as long as all buttons are pressed. Type boolean &lt;static&gt; onConnect(callbackFunction [, keepOldFunction]) Sets a function to execute when a gamepad is connected (\"onGamepadConnected\" event is fired) or removes it. More information: Gamepad API. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first parameter received for this function will be the gamepad object affected and the second parameter will be an object containing all current gamepads objects (properties will be the index of each gamepad). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. Source: CrossBase/input/controllers/CB_Controllers.js, line 176 To Do: Make it compatible with proprietary ones (if possible). &lt;static&gt; onDisconnect(callbackFunction [, keepOldFunction]) Sets a function to execute when a gamepad is disconnected (\"onGamepadDisconnected\" event is fired) or removes it. More information: Gamepad API. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first parameter received for this function will be the gamepad object affected and the second parameter will be an object containing all current gamepads objects (properties will be the index of each gamepad). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. Source: CrossBase/input/controllers/CB_Controllers.js, line 189 To Do: Make it compatible with proprietary ones (if possible). × Search results Close "},"CB_Controllers_Proprietary.html":{"id":"CB_Controllers_Proprietary.html","title":"Namespace: CB_Controllers_Proprietary","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Controllers_Proprietary CB_Controllers_Proprietary Static class to manage proprietary controller APIs. Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII.js, line 7 Namespaces WII WII_U × Search results Close "},"CB_Controllers_Proprietary.WII.html":{"id":"CB_Controllers_Proprietary.WII.html","title":"Namespace: WII","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: WII CB_Controllers_Proprietary. WII Static class to manage the Nintendo Wii remotes (Wiimotes). It will return itself if it is tried to be instantiated. It uses wii-js. NOTE: This class is still under development. Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII.js, line 12 To Do: Find a way to know how to check when a button is released. Update values of CB_Controllers_Proprietary.WII._wiimotes[x].UP, etc. Do not forget x and y properties (?). Methods &lt;static&gt; getGamePads() → {Object} Returns an object with all gamepads simulating the GamePad API. Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII.js, line 143 Returns: Returns an object with the \"remotes\" property which contains another object whose properties are the index of each device and the value an object with the status of that device. The number of remotes is 4 (index from \"0\" to \"3\"). Simulating the GamePad API. Those status objects which are not using the real API will have a property called \"usingPrototype\" set to true. Type Object × Search results Close "},"CB_Controllers_Proprietary.WII_U.html":{"id":"CB_Controllers_Proprietary.WII_U.html","title":"Namespace: WII_U","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: WII_U CB_Controllers_Proprietary. WII_U Static class to manage the Nintendo Wii U gamepad and remotes. It will return itself if it is tried to be instantiated. NOTE: This class is still under development. Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js, line 7 To Do: Function or option that returns an array with the pressed buttons (LEFT: true, L: true, R: false, etc.). Use the bitmasks of CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS and CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS. Members &lt;static, constant&gt; GAMEPAD_BUTTONS :Object Object which keeps the values for the Nintendo Wii U gamepad's buttons (bitmasks). Type: Object Properties: Name Type Description LEFT_STICK_LEFT number LEFT on the LEFT STICK. Default action: Scroll/Pan. LEFT_STICK_RIGHT number RIGHT on the LEFT STICK. Default action: Scroll/Pan. LEFT_STICK_UP number UP on the LEFT STICK. Default action: Scroll/Pan. LEFT_STICK_DOWN number DOWN on the LEFT STICK. Default action: Scroll/Pan. LEFT_STICK_CLICK number CLICK on the LEFT STICK. Default action: Hide/show bottom toolbar. RIGHT_STICK_LEFT number LEFT on the RIGHT STICK. Default action: Zoom. RIGHT_STICK_RIGHT number RIGHT on the RIGHT STICK. Default action: Zoom. RIGHT_STICK_UP number UP on the RIGHT STICK. Default action: Zoom. RIGHT_STICK_DOWN number DOWN on the RIGHT STICK. Default action: Zoom. RIGHT_STICK_CLICK number CLICK on the RIGHT STICK. Default actionn: Toggle zoom in/out on center of screen. TV number \"TV\" button. A number \"A\" button. Send the \"Enter\" key (keyCode 13). B number \"B\" button. Default action: Back to previous page (hold B: Close current tab). X number \"X\" button. Default action: Toggle curtain mode. Y number \"Y\" button. Default action: View bookmarks. LEFT number LEFT button on the control pad. Default action: Select links / form fields. RIGHT number RIGHT button on the control pad. Default action: Select links / form fields. UP number UP button on the control pad. Default action: Select links / form fields. DOWN number DOWN button on the control pad. Default action: Select links / form fields. ZL number \"ZL\" button. Default action: Switch to previous tab (hold ZL+ZR: Tilt scrolling). ZR number \"ZR\" button. Default action: Switch to next tab (hold ZL+ZR: Tilt scrolling). L number \"L\" button. Default action: Back to previous page. R number \"R\" button. Default action: Forward to next page. START number \"START\" button. PLUS number Alias for CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.START. SELECT number \"SELECT\" button. MINUS number Alias for CB_Controllers_Proprietary.WII_U.GAMEPAD_BUTTONS.SELECT. HOME number HOME button. Default action: Quit browser. Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js, line 46 &lt;static, readonly&gt; gamepadLastStatus :Object Keeps the last return value of the CB_Controllers_Proprietary.WII_U.getGamePadStatus function (if any). The value should be the last status object returned. Type: Object Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js, line 34 &lt;static, constant&gt; REMOTE_BUTTONS :Object Object which keeps the values for the Nintendo Wii U remote's buttons (bitmasks). Type: Object Properties: Name Type Description UP number UP button. DOWN number DOWN button. LEFT number LEFT button. RIGHT number RIGHT button. A number \"A\" button. B number \"B\" button. ONE number \"1\" button. _1 number Alias for CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.ONE. 1 number Alias for CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.ONE. TWO number \"2\" button. _2 number Alias for CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.TWO. 2 number Alias for CB_Controllers_Proprietary.WII_U.REMOTE_BUTTONS.TWO. PLUS number PLUS (\"+\") button. MINUS number MINUS (\"-\") button. HOME number HOME button. Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js, line 111 &lt;static, readonly&gt; remoteLastStatus :array Keeps an array with numeric indexes (should be from 0 to 7 maximum) that belong to each remote number and whose values contain the last return value of the CB_Controllers_Proprietary.WII_U.getRemoteStatus function (if any). Each value should be the last status object returned. Type: array Default Value: [] Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js, line 44 &lt;static, readonly&gt; wiiuObject :Object Keeps the \"wiiu\" object (if any). Type: Object Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js, line 25 Methods &lt;static&gt; getGamePads() → {Object} Returns an object with the gamepad and all remotes simulating the GamePad API. Uses the CB_Controllers_Proprietary.WII_U.getRemoteStatus and CB_Controllers_Proprietary.WII_U.getRemoteStatus internally so the objects will be normalized already. Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js, line 445 To Do: Check the documentation to find out the maximum number of remotes allowed and find out whether the first index should be 0 or 1 and last one 7 or 8. Returns: Returns an object with two properties: \"gamepads\" and \"remotes\". Each of those two properties will have an object as value whose names will be the index of the device and the value an object with the status of that device. In the case of the gamepad (which is unique), there will only be one index (\"0\", zero). In the case of the remotes, it will contain the status objects of all the remotes. The number of remotes is 8 (index from \"0\" to \"7\"). Simulating the GamePad API. Those status objects which are not using the real API will have a property called \"usingPrototype\" set to true. Type Object &lt;static&gt; getGamePadStatus() → {Object} Returns an object with the current status of each button of the gamepad. Already calls CB_Controllers_Proprietary.WII_U.normalizeGamepad automatically. Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js, line 418 Returns: Returns an object with the current status of each button of the gamepad. Type Object &lt;static&gt; getRemoteStatus( [n]) → {Object} Returns an object with the current status of each button of the desired remote. Already calls CB_Controllers_Proprietary.WII_U.normalizeRemote automatically. Parameters: Name Type Argument Default Description n integer &lt;optional&gt; 0 Number of the remote whose status we want to get, from 0 to 7 (both numbers included, 8 in total). Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js, line 431 To Do: Check documentation to see whether the first index should be 0 or 1 and maximum 7 or 8. Returns: Returns an object with the current status of each button of the desired remote. Type Object &lt;static&gt; normalizeGamepad(gamepadStatusObject) → {Object} Normalizes the given gamepad status object, adding missing properties. Parameters: Name Type Description gamepadStatusObject object The gamepad status object that we want to normalize. Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js, line 294 Returns: Returns the given gamepad status object but normalized, adding missing properties. Type Object &lt;static&gt; normalizeRemote(gamepadStatusObject [, n]) → {Object} Normalizes the given remote status object, adding missing properties. Parameters: Name Type Argument Default Description gamepadStatusObject object The remote status object that we want to normalize. n integer &lt;optional&gt; 0 Number of the remote whose status we want to get, from 0 to 7 (both numbers included, 8 in total). It will be used as its identifier. Source: CrossBase/input/controllers/CB_Controllers_Proprietary_WII_U.js, line 371 Returns: Returns the given remote status object but normalized, adding missing properties. Type Object × Search results Close "},"CB_Device.html":{"id":"CB_Device.html","title":"Namespace: CB_Device","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Device CB_Device Static class to manage the device. It will return itself if it is tried to be instantiated. Source: CrossBase/device/CB_Device.js, line 13 To Do: Think about defining a parameter on many of the events to disable automatic normalization of the event object. Namespaces AmbientLight Battery Location Motion Orientation Proximity Vibration Methods &lt;static&gt; getTime() → {integer} Gets a timestamp in milliseconds (elapsed since 1st of January 1970 00:00:00 UTC) representing the current time. Using high precision if the CB_Configuration.CrossBase.CB_Device_getTime_HIGH_PRECISION option is true (it would return 'window.performance.timing.navigationStart + window.performance.now()', where 'window.performance.now' could be polyfilled) or normal precision otherwise (it would return 'Date.now()', where 'Date.now' could be polyfilled). Source: CrossBase/device/CB_Device.js, line 47 Returns: 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. Type integer &lt;static&gt; getTiming() → {number} Gets the time elapsed since the time origin. If possible, it uses window.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). Source: CrossBase/device/CB_Device.js, line 58 Returns: Returns the time elapsed since the time origin. If possible, it uses window.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). Type number × Search results Close "},"CB_Device.AmbientLight.html":{"id":"CB_Device.AmbientLight.html","title":"Namespace: AmbientLight","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: AmbientLight CB_Device. AmbientLight Static class to manage the device's ambient light sensor. It will return itself if it is tried to be instantiated. Source: CrossBase/device/CB_Device.js, line 1063 To Do: Normalize more differences between web clients. Methods &lt;static&gt; isSupported() → {boolean} Tells whether the Ambient Light Sensor API or the Ambient Light Sensor Events (\"ondevicelight\") or \"onlightlevel\" event are supported or not. Source: CrossBase/device/CB_Device.js, line 1070 Returns: Type boolean &lt;static&gt; normalizeEvent(e, eventName [, sensor]) → {Event} Normalizes the data gotten from the the Ambient Light Sensor API or the Ambient Light Sensor Events (\"ondevicelight\") or \"onlightlevel\" event to try to match the Ambient Light Sensor API and follow always the same rules as much as possible. Parameters: Name Type Argument Description e Event The event object that we want to normalize. eventName 'change' | 'reading' | 'devicelight' | 'lightlevel' The name of the event that we want to normalize. Case sensitive. sensor AmbientLightSensor &lt;optional&gt; AmbientLightSensor object used by the Ambient Light Sensor API. Source: CrossBase/device/CB_Device.js, line 1144 To Do: Normalize more differences between web clients. Returns: Returns the given event object again but normalized (if possible). Type Event &lt;static&gt; onChange(eventFunction [, keepOldFunction] [, useCapture] [, callbackError]) → {undefined|false} Sets the event to get the ambient light or removes it. Uses the Ambient Light Sensor API or the Ambient Light Sensor Events (\"ondevicelight\") or \"onlightlevel\" event. 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): First choice, if available, uses the Ambient Light Sensor API and \"event.value\" will contain the units in lux. Second choice, if available, uses the Ambient Light Sensor Events (\"ondevicelight\") and \"event.value\" will contain the units in lux. Third choice, if available, uses the \"onlightlevel\" event and \"event.value\" will be \"\" (an empty string), \"dim\", \"normal\" or \"bright\" instead of a number. Parameters: Name Type Argument Default Description eventFunction function | null The function that will be called when the event is fired. The event object received will already be normalized by the 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. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. useCapture float &lt;optional&gt; 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 method and will be used as its third parameter. callbackError function &lt;optional&gt; Callback that will be called if there is any error getting the ambient light. Only used by the Ambient Light Sensor API (if available). Source: CrossBase/device/CB_Device.js, line 1093 Returns: Returns false in the case that no way to get the ambient light is available or undefined otherwise. Type undefined | false × Search results Close "},"CB_Device.Battery.html":{"id":"CB_Device.Battery.html","title":"Namespace: Battery","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: Battery CB_Device. Battery Static class to manage the device's battery. It will return itself if it is tried to be instantiated. Source: CrossBase/device/CB_Device.js, line 746 To Do: Normalize more differences between web clients. Methods &lt;static&gt; cordova_onChange(eventFunction [, keepOldFunction] [, useCapture]) 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. Parameters: Name Type Argument Default Description eventFunction function | null The function that will be called when the event is fired. Following the same rules as in https://github.com/apache/cordova-plugin-battery-status. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. useCapture float &lt;optional&gt; 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 method and will be used as its third parameter. Source: CrossBase/device/CB_Device.js, line 976 &lt;static&gt; cordova_onCritical(eventFunction [, keepOldFunction] [, useCapture]) 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. Parameters: Name Type Argument Default Description eventFunction function | null The function that will be called when the event is fired. Following the same rules as in https://github.com/apache/cordova-plugin-battery-status. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. useCapture float &lt;optional&gt; 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 method and will be used as its third parameter. Source: CrossBase/device/CB_Device.js, line 1002 &lt;static&gt; cordova_onLow(eventFunction [, keepOldFunction] [, useCapture]) 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. Parameters: Name Type Argument Default Description eventFunction function | null The function that will be called when the event is fired. Following the same rules as in https://github.com/apache/cordova-plugin-battery-status. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. useCapture float &lt;optional&gt; 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 method and will be used as its third parameter. Source: CrossBase/device/CB_Device.js, line 989 &lt;static&gt; get( [callbackOk] [, chargingOnFail] [, levelOnFail] [, chargingTimeOnFail] [, dischargingTimeOnFail]) → {Object|Promise} Gets the battery object (BatteryManager) using the Battery Status API (or compatible one) if available or falling back to Apache Cordova's Battery Status plugin emulating the object if possible or a fake object otherwise. It could be synchronous or asynchronous depending on the client. When the 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 if possible. The return will be synchronous only when 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). Parameters: Name Type Argument Description callbackOk function &lt;optional&gt; 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). chargingOnFail boolean &lt;optional&gt; Desired value for the \"charging\" property of the fake battery object when neither the Battery Status API (or compatible one) nor Apache Cordova's Battery Status plugin are available. It should follow the same rules as the real property of the BatteryManager object. levelOnFail float &lt;optional&gt; Desired value for the \"level\" property of the fake battery object when neither the Battery Status API (or compatible one) nor Apache Cordova's Battery Status plugin are available. It should follow the same rules as the real property of the BatteryManager object. chargingTimeOnFail integer &lt;optional&gt; Desired value for the \"chargingTime\" property of the fake battery object when the Battery Status API (or compatible one) is not available. It should follow the same rules as the real property of the BatteryManager object. dischargingTimeOnFail integer &lt;optional&gt; Desired value for the \"dischargingTime\" property of the fake battery object when the Battery Status API (or compatible one) is not available. It should follow the same rules as the real property of the BatteryManager object. Source: CrossBase/device/CB_Device.js, line 785 Returns: Returns the battery object (fake or real) synchronously only when the native getBattery function is not available. Otherwise it returns a Promise (the result of calling navigator.getBattery().then(callbackOk)). It is highly recommended to ignore this returned value. Type Object | Promise &lt;static&gt; getChargingTime( [callbackOk] [, valueOnFail]) → {integer|Promise} Returns the time (in seconds) that the battery needs to be completely charged. Using the CB_Device.Battery.get function internally. It could be synchronous or asynchronous depending on the client. The return will be synchronous only sometimes (when it is asynchronous it will just return a Promise), following the same rules as the 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). Parameters: Name Type Argument Description callbackOk function &lt;optional&gt; 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). valueOnFail integer &lt;optional&gt; 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 object. Source: CrossBase/device/CB_Device.js, line 858 Returns: Returns the desired value only when the function is executed synchronously (following the same rules as the CB_Device.Battery.get function which is called internally). It is highly recommended to ignore this returned value. Type integer | Promise &lt;static&gt; getDischargingTime( [callbackOk] [, valueOnFail]) → {integer|Promise} 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 CB_Device.Battery.get function internally. It could be synchronous or asynchronous depending on the client. The return will be synchronous only sometimes (when it is asynchronous it will just return a Promise), following the same rules as the 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). Parameters: Name Type Argument Description callbackOk function &lt;optional&gt; 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). valueOnFail integer &lt;optional&gt; 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 object. Source: CrossBase/device/CB_Device.js, line 875 Returns: Returns the desired value only when the function is executed synchronously (following the same rules as the CB_Device.Battery.get function which is called internally). It is highly recommended to ignore this returned value. Type integer | Promise &lt;static&gt; getLevel( [callbackOk] [, valueOnFail]) → {float|Promise} Returns tha current charging level of the battery. Using the CB_Device.Battery.get function internally. It could be synchronous or asynchronous depending on the client. The return will be synchronous only sometimes (when it is asynchronous it will just return a Promise), following the same rules as the 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). Parameters: Name Type Argument Description callbackOk function &lt;optional&gt; 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). valueOnFail float &lt;optional&gt; 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 object. Source: CrossBase/device/CB_Device.js, line 841 Returns: Returns the desired value only when the function is executed synchronously (following the same rules as the CB_Device.Battery.get function which is called internally). It is highly recommended to ignore this returned value. Type float | Promise &lt;static&gt; isCharging( [callbackOk] [, valueOnFail]) → {boolean|Promise} Returns whether the battery is charging or not. Using the CB_Device.Battery.get function internally. It could be synchronous or asynchronous depending on the client. The return will be synchronous only sometimes (when it is asynchronous it will just return a Promise), following the same rules as the 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). Parameters: Name Type Argument Description callbackOk function &lt;optional&gt; 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). valueOnFail boolean &lt;optional&gt; 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 object. Source: CrossBase/device/CB_Device.js, line 824 Returns: Returns the desired value only when the function is executed synchronously (following the same rules as the CB_Device.Battery.get function which is called internally). It is highly recommended to ignore this returned value. Type boolean | Promise &lt;static&gt; isSupported() → {boolean} Tells whether the Battery Status API (or compatible one) is available or not. Source: CrossBase/device/CB_Device.js, line 765 Returns: Type boolean &lt;static&gt; onChargingChange(eventFunction [, keepOldFunction] [, useCapture]) → {undefined|false|Promise} 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 (or compatible one). Parameters: Name Type Argument Default Description eventFunction function | null The function that will be called when the event is fired. Following the same rules as in https://developer.mozilla.org/docs/Web/Events/chargingchange. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. useCapture float &lt;optional&gt; 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 method and will be used as its third parameter. Source: CrossBase/device/CB_Device.js, line 891 Returns: Returns false when the Battery Status API (or compatible one) is not available. Returns a Promise when the native getBattery function is available. Otherwise, it returns undefined. Type undefined | false | Promise &lt;static&gt; onChargingTimeChange(eventFunction [, keepOldFunction] [, useCapture]) → {undefined|false|Promise} 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 (or compatible one). Parameters: Name Type Argument Default Description eventFunction function | null The function that will be called when the event is fired. Following the same rules as in https://developer.mozilla.org/docs/Web/Events/chargingtimechange. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. useCapture float &lt;optional&gt; 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 method and will be used as its third parameter. Source: CrossBase/device/CB_Device.js, line 905 Returns: Returns false when the Battery Status API (or compatible one) is not available. Returns a Promise when the native getBattery function is available. Otherwise, it returns undefined. Type undefined | false | Promise &lt;static&gt; onDischargingTimeChange(eventFunction [, keepOldFunction] [, useCapture]) → {undefined|false|Promise} 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 (or compatible one). Parameters: Name Type Argument Default Description eventFunction function | null The function that will be called when the event is fired. Following the same rules as in https://developer.mozilla.org/docs/Web/Events/dischargingtimechange. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. useCapture float &lt;optional&gt; 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 method and will be used as its third parameter. Source: CrossBase/device/CB_Device.js, line 919 Returns: Returns false when the Battery Status API (or compatible one) is not available. Returns a Promise when the native getBattery function is available. Otherwise, it returns undefined. Type undefined | false | Promise &lt;static&gt; onLevelChange(eventFunction [, keepOldFunction] [, useCapture]) → {undefined|false|Promise} 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 (or compatible one). Parameters: Name Type Argument Default Description eventFunction function | null The function that will be called when the event is fired. Following the same rules as in https://developer.mozilla.org/docs/Web/Events/levelchange. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. useCapture float &lt;optional&gt; 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 method and will be used as its third parameter. Source: CrossBase/device/CB_Device.js, line 933 Returns: Returns false when the Battery Status API (or compatible one) is not available. Returns a Promise when the native getBattery function is available. Otherwise, it returns undefined. Type undefined | false | Promise × Search results Close "},"CB_Device.Location.html":{"id":"CB_Device.Location.html","title":"Namespace: Location","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: Location CB_Device. Location Static class to manage the device's location. It will return itself if it is tried to be instantiated. Source: CrossBase/device/CB_Device.js, line 96 To Do: Normalize more differences between web clients. Members &lt;static, readonly&gt; get_callbackError :function|null Keeps the callback function used when there is an error getting the location for the CB_Device.Location.get function. Type: function | null Source: CrossBase/device/CB_Device.js, line 135 &lt;static, readonly&gt; get_callbackOk :function|null Keeps the callback function used when location can be gotten successfully for the CB_Device.Location.get function. Type: function | null Source: CrossBase/device/CB_Device.js, line 125 &lt;static, readonly&gt; get_options :Object|undefined Keeps the last options used by the CB_Device.Location.get function. Type: Object | undefined Source: CrossBase/device/CB_Device.js, line 145 &lt;static, readonly&gt; getConstantly_callbackError :function|null Keeps the callback function used when there is an error getting the location for the CB_Device.Location.getConstantly function. Type: function | null Source: CrossBase/device/CB_Device.js, line 165 &lt;static, readonly&gt; getConstantly_callbackOk :function|null Keeps the callback function used when location can be gotten successfully for the CB_Device.Location.getConstantly function. Type: function | null Source: CrossBase/device/CB_Device.js, line 155 &lt;static, readonly&gt; getConstantly_lastId :integer|null Keeps the last watch ID that gets the location constantly. Used by the CB_Device.Location.getConstantly function. Type: integer | null Source: CrossBase/device/CB_Device.js, line 105 &lt;static, readonly&gt; getConstantly_options :Object|undefined Keeps the last options used by the CB_Device.Location.getConstantly function. Type: Object | undefined Source: CrossBase/device/CB_Device.js, line 175 &lt;static, readonly&gt; keepAwake_locationLockGPS :Object|null Keeps the \"WakeLock\" (MozWakeLock) object to be able to release the lock related with the GPS (so far, only works in Firefox/Firefox OS). Used by the CB_Device.Location.keepAwake function. Type: Object | null Source: CrossBase/device/CB_Device.js, line 115 Methods &lt;static&gt; get( [callbackOk] [, callbackError] [, options] [, keepOldCallbackOk] [, keepOldCallbackError] [, keepOldOptions]) → {undefined|false} Gets the current position. Uses the Geolocation API (or compatible one as Apache Cordova's Geolocation plugin). Parameters: Name Type Argument Default Description callbackOk function &lt;optional&gt; Callback that will be called if it gets the location successfully. Following the same rules as the first parameter of the native getCurrentPosition function. callbackError function &lt;optional&gt; 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 function. options Object &lt;optional&gt; 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 function. keepOldCallbackOk boolean &lt;optional&gt; 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. keepOldCallbackError boolean &lt;optional&gt; 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. keepOldOptions boolean &lt;optional&gt; 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. Source: CrossBase/device/CB_Device.js, line 201 Returns: Returns false in the case that Geolocation API (or compatible one as Apache Cordova's Geolocation plugin) is not supported or undefined otherwise. Type undefined | false &lt;static&gt; getConstantly( [callbackOkOrId] [, callbackError] [, options] [, keepOldCallbackOk] [, keepOldCallbackError] [, keepOldOptions]) → {integer|undefined|false} Starts or stops getting the current position constantly (real-time) every time it changes. Uses the Geolocation API (or compatible one as Apache Cordova's Geolocation plugin). Parameters: Name Type Argument Default Description callbackOkOrId function | integer &lt;optional&gt; 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 function). To stop getting the position, use the watch ID that we want to stop (using the native clearWatch function). Following the same rules as the first parameter of the native watchPosition function (when we want to start watching) or the first parameter of clearWatch function (when we want to stop watching). callbackError function &lt;optional&gt; 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 function. options Object &lt;optional&gt; 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 function. keepOldCallbackOk boolean &lt;optional&gt; 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). keepOldCallbackError boolean &lt;optional&gt; 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). keepOldOptions boolean &lt;optional&gt; 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). Source: CrossBase/device/CB_Device.js, line 265 Returns: Returns false in the case that Geolocation API (or compatible one as Apache Cordova's Geolocation plugin) 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. Type integer | undefined | false &lt;static&gt; getConstantlyDisable( [id] [, keepOldCallbackOk] [, keepOldCallbackError] [, keepOldOptions]) → {undefined|false} Stops getting the current position constantly (real-time) every time it changes. Uses the Geolocation API (or compatible one as Apache Cordova's Geolocation plugin). Parameters: Name Type Argument Default Description id integer &lt;optional&gt; 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 function. keepOldCallbackOk boolean &lt;optional&gt; false If it is set to false, it will not remove the current \"callbackOk\" (if any) which was/were set previously. keepOldCallbackError boolean &lt;optional&gt; false If it is set to false, it will remove the current \"callbackError\" (if any) which was/were set previously. keepOldOptions boolean &lt;optional&gt; false If it is set to false, it will remove the current \"options\" (if any) which were set previously. Source: CrossBase/device/CB_Device.js, line 342 Returns: Returns false in the case that Geolocation API (or compatible one as Apache Cordova's Geolocation plugin) is not supported or undefined otherwise. Type undefined | false &lt;static&gt; isSupported() → {boolean} Tells whether the Geolocation API (or compatible one as Apache Cordova's Geolocation plugin) is supported or not. Source: CrossBase/device/CB_Device.js, line 183 Returns: Type boolean &lt;static&gt; keepAwake( [keepAwake] [, lock]) → {undefined|Object|false} Keeps or stops keeping the application getting the position, even when the application is invisible or screen is locked, by using requestWakeLock (so far, only works in Firefox/Firefox OS). Parameters: Name Type Argument Default Description keepAwake boolean &lt;optional&gt; true Defines whether we want to keep it awake or stop doing it. lock Object &lt;optional&gt; CB_Device.Location.keepAwake_locationLockGPS The \"WakeLock\" (MozWakeLock) object that we want to unlock. It will be used only when \"keepAwake\" is set to false. Source: CrossBase/device/CB_Device.js, line 360 Returns: Returns false in the case that \"WakeLock\" (MozWakeLock) is not supported or something went wrong. Returns the \"WakeLock\" (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). Type undefined | Object | false × Search results Close "},"CB_Device.Motion.html":{"id":"CB_Device.Motion.html","title":"Namespace: Motion","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: Motion CB_Device. Motion Static class to manage the device's motion. It will return itself if it is tried to be instantiated. Source: CrossBase/device/CB_Device.js, line 605 To Do: Normalize more differences between web clients. Members &lt;static, readonly&gt; cordova_getAccelerationConstantly_lastId :integer|null Keeps the last watch ID that gets the acceleration constantly using the Apache Cordova's Device Motion plugin. Used by the CB_Device.Motion.cordova_getAccelerationConstantly function. Type: integer | null Source: CrossBase/device/CB_Device.js, line 614 Methods &lt;static&gt; cordova_getAcceleration(callbackOk, callbackError) → {undefined|false} Gets the acceleration using the Apache Cordova's Device Motion plugin. Uses \"navigator.accelerometer.getCurrentAcceleration\" internally. Parameters: Name Type Description callbackOk function The function that will be called when it succeeds getting the acceleration. The event object received will already be normalized by the CB_Device.Motion.cordova_getAccelerationNormalized function automatically. Following the same rules as in https://github.com/apache/cordova-plugin-device-motion (\"navigator.accelerometer.getCurrentAcceleration\" function). callbackError function The function that will be called if there is any error getting the acceleration. Following the same rules as in https://github.com/apache/cordova-plugin-device-motion (\"navigator.accelerometer.getCurrentAcceleration\" function). Source: CrossBase/device/CB_Device.js, line 661 Returns: Returns false in the case that the Apache Cordova's Device Motion plugin is not supported or undefined otherwise. Type undefined | false &lt;static&gt; cordova_getAccelerationConstantly( [callbackOkOrId] [, callbackError] [, options]) → {integer|undefined|false} Starts or stops getting the acceleration constantly at a regular interval. Uses the Apache Cordova's Device Motion plugin (\"navigator.accelerometer.watchAcceleration\" and \"navigator.accelerometer.clearWatch\" functions). Parameters: Name Type Argument Default Description callbackOkOrId function | integer &lt;optional&gt; 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 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 https://github.com/apache/cordova-plugin-device-motion. callbackError function &lt;optional&gt; 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 https://github.com/apache/cordova-plugin-device-motion. options Object &lt;optional&gt; 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 https://github.com/apache/cordova-plugin-device-motion. Source: CrossBase/device/CB_Device.js, line 678 To Do: Add parameters to keep old callbacks and options. Returns: Returns false in the case that Apache Cordova's Device Motion plugin 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. Type integer | undefined | false &lt;static&gt; cordova_getAccelerationConstantlyDisable( [id]) → {undefined|false} Stops getting the acceleration constantly at a regular interval. Uses the Apache Cordova's Device Motion plugin (\"navigator.accelerometer.clearWatch\" function). Parameters: Name Type Argument Default Description id integer &lt;optional&gt; 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 https://github.com/apache/cordova-plugin-device-motion. Source: CrossBase/device/CB_Device.js, line 708 To Do: Add parameters to keep old callbacks and options. Returns: Returns false in the case that Apache Cordova's Device Motion plugin is not supported or undefined otherwise. Type undefined | false &lt;static&gt; cordova_getAccelerationNormalized(accelerometerData) → {Event} Normalizes the data gotten from the Apache Cordova's Device Motion plugin to try to match the Device Motion Event and follow always the same rules as much as possible. Parameters: Name Type Description accelerometerData Object The acceleration object that we want to normalize. Source: CrossBase/device/CB_Device.js, line 722 To Do: Normalize the values without gravity too (accelerometerData.acceleration.x, accelerometerData.acceleration.y, accelerometerData.acceleration.z) if possible (needs gyroscope probably) and maybe more properties. Returns: Returns the given acceleration object again but normalized (if possible). Type Event &lt;static&gt; cordova_isAccelerationSupported() → {boolean} Tells whether the Apache Cordova's Device Motion plugin is available or not. Source: CrossBase/device/CB_Device.js, line 648 Returns: Type boolean &lt;static&gt; isSupported() → {boolean} Tells whether the Device Motion Event (used by the Device Orientation API or compatible one) is supported or not. Source: CrossBase/device/CB_Device.js, line 622 Returns: Type boolean &lt;static&gt; onChange(eventFunction [, keepOldFunction] [, useCapture]) → {undefined|false} Sets a function to execute for the Device Motion Event (used by the Device Orientation API or compatible one) or removes it. Parameters: Name Type Argument Default Description eventFunction function | null The function that will be called when the event is fired. Following the same rules as in https://developer.mozilla.org/docs/Web/API/DeviceMotionEvent. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. useCapture float &lt;optional&gt; 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 method and will be used as its third parameter. Source: CrossBase/device/CB_Device.js, line 636 Returns: Returns false in the case that the Device Motion Event is not supported or undefined otherwise. Type undefined | false × Search results Close "},"CB_Device.Orientation.html":{"id":"CB_Device.Orientation.html","title":"Namespace: Orientation","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: Orientation CB_Device. Orientation Static class to manage the device's orientation. It will return itself if it is tried to be instantiated. Source: CrossBase/device/CB_Device.js, line 394 To Do: Normalize more differences between web clients. Members &lt;static, readonly&gt; cordova_getCompassConstantly_lastId :integer|null Keeps the last watch ID that gets the compass heading constantly using the Apache Cordova's Device Orientation plugin. Used by the CB_Device.Orientation.cordova_getCompassConstantly function. Type: integer | null Source: CrossBase/device/CB_Device.js, line 403 Methods &lt;static&gt; cordova_getCompass(callbackOk, callbackError) → {undefined|false} Gets the compass heading using the Apache Cordova's Device Orientation plugin. Uses \"navigator.compass.getCurrentHeading\" internally. Parameters: Name Type Description callbackOk function The function that will be called when it succeeds getting the compass heading. Following the same rules as in https://github.com/apache/cordova-plugin-device-orientation (\"navigator.compass.getCurrentHeading\" function). callbackError function The function that will be called if there is any error getting the compass heading. Following the same rules as in https://github.com/apache/cordova-plugin-device-orientation (\"navigator.compass.getCurrentHeading\" function). Source: CrossBase/device/CB_Device.js, line 545 To Do: Add a function to normalize the event and call it automatically. Returns: Returns false in the case that the Apache Cordova's Device Orientation plugin is not supported or undefined otherwise. Type undefined | false &lt;static&gt; cordova_getCompassConstantly( [callbackOkOrId] [, callbackError] [, options]) → {integer|undefined|false} Starts or stops getting the compass heading constantly at a regular interval. Uses the Apache Cordova's Device Orientation plugin (\"navigator.compass.watchHeading\" and \"navigator.compass.clearWatch\" functions). Parameters: Name Type Argument Default Description callbackOkOrId function | integer &lt;optional&gt; 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 https://github.com/apache/cordova-plugin-device-orientation. callbackError function &lt;optional&gt; 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 https://github.com/apache/cordova-plugin-device-orientation. options Object &lt;optional&gt; 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 https://github.com/apache/cordova-plugin-device-orientation. Source: CrossBase/device/CB_Device.js, line 562 To Do: Add a function to normalize the event and call it automatically. Add parameters to keep old callbacks and options. Returns: Returns false in the case that Apache Cordova's Device Orientation plugin 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. Type integer | undefined | false &lt;static&gt; cordova_getCompassConstantlyDisable( [id]) → {undefined|false} Stops getting the compass heading constantly at a regular interval. Uses the Apache Cordova's Device Orientation plugin (\"navigator.compass.clearWatch\" function). Parameters: Name Type Argument Default Description id integer &lt;optional&gt; 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 https://github.com/apache/cordova-plugin-device-orientation. Source: CrossBase/device/CB_Device.js, line 591 To Do: Add parameters to keep old callbacks and options. Returns: Returns false in the case that Apache Cordova's Device Orientation plugin is not supported or undefined otherwise. Type undefined | false &lt;static&gt; cordova_isCompassSupported() → {boolean} Tells whether the Apache Cordova's Device Orientation plugin is available or not. Source: CrossBase/device/CB_Device.js, line 531 Returns: Type boolean &lt;static&gt; isCompassNeedsCalibrationSupported() → {boolean} Tells whether the Compass Needs Calibration Event (used by the Device Orientation API or compatible one) is supported or not. Source: CrossBase/device/CB_Device.js, line 505 Returns: Type boolean &lt;static&gt; isMozOrientationSupported() → {boolean} Tells whether the MozOrientation API is supported or not. Source: CrossBase/device/CB_Device.js, line 423 Returns: Type boolean &lt;static&gt; isSupported() → {boolean} Tells whether the Device Orientation Event (used by the Device Orientation API or compatible one) is supported or not. Source: CrossBase/device/CB_Device.js, line 412 To Do: Think about using the \"ondeviceorientationabsolute\" event. Returns: Type boolean &lt;static&gt; normalizeEvent(e, eventName) → {Event} Normalizes the data gotten from the Device Orientation Event produced by different clients to try to match the Device Orientation API and follow always the same rules as much as possible. Parameters: Name Type Description e Event The event object that we want to normalize. eventName 'deviceorientation' | 'MozOrientation' The name of the event that we want to normalize. Case sensitive. Source: CrossBase/device/CB_Device.js, line 477 To Do: Think about using the \"deviceorientationabsolute\" event. Normalize more differences between web clients. Returns: Returns the given event object again but normalized (if possible). Type Event &lt;static&gt; onChange(eventFunction [, keepOldFunction] [, useCapture]) → {undefined|false} Sets a function to execute for the Device Orientation Event (used by the Device Orientation API or compatible one) or removes it. Falls back to the MozOrientation API if possible. Parameters: Name Type Argument Default Description eventFunction function | null The function that will be called when the event is fired. The event object received will already be normalized by the CB_Device.Orientation.normalizeEvent function automatically. Following the same rules as in https://developer.mozilla.org/docs/Web/API/DeviceOrientationEvent. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. useCapture float &lt;optional&gt; 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 method and will be used as its third parameter. Source: CrossBase/device/CB_Device.js, line 438 To Do: Think about using the \"deviceorientationabsolute\" event. Returns: Returns false in the case that neither the Device Orientation API (or compatible one) nor the MozOrientation API are supported or undefined otherwise. Type undefined | false &lt;static&gt; onCompassNeedsCalibration(eventFunction [, keepOldFunction] [, useCapture]) → {undefined|false} Sets a function to execute for the Compass Needs Calibration Event (used by the Device Orientation API or compatible one) or removes it. Parameters: Name Type Argument Default Description eventFunction function | null The function that will be called when the event is fired. Following the same rules as in https://w3c.github.io/deviceorientation/spec-source-orientation.html#compassneedscalibration. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. useCapture float &lt;optional&gt; 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 method and will be used as its third parameter. Source: CrossBase/device/CB_Device.js, line 519 Returns: Returns false in the case that the Compass Needs Calibration Event is not supported or undefined otherwise. Type undefined | false × Search results Close "},"CB_Device.Proximity.html":{"id":"CB_Device.Proximity.html","title":"Namespace: Proximity","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: Proximity CB_Device. Proximity Static class to manage the device's proximity sensor. It will return itself if it is tried to be instantiated. Source: CrossBase/device/CB_Device.js, line 1181 To Do: Normalize more differences between web clients. Methods &lt;static&gt; isSupported() → {boolean} Tells whether the Proximity Sensor API or the Proximity Sensor Events as \"ondeviceproximity\" or \"onuserproximity\" are supported or not. Source: CrossBase/device/CB_Device.js, line 1188 Returns: Type boolean &lt;static&gt; normalizeEvent(e, eventName [, sensor]) → {Event} Normalizes the data gotten from the the Proximity Sensor API or the Proximity Sensor Events as \"ondeviceproximity\" or \"onuserproximity\" to try to match the Proximity Sensor API and follow always the same rules as much as possible. Parameters: Name Type Argument Description e Event The event object that we want to normalize. eventName 'change' | 'reading' | 'deviceproximity' | 'userproximity' The name of the event that we want to normalize. Case sensitive. sensor ProximitySensor &lt;optional&gt; ProximitySensor object used by the Proximity Sensor API. Source: CrossBase/device/CB_Device.js, line 1269 To Do: Normalize more differences between web clients. Returns: Returns the given event object again but normalized (if possible). Type Event &lt;static&gt; onChange(eventFunction [, detectNear] [, keepOldFunction] [, useCapture] [, callbackError]) → {undefined|false} Sets the event to get the proximity or removes it. Uses the Proximity Sensor API or the Proximity Sensor Events as \"ondeviceproximity\" or \"onuserproximity\". 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: If \"detectNear\" is not set to true, Proximity Sensor API 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). If \"detectNear\" is not set to true, Proximity Sensor Events (\"ondeviceproximity\") is used as the second option (if available) and \"event.value\" will contain the units in centimeters. If \"detectNear\" is set to true, \"onuserproximity\" event is the unique option used (if available) and \"event.near\" will be a boolean which tell us whether something is near or not. Parameters: Name Type Argument Default Description eventFunction function | null The function that will be called when the event is fired. The event object received will already be normalized by the 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. detectNear boolean &lt;optional&gt; 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. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener or not. useCapture float &lt;optional&gt; 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 method and will be used as its third parameter. callbackError function &lt;optional&gt; Callback that will be called if there is any error getting the proximity. Only used by the Proximity Sensor API (if available). Source: CrossBase/device/CB_Device.js, line 1212 Returns: Returns false in the case that no way to get the proximity is available or undefined otherwise. Type undefined | false × Search results Close "},"CB_Device.Vibration.html":{"id":"CB_Device.Vibration.html","title":"Namespace: Vibration","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: Vibration CB_Device. Vibration Static class to manage the device's vibration. It will return itself if it is tried to be instantiated. Source: CrossBase/device/CB_Device.js, line 1014 Methods &lt;static&gt; isSupported() → {boolean} Tells whether the Vibration API (or compatible one as Apache Cordova's Vibration plugin) is available or not. Source: CrossBase/device/CB_Device.js, line 1021 Returns: Type boolean &lt;static&gt; start( [vibration]) → {undefined|false} Makes the device vibrate using the Vibration API (or compatible one as Apache Cordova's Vibration plugin). Parameters: Name Type Argument Description vibration integer | array &lt;optional&gt; 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 function. Source: CrossBase/device/CB_Device.js, line 1033 Returns: Returns false in the case that Vibration API (or compatible one as Apache Cordova's Vibration plugin) cannot be used or undefined otherwise. Type undefined | false &lt;static&gt; stop() → {undefined|false} Makes the device stop vibrating using the Vibration API (or compatible one as Apache Cordova's Vibration plugin). Source: CrossBase/device/CB_Device.js, line 1049 Returns: Returns false in the case that Vibration API (or compatible one as Apache Cordova's Vibration plugin) cannot be used or undefined otherwise. Type undefined | false × Search results Close "},"CB_Elements.html":{"id":"CB_Elements.html","title":"Namespace: CB_Elements","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Elements CB_Elements Static class to manage DOM elements. It will return itself if it is tried to be instantiated. Source: CrossBase/general/CB_Elements.js, line 14 To Do: Think about creating a function called \"add\" or \"create\" to create a new element (it could accept \"tagName\", \"id\" and \"content\" parameters). Think about creating \"setStyle\" and \"setStyleById\" methods to add a given style attribute and also supporting a boolean parameter to also add the style attribute with vendor prefixes (webkit, moz, ms, o, khtml) if we want to. Methods &lt;static&gt; addClass(element, className [, checkValues] [, onAddClass]) → {Node} Adds a desired class to a given element. The element can contain other classes and they will be kept. Parameters: Name Type Argument Default Description element Node The element that will get the new given class. className string The class that will be added. checkValues boolean &lt;optional&gt; false If it is set to true, it will only try to add the given class if it is not being used already. It is recommended to use true to prevent some old clients from adding the same class multiple times. onAddClass function &lt;optional&gt; Callback function that will be called if the class of the element has been added, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. Source: CrossBase/general/CB_Elements.js, line 1322 To Do: Think about allowing to use more than once class (and think how many times the \"onAddClass\" function should be called). Returns: Returns the given element again. Type Node &lt;static&gt; addClassById(elementId, className [, checkValues] [, onAddClass]) → {Node|null} Adds a desired class to a given element (by its identifier). The element can contain other classes and they will be kept. Parameters: Name Type Argument Default Description elementId string The identifier of the element that will get the new given class. className string The class that will be added. checkValues boolean &lt;optional&gt; false If it is set to true, it will only try to add the given class if it is not being used already. It is recommended to use true to prevent some old clients from adding the same class multiple times. onAddClass function &lt;optional&gt; Callback function that will be called if the class of the element has been added, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. Source: CrossBase/general/CB_Elements.js, line 1349 To Do: Think about allowing to use more than once class (and think how many times the \"onAddClass\" function should be called). Returns: Returns the affected element (if any) or null otherwise. Type Node | null &lt;static&gt; appendContent(container, content [, displayValue] [, checkValues] [, computed] [, onContentWritten] [, onShow] [, appendAtBeginning]) → {Node} Appends the desired content inside a given element, keeping the existing one (using innerHTML). Calls the CB_Elements.insertContent internally. Parameters: Name Type Argument Default Description container Node The element whose content we want to modify. content string The content that we want to add. displayValue string &lt;optional&gt; If provided, it will call CB_Elements.show internally after inserting the content to set the given display property to the element. checkValues boolean &lt;optional&gt; false If it is set to true, it will only change the content if the current one is different from the given one and it will pass the same parameter to CB_Elements.show if it is called internally (when \"displayValue\" is given). computed boolean &lt;optional&gt; false If \"displayValue\" is given, it will pass this parameter to CB_Elements.show if it is called internally (when \"displayValue\" is given). onContentWritten function &lt;optional&gt; Callback function that will be called if the content has been written, after doing it (this will happens always if \"checkValues\" is false). The unique parameter passed will be the container itself. onShow function &lt;optional&gt; If \"displayValue\" is given, it will pass this parameter to CB_Elements.show when it is called internally. appendAtBeginning boolean &lt;optional&gt; false If set to true, it will append the given content to the existing one instead of overwritten it. Source: CrossBase/general/CB_Elements.js, line 833 Returns: Returns the given container again. Type Node &lt;static&gt; appendContentBeginning(container, content [, displayValue] [, checkValues] [, computed] [, onContentWritten] [, onShow]) → {Node} Appends the desired content inside a given element at the beginning, keeping the existing one (using innerHTML). Calls the CB_Elements.insertContent internally. Parameters: Name Type Argument Default Description container Node The element whose content we want to modify. content string The content that we want to add. displayValue string &lt;optional&gt; If provided, it will call CB_Elements.show internally after inserting the content to set the given display property to the element. checkValues boolean &lt;optional&gt; false If it is set to true, it will only change the content if the current one is different from the given one and it will pass the same parameter to CB_Elements.show if it is called internally (when \"displayValue\" is given). computed boolean &lt;optional&gt; false If \"displayValue\" is given, it will pass this parameter to CB_Elements.show if it is called internally (when \"displayValue\" is given). onContentWritten function &lt;optional&gt; Callback function that will be called if the content has been written, after doing it (this will happens always if \"checkValues\" is false). The unique parameter passed will be the container itself. onShow function &lt;optional&gt; If \"displayValue\" is given, it will pass this parameter to CB_Elements.show when it is called internally. Source: CrossBase/general/CB_Elements.js, line 851 Returns: Returns the given container again. Type Node &lt;static&gt; appendContentById(containerId, content [, displayValue] [, checkValues] [, computed] [, onContentWritten] [, onShow] [, append] [, appendAtBeginning]) → {Node|null} Appends the desired content inside a given element, keeping the existing one (using innerHTML), by its identifier. Calls the CB_Elements.insertContent internally. Parameters: Name Type Argument Default Description containerId string The identifier of the element whose content we want to modify. content string The content that we want to add. displayValue string &lt;optional&gt; If provided, it will call CB_Elements.show internally after inserting the content to set the given display property to the element. checkValues boolean &lt;optional&gt; false If it is set to true, it will only change the content if the current one is different from the given one and it will pass the same parameter to CB_Elements.show if it is called internally (when \"displayValue\" is given). computed boolean &lt;optional&gt; false If \"displayValue\" is given, it will pass this parameter to CB_Elements.show if it is called internally (when \"displayValue\" is given). onContentWritten function &lt;optional&gt; Callback function that will be called if the content has been written, after doing it (this will happens always if \"checkValues\" is false). The unique parameter passed will be the affected container itself. onShow function &lt;optional&gt; If \"displayValue\" is given, it will pass this parameter to CB_Elements.show when it is called internally. append boolean &lt;optional&gt; false If set to true, it will append the given content to the existing one instead of overwritten it. By default, it appends it at the end unless that the \"appendAtBeginning\" is set to true. appendAtBeginning boolean &lt;optional&gt; false If set to true, it will append the given content to the existing one instead of overwritten it. Source: CrossBase/general/CB_Elements.js, line 891 Returns: Returns the affected container (if any) or null otherwise. Type Node | null &lt;static&gt; appendContentByIdBeginning(containerId, content [, displayValue] [, checkValues] [, computed] [, onContentWritten] [, onShow] [, append]) → {Node|null} Appends the desired content inside a given element at the beginning, keeping the existing one (using innerHTML), by its identifier. Calls the CB_Elements.insertContent internally. Parameters: Name Type Argument Default Description containerId string The identifier of the element whose content we want to modify. content string The content that we want to add. displayValue string &lt;optional&gt; If provided, it will call CB_Elements.show internally after inserting the content to set the given display property to the element. checkValues boolean &lt;optional&gt; false If it is set to true, it will only change the content if the current one is different from the given one and it will pass the same parameter to CB_Elements.show if it is called internally (when \"displayValue\" is given). computed boolean &lt;optional&gt; false If \"displayValue\" is given, it will pass this parameter to CB_Elements.show if it is called internally (when \"displayValue\" is given). onContentWritten function &lt;optional&gt; Callback function that will be called if the content has been written, after doing it (this will happens always if \"checkValues\" is false). The unique parameter passed will be the affected container itself. onShow function &lt;optional&gt; If \"displayValue\" is given, it will pass this parameter to CB_Elements.show when it is called internally. append boolean &lt;optional&gt; false If set to true, it will append the given content to the existing one instead of overwritten it. By default, it appends it at the end unless that the \"appendAtBeginning\" is set to true. Source: CrossBase/general/CB_Elements.js, line 910 Returns: Returns the affected container (if any) or null otherwise. Type Node | null &lt;static&gt; byId() Alias for CB_Elements.id. Source: CrossBase/general/CB_Elements.js, line 521 See: CB_Elements.id &lt;static&gt; classes(classNames [, baseElement] [, useCache]) → {NodeList|array} Returns elements by their class or classes name. Parameters: Name Type Argument Default Description classNames string The name of the class or classes (separated by a blank space) whose elements we want to find. The order of the classes is just important for the internal cache. baseElement Node &lt;optional&gt; document The node element parent where we want to focus our search. useCache boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Elements_classes_USE_CACHE Defines whether to try to get the result from an internal cache (it will exist if we previously called the function with the same parameters) or not. The internal cache will be updated when this parameter is set to false or it will be created automatically when it did not exist before. Source: CrossBase/general/CB_Elements.js, line 274 Returns: Returns the elements (NodeList or array, depending on the web client). Type NodeList | array &lt;static&gt; classesCacheClear( [classNames] [, baseElement]) → {Object} Clears the internal cache used by CB_Elements.classes and others. If no parameter is given, whole internal cache will be cleared. Parameters: Name Type Argument Description classNames string &lt;optional&gt; The name of the class or classes (separated by a blank space) whose internal cache we want to clear. The order of the classes is important for the internal cache. If not provided, it will clear the whole internal cache or the internal cache that belongs to the \"baseElement\" given (if provided). baseElement Node &lt;optional&gt; The node element parent whose internal cache we want to clear. If not provided but \"classNames\" is provided, it will clear the internal cache which matches the given \"classNames\" for any nodes. If it is provided but \"classNames\" is not, it will clear all the internal cache that belongs to this node element. Source: CrossBase/general/CB_Elements.js, line 440 Returns: Returns the current internal cache after cleaning it (if it is has been possible), which is an associative array of two dimensions (JavaScript object) whose first index belongs to the nodes, the second and last index belongs to the class name or class names and the value belongs to the returning value of the CB_Elements.classes function when it was called for those parameters. Type Object &lt;static&gt; classesCacheUpdate(classNames [, baseElement]) → {NodeList|array} Returns elements by their class or classes name, updating (or creating) the internal cache. Calls the CB_Elements.classes function internally, with the \"useCache\" parameter set to false. Parameters: Name Type Argument Default Description classNames string The name of the class or classes (separated by a blank space) whose elements we want to find. The order of the classes is just important for the internal cache. baseElement Node &lt;optional&gt; document The node element parent where we want to focus our search. Source: CrossBase/general/CB_Elements.js, line 427 Returns: Returns the elements (NodeList or array, depending on the web client). Type NodeList | array &lt;static&gt; classesRemove(classNames [, baseElement] [, useCache]) Removes elements by their class or classes name. Parameters: Name Type Argument Default Description classNames string The name of the class or classes (separated by a blank space) whose elements we want to delete. The order of the classes is just important for the internal cache. baseElement Node &lt;optional&gt; document The node element parent where we want to focus our search. useCache boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Elements_classes_USE_CACHE Defines whether to try to get the result from an internal cache (it will exist if we previously called the function with the same parameters) or not. The internal cache will be updated when this parameter is set to false or it will be created automatically when it did not exist before. Source: CrossBase/general/CB_Elements.js, line 496 &lt;static&gt; contextMenuDisable( [element] [, disableContextMenu]) → {Node} Disables or enables the contextual menu for a given element or in the whole document. Parameters: Name Type Argument Default Description element Node &lt;optional&gt; document The element whose contextual menu we want to disable or enable. If not given, it will affect the whole document. disableContextMenu boolean &lt;optional&gt; true If set to false, it will allow showing the contextual menu. Otherwise, it will prevent it to show. Source: CrossBase/general/CB_Elements.js, line 1839 Returns: Returns the affected element. Type Node &lt;static&gt; contextMenuDisableById(elementId [, disableContextMenu]) → {Node|null} Disables or enables the contextual menu for a given element (by its identifier). Parameters: Name Type Argument Default Description elementId string The identifier of the element whose contextual menu we want to disable or enable. disableContextMenu boolean &lt;optional&gt; true If set to false, it will allow showing the contextual menu. Otherwise, it will prevent it to show. Source: CrossBase/general/CB_Elements.js, line 1862 Returns: Returns the affected element (if any) or null otherwise. Type Node | null &lt;static&gt; get() Alias for CB_Elements.id. Source: CrossBase/general/CB_Elements.js, line 526 See: CB_Elements.id &lt;static&gt; getById() Alias for CB_Elements.id. Source: CrossBase/general/CB_Elements.js, line 531 See: CB_Elements.id &lt;static&gt; getFrameBodyContent(frameElement) → {string|null} Tries to get the body content of an iframe. Depending on the client and the safety measures, this might fail. Parameters: Name Type Description frameElement HTMLIFrameElement The iframe element whose body content we want to get. Source: CrossBase/general/CB_Elements.js, line 1880 Returns: Returns null if something goes wrong. Type string | null &lt;static&gt; getFrameBodyContentById(frameElementId) → {string|null} Tries to get the body content of an iframe (by its identifier). Depending on the client and the safety measures, this might fail. Parameters: Name Type Description frameElementId string The identifier of the iframe element whose body content we want to get. Source: CrossBase/general/CB_Elements.js, line 1924 Returns: Returns null if something goes wrong. Type string | null &lt;static&gt; getHeight(element [, returnNullOnFail] [, computed]) → {*} Returns the height of an element (having in mind its border). Parameters: Name Type Argument Default Description element Node The element whose data we are interested in. returnNullOnFail function &lt;optional&gt; false If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. computed boolean &lt;optional&gt; false This parameter will be used when it calls CB_Elements.getStylePropertyInteger internally. Source: CrossBase/general/CB_Elements.js, line 1716 Returns: It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). Type * &lt;static&gt; getHeightById(elementId [, returnNullOnFail] [, computed]) → {*} Returns the height of an element (having in mind its border), by its identifier. Parameters: Name Type Argument Default Description elementId string The identifier of the element whose data we are interested in. returnNullOnFail function &lt;optional&gt; false If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. computed boolean &lt;optional&gt; false This parameter will be used when it calls CB_Elements.getStylePropertyInteger internally. Source: CrossBase/general/CB_Elements.js, line 1766 Returns: It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). Type * &lt;static&gt; getLeft(element [, ignoreScroll] [, returnNullOnFail] [, computed]) → {*} Returns the left position of an element (having in mind getBoundingClientRect if available, its parents, etc.). Parameters: Name Type Argument Default Description element Node The element whose data we are interested in. ignoreScroll boolean &lt;optional&gt; true If it is set to false, it will have in mind the current scroll position to calculate the result. returnNullOnFail function &lt;optional&gt; false If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. computed boolean &lt;optional&gt; false This parameter will be used when it calls CB_Elements.getStyleProperty and CB_Elements.getStylePropertyInteger internally. Source: CrossBase/general/CB_Elements.js, line 1402 Returns: It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). Type * &lt;static&gt; getLeftById(elementId [, ignoreScroll] [, returnNullOnFail] [, computed]) → {*} Returns the left position of an element (having in mind getBoundingClientRect if available, its parents, etc.), by its identifier. Parameters: Name Type Argument Default Description elementId string The identifier of the element whose data we are interested in. ignoreScroll boolean &lt;optional&gt; true If it is set to false, it will have in mind the current scroll position to calculate the result. returnNullOnFail function &lt;optional&gt; false If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. computed boolean &lt;optional&gt; false This parameter will be used when it calls CB_Elements.getStyleProperty and CB_Elements.getStylePropertyInteger internally. Source: CrossBase/general/CB_Elements.js, line 1511 Returns: It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). Type * &lt;static&gt; getParent(element) → {Node|null} Returns the first parent of a given element: Parameters: Name Type Description element Node The element whose parent we want to get. Source: CrossBase/general/CB_Elements.js, line 721 Returns: Returns null if the parent cannot be found. Type Node | null &lt;static&gt; getParentById(elementId) → {Node|null} Returns the first parent of a given element (by its identifier): Parameters: Name Type Description elementId string The identifier of the element whose parent we want to get. Source: CrossBase/general/CB_Elements.js, line 743 Returns: Returns null if the parent cannot be found. Type Node | null &lt;static&gt; getParents(element) → {array} Returns an array with the parents of a given element, with the topmost parent in the highest index: Parameters: Name Type Description element Node The element whose parents we want to get. Source: CrossBase/general/CB_Elements.js, line 689 Returns: Type array &lt;static&gt; getParentsById(elementId) → {array} Returns an array with the parents of a given element (by its identifier), with the topmost parent in the highest index: Parameters: Name Type Description elementId string The identifier of the element whose parents we want to get. Source: CrossBase/general/CB_Elements.js, line 709 Returns: Type array &lt;static&gt; getScrollLeftById( [elementId] [, onScrollLeftChanges] [, fireFirstTime] [, fireAlways] [, timeoutMs] [, returnNullOnFail]) → {number|null} Returns the horizontal scroll of a given element (by its identifier) and allows running a callback function (becoming recursive if desired). Any previous interval started by a previous call to this function, for the same \"elementId\", will be stopped. Parameters: Name Type Argument Default Description elementId string | window &lt;optional&gt; window The identifier of the element whose horizontal scroll position we want to get. If a string with the identifier is not given, the unique value allowed is the window object (which is the default value when a non-valid value or no value is given). onScrollLeftChanges CB_Elements.getScrollLeftById_getScrollTopById_ON_SCROLL_CHANGES &lt;optional&gt; The desired callback function. It will be called as an interval if \"timeoutMs\" is a valid integer value. fireFirstTime boolean &lt;optional&gt; false If it is set to true, it will call the callback function (if any) as soon as this function is called. fireAlways boolean &lt;optional&gt; false If it is set to true, it will call the callback function (if any) every interval even if the horizontal scroll value has not changed from the last call. timeoutMs integer &lt;optional&gt; The number of milliseconds between one call to the callback function (if any) and the next one. If not given, it will not perform any interval. returnNullOnFail function &lt;optional&gt; false If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. Source: CrossBase/general/CB_Elements.js, line 1956 Returns: Returns the horizontal scroll of the given element (by its identifier). It could return zero (0) if something fails (use \"returnNullOnFail\" set to true to return null when it fails). Type number | null &lt;static&gt; getScrollTopById( [elementId] [, onScrollTopChanges] [, fireFirstTime] [, fireAlways] [, timeoutMs] [, returnNullOnFail]) → {number|null} Returns the vertical scroll of a given element (by its identifier) and allows running a callback function (becoming recursive if desired). Any previous interval started by a previous call to this function, for the same \"elementId\", will be stopped. Parameters: Name Type Argument Default Description elementId string | window &lt;optional&gt; window The identifier of the element whose vertical scroll position we want to get. If a string with the identifier is not given, the unique value allowed is the window object (which is the default value when a non-valid value or no value is given). onScrollTopChanges CB_Elements.getScrollLeftById_getScrollTopById_ON_SCROLL_CHANGES &lt;optional&gt; The desired callback function. It will be called as an interval if \"timeoutMs\" is a valid integer value. fireFirstTime boolean &lt;optional&gt; false If it is set to true, it will call the callback function (if any) as soon as this function is called. fireAlways boolean &lt;optional&gt; false If it is set to true, it will call the callback function (if any) every interval even if the vertical scroll value has not changed from the last call. timeoutMs integer &lt;optional&gt; The number of milliseconds between one call to the callback function (if any) and the next one. If not given, it will not perform any interval. returnNullOnFail function &lt;optional&gt; false If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. Source: CrossBase/general/CB_Elements.js, line 2067 Returns: Returns the vertical scroll of the given element (by its identifier). It could return zero (0) if something fails (use \"returnNullOnFail\" set to true to return null when it fails). Type number | null &lt;static&gt; getStyle(element [, computed]) → {Object|null} Returns the style of an element, computed or static: Parameters: Name Type Argument Default Description element Node The element whose style property we want to get. computed boolean &lt;optional&gt; false If it is set to true, it will try to use the native function window.getComputedStyle (if available). Source: CrossBase/general/CB_Elements.js, line 923 Returns: Returns an associative array (JavaScript object) with all the styles retrieved or null if nothing can be retrieved. Type Object | null &lt;static&gt; getStyleById(elementId [, computed]) → {Object|null} Returns the style of an element, computed or static (by its identifier): Parameters: Name Type Argument Default Description elementId string The identifier of the element whose style property we want to get. computed boolean &lt;optional&gt; false If it is set to true, it will try to use the native function window.getComputedStyle (if available). Source: CrossBase/general/CB_Elements.js, line 955 Returns: Returns an associative array (JavaScript object) with all the styles retrieved or null if nothing can be retrieved. Type Object | null &lt;static&gt; getStyleProperty(element, attribute [, computed]) → {*} Returns the desired attribute value from the style of an element, computed or static: Parameters: Name Type Argument Default Description element Node The element whose attribute value from its style we want to get. attribute string The name of the attribute whose value we want to get from the style. computed boolean &lt;optional&gt; false If it is set to true, it will try to use the native function window.getComputedStyle (if available). Source: CrossBase/general/CB_Elements.js, line 970 To Do: Think about supporting a boolean parameter to try to find the attribute having into account vendor prefixes (webkit, moz, ms, o, khtml). Returns: Returns null if nothing can be retrieved. Type * &lt;static&gt; getStylePropertyById(elementId, attribute [, computed]) → {*} Returns the desired attribute value from the style of an element, computed or static (by its identifier): Parameters: Name Type Argument Default Description elementId string The identifier of the element whose attribute value from its style we want to get. attribute string The name of the attribute whose value we want to get from the style. computed boolean &lt;optional&gt; false If it is set to true, it will try to use the native function window.getComputedStyle (if available). Source: CrossBase/general/CB_Elements.js, line 991 To Do: Think about supporting a boolean parameter to try to find the attribute having into account vendor prefixes (webkit, moz, ms, o, khtml). Returns: Returns null if nothing can be retrieved. Type * &lt;static&gt; getStylePropertyInteger(element, attribute [, computed]) → {array} Returns the integer value or values (base decimal) of a desired attribute from the style of an element, computed or static: Parameters: Name Type Argument Default Description element Node The element whose attribute value from its style we want to get. attribute string The name of the attribute whose value we want to get from the style. computed boolean &lt;optional&gt; false If it is set to true, it will try to use the native function window.getComputedStyle (if available). Source: CrossBase/general/CB_Elements.js, line 1006 To Do: Think about supporting a boolean parameter to try to find the attribute having into account vendor prefixes (webkit, moz, ms, o, khtml). Returns: Returns a numeric array with the values retrieved. If nothing could be retrieved, the first and unique index of the array will contain the value of zero (0). Type array &lt;static&gt; getStylePropertyIntegerById(elementId, attribute [, computed]) → {array} Returns the integer value or values (base decimal) of a desired attribute from the style of an element, computed or static (by its identifier): Parameters: Name Type Argument Default Description elementId string The identifier of the element whose attribute value from its style we want to get. attribute string The name of the attribute whose value we want to get from the style. computed boolean &lt;optional&gt; false If it is set to true, it will try to use the native function window.getComputedStyle (if available). Source: CrossBase/general/CB_Elements.js, line 1021 To Do: Think about supporting a boolean parameter to try to find the attribute having into account vendor prefixes (webkit, moz, ms, o, khtml). Returns: Returns a numeric array with the values retrieved. If nothing could be retrieved, the first and unique index of the array will contain the value of zero (0). Type array &lt;static&gt; getStylePropertyNumeric(element, attribute [, computed] [, parseToInteger]) → {array} Returns the numeric value or values (base decimal) of a desired attribute from the style of an element, computed or static: Parameters: Name Type Argument Default Description element Node The element whose attribute value from its style we want to get. attribute string The name of the attribute whose value we want to get from the style. computed boolean &lt;optional&gt; false If it is set to true, it will try to use the native function window.getComputedStyle (if available). parseToInteger boolean &lt;optional&gt; false If it is set to true, the value or values will be parsed to integer. Source: CrossBase/general/CB_Elements.js, line 1037 To Do: Think about supporting a boolean parameter to try to find the attribute having into account vendor prefixes (webkit, moz, ms, o, khtml). Returns: Returns a numeric array with the values retrieved. If nothing could be retrieved, the first and unique index of the array will contain the value of zero (0). Type array &lt;static&gt; getStylePropertyNumericById(elementId, attribute [, computed] [, parseToInteger]) → {array} Returns the numeric value or values (base decimal) of a desired attribute from the style of an element, computed or static (by its identifier): Parameters: Name Type Argument Default Description elementId string The identifier of the element whose attribute value from its style we want to get. attribute string The name of the attribute whose value we want to get from the style. computed boolean &lt;optional&gt; false If it is set to true, it will try to use the native function window.getComputedStyle (if available). parseToInteger boolean &lt;optional&gt; false If it is set to true, the value or values will be parsed to integer. Source: CrossBase/general/CB_Elements.js, line 1082 To Do: Think about supporting a boolean parameter to try to find the attribute having into account vendor prefixes (webkit, moz, ms, o, khtml). Returns: Returns a numeric array with the values retrieved. If nothing could be retrieved, the first and unique index of the array will contain the value of zero (0). Type array &lt;static&gt; getTop(element [, ignoreScroll] [, returnNullOnFail] [, computed]) → {*} Returns the top position of an element (having in mind getBoundingClientRect if available, its parents, etc.). Parameters: Name Type Argument Default Description element Node The element whose data we are interested in. ignoreScroll boolean &lt;optional&gt; true If it is set to false, it will have in mind the current scroll position to calculate the result. returnNullOnFail function &lt;optional&gt; false If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. computed boolean &lt;optional&gt; false This parameter will be used when it calls CB_Elements.getStyleProperty and CB_Elements.getStylePropertyInteger internally. Source: CrossBase/general/CB_Elements.js, line 1526 Returns: It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). Type * &lt;static&gt; getTopById(elementId [, ignoreScroll] [, returnNullOnFail] [, computed]) → {*} Returns the top position of an element (having in mind getBoundingClientRect if available, its parents, etc.), by its identifier. Parameters: Name Type Argument Default Description elementId string The identifier of the element whose data we are interested in. ignoreScroll boolean &lt;optional&gt; true If it is set to false, it will have in mind the current scroll position to calculate the result. returnNullOnFail function &lt;optional&gt; false If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. computed boolean &lt;optional&gt; false This parameter will be used when it calls CB_Elements.getStyleProperty and CB_Elements.getStylePropertyInteger internally. Source: CrossBase/general/CB_Elements.js, line 1638 Returns: It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). Type * &lt;static&gt; getWidth(element [, returnNullOnFail] [, computed]) → {*} Returns the width of an element (having in mind its border). Parameters: Name Type Argument Default Description element Node The element whose data we are interested in. returnNullOnFail function &lt;optional&gt; false If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. computed boolean &lt;optional&gt; false This parameter will be used when it calls CB_Elements.getStylePropertyInteger internally. Source: CrossBase/general/CB_Elements.js, line 1652 Returns: It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). Type * &lt;static&gt; getWidthById(elementId [, returnNullOnFail] [, computed]) → {*} Returns the width of an element (having in mind its border), by its identifier. Parameters: Name Type Argument Default Description elementId string The identifier of the element whose data we are interested in. returnNullOnFail function &lt;optional&gt; false If it is set to true, it will return null instead of zero (0) in the case that something goes wrong. computed boolean &lt;optional&gt; false This parameter will be used when it calls CB_Elements.getStylePropertyInteger internally. Source: CrossBase/general/CB_Elements.js, line 1702 Returns: It could return zero (0) or even a non-numeric value if something fails (use \"returnNullOnFail\" set to true to return null when it fails). Type * &lt;static&gt; hide(element [, checkValues] [, computed] [, onHide]) → {Node} Hides a given element by changing its display property to \"none\" and its visibility to \"hidden\". Parameters: Name Type Argument Default Description element Node The element that we want to hide. checkValues boolean &lt;optional&gt; false If it is set to true, it will only perform the change if either the current visibility property is not \"hidden\" or the current display property is not \"none\". computed boolean &lt;optional&gt; false This parameter will be used when it calls CB_Elements.getStyle internally. onHide function &lt;optional&gt; Callback function that will be called if the element has been hidden, after doing it (this will happens always if \"checkValues\" is false). The first parameter passed will be the affected element itself and the second and last parameter will be the new value of the display property (not computed) which should be \"none\". Source: CrossBase/general/CB_Elements.js, line 1185 Returns: Returns the given element again. Type Node &lt;static&gt; hideById(elementId [, checkValues] [, computed] [, onHide]) → {Node|null} Hides a given element by changing its display property to \"none\" and its visibility to \"hidden\" (by its identifier). Parameters: Name Type Argument Default Description elementId string The identifier of the element that we want to hide. checkValues boolean &lt;optional&gt; false If it is set to true, it will only perform the change if either the current visibility property is not \"hidden\" or the current display property is not \"none\". computed boolean &lt;optional&gt; false This parameter will be used when it calls CB_Elements.getStyle internally. onHide function &lt;optional&gt; Callback function that will be called if the element has been hidden, after doing it (this will happens always if \"checkValues\" is false). The first parameter passed will be the affected element itself and the second and last parameter will be the new value of the display property (not computed) which should be \"none\". Source: CrossBase/general/CB_Elements.js, line 1210 Returns: Returns the affected element (if any) or null otherwise. Type Node | null &lt;static&gt; id(id [, useCache]) → {Node|Object|null} Returns an element by its ID. Parameters: Name Type Argument Default Description id string The identifier of the element that we want to find. useCache boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Elements_id_USE_CACHE Defines whether to try to get the result from an internal cache (it will exist if we previously called the function with the same parameters) or not. The internal cache will be updated when this parameter is set to false or it will be created automatically when it did not exist before. Source: CrossBase/general/CB_Elements.js, line 543 Returns: Returns the elements (Node or object, depending on the web client). It will return null when not found. Type Node | Object | null &lt;static&gt; idCacheClear( [id]) → {Object} Clears the internal cache used by CB_Elements.id and others. If no parameter is given, whole internal cache will be cleared. Parameters: Name Type Argument Description id string &lt;optional&gt; The identifier of the element whose internal cache we want to clear. If not provided, it will clear the whole internal cache. Source: CrossBase/general/CB_Elements.js, line 601 Returns: Returns the current internal cache after cleaning it (if it is has been possible), which is an associative array of one dimension (JavaScript object) whose first and unique index belongs to the identifier and the value belongs to each element. Type Object &lt;static&gt; idCacheUpdate(id) → {node|Object|null} Returns an element by its ID, updating (or creating) the internal cache. Calls the CB_Elements.id function internally, with the \"useCache\" parameter set to false. Parameters: Name Type Description id string The identifier of the element that we want to find. Source: CrossBase/general/CB_Elements.js, line 589 Returns: Returns the elements (Node or object, depending on the web client). It will return null when not found. Type node | Object | null &lt;static&gt; idRemove(id [, useCache]) Removes an element by its ID. Parameters: Name Type Argument Default Description id string The identifier of the element that we want to delete. useCache boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Elements_id_USE_CACHE Defines whether to try to get the result from an internal cache (it will exist if we previously called the function with the same parameters) or not. The internal cache will be updated when this parameter is set to false or it will be created automatically when it did not exist before. Source: CrossBase/general/CB_Elements.js, line 621 &lt;static&gt; insertContent(container, content [, displayValue] [, checkValues] [, computed] [, onContentWritten] [, onShow] [, append] [, appendAtBeginning]) → {Node} Inserts the desired content inside a given element (using innerHTML). Parameters: Name Type Argument Default Description container Node The element whose content we want to modify. content string The content that we want to add. displayValue string &lt;optional&gt; If provided, it will call CB_Elements.show internally after inserting the content to set the given display property to the element. checkValues boolean &lt;optional&gt; false If it is set to true, it will only change the content if the current one is different from the given one and it will pass the same parameter to CB_Elements.show if it is called internally (when \"displayValue\" is given). computed boolean &lt;optional&gt; false If \"displayValue\" is given, it will pass this parameter to CB_Elements.show if it is called internally (when \"displayValue\" is given). onContentWritten function &lt;optional&gt; Callback function that will be called if the content has been written, after doing it (this will happens always if \"checkValues\" is false). The unique parameter passed will be the container itself. onShow function &lt;optional&gt; If \"displayValue\" is given, it will pass this parameter to CB_Elements.show when it is called internally. append boolean &lt;optional&gt; false If set to true, it will append the given content to the existing one instead of overwritten it. By default, it appends it at the end unless that the \"appendAtBeginning\" is set to true. appendAtBeginning boolean &lt;optional&gt; false If set to true, it will append the given content to the existing one instead of overwritten it. Source: CrossBase/general/CB_Elements.js, line 801 Returns: Returns the given container again. Type Node &lt;static&gt; insertContentById(containerId, content [, displayValue] [, checkValues] [, computed] [, onContentWritten] [, onShow] [, append] [, appendAtBeginning]) → {Node|null} Inserts the desired content inside a given element (using innerHTML), by its identifier. Parameters: Name Type Argument Default Description containerId string The identifier of the element whose content we want to modify. content string The content that we want to add. displayValue string &lt;optional&gt; If provided, it will call CB_Elements.show internally after inserting the content to set the given display property to the element. checkValues boolean &lt;optional&gt; false If it is set to true, it will only change the content if the current one is different from the given one and it will pass the same parameter to CB_Elements.show if it is called internally (when \"displayValue\" is given). computed boolean &lt;optional&gt; false If \"displayValue\" is given, it will pass this parameter to CB_Elements.show if it is called internally (when \"displayValue\" is given). onContentWritten function &lt;optional&gt; Callback function that will be called if the content has been written, after doing it (this will happens always if \"checkValues\" is false). The unique parameter passed will be the affected container itself. onShow function &lt;optional&gt; If \"displayValue\" is given, it will pass this parameter to CB_Elements.show when it is called internally. append boolean &lt;optional&gt; false If set to true, it will append the given content to the existing one instead of overwritten it. By default, it appends it at the end unless that the \"appendAtBeginning\" is set to true. appendAtBeginning boolean &lt;optional&gt; false If set to true, it will append the given content to the existing one instead of overwritten it. Source: CrossBase/general/CB_Elements.js, line 871 Returns: Returns the affected container (if any) or null otherwise. Type Node | null &lt;static&gt; preventSelection(element [, avoidSelection]) → {Node|null} Prevents or allows the possibility of selecting the content of a given element (makes it unselectable). Parameters: Name Type Argument Default Description element Node The element which we want to affect. avoidSelection boolean &lt;optional&gt; true If set to false, it will allow selecting the content. Otherwise, it will prevent it to be selected. Source: CrossBase/general/CB_Elements.js, line 1779 Returns: Returns the given element again or null. Type Node | null &lt;static&gt; preventSelectionById(elementId [, avoidSelection]) → {Node|null} Prevents or allows the possibility of selecting the content of a given element (makes it unselectable), by its ID. Parameters: Name Type Argument Default Description elementId string The identifier of the element which we want to affect. avoidSelection boolean &lt;optional&gt; true If set to false, it will allow selecting the content. Otherwise, it will prevent it to be selected. Source: CrossBase/general/CB_Elements.js, line 1826 Returns: Returns the affected element (if any) or null otherwise. Type Node | null &lt;static&gt; remove(element) Removes an element given. Parameters: Name Type Description element Node The element that we want to delete. Source: CrossBase/general/CB_Elements.js, line 639 &lt;static&gt; removeByClasses() Alias for CB_Elements.classesRemove. Source: CrossBase/general/CB_Elements.js, line 484 See: CB_Elements.classesRemove &lt;static&gt; removeById() Alias for CB_Elements.idRemove. Source: CrossBase/general/CB_Elements.js, line 610 See: CB_Elements.idRemove &lt;static&gt; removeByTagName() Alias for CB_Elements.tagRemove. Source: CrossBase/general/CB_Elements.js, line 229 See: CB_Elements.tagRemove &lt;static&gt; removeClass(element, className [, checkValues] [, onRemoveClass]) → {Node} Removes a desired class from a given element. The element can contain other classes and they will be kept. Parameters: Name Type Argument Default Description element Node The element whose class we want to remove. className string The class that will be removed if the element is using it. checkValues boolean &lt;optional&gt; false If it is set to true, it will only try to perform the action if the given \"className\" is being used. The result will be the same with either true or false, but depending on the client used it could gain or lose performance. onRemoveClass function &lt;optional&gt; Callback function that will be called if the class of the element has been tried to be removed, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. Source: CrossBase/general/CB_Elements.js, line 1279 To Do: Think about allowing to remove more than once class at the same time, regardless of the order given and order set. Returns: Returns the given element again. Type Node &lt;static&gt; removeClassById(elementId, className [, checkValues] [, onRemoveClass]) → {Node|null} Removes a desired class from a given element (by its identifier). The element can contain other classes and they will be kept. Parameters: Name Type Argument Default Description elementId string The identifier of the element whose class we want to remove. className string The class that will be removed if the element is using it. checkValues boolean &lt;optional&gt; false If it is set to true, it will only try to perform the action if the given \"className\" is being used. The result will be the same with either true or false, but depending on the client used it could gain or lose performance. onRemoveClass function &lt;optional&gt; Callback function that will be called if the class of the element has been tried to be removed, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. Source: CrossBase/general/CB_Elements.js, line 1306 To Do: Think about allowing to remove more than once class at the same time, regardless of the order given and order set. Returns: Returns the affected element (if any) or null otherwise. Type Node | null &lt;static&gt; setClass(element, classNames [, checkValues] [, onSetClass]) → {Node} Sets a desired class or classes to a given element. All previous classes (if any) will be replaced by the new one or new ones. Parameters: Name Type Argument Default Description element Node The element that will get the new given class or classes. classNames string The class or classes that will be set. More than one class can be given (separated by blank spaces). checkValues boolean &lt;optional&gt; false If it is set to true, it will only try to set the given class or classes if they are not being used already. onSetClass function &lt;optional&gt; Callback function that will be called if the class or classes of the element have been set, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. Source: CrossBase/general/CB_Elements.js, line 1364 Returns: Returns the given element again. Type Node &lt;static&gt; setClassById(elementId, classNames [, checkValues] [, onSetClass]) → {Node|null} Sets a desired class or classes to a given element (by its identifier). All previous classes (if any) will be replaced by the new one or new ones. Parameters: Name Type Argument Default Description elementId string The identifier of the element that will get the new given class or classes. classNames string The class or classes that will be set. More than one class can be given (separated by blank spaces). checkValues boolean &lt;optional&gt; false If it is set to true, it will only try to set the given class or classes if they are not being used already. onSetClass function &lt;optional&gt; Callback function that will be called if the class or classes of the element have been set, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. Source: CrossBase/general/CB_Elements.js, line 1387 Returns: Returns the affected element (if any) or null otherwise. Type Node | null &lt;static&gt; setProperty(element, property, propertyValue [, checkValues] [, onSetProperty]) → {Node|null} Changes a desired element property with the given value. Parameters: Name Type Argument Default Description element Node The element whose property we want to modify. property string The name of the property that we want to modify. propertyValue * The value desired for the property. checkValues boolean &lt;optional&gt; false If set to true, it will only modify the property if the current value is different from the given one. onSetProperty function &lt;optional&gt; Callback function that will be called if the property of the element has been set, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. Source: CrossBase/general/CB_Elements.js, line 759 Returns: Returns the given element again or null. Type Node | null &lt;static&gt; setPropertyById(elementId, property, propertyValue [, checkValues] [, onSetProperty]) → {Node|null} Changes a desired element property with the given value (by its identifier). Parameters: Name Type Argument Default Description elementId string The identifier of the element whose property we want to modify. property string The name of the property that we want to modify. propertyValue * The value desired for the property. checkValues boolean &lt;optional&gt; false If set to true, it will only modify the property if the current value is different from the given one. onSetProperty function &lt;optional&gt; Callback function that will be called if the property of the element has been set, after doing it (this will happens always if \"checkValues\" is false). The first and unique parameter passed will be the affected element itself. Source: CrossBase/general/CB_Elements.js, line 781 Returns: Returns the affected element (if any) or null otherwise. Type Node | null &lt;static&gt; show(element [, displayValue] [, checkValues] [, computed] [, onShow]) → {Node} Changes the display property to the desired value of a given element, to show it. Its visibility property will be set to \"visible\". Parameters: Name Type Argument Default Description element Node The element whose display property we want to change. displayValue string &lt;optional&gt; 'block' The display value we want to set. If not provided or \"none\" is provided, it will use \"block\" instead. checkValues boolean &lt;optional&gt; false If it is set to true, it will only perform the change if either the current visibility property is not \"visible\" or the current display property is different from the given one. computed boolean &lt;optional&gt; false This parameter will be used when it calls CB_Elements.getStyle internally. onShow function &lt;optional&gt; Callback function that will be called if the change has been performed, after doing it (this will happens always if \"checkValues\" is false). The first parameter passed will be the affected element itself and the second and last parameter will be the new value of the display property (not computed). Source: CrossBase/general/CB_Elements.js, line 1142 Returns: Returns the given element again. Type Node &lt;static&gt; showById(elementId [, displayValue] [, checkValues] [, computed] [, onShow]) → {Node|null} Changes the display property to the desired value of a given element, to show it (by its identifier). Its visibility property will be set to \"visible\". Parameters: Name Type Argument Default Description elementId string The identifier of the element whose display property we want to change. displayValue string &lt;optional&gt; 'block' The display value we want to set. If not provided or \"none\" is provided, it will use \"block\" instead. checkValues boolean &lt;optional&gt; false If it is set to true, it will only perform the change if either the current visibility property is not \"visible\" or the current display property is different from the given one. computed boolean &lt;optional&gt; false This parameter will be used when it calls CB_Elements.getStyle internally. onShow function &lt;optional&gt; Callback function that will be called if the change has been performed, after doing it (this will happens always if \"checkValues\" is false). The first parameter passed will be the affected element itself and the second and last parameter will be the new value of the display property (not computed). Source: CrossBase/general/CB_Elements.js, line 1170 Returns: Returns the affected element (if any) or null otherwise. Type Node | null &lt;static&gt; showHide(element [, displayValue] [, checkValues] [, computed] [, onToggleDisplay] [, onShow] [, onHide]) → {Node} Toggles the display property (from \"none\" to the desired value or vice versa) of a given element, to show or hide it.If the element is hidden (its display is \"none\"), it will call CB_Elements.show internally to show it. Otherwise, it will call CB_Elements.hide internally. Note that these two functions will also change the visibility property (setting it to either \"visible\" or \"hidden\", respectively) of the element. Parameters: Name Type Argument Default Description element Node The element whose display property we want to toggle. displayValue string &lt;optional&gt; 'block' The display value when we want to show the element (it will be used only if the element is currently hidden, when it calls CB_Elements.show internally). The display value to hide the element is always \"none\". checkValues boolean &lt;optional&gt; false This parameter will be used when it calls either CB_Elements.show or CB_Elements.hide internally. computed boolean &lt;optional&gt; false This parameter will be used to get the current style and also when it calls either CB_Elements.show or CB_Elements.hide internally. onToggleDisplay function &lt;optional&gt; This parameter will be used when it calls either CB_Elements.show if \"onShow\" is not provided or CB_Elements.hide if \"onHide\" is not provided, internally. onShow function &lt;optional&gt; This parameter will be used when it calls CB_Elements.show internally. If not provided but \"onToggleDisplay\" is provided, it will use the latter instead. onHide function &lt;optional&gt; This parameter will be used when it calls CB_Elements.hide internally. If not provided but \"onToggleDisplay\" is provided, it will use the latter instead. Source: CrossBase/general/CB_Elements.js, line 1101 Returns: Returns the given element again. Type Node &lt;static&gt; showHideById(elementId [, displayValue] [, checkValues] [, computed] [, onToggleDisplay] [, onShow] [, onHide]) → {Node|null} Toggles the display property (from \"none\" to the desired value or vice versa) of a given element, to show or hide it (by its identifier).If the element is hidden (its display is \"none\"), it will call CB_Elements.show internally to show it. Otherwise, it will call CB_Elements.hide internally. Note that these two functions will also change the visibility property (setting it to either \"visible\" or \"hidden\", respectively) of the element. Parameters: Name Type Argument Default Description elementId string The identifier of the element whose display property we want to toggle. displayValue string &lt;optional&gt; 'block' The display value when we want to show the element (it will be used only if the element is currently hidden, when it calls CB_Elements.show internally). The display value to hide the element is always \"none\". checkValues boolean &lt;optional&gt; false This parameter will be used when it calls either CB_Elements.show or CB_Elements.hide internally. computed boolean &lt;optional&gt; false This parameter will be used to get the current style and also when it calls either CB_Elements.show or CB_Elements.hide internally. onToggleDisplay function &lt;optional&gt; This parameter will be used when it calls either CB_Elements.show if \"onShow\" is not provided or CB_Elements.hide if \"onHide\" is not provided, internally. onShow function &lt;optional&gt; This parameter will be used when it calls CB_Elements.show internally. If not provided but \"onToggleDisplay\" is provided, it will use the latter instead. onHide function &lt;optional&gt; This parameter will be used when it calls CB_Elements.hide internally. If not provided but \"onToggleDisplay\" is provided, it will use the latter instead. Source: CrossBase/general/CB_Elements.js, line 1126 Returns: Returns the affected element (if any) or null otherwise. Type Node | null &lt;static&gt; tag( [tagName] [, baseElement] [, useCache]) → {NodeList|array} Returns elements by their tag name. Parameters: Name Type Argument Default Description tagName string &lt;optional&gt; '*' The name of the tag whose elements we want to find. Use asterisk (\"*\") in the case that we want all the elements. baseElement Node &lt;optional&gt; document The node element parent where we want to focus our search. useCache boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Elements_tag_USE_CACHE Defines whether to try to get the result from an internal cache (it will exist if we previously called the function with the same parameters) or not. The internal cache will be updated when this parameter is set to false or it will be created automatically when it did not exist before. Source: CrossBase/general/CB_Elements.js, line 52 Returns: Returns the elements (NodeList or array, depending on the web client). Type NodeList | array &lt;static&gt; tagCacheClear( [tagName] [, baseElement]) → {Object} Clears the internal cache user by CB_Elements.tag and others. If no parameter is given, whole internal cache will be cleared. Parameters: Name Type Argument Description tagName string &lt;optional&gt; The name of the tag whose internal cache we want to clear. Use asterisk (\"*\") in the case that we want to clear the internal cache for CB_Elements.tag which is used when it is called with this exact parameter. If not provided, it will clear the whole internal cache or the internal cache that belongs to the \"baseElement\" given (if provided). baseElement Node &lt;optional&gt; The node element parent whose internal cache we want to clear. If not provided but \"tagName\" is provided, it will clear the internal cache which matches the given \"tagName\" for any nodes. If it is provided but \"tagName\" is not, it will clear all the internal cache that belongs to this node element. Source: CrossBase/general/CB_Elements.js, line 185 Returns: Returns the current internal cache after clearing it (if it is has been possible), which is an associative array of two dimensions (JavaScript object) whose first index belongs to the nodes, the second and last index belongs to the tag name and the value belongs to the returning value of the CB_Elements.tag function when it was called for those parameters. Type Object &lt;static&gt; tagCacheUpdate( [tagName] [, baseElement]) → {NodeList|array} Returns elements by their tag name, updating (or creating) the internal cache. Calls the CB_Elements.tag function internally, with the \"useCache\" parameter set to false. Parameters: Name Type Argument Default Description tagName string &lt;optional&gt; '*' The name of the tag whose elements we want to find. Use asterisk (\"*\") in the case that we want all the elements. baseElement Node &lt;optional&gt; document The node element parent where we want to focus our search. Source: CrossBase/general/CB_Elements.js, line 172 Returns: Returns the elements (NodeList or array, depending on the web client). Type NodeList | array &lt;static&gt; tagRemove( [tagName] [, baseElement] [, useCache]) Removes elements by their tag name. Parameters: Name Type Argument Default Description tagName string &lt;optional&gt; '*' The name of the tag whose elements we want to delete. Use asterisk (\"*\") in the case that we want all the elements. baseElement Node &lt;optional&gt; document The node element parent where we want to focus our search. useCache boolean &lt;optional&gt; CB_Configuration.CrossBase.CB_Elements_tag_USE_CACHE Defines whether to try to get the result from an internal cache (it will exist if we previously called the function with the same parameters) or not. The internal cache will be updated when this parameter is set to false or it will be created automatically when it did not exist before. Source: CrossBase/general/CB_Elements.js, line 241 &lt;static&gt; toggleClass(element, classA [, classB] [, onToggleClass]) → {Node} Toggles the class of a given element between two given classes or adds/removes the given class. The element can contain other classes and they will be kept. Parameters: Name Type Argument Default Description element Node The element whose class we want to toggle. classA string The class that will be used in the case that the element is not using it already. classB string &lt;optional&gt; '' The class that will be used in the case that the given \"classA\" is being used by the element. If not given or an empty string is given, it will just remove the \"classA\" in the case it is being used by the element. onToggleClass function &lt;optional&gt; Callback function that will be called if the class of the element has been toggled or removed, after doing it. The first parameter passed will be the affected element itself and the second and last parameter will be the class used this time (or an empty string). Source: CrossBase/general/CB_Elements.js, line 1225 Returns: Returns the given element again. Type Node &lt;static&gt; toggleClassById(elementId, classA [, classB] [, onToggleClass]) → {Node|null} Toggles the class of a given element between two given classes (by its identifier). The element can contain other classes and they will be kept. Parameters: Name Type Argument Default Description elementId string The identifier of the element whose class we want to toggle. classA string The class that will be used in the case that the element is not using it already. classB string &lt;optional&gt; '' The class that will be used in the case that the given \"classA\" is being used by the element. If not given or an empty string is given, it will just remove the \"classA\" in the case it is being used by the element. onToggleClass function &lt;optional&gt; Callback function that will be called if the class of the element has been toggled or removed, after doing it. The first parameter passed will be the affected element itself and the second and last parameter will be the class used this time (or an empty string). Source: CrossBase/general/CB_Elements.js, line 1263 Returns: Returns the affected element (if any) or null otherwise. Type Node | null Type Definitions getScrollLeftById_getScrollTopById_ON_SCROLL_CHANGES(scrollLeftOrTop, scrollLeftOrTopPrevious, scrollWidthOrHeight, clientWidthOrHeight, scrollLeftOrTopRelative, scrollLeftOrTopRelativePrevious) Callback that is used as the \"onScrollLeftChanges\" parameter for the CB_Elements.getScrollLeftById function or as the \"onScrollTopChanges\" parameter for the CB_Elements.getScrollTopById function. All values received should be checked since some could be not numbers. Parameters: Name Type Description scrollLeftOrTop * The scroll left or scroll top position. scrollLeftOrTopPrevious * The previous scroll left or scroll top position. scrollWidthOrHeight * The scroll width or scroll height. clientWidthOrHeight * The client width or client height (element.clientWidth/element.offsetWidth or element.clientHeight/element.offsetHeight, depending on the web client). scrollLeftOrTopRelative * The relative scroll left or scroll top position. scrollLeftOrTopRelativePrevious * The previous relative scroll left or scroll top position. Source: CrossBase/general/CB_Elements.js, line 1930 × Search results Close "},"CB_Events.html":{"id":"CB_Events.html","title":"Namespace: CB_Events","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Events CB_Events Static class to manage events. It will return itself if it is tried to be instantiated. Source: CrossBase/general/CB_Events.js, line 12 Methods &lt;static&gt; add() Alias for CB_Events.on. Source: CrossBase/general/CB_Events.js, line 148 See: CB_Events.on &lt;static&gt; executeByName(eventTarget, eventName [, e] [, returnOnNothingExecuted]) → {boolean} Executes all event listeners for an specific event from a node (target). Parameters: Name Type Argument Description eventTarget Object The target whose event listeners we want to execute. It will be the value of \"this\" for every call to each listener. eventName string The name of the event whose event listeners we want to execute. e Event &lt;optional&gt; Event object that will be passed as the first and unique parameter for every call to each listener. returnOnNothingExecuted * &lt;optional&gt; The value that will be returned by the function if nothing is executed. Source: CrossBase/general/CB_Events.js, line 364 Returns: Returns the result of doing the AND operator of all return values of each listener executed. If only one listener is executed, it will return the result of doing the AND operator with its returning value and \"true\". Returns the value of the \"returnOnNothingExecuted\" parameter if nothing is executed. Type boolean &lt;static&gt; getAll() → {array} Returns all stored event handlers (if any). Source: CrossBase/general/CB_Events.js, line 426 Returns: Returns an array of CB_Events.EVENT_HANDLER objects. Type array &lt;static&gt; getByName(eventTarget, eventName [, onlyWithFunction]) → {array} Returns all handlers for an specific event from a node (target), if any. Parameters: Name Type Argument Default Description eventTarget Object The target whose event listeners we want to get. eventName string The name of the event whose event listeners we want to get. onlyWithFunction boolean &lt;optional&gt; false Defines whether to return only the handlers which have a function as the listener. Source: CrossBase/general/CB_Events.js, line 398 Returns: Returns an array of CB_Events.EVENT_HANDLER objects. Type array &lt;static&gt; getType(e) → {string} Returns the type of an event, if any (otherwise, returns an empty string). Parameters: Name Type Description e Event Event object. Source: CrossBase/general/CB_Events.js, line 109 Returns: Type string &lt;static&gt; normalize(e) → {Event} Gets the right event object for the current web client and normalizes it attaching to it some methods and properties if they were not present (as preventDefault, stopPropagation, target, etc.). The new attached methods and properties may include polyfills, etc. Parameters: Name Type Description e Event Event object. If not provided, it will use the value of \"event\", \"window.event\", \"Event\" or an empty object (\"{}\"). Source: CrossBase/general/CB_Events.js, line 38 Returns: Returns the event object normalized. Type Event &lt;static&gt; on(eventTarget, eventName, eventFunction [, useCapture] [, keepOldEventFunction] [, erasable]) Adds an event listener. Parameters: Name Type Argument Default Description eventTarget Object The target where we want to attach the event listener. eventName string The name of the event that we want to add. eventFunction function The function (event listener) of the event that we want to add. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. keepOldEventFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. erasable boolean &lt;optional&gt; true Defines whether the event listener will be erasable by CB_Events.removeAll or CB_Events.removeByName functions later or not (it will always be erasable if we force delete). Source: CrossBase/general/CB_Events.js, line 164 To Do: Try to simulate \"useCapture\" when the \"addEventListener\" method is not available. &lt;static&gt; remove(eventTarget, eventName, eventFunction [, useCapture]) Removes an event listener (even if it is not erasable). Parameters: Name Type Argument Default Description eventTarget Object The target whose event listener we want to remove. eventName string The name of the event that we want to remove. eventFunction function The function (event listener) of the event that we want to remove. useCapture boolean &lt;optional&gt; false Defines whether the event we want to remove was defined to use capture or not. Source: CrossBase/general/CB_Events.js, line 125 &lt;static&gt; removeAll( [forceDelete]) Removes all event listeners. Parameters: Name Type Argument Default Description forceDelete boolean &lt;optional&gt; false If it is set to true, it will remove all event listeners (even the ones which were added as not erasable). Source: CrossBase/general/CB_Events.js, line 340 &lt;static&gt; removeByName(eventTarget, eventName [, forceDelete]) Deletes all handlers for an specific event from a node (target). Parameters: Name Type Argument Default Description eventTarget Object The target whose event listeners we want to remove. eventName string The name of the event whose event listeners we want to remove. forceDelete boolean &lt;optional&gt; false If it is set to true, it will remove any listener (even the ones which were added as not erasable). Source: CrossBase/general/CB_Events.js, line 313 Type Definitions EVENT_HANDLER Object that contains an event handler. Type: Object Properties: Name Type Description eventTarget Object The target of the event. eventName string The name of the event. eventFunction function The event listener. useCapture boolean Defines whether the event listener was defined to use capture or not. erasable boolean Defines whether the event handler is erasable (without forcing delete) or not. Source: CrossBase/general/CB_Events.js, line 254 × Search results Close "},"CB_GraphicSprites.html":{"id":"CB_GraphicSprites.html","title":"Class: CB_GraphicSprites","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Class: CB_GraphicSprites CB_GraphicSprites Class to manage a group of graphic sprites (2D or 3D). new CB_GraphicSprites( [spritesGroup] [, byReference]) → {CB_GraphicSprites} Class to manage a group of graphic sprites (2D or 3D). Parameters: Name Type Argument Default Description spritesGroup CB_GraphicSprites.SPRITES_OBJECT &lt;optional&gt; Object with the desired sprites. The information will be used for the CB_GraphicSprites#spritesGroup property. Used as the \"spritesGroup\" parameter when calling the CB_GraphicSprites#insertSprites method internally. byReference boolean &lt;optional&gt; !!CB_GraphicSprites.SPRITES_OBJECT.byReference_DEFAULT This value will be used as the default value when the \"byReference\" property is not given in the sprites (CB_GraphicSprites.SPRITE_OBJECT objects) or sub-sprites (CB_GraphicSprites.SUBSPRITE_OBJECT objects). The value will be stored in the CB_GraphicSprites#byReference_DEFAULT property. If a boolean value is not provided, it will use the value of the CB_GraphicSprites.SPRITES_OBJECT.byReference_DEFAULT property of the given CB_GraphicSprites.SPRITES_OBJECT object (parsed to boolean). Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 233 To Do: Think about a \"createCopy\" parameter on different the insert methods (to insert sprites groups/graphic sprites objects, etc.) so it will make a copy of the object to avoid using/modifying the original one. If the \"createCopy\" is set to false, it should always use the object as reference (using/modifying it). Think about a method to remove a sprite when the same sprite is received by parameter. The same with sub-sprites, receiving the sub-sprite by parameter. The same to remove the sprites group object, receiving a sprites group object by parameter. Only remove them if they match exactly. Returns: Returns a new CB_GraphicSprites object. Type CB_GraphicSprites Members &lt;static, constant&gt; filterProperties_DEFAULT_PROPERTIES :CB_GraphicSprites.filterProperties_propertiesToKeepObject_TYPE Object used as the default value for the \"propertiesToKeepObject\" parameter if not provided when calling the CB_GraphicSprites.filterProperties function. Type: CB_GraphicSprites.filterProperties_propertiesToKeepObject_TYPE Default Value: {\"spritesScene\":\"\",\"spritesGroups\":\"\",\"sprites\":\"\",\"spritesGroup\":\"\",\"sprite\":\"\",\"subSprite\":\"\"} Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1887 &lt;static, constant&gt; HEIGHT_DEFAULT :number Default \"height\" of the destiny. Unit agnostic. Type: number Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 417 &lt;static, constant&gt; HEIGHT_SOURCE_DEFAULT :number Default height (\"srcHeight\") of the original source. Unit agnostic. Type: number Default Value: 32 Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 387 &lt;static, constant&gt; LEFT_DEFAULT :number Default \"left\" (horizontal position) in the destiny. Unit agnostic. Type: number Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 425 &lt;static, constant&gt; LEFT_SOURCE_DEFAULT :number Default left (\"srcLeft\", horizontal position) in the original source. Unit agnostic. Type: number Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 395 &lt;static, constant&gt; SRC_TYPES :object Object with some \"srcType\". Each property of this object belong to one source type, having an integer as value which represents it. You can define more source types here. Type: object Default Value: {\"DEFAULT\":0,\"IMAGE\":0,\"TEXT\":1,\"SEGMENT\":2,\"PIXEL\":3,\"RECTANGLE\":4,\"CIRCLE\":5,\"ARC\":6,\"ELLIPSE\":7,\"TRIANGLE\":8,\"BEZIER_CURVE\":9,\"QUADRATIC_BEZIER_CURVE\":10,\"BITMAP\":11,\"MAP\":12} Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 344 &lt;static, constant&gt; SRC_TYPES_DEFAULT :integer Default \"srcType\", the type of the original source. Type: integer Default Value: CB_GraphicSprites.SRC_TYPES.IMAGE Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 372 &lt;static, constant&gt; TOP_DEFAULT :number Default \"top\" (vertical position) in the destiny. Unit agnostic. Type: number Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 432 &lt;static, constant&gt; TOP_SOURCE_DEFAULT :number Default top (\"srcTop\", vertical position) in the original source. Unit agnostic. Type: number Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 402 &lt;static, constant&gt; WIDTH_DEFAULT :number Default \"width\" of the destiny. Unit agnostic. Type: number Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 410 &lt;static, constant&gt; WIDTH_SOURCE_DEFAULT :number Default width (\"srcWidth\") of the original source. Unit agnostic. Type: number Default Value: 32 Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 380 &lt;static, constant&gt; ZINDEX_DEFAULT :number Default \"zIndex\" in the destiny. Type: number Default Value: 1 Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 440 byReference_DEFAULT :boolean This value will be used as the default value when the \"byReference\" property is not given in the sprites (CB_GraphicSprites.SPRITE_OBJECT objects) or sub-sprites (CB_GraphicSprites.SUBSPRITE_OBJECT objects). Type: boolean Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 311 &lt;readonly&gt; id :string|* Identifier of the sprites group object (the \"id\" property of the CB_GraphicSprites.SPRITES_OBJECT stored in the CB_GraphicSprites#spritesGroup property) and the CB_GraphicSprites object itself (same one). It should be unique. It must be a value which evaluates to true. By default, it is generated automatically (with an internal counter). Type: string | * Default Value: 'CB_GraphicSprites_' + CB_GraphicSprites._idUnique++ Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 246 &lt;constant&gt; isSprites :boolean Property which is always set to true to help identify this type of object. Type: boolean Default Value: true Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 326 &lt;readonly&gt; parent :* Property pointing to or containing its parent. It could be a CB_GraphicSpritesScene object. It is the same as the \"parent\" property of the CB_GraphicSprites.SPRITES_OBJECT stored in the CB_GraphicSprites#spritesGroup property. Type: * Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 255 &lt;readonly&gt; pointer :integer Pointer with the position of the current sprite (belongs to an index of the CB_GraphicSprites#spritesGroup.sprites array). Type: integer Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 282 &lt;readonly&gt; pointerPrevious :integer Keeps the previous value of the CB_GraphicSprites#pointer property (if any). Type: integer Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 292 &lt;readonly&gt; spritesGroup :CB_GraphicSprites.SPRITES_OBJECT Object with information about the sprites. Type: CB_GraphicSprites.SPRITES_OBJECT Default Value: {} Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 273 &lt;readonly&gt; time :integer Stores the time in milliseconds when the current sprite was started being pointed (time elapsed since the time origin which will be obtained calling the CB_Device.getTiming function internally). Type: integer Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 302 &lt;constant&gt; type :string Indicates the type of object (always \"sprites\"). Type: string Default Value: sprites Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 335 &lt;readonly&gt; zIndex :number Z-index of the sprites group object (the \"zIndex\" property of the CB_GraphicSprites.SPRITES_OBJECT stored in the CB_GraphicSprites#spritesGroup property) and the CB_GraphicSprites object itself (same one). To change the value of this property, use the CB_GraphicSprites#setZIndex method (which will call the CB_GraphicSpritesScene#updateGraphicSpritesByZIndex method internally if there is a CB_GraphicSpritesScene parent object). Only numeric values which are not zero (0) are allowed. Type: number Default Value: CB_GraphicSprites.ZINDEX_DEFAULT Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 264 Methods &lt;static&gt; clearReferences(element) → {*} Clears the \"container\", the \"parent\" and the \"data.that\" properties (sets to null) of the given object and its sub-objects (works recursively, internally). Parameters: Name Type Description element * The object whose properties we want to clear. It can be different kinds (CB_GraphicSpritesScene, CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT, CB_GraphicSprites, CB_GraphicSprites.SPRITES_OBJECT, CB_GraphicSprites.SPRITE_OBJECT, CB_GraphicSprites.SUBSPRITE_OBJECT, etc.). Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1844 Returns: Returns the same object with the the \"container\", the \"parent\", \"data.that\" and the \"data.getThis\" properties cleared (set to null), if possible. Type * &lt;static&gt; filterProperties(element [, propertiesToKeepObject]) → {*} Gets a new object with the properties filtered of a given element and its sub-elements, keeping only the ones that are in the given \"propertiesToKeepObject\" (works recursively, internally). Parameters: Name Type Argument Default Description element * The object whose properties we want to clear. It can be different kinds (CB_GraphicSpritesScene, CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT, CB_GraphicSprites, CB_GraphicSprites.SPRITES_OBJECT, CB_GraphicSprites.SPRITE_OBJECT, CB_GraphicSprites.SUBSPRITE_OBJECT, etc.). propertiesToKeepObject CB_GraphicSprites.filterProperties_propertiesToKeepObject_TYPE &lt;optional&gt; CB_GraphicSprites.filterProperties_DEFAULT_PROPERTIES The object with the properties that we want to keep. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1914 To Do: Implement a boolean property and when it is true it will not keep the properties whose values are the default ones (for example, if \"byReference\" property is false it will not be kept as it is its default value). So the output can be reduced this way. Returns: Returns a new object with the properties filtered of a given element and its sub-elements, keeping only the ones that are in the given \"propertiesToKeepObject\". If no valid \"element\" is provided, returns null. Type * current() Alias for CB_GraphicSprites#getCurrent. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1361 See: CB_GraphicSprites#getCurrent destructor() Destroys the graphic sprites object (removing all the sprites and their sub-sprites, etc.) and frees memory. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 462 executeAll() Alias for CB_GraphicSprites#executeFunctionAll. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1219 See: CB_GraphicSprites#executeFunctionAll executeFunctionAll(functionEach [, orderedByZIndex] [, delayBetweenEach] [, sprites] [, returnSetTimeoutsArray] [, delayBetweenEachAffectsFirst] [, functionFinish]) → {integer|array} Performs a desired action, using the provided function, on all the existing sprites (CB_GraphicSprites.SPRITE_OBJECT objects) or on the desired ones (if provided). Calls the CB_Arrays.executeFunctionAll function internally and returns its returning value. Parameters: Name Type Argument Default Description functionEach CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK Function that will be called for each sprite (CB_GraphicSprites.SPRITE_OBJECT object). As the first parameter it receives the CB_GraphicSprites.SPRITE_OBJECT object of the \"sprites\" being looped, as the second parameter the position of this CB_GraphicSprites.SPRITE_OBJECT object in the \"sprites\" array provided (or, if not provided, in the array returned by the CB_GraphicSprites#getSprites method), the third parameter is the array being looped and the fourth parameter will be the \"delayBetweenEach\" being used, being \"this\" the CB_GraphicSprites.SPRITE_OBJECT object itself. orderedByZIndex boolean &lt;optional&gt; false If set to true, it will loop the sprites sorted by their z-index (ascending order). delayBetweenEach number | CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK &lt;optional&gt; 0 If a value greater than zero is used, it will be used as the delay desired between each call to the \"functionEach\" function (calling them using the setTimeout function internally). If not provided or the value is 0 (zero) or lower, each call to the \"functionEach\" function will be performed immediately one after the other. If a function is provided, it will be called with the same parameters as the \"functionEach\" function and its returning value will be used as the delay (executed every loop for each CB_GraphicSprites.SPRITE_OBJECT object). sprites array &lt;optional&gt; CB_GraphicSprites#getSprites() A numeric array containing the sprites (CB_GraphicSprites.SPRITE_OBJECT objects) that we want to loop. It should contain only CB_GraphicSprites.SPRITE_OBJECT objects which are already in the current CB_GraphicSprites object. If not provided, it will use all the CB_GraphicSprites.SPRITE_OBJECT objects contained in the CB_GraphicSprites object. returnSetTimeoutsArray boolean &lt;optional&gt; false Defines whether we want the method to return an integer or a numeric array with information of each setTimeout call. Returning an array with information of each setTimeout call is only useful when the setTimeout function is called internally, which happens when the \"delayBetweenEach\" parameter is greater than 0 (zero). delayBetweenEachAffectsFirst boolean &lt;optional&gt; false If set to true, the desired delay (if any) will also affect the first call to the \"functionEach\" function. functionFinish CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK &lt;optional&gt; Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1247 To Do: Think about only allowing CB_GraphicSprites.SPRITE_OBJECT objects (in the \"sprites\" parameter) which are already in the CB_GraphicSprites (identify them by their ID), to avoid problems. Returns: If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the CB_GraphicSprites.SPRITE_OBJECT objects given in the \"sprites\" parameter). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a CB_Arrays.executeFunctionAll_OBJECT object for each CB_GraphicSprites.SPRITE_OBJECT given. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the setTimeout function. Type integer | array executeFunctionAllSubSprites(functionEach [, orderedByZIndex] [, delayBetweenEach] [, sprite] [, returnSetTimeoutsArray] [, delayBetweenEachAffectsFirst] [, functionFinish]) → {integer|array} Performs a desired action, using the provided function, on all the existing sub-sprites (CB_GraphicSprites.SUBSPRITE_OBJECT objects) from a given sprite (CB_GraphicSprites.SPRITE_OBJECT object). Calls the CB_Arrays.executeFunctionAll function internally and returns its returning value. Parameters: Name Type Argument Default Description functionEach CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK Function that will be called for each sub-sprite (CB_GraphicSprites.SUBSPRITE_OBJECT object) from the given sprite (CB_GraphicSprites.SPRITE_OBJECT object). As the first parameter it receives the CB_GraphicSprites.SUBSPRITE_OBJECT object of the sub-sprites being looped, as the second parameter the position of this CB_GraphicSprites.SUBSPRITE_OBJECT object in the \"subSprites\" property of the sprite (CB_GraphicSprites.SPRITE_OBJECT object) provided (which is an array), the third parameter is the array being looped and the fourth parameter will be the \"delayBetweenEach\" being used, being \"this\" the CB_GraphicSprites.SUBSPRITE_OBJECT object itself. orderedByZIndex boolean &lt;optional&gt; false If set to true, it will loop the sub-sprites sorted by their z-index (ascending order). delayBetweenEach number | CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK &lt;optional&gt; 0 If a value greater than zero is used, it will be used as the delay desired between each call to the \"functionEach\" function (calling them using the setTimeout function internally). If not provided or the value is 0 (zero) or lower, each call to the \"functionEach\" function will be performed immediately one after the other. If a function is provided, it will be called with the same parameters as the \"functionEach\" function and its returning value will be used as the delay (executed every loop for each CB_GraphicSprites.SUBSPRITE_OBJECT object). sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; CB_GraphicSprites#getCurrent() The CB_GraphicSprites.SPRITE_OBJECT object which contains the sprite and its sub-sprites. If not provided, it will use the CB_GraphicSprites.SPRITE_OBJECT object which the pointer (set in the CB_GraphicSprites#pointer property) is currently pointing to (using the returning value of the CB_GraphicSprites#getCurrent method internally). returnSetTimeoutsArray boolean &lt;optional&gt; false Defines whether we want the method to return an integer or a numeric array with information of each setTimeout call. Returning an array with information of each setTimeout call is only useful when the setTimeout function is called internally, which happens when the \"delayBetweenEach\" parameter is greater than 0 (zero). delayBetweenEachAffectsFirst boolean &lt;optional&gt; false If set to true, the desired delay (if any) will also affect the first call to the \"functionEach\" function. functionFinish CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK &lt;optional&gt; Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1276 To Do: Think about only allowing CB_GraphicSprites.SPRITE_OBJECT objects (in the \"sprite\" parameter) which are already in the CB_GraphicSprites.SPRITE_OBJECT (identify them by their ID), to avoid problems. Returns: If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the existing CB_GraphicSprites.SUBSPRITE_OBJECT objects in the given CB_GraphicSprites.SPRITE_OBJECT object). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a CB_Arrays.executeFunctionAll_OBJECT object for each CB_GraphicSprites.SUBSPRITE_OBJECT. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the setTimeout function. Type integer | array forEach() Alias for CB_GraphicSprites#executeFunctionAll. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1224 See: CB_GraphicSprites#executeFunctionAll forEachSprite() Alias for CB_GraphicSprites#executeFunctionAll. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1229 See: CB_GraphicSprites#executeFunctionAll get() Alias for CB_GraphicSprites#getSprite. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1069 See: CB_GraphicSprites#getSprite getAll() Alias for CB_GraphicSprites#getSprites. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1035 See: CB_GraphicSprites#getSprites getById() Alias for CB_GraphicSprites#getSpriteById. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1090 See: CB_GraphicSprites#getSpriteById getCopy( [avoidCopyingPointer] [, avoidCopyingTimes] [, clearReferences] [, filterProperties] [, propertiesToKeepObject]) → {CB_GraphicSprites} Gets a new copy of this object with the same attributes (all sub-objects will be a copy, they will not the same reference). Parameters: Name Type Argument Default Description avoidCopyingPointer boolean &lt;optional&gt; false If set to true, it will not copy the CB_GraphicSprites#pointer property of the object. avoidCopyingTimes boolean &lt;optional&gt; false If set to true, it will not copy neither the CB_GraphicSprites#time property property of the object nor the \"time\" property of each of its sprites (CB_GraphicSprites.SPRITE_OBJECT objects). clearReferences boolean &lt;optional&gt; false If set to true, it will not copy neither the \"container\" nor the \"parent\" nor the \"data.that\" nor the \"data.getThis\" properties of any element. Useful to be able to stringify the object preventing the \"TypeError: cyclic object value\" error. When set to true, calls the CB_GraphicSprites.clearReferences function internally. If set to true and the \"filterProperties\" parameter is also set to true, the CB_GraphicSprites.filterProperties will always be called before calling the CB_GraphicSprites.clearReferences function. filterProperties boolean &lt;optional&gt; false If set to true, it will call the CB_GraphicSprites.filterProperties function internally to filter the properties that we do not want to keep (using the given \"propertiesToKeepObject\" as the parameter to call it). When set to true, calls the CB_GraphicSprites.filterProperties function internally. If set to true and the \"clearReferences\" parameter is also set to true, the CB_GraphicSprites.filterProperties will always be called before calling the CB_GraphicSprites.clearReferences function. propertiesToKeepObject CB_GraphicSprites.filterProperties_propertiesToKeepObject_TYPE &lt;optional&gt; CB_GraphicSprites.filterProperties_DEFAULT_PROPERTIES The object with the properties that we want to keep. Only used when the \"filterProperties\" parameter is set to true, as the \"propertiesToKeepObject\" when calling the CB_GraphicSprites.filterProperties function internally. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1760 Returns: Returns a copy of this object with the same attributes (all sub-objects will be a copy, not the same reference). Type CB_GraphicSprites getCurrent() → {CB_GraphicSprites.SPRITE_OBJECT|null} Gets the sprite (a CB_GraphicSprites.SPRITE_OBJECT object) which is being currently pointed (by the pointer set in the CB_GraphicSprites#pointer property). Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1371 Returns: Returns the CB_GraphicSprites.SPRITE_OBJECT object which is currently pointed by the pointer (set in the CB_GraphicSprites#pointer property). Returns null if not found. Type CB_GraphicSprites.SPRITE_OBJECT | null getCurrentPosition() Alias for CB_GraphicSprites#getPointer. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1298 See: CB_GraphicSprites#getPointer getIndexById() Alias for CB_GraphicSprites#getSpriteIndexById. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1109 See: CB_GraphicSprites#getSpriteIndexById getPointer() → {integer} Gets the current position of the pointer. It belongs to an index of the CB_GraphicSprites#spritesGroup.sprites array where a CB_GraphicSprites.SPRITE_OBJECT object is placed (containing a sprite). Internally, it uses the CB_GraphicSprites#pointer property. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1308 Returns: Returns the position where the pointer is currently pointing to. It belongs to an index of the CB_GraphicSprites#spritesGroup.sprites array where a CB_GraphicSprites.SPRITE_OBJECT object is placed (containing a sprite). If not found, returns zero (0) by default. Type integer getPointerPrevious() → {integer} Gets the previous position of the pointer. It belongs to an index of the CB_GraphicSprites#spritesGroup.sprites array where a CB_GraphicSprites.SPRITE_OBJECT object is placed (containing a sprite). Internally, it uses the CB_GraphicSprites#pointerPrevious property. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1292 Returns: Returns the position where the pointer was previously pointing to. It belongs to an index of the CB_GraphicSprites#spritesGroup.sprites array where a CB_GraphicSprites.SPRITE_OBJECT object is placed (containing a sprite). If not found, returns -1 by default. Type integer getPrevious() → {CB_GraphicSprites.SPRITE_OBJECT|null} Gets the sprite (a CB_GraphicSprites.SPRITE_OBJECT object) which was previously pointed (by the previous value of the pointer set in the CB_GraphicSprites#pointer property, whose value is now in the CB_GraphicSprites#pointerPrevious property). Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1349 Returns: Returns the CB_GraphicSprites.SPRITE_OBJECT object which was previously pointed by the pointer (by the previous value of the pointer set in the CB_GraphicSprites#pointer property, whose value is now in the CB_GraphicSprites#pointerPrevious property). Returns null if not found. Type CB_GraphicSprites.SPRITE_OBJECT | null getPreviousPosition() Alias for CB_GraphicSprites#getPointerPrevious. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1282 See: CB_GraphicSprites#getPointerPrevious getSprite( [index] [, returnValueOnFail]) → {CB_GraphicSprites.SPRITE_OBJECT|*} Gets a desired sprite object through its index (its position in the CB_GraphicSprites#spritesGroup.sprites array). Faster than getting it through its identifier with the CB_GraphicSprites#getSpriteById method. Parameters: Name Type Argument Default Description index integer &lt;optional&gt; 0 The index where the desired sprite must be located (its position in the CB_GraphicSprites#spritesGroup.sprites array). returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1081 Returns: Returns a CB_GraphicSprites.SPRITE_OBJECT object if found or the value of \"returnValueOnFail\" otherwise. Type CB_GraphicSprites.SPRITE_OBJECT | * getSpriteById( [id] [, returnValueOnFail]) → {CB_GraphicSprites.SPRITE_OBJECT|*} Gets a desired sprite object through its identifier. Slower than getting it through its index with the CB_GraphicSprites#getSprite method. Parameters: Name Type Argument Description id string | * &lt;optional&gt; The identifier of the sprite that we want to get. returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1102 Returns: Returns a CB_GraphicSprites.SPRITE_OBJECT object if found or the value of \"returnValueOnFail\" otherwise. Type CB_GraphicSprites.SPRITE_OBJECT | * getSpriteIndexById( [id]) → {integer} Gets the index (the position in the CB_GraphicSprites#spritesGroup.sprites array) of a desired sprite by its identifier. Parameters: Name Type Argument Description id string | * &lt;optional&gt; The identifier of the sprite whose index we want to get. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1121 To Do: Optimize it (perhaps using a cache matching the IDs with their position, maybe using the \"position\" or \"positionByZIndex\" properties). Returns: Returns the index (the position in the CB_GraphicSprites#spritesGroup.sprites array) of the desired sprite or -1 if not found. Type integer getSprites( [orderedByZIndex] [, returnValueOnFail]) → {array|*} Gets all the sprites (the \"sprites\" property of the internal CB_GraphicSprites.SPRITES_OBJECT object, if any). Parameters: Name Type Argument Default Description orderedByZIndex boolean &lt;optional&gt; false If set to true, it will return the sprites sorted by their z-index (ascending order). returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1052 Returns: Returns an array with all the CB_GraphicSprites.SPRITE_OBJECT objects or the value of \"returnValueOnFail\" otherwise. Type array | * getSpritesAll() Alias for CB_GraphicSprites#getSprites. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1040 See: CB_GraphicSprites#getSprites getSpritesGroup( [returnValueOnFail]) → {CB_GraphicSprites.SPRITES_OBJECT|*} Gets the sprites group object (the internal CB_GraphicSprites.SPRITES_OBJECT object, if any). Parameters: Name Type Argument Description returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1029 Returns: Returns a CB_GraphicSprites.SPRITES_OBJECT object with all the sprites or the value of \"returnValueOnFail\" otherwise. Type CB_GraphicSprites.SPRITES_OBJECT | * getSubSprite( [index] [, sprite] [, returnValueOnFail]) → {CB_GraphicSprites.SUBSPRITE_OBJECT|*} Gets a desired sub-sprite object through its index (its position in the array which is in the \"subSprites\" property of the given CB_GraphicSprites.SPRITE_OBJECT object). Faster than getting it through its identifier with the CB_GraphicSprites#getSubSpriteById method. Parameters: Name Type Argument Default Description index integer &lt;optional&gt; 0 The index where the desired sub-sprite must be located (its position in the array which is in the \"subSprites\" property of the given CB_GraphicSprites.SPRITE_OBJECT object). sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; CB_GraphicSprites#getCurrent() The CB_GraphicSprites.SPRITE_OBJECT object which contains the sprite and its sub-sprites. If not provided, it will use the CB_GraphicSprites.SPRITE_OBJECT object which the pointer (set in the CB_GraphicSprites#pointer property) is currently pointing to (using the returning value of the CB_GraphicSprites#getCurrent method internally). returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1170 Returns: Returns a CB_GraphicSprites.SUBSPRITE_OBJECT object if found or the value of \"returnValueOnFail\" otherwise. Type CB_GraphicSprites.SUBSPRITE_OBJECT | * getSubSpriteById( [id] [, sprite] [, returnValueOnFail]) → {CB_GraphicSprites.SUBSPRITE_OBJECT|*} Gets a desired sub-sprite object through its identifier from the given CB_GraphicSprites.SPRITE_OBJECT object. Slower than getting it through its index with the CB_GraphicSprites#getSubSprite method. Parameters: Name Type Argument Default Description id string | * &lt;optional&gt; The identifier of the sub-sprite that we want to get. sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; CB_GraphicSprites#getCurrent() The CB_GraphicSprites.SPRITE_OBJECT object which contains the sprite and its sub-sprites. If not provided, it will use the CB_GraphicSprites.SPRITE_OBJECT object which the pointer (set in the CB_GraphicSprites#pointer property) is currently pointing to (using the returning value of the CB_GraphicSprites#getCurrent method internally). returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1188 Returns: Returns a CB_GraphicSprites.SUBSPRITE_OBJECT object if found or the value of \"returnValueOnFail\" otherwise. Type CB_GraphicSprites.SUBSPRITE_OBJECT | * getSubSpriteIndexById( [id] [, sprite]) → {integer} Gets the index (its position in the array which is in the \"subSprites\" property of the given CB_GraphicSprites.SPRITE_OBJECT object) of a desired sub-sprite by its identifier. Parameters: Name Type Argument Default Description id string | * &lt;optional&gt; The identifier of the sub-sprite whose index we want to get. sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; CB_GraphicSprites#getCurrent() The CB_GraphicSprites.SPRITE_OBJECT object which contains the sprite and its sub-sprites. If not provided, it will use the CB_GraphicSprites.SPRITE_OBJECT object which the pointer (set in the CB_GraphicSprites#pointer property) is currently pointing to (using the returning value of the CB_GraphicSprites#getCurrent method internally). Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1204 To Do: Optimize it (perhaps using a cache matching the IDs with their position, maybe using the \"position\" or \"positionByZIndex\" properties). Returns: Returns the index (its position in the array which is in the \"subSprites\" property of the given CB_GraphicSprites.SPRITE_OBJECT object) of the desired sub-sprite or -1 if not found. Type integer getSubSprites( [sprite] [, orderedByZIndex] [, returnValueOnFail]) → {array|*} Gets an array with all the CB_GraphicSprites.SUBSPRITE_OBJECT objects of a given CB_GraphicSprites.SPRITE_OBJECT object. Parameters: Name Type Argument Default Description sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; CB_GraphicSprites#getCurrent() The CB_GraphicSprites.SPRITE_OBJECT object which contains the sprite and its sub-sprites. If not provided, it will use the CB_GraphicSprites.SPRITE_OBJECT object which the pointer (set in the CB_GraphicSprites#pointer property) is currently pointing to (using the returning value of the CB_GraphicSprites#getCurrent method internally). orderedByZIndex boolean &lt;optional&gt; false If set to true, it will return the sub-sprites sorted by their z-index (ascending order). returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1143 Returns: Returns an array with all the CB_GraphicSprites.SUBSPRITE_OBJECT objects of the given CB_GraphicSprites.SPRITE_OBJECT object or the value of \"returnValueOnFail\" otherwise. Type array | * getTime( [returnValueOnFail] [, parentTimeFallback]) → {number} Gets the time in milliseconds when the current sprite or a sub-sprite started being pointed (time elapsed since the time origin which was obtained calling the CB_Device.getTiming function internally). Parameters: Name Type Argument Default Description returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. parentTimeFallback boolean &lt;optional&gt; false If the \"time\" property of \"this\" is not found, it will try to get the \"time\" property of \"this.time\" before returning \"returnValueOnFail\". Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1674 Returns: Returns the time in milliseconds when the current sprite or a sub-sprite started being pointed (time elapsed since the time origin which was obtained calling the CB_Device.getTiming function internally). If it could not be found, it will return \"returnValueOnFail\". Type number getTimeElapsed( [timeToCompare] [, parentTimeFallback]) → {number} Tells how many milliseconds elapsed since the current sprite or a sub-sprite was or will be pointed (checking the CB_GraphicSprites#time property), comparing with the time given in milliseconds (time elapsed since the time origin which can be obtained calling the CB_Device.getTiming function) or with the current one if none is given. Parameters: Name Type Argument Default Description timeToCompare number &lt;optional&gt; CB_Device.getTiming() The time (time elapsed since the time origin which can obtained calling the CB_Device.getTiming function) that we want to compare to (normally, it will be a newer time than the one stored in the CB_GraphicSprites#time property). It must be a positive number (or zero). If not provided, it will use the current time (by calling the CB_Device.getTiming function internally). parentTimeFallback boolean &lt;optional&gt; false If the \"time\" property of \"this\" is not found, it will try to get the \"time\" property of \"this.time\" before using \"returnValueOnFail\". Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1688 Returns: Returns how many milliseconds elapsed since the current sprite or a sub-sprite was or will be pointed, comparing with the time given (in milliseconds) or with the current one if none was given. This is just the given \"timeToCompare\" minus the returning value of calling the CB_GraphicSprites#getTime method. Type number getZIndex( [returnValueOnFail]) → {number} Gets the z-index (\"zIndex\" property) of the sprites group object (and the {@CB_GraphicSprites} object itself). Parameters: Name Type Argument Description returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1429 Returns: Returns the z-index (\"zIndex\") of the sprites group object (and the {@CB_GraphicSprites} object itself). If not found, returns the value of the CB_GraphicSprites.ZINDEX_DEFAULT property of evaluates to true or \"returnValueOnFail\" otherwise. Type number getZIndexSprite( [sprite] [, returnValueOnFail]) → {number} Gets the z-index (\"zIndex\" property) of a given sprite object. Parameters: Name Type Argument Default Description sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; CB_GraphicSprites#getCurrent() The CB_GraphicSprites.SPRITE_OBJECT object which contains the sprite. If not provided, it will use the CB_GraphicSprites.SPRITE_OBJECT object which the pointer (set in the CB_GraphicSprites#pointer property) is currently pointing to (using the returning value of the CB_GraphicSprites#getCurrent method internally). returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1460 Returns: Returns the z-index (\"zIndex\") of the given sprite. If not found, returns the value of the CB_GraphicSprites.ZINDEX_DEFAULT property of evaluates to true or \"returnValueOnFail\" otherwise. Type number getZIndexSubSprite(subSprite [, returnValueOnFail]) → {number} Gets the z-index (\"zIndex\" property) of a given sub-sprite object. Parameters: Name Type Argument Description subSprite CB_GraphicSprites.SUBSPRITE_OBJECT The CB_GraphicSprites.SUBSPRITE_OBJECT object which contains the sub-sprite. returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1495 Returns: Returns the z-index (\"zIndex\") of the given sub-sprite. If not found, returns the value of the CB_GraphicSprites.ZINDEX_DEFAULT property of evaluates to true or \"returnValueOnFail\" otherwise. Type number insert() Alias for CB_GraphicSprites#insertSprite. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 645 See: CB_GraphicSprites#insertSprite insertSprite( [sprite] [, avoidUpdatingSpritesByZIndex]) → {CB_GraphicSprites.SPRITE_OBJECT} Adds the desired graphic sprite. Calls CB_GraphicSprites#insertSubSprites internally. If a sprite with the same identifier already exists, it will be replaced by the new one in its same position. Parameters: Name Type Argument Default Description sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; Object with the desired sprite. It will be stored inside the CB_GraphicSprites#spritesGroup property. avoidUpdatingSpritesByZIndex boolean &lt;optional&gt; false If set to true, it will not call the {CB_GraphicSprites#updateSpritesByZIndex} method internally. Internal usage recommended only. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 657 Returns: Returns the CB_GraphicSprites.SPRITE_OBJECT object which has been inserted (it could have been modified/sanitized from the given one and some missing properties or those which were wrong could have been inherited). Type CB_GraphicSprites.SPRITE_OBJECT insertSprites( [spritesGroup] [, byReference]) → {CB_GraphicSprites.SPRITES_OBJECT} Adds the desired group of graphic sprites. Calls the CB_GraphicSprites#insertSprite and CB_GraphicSprites#updateSpritesByZIndex methods internally. Parameters: Name Type Argument Default Description spritesGroup CB_GraphicSprites.SPRITES_OBJECT &lt;optional&gt; Object with the desired sprites. They will be stored in the CB_GraphicSprites#spritesGroup property. byReference boolean &lt;optional&gt; !!CB_GraphicSprites.SPRITES_OBJECT.byReference_DEFAULT This value will be used as the default value when the \"byReference\" property is not given in the sprites (CB_GraphicSprites.SPRITE_OBJECT objects) or sub-sprites (CB_GraphicSprites.SUBSPRITE_OBJECT objects). The value will be stored in the CB_GraphicSprites#byReference_DEFAULT property. If a boolean value is not provided, it will use the value of the CB_GraphicSprites.SPRITES_OBJECT.byReference_DEFAULT property of the given CB_GraphicSprites.SPRITES_OBJECT object (parsed to boolean). Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 507 Returns: Returns the CB_GraphicSprites#spritesGroup property after updating it. Type CB_GraphicSprites.SPRITES_OBJECT insertSpritesGroup() Alias for CB_GraphicSprites#insertSprites. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 495 See: CB_GraphicSprites#insertSprites insertSubSprite(subSprite, sprite [, avoidUpdatingSubSpritesByZIndex]) → {CB_GraphicSprites.SUBSPRITE_OBJECT} Adds the given sub-sprite to the desired sprite. If a sub-sprite with the same identifier already exists, it will be replaced by the new one in its same position. Parameters: Name Type Argument Default Description subSprite CB_GraphicSprites.SUBSPRITE_OBJECT Object with the desired sub-sprite. It will be stored inside the given sprite. sprite CB_GraphicSprites.SPRITE_OBJECT Object with the desired sprite. avoidUpdatingSubSpritesByZIndex boolean &lt;optional&gt; false If set to true, it will not call the {CB_GraphicSprites#updateSubSpritesByZIndex} method internally. Internal usage recommended only. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 937 Returns: Returns the CB_GraphicSprites.SUBSPRITE_OBJECT object which has been inserted (it could have been modified/sanitized from the given one and some missing properties or those which were wrong could have been inherited). Type CB_GraphicSprites.SUBSPRITE_OBJECT insertSubSprites(subSprites [, sprite]) → {array} Adds the given sub-sprites to the desired sprite. Calls the CB_GraphicSprites#insertSubSprite and CB_GraphicSprites#updateSubSpritesByZIndex methods internally. Parameters: Name Type Argument Default Description subSprites array Numeric array with the desired sub-sprites (CB_GraphicSprites.SUBSPRITE_OBJECT objects). They will be stored inside the given sprite. sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; CB_GraphicSprites#getCurrent() Object with the desired sprite. If not provided, it will use the CB_GraphicSprites.SPRITE_OBJECT object which the pointer (set in the CB_GraphicSprites#pointer property) is currently pointing to (using the returning value of the CB_GraphicSprites#getCurrent method internally). Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 795 Returns: Returns an array with the CB_GraphicSprites.SUBSPRITE_OBJECT objects which have been inserted (they could have been modified/sanitized from the given one and some missing properties or those which were wrong could have been inherited). Type array isDisabled() → {boolean} Tells whether the sprites group object (and the {@CB_GraphicSprites} object itself) is disabled or not. Internally, it checks the \"CB_GraphicSprites.spritesGroup.disabled\" property. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1526 Returns: Returns whether the sprites group object (and the CB_GraphicSprites object itself) is disabled or not. Type boolean isDisabledSprite( [sprite]) → {boolean} Tells whether the given sprite is disabled or not. Internally, it checks its \"disabled\" property and also the \"CB_GraphicSprites.spritesGroup.disabled\" property (calling the CB_GraphicSprites#isDisabled method internally). A sprite is considered disabled if its sprites group parent is also disabled. Parameters: Name Type Argument Default Description sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; CB_GraphicSprites#getCurrent() The CB_GraphicSprites.SPRITE_OBJECT object which contains the sprite. If not provided, it will use the CB_GraphicSprites.SPRITE_OBJECT object which the pointer (set in the CB_GraphicSprites#pointer property) is currently pointing to (using the returning value of the CB_GraphicSprites#getCurrent method internally). Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1558 Returns: Returns whether the sprite is disabled or not. A sprite is considered disabled if its sprites group parent is also disabled. Type boolean isDisabledSubSprite(subSprite) → {boolean} Tells whether the given sub-sprite is disabled or not. Internally, it checks its \"disabled\" property and also whether its sprite parent is disabled (calling the CB_GraphicSprites#isDisabledSprite method internally, for its sprite parent). A sub-sprite is considered disabled if its sprite parent is disabled (a sprite is considered disabled if its sprites group parent is also disabled). Parameters: Name Type Description subSprite CB_GraphicSprites.SUBSPRITE_OBJECT The CB_GraphicSprites.SUBSPRITE_OBJECT object which contains the sub-sprite. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1607 Returns: Returns whether the sub-sprite is disabled or not. A sub-sprite is considered disabled if its sprite parent is disabled (a sprite is considered disabled if its sprites group parent is also disabled). Type boolean next() Alias for CB_GraphicSprites#setNext. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1402 See: CB_GraphicSprites#setNext now() Alias for CB_GraphicSprites#getCurrent. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1356 See: CB_GraphicSprites#getCurrent previous() Alias for CB_GraphicSprites#setPrevious. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1377 See: CB_GraphicSprites#setPrevious remove() Alias for CB_GraphicSprites#removeSprite. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 588 See: CB_GraphicSprites#removeSprite removeAll() Alias for CB_GraphicSprites#removeSprites. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 469 See: CB_GraphicSprites#removeSprites removeById() Alias for CB_GraphicSprites#removeSpriteById. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 616 See: CB_GraphicSprites#removeSpriteById removeSprite( [index]) → {boolean} Removes a sprite by its index (its position in the CB_GraphicSprites#spritesGroup.sprites array). Calls the CB_GraphicSprites#updateSpritesByZIndex method internally. Parameters: Name Type Argument Default Description index integer &lt;optional&gt; 0 The index where the sprite is located (its position in the CB_GraphicSprites#spritesGroup.sprites array). Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 599 Returns: Returns true if the sprite has been deleted or false otherwise. Type boolean removeSpriteById( [id]) → {boolean} Removes a sprite by its identifier. Calls the CB_GraphicSprites#updateSpritesByZIndex method internally. Parameters: Name Type Argument Description id string | * &lt;optional&gt; The identifier of the sprite. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 628 To Do: Optimize it (perhaps using a cache matching the IDs with their position, maybe using the \"position\" or \"positionByZIndex\" properties). Returns: Returns true if the sprite has been deleted or false otherwise. Type boolean removeSprites() Removes all the sprites by clearing the CB_GraphicSprites#spritesGroup property. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 488 removeSpritesAll() Alias for CB_GraphicSprites#removeSprites. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 479 See: CB_GraphicSprites#removeSprites removeSpritesGroup() Alias for CB_GraphicSprites#removeSprites. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 474 See: CB_GraphicSprites#removeSprites removeSubSprite( [index] [, sprite]) → {boolean} Removes a sub-sprite from a given sprite (CB_GraphicSprites.SPRITE_OBJECT object) by its index (its position in the array which is in the \"subSprites\" property of the given CB_GraphicSprites.SPRITE_OBJECT object). Calls the CB_GraphicSprites#updateSubSpritesByZIndex method internally. Parameters: Name Type Argument Default Description index integer &lt;optional&gt; 0 The index where the sub-sprite is located (its position in the array which is in the \"subSprites\" property of the given CB_GraphicSprites.SPRITE_OBJECT object). sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; CB_GraphicSprites#getCurrent() Object with the sprite whose sub-sprites we want to remove. If not provided, it will use the CB_GraphicSprites.SPRITE_OBJECT object which the pointer (set in the CB_GraphicSprites#pointer property) is currently pointing to (using the returning value of the CB_GraphicSprites#getCurrent method internally). Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 852 Returns: Returns true if the sub-sprite has been deleted or false otherwise. Type boolean removeSubSpriteById( [id] [, sprite]) → {boolean} Removes a sub-sprite from a given sprite (CB_GraphicSprites.SPRITE_OBJECT object) by its identifier. Calls the CB_GraphicSprites#updateSubSpritesByZIndex method internally. Parameters: Name Type Argument Default Description id string | * &lt;optional&gt; The identifier of the sprite. sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; CB_GraphicSprites#getCurrent Object with the sprite whose sub-sprites we want to remove. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 896 To Do: Optimize it (perhaps using a cache matching the IDs with their position, maybe using the \"position\" or \"positionByZIndex\" properties). Returns: Returns true if the sub-sprite has been deleted or false otherwise. Type boolean removeSubSprites( [sprite]) → {boolean} Removes all the sub-sprites from a given sprite (CB_GraphicSprites.SPRITE_OBJECT object) by clearing its \"subSprites\" property (leaving an empty array). Parameters: Name Type Argument Default Description sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; CB_GraphicSprites#getCurrent() Object with the sprite whose sub-sprites we want to remove. If not provided, it will use the CB_GraphicSprites.SPRITE_OBJECT object which the pointer (set in the CB_GraphicSprites#pointer property) is currently pointing to (using the returning value of the CB_GraphicSprites#getCurrent method internally). Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 769 Returns: Returns true if the sub-sprites have been deleted or false otherwise. Type boolean removeSubSpritesAll() Alias for CB_GraphicSprites#removeSubSprites. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 758 See: CB_GraphicSprites#removeSubSprites setCurrentPosition() Alias for CB_GraphicSprites#setPointer. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1314 See: CB_GraphicSprites#setPointer setDisabled( [disabled] [, affectChildren]) Sets whether the sprites group object (and the {@CB_GraphicSprites} object itself) is disabled or enabled. Internally, it edits the \"CB_GraphicSprites.spritesGroup.disabled\" property. Parameters: Name Type Argument Default Description disabled boolean &lt;optional&gt; false Set to true to disable it or false to enable it. affectChildren boolean &lt;optional&gt; disabled If this parameter is set to true, it will also modify the \"disabled\" property of all the sprites and their sub-sprites. By default, it is false if the \"disabled\" parameter is set to false or it is true otherwise. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1538 setDisabledSprite( [sprite] [, disabled] [, affectSubSprites] [, affectParent] [, affectParentChildren]) Sets a given sprite disabled or enabled. Internally, it edits its \"disabled\" property. Parameters: Name Type Argument Default Description sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; CB_GraphicSprites#getCurrent() The CB_GraphicSprites.SPRITE_OBJECT object which contains the sprite. If not provided, it will use the CB_GraphicSprites.SPRITE_OBJECT object which the pointer (set in the CB_GraphicSprites#pointer property) is currently pointing to (using the returning value of the CB_GraphicSprites#getCurrent method internally). disabled boolean &lt;optional&gt; false Set to true to disable it or false to enable it. affectSubSprites boolean &lt;optional&gt; disabled If this parameter is set to true, it will also modify the \"disabled\" property of all the sub-sprites of the given sprite. This parameter will be ignored if the \"affectParent\" parameter is set to true (as all existing sprites and sub-sprites in the CB_GraphicSprites object will be affected anyway). By default, it is false if the \"disabled\" parameter is set to false or it is true otherwise. affectParent boolean &lt;optional&gt; affectParentChildren|!disabled If this parameter is set to true, it will also modify the \"disabled\" property of the sprites group object (which is considered the status of the whole {@CB_GraphicSprites} object). By default, it is true if either the \"affectParentChildren\" parameter is set to true or the \"disabled\" parameter is set to false and it is false otherwise. affectParentChildren boolean &lt;optional&gt; !disabled Defines whether to also affect the sprites and sub-sprites of the sprites group object (which is considered the status of the whole {@CB_GraphicSprites} object) or not. If it is set to true and the \"affectParent\" is also set to true, it will also modify the \"disabled\" property of all the existing sprites and sub-sprites in the CB_GraphicSprites object. This parameter is ignored if the \"affectParent\" parameter is set to false. By default, it is false if the \"disabled\" parameter is set to true or it is false otherwise. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1574 setDisabledSubSprite(subSprite [, disabled] [, affectParents] [, affectParentsChildren]) Sets a given sub-sprite disabled or enabled. Internally, it edits its \"disabled\" property. Parameters: Name Type Argument Default Description subSprite CB_GraphicSprites.SUBSPRITE_OBJECT The CB_GraphicSprites.SUBSPRITE_OBJECT object which contains the sub-sprite. disabled boolean &lt;optional&gt; false Set to true to disable it or false to enable it. affectParents boolean &lt;optional&gt; affectParentsChildren|!disabled If this parameter is set to true, it will also modify the \"disabled\" property of the sprite parent and of the sprites group object (which is considered the status of the whole {@CB_GraphicSprites} object). By default, it is true if either the \"affectParentChildren\" parameter is set to true or the \"disabled\" parameter is set to false and it is false otherwise. affectParentsChildren boolean &lt;optional&gt; !disabled Defines whether to also affect the sprites and sub-sprites of the sprite parent and its sprites group object (which is considered the status of the whole {@CB_GraphicSprites} object) or not. If it is set to true and the \"affectParents\" is also set to true, it will also modify the \"disabled\" property of all the existing sprites and sub-sprites in the CB_GraphicSprites object. This parameter is ignored if the \"affectParents\" parameter is set to false. By default, it is false if the \"disabled\" parameter is set to true or it is false otherwise. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1622 setNext( [loop]) → {CB_GraphicSprites.SPRITE_OBJECT|null} Makes the pointer to advance to the next position (if possible) and returns the sprite located there (if any). The position should belong to an index of the CB_GraphicSprites#spritesGroup.sprites array where a CB_GraphicSprites.SPRITE_OBJECT object is placed (containing a sprite) and it will be returned if found. Internally, it modifies the CB_GraphicSprites#pointer property (if possible). If the position was updated, it will also update the CB_GraphicSprites#time property (setting the current time in milliseconds). Parameters: Name Type Argument Default Description loop boolean &lt;optional&gt; false If set to false and the next position is greater than the current number of sprites, it will return null. Otherwise, if set to true and the position is greater than the current number of sprites, it will modify the position making it cycle (from the end to the beginning). This parameter is ignored when the position has not reached the limit. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1413 Returns: Makes it to point to the next CB_GraphicSprites.SPRITE_OBJECT object (making it the current one) and returns it. Returns null if it cannot be found. Type CB_GraphicSprites.SPRITE_OBJECT | null setPointer( [position] [, loop]) → {integer} Sets the pointer to the desired position (if possible). The position should belong to an index of the CB_GraphicSprites#spritesGroup.sprites array where a CB_GraphicSprites.SPRITE_OBJECT object is placed (containing a sprite). Internally, it modifies the CB_GraphicSprites#pointer property (if possible). If the position was updated, it will also reset the CB_GraphicSprites#time property (setting the current time in milliseconds). Parameters: Name Type Argument Default Description position integer &lt;optional&gt; 0|CB_GraphicSprites#spritesGroup.sprites.length-1|position%CB_GraphicSprites#spritesGroup.sprites.length The position that we want the pointer to use. The position should belong to an index of the CB_GraphicSprites#spritesGroup.sprites array where a CB_GraphicSprites.SPRITE_OBJECT object is placed (containing a sprite). loop boolean &lt;optional&gt; false If set to false and the \"position\" given is greater than the current number of sprites, the \"position\" used will be the one which belongs to the last sprite. If set to false and the \"position\" given is lower than zero, the \"position\" used will be zero (the first position). Otherwise, if set to true and the \"position\" given is greater than the current number of sprites or lower than zero, it will modify the given \"position\" making it cycle (from the end to the beginning) treating always the \"position\" as a positive number. This parameter is ignored when the given \"position\" has not reached the limit. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1326 Returns: Returns the position where the pointer is currently pointing to. It belongs to an index of the CB_GraphicSprites#spritesGroup.sprites array where a CB_GraphicSprites.SPRITE_OBJECT object is placed (containing a sprite). Type integer setPrevious( [loop]) → {CB_GraphicSprites.SPRITE_OBJECT|null} Makes the pointer to go back to the previous position (if possible) and returns the sprite located there (if any). The position should belong to an index of the CB_GraphicSprites#spritesGroup.sprites array where a CB_GraphicSprites.SPRITE_OBJECT object is placed (containing a sprite) and it will be returned if found. Internally, it modifies the CB_GraphicSprites#pointer property (if possible). If the position was updated, it will update also the CB_GraphicSprites#time property (setting the current time in milliseconds). Parameters: Name Type Argument Default Description loop boolean &lt;optional&gt; false If set to false and the previous position is lower than zero, it will return null. Otherwise, if set to true and the position is lower than zero, it will modify the position making it cycle (from the beginning to the end). This parameter is ignored when the position has not reached the limit. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1388 Returns: Makes it to point to the previous CB_GraphicSprites.SPRITE_OBJECT object (making it the current one) and returns it. Returns null if it cannot be found. Type CB_GraphicSprites.SPRITE_OBJECT | null setPropertyCascade(propertyName [, value] [, onlyCurrent]) → {integer} Sets the desired value of a given property name to the CB_GraphicSprites.SPRITES_OBJECT object as well to its children elements (CB_GraphicSprites.SPRITE_OBJECT and CB_GraphicSprites.SUBSPRITE_OBJECT objects). Parameters: Name Type Argument Default Description propertyName number The name of the property we want to affect. value * &lt;optional&gt; The value desired for the given property. onlyCurrent boolean &lt;optional&gt; false If set to true, it will only affect the current sprite and its sub-sprites (and also the CB_GraphicSprites.SPRITES_OBJECT object). Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1704 Returns: Returns the number of elements affected (counting the CB_GraphicSprites.SPRITES_OBJECT object). Type integer setTime( [time] [, updateTimeCurrentSprite] [, updateTimeCurrentSpriteSubSprites]) → {number} Sets (updates) the time in milliseconds when the current sprite or a sub-sprite started being pointed. Parameters: Name Type Argument Default Description time number &lt;optional&gt; CB_Device.getTiming() The time that we want to set, in milliseconds (time elapsed since the time origin which can be obtained calling the CB_Device.getTiming function). It must be a positive number (or zero). If not provided, it will use the current time (by calling the CB_Device.getTiming function internally). updateTimeCurrentSprite boolean &lt;optional&gt; false If set to true, it will also update the \"time\" property of the CB_GraphicSprites.SPRITE_OBJECT object which is currently pointed by the pointer (set in the CB_GraphicSprites#pointer property). updateTimeCurrentSpriteSubSprites boolean &lt;optional&gt; false If set to true and the \"updateTimeCurrentSprite\" is set to true, it will also update the \"time\" property of the CB_GraphicSprites.SUBSPRITE_OBJECT objects that belong to the sprite which is currently pointed by the pointer (set in the CB_GraphicSprites#pointer property). This parameter is ignored if the \"updateTimeCurrentSprite\" parameter is set to false. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1646 Returns: Returns the time in milliseconds when the current sprite or a sub-sprite started being pointed (time elapsed since the time origin which can be obtained calling the CB_Device.getTiming function). Type number setZIndex( [zIndex]) → {number} Sets the desired z-index (\"zIndex\" property) of the sprites group object (and the {@CB_GraphicSprites} object itself). If there is a CB_GraphicSpritesScene parent object (set in the CB_GraphicSprites.parent property), it will also call its CB_GraphicSpritesScene#updateGraphicSpritesByZIndex method internally. Parameters: Name Type Argument Default Description zIndex number &lt;optional&gt; parseFloat(zIndex)||CB_GraphicSprites.ZINDEX_DEFAULT||1 The z-index value we want. It must be a number but never zero (0). If no valid number is given, it will use the value of the CB_GraphicSprites.ZINDEX_DEFAULT property of evaluates to true or 1 otherwise. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1441 Returns: Returns the z-index (\"zIndex\") of the sprites group object (and the {@CB_GraphicSprites} object itself) after setting it (it could have been sanitized). Type number setZIndexSprite( [sprite] [, zIndex]) → {number} Sets the desired z-index (\"zIndex\") of the given sprite object. Calls the CB_GraphicSprites#updateSpritesByZIndex method internally. Parameters: Name Type Argument Default Description sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; CB_GraphicSprites#getCurrent() The CB_GraphicSprites.SPRITE_OBJECT object which contains the sprite. If not provided, it will use the CB_GraphicSprites.SPRITE_OBJECT object which the pointer (set in the CB_GraphicSprites#pointer property) is currently pointing to (using the returning value of the CB_GraphicSprites#getCurrent method internally). zIndex number &lt;optional&gt; parseFloat(zIndex)||CB_GraphicSprites.ZINDEX_DEFAULT||1 The z-index value we want. It must be a number but never zero (0). If no valid number is given, it will use the value of the CB_GraphicSprites.ZINDEX_DEFAULT property of evaluates to true or 1 otherwise. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1474 Returns: Returns the z-index (\"zIndex\") of the given sprite after setting it (it could have been sanitized). Type number setZIndexSubSprite(sprite [, zIndex]) → {number} Sets the desired z-index (\"zIndex\") of the given sub-sprite object. Calls the CB_GraphicSprites#updateSubSpritesByZIndex method internally. Parameters: Name Type Argument Default Description sprite CB_GraphicSprites.SUBSPRITE_OBJECT The CB_GraphicSprites.SUBSPRITE_OBJECT object which contains the sub-sprite. zIndex number &lt;optional&gt; parseFloat(zIndex)||CB_GraphicSprites.ZINDEX_DEFAULT||0 The z-index value we want. It must be a number but never zero (0). If no valid number is given, it will use the value of the CB_GraphicSprites.ZINDEX_DEFAULT property of evaluates to true or 1 otherwise. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1508 Returns: Returns the z-index (\"zIndex\") of the given sub-sprite after setting it (it could have been sanitized). Type number updateSpritesByZIndex() → {array} Updates (sorts again) the \"spritesByZIndex\" property (which is an array with the sprites ordered by z-index, whose data comes from the array in the \"sprites\" property of the CB_GraphicSprites#spritesGroup object) of the CB_GraphicSprites#spritesGroup object. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 565 Returns: Returns the \"spritesByZIndex\" array of the CB_GraphicSprites#spritesGroup object after updating it. Returns null if the property could not be obtained or updated. Type array updateSubSpritesByZIndex( [sprite]) → {array} Updates (sorts again) the \"subSpritesByZIndex\" property (which is an array with the sub-sprites ordered by z-index, whose data comes from the array in the \"subSprites\" property of the given CB_GraphicSprites.SPRITE_OBJECT object)) of the desired sprite. Parameters: Name Type Argument Default Description sprite CB_GraphicSprites.SPRITE_OBJECT &lt;optional&gt; CB_GraphicSprites#getCurrent() Object with the sprite whose sub-sprites we want to remove. If not provided, it will use the CB_GraphicSprites.SPRITE_OBJECT object which the pointer (set in the CB_GraphicSprites#pointer property) is currently pointing to (using the returning value of the CB_GraphicSprites#getCurrent method internally). Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 822 Returns: Returns the \"subSpritesByZIndex\" array after updating it. Returns null if the property could not be obtained or updated. Type array Type Definitions filterProperties_propertiesToKeepObject_TYPE Object used to know what properties keep when calling the CB_GraphicSprites.filterProperties function (type used for its \"propertiesToKeepObject\" parameter). Its properties must have the name that matches the value returned by the \"type\" property of each element, being their value an array of strings with the name of the properties we want to keep. The property names which start with a \"\" symbol will not considered inherited from the element's parent and will always be copied. The other properties (which do not start with the \"\" symbol) will only be copied when the element contains a value which is different from the same property of its parent. Type: Object Properties: Name Type Argument Description spritesScene array &lt;optional&gt; Array of strings with the name of the properties to keep for the CB_GraphicSpritesScene objects. If no provided, no properties will be kept for this kind of element. spritesGroups array &lt;optional&gt; Array of strings with the name of the properties to keep for the CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT objects. If no provided, no properties will be kept for this kind of element. sprites array &lt;optional&gt; Array of strings with the name of the properties to keep for the CB_GraphicSprites objects. If no provided, no properties will be kept for this kind of element. spritesGroup array &lt;optional&gt; Array of strings with the name of the properties to keep for the CB_GraphicSprites.SPRITES_OBJECT objects. If no provided, no properties will be kept for this kind of element. sprite array &lt;optional&gt; Array of strings with the name of the properties to keep for the CB_GraphicSprites.SPRITE_OBJECT objects. If no provided, no properties will be kept for this kind of element. subSprite array &lt;optional&gt; Array of strings with the name of the properties to keep for the CB_GraphicSprites.SUBSPRITE_OBJECT objects. If no provided, no properties will be kept for this kind of element. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 1869 SPRITE_OBJECT An object with the information that belongs to a certain graphic sprite, being able to contain more than one source used by this graphic sprite (inside sub-sprites). Type: Object Properties: Name Type Argument Default Description id string | * &lt;optional&gt; 'CB_GraphicSprites.sprite_' + CB_GraphicSprites._idSpriteUnique++ Identifier of the sprite. It should be unique. Recommended. It must be a value which evaluates to true. By default, it is generated automatically (with an internal counter). src * &lt;optional&gt; this.parent.src|\"\" Source of origin. Can be a path or identifier of an image, text, bitmap, 3D object, etc. They can be used for any kind of source you may think of, including (but not limited to) one sprites sheet or more, one atlas or more, etc. or even a mix of all of them. If not provided, as default it will use the value from the sprites group that it belongs to. srcType string &lt;optional&gt; this.parent.srcType|CB_GraphicSprites.SRC_TYPES_DEFAULT Type of the source of origin. If not provided, as default it will use the value from the sprites group that it belongs to. It should point to a property of the CB_GraphicSprites.SRC_TYPES object. You can use other values of the CB_GraphicSprites.SRC_TYPES object or create new ones. srcLeft number &lt;optional&gt; this.parent.srcLeft|CB_GraphicSprites.LEFT_SOURCE_DEFAULT Left (horizontal) position in the original source (having in mind its real width and height). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprites group that it belongs to. srcTop number &lt;optional&gt; this.parent.srcTop|CB_GraphicSprites.TOP_SOURCE_DEFAULT Top (vertical) position in the original source (having in mind its real width and height). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprites group that it belongs to. srcWidth number &lt;optional&gt; this.parent.srcWidth|CB_GraphicSprites.WIDTH_SOURCE_DEFAULT Width of the original source. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprites group that it belongs to. srcHeight number &lt;optional&gt; this.parent.srcHeight|CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT Height of the original source. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprites group that it belongs to. left number &lt;optional&gt; CB_GraphicSprites.LEFT_DEFAULT Left (horizontal) position in the destiny (inside the sprites group). Unit agnostic (only numeric values are allowed). top number &lt;optional&gt; CB_GraphicSprites.TOP_DEFAULT Top (vertical) position in the destiny (inside the sprites group). Unit agnostic (only numeric values are allowed). width number &lt;optional&gt; this.parent.width|CB_GraphicSprites.WIDTH_DEFAULT Width of the destiny (inside the sprites group). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprites group that it belongs to. height number &lt;optional&gt; this.parent.height|CB_GraphicSprites.HEIGHT_DEFAULT Height of the destiny (inside the sprites group). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprites group that it belongs to. zIndex number &lt;optional&gt; this.parent.zIndex|CB_GraphicSprites.ZINDEX_DEFAULT The z-index for the destiny (inside the sprites group). Only numeric values which are not zero (0) are allowed. If not provided, as default it will use the value from the sprites group that it belongs to. To change the value of this property, use the \"setZIndex\" method of the sprite or the CB_GraphicSprites#setZIndexSprite method (which will call the CB_GraphicSpritesScene#updateSpritesByZIndex method internally). disabled boolean &lt;optional&gt; this.parent.disabled|false Tells whether this sprite is disabled or not. Regardless its value, it will be considered disabled if its sprites group parent is also disabled. If not provided, as default it will use the value from the sprites group that it belongs to. data object &lt;optional&gt; CB_combineJSON(this.parent.data, this.data)||this.parent.data||{ 'that' : CB_GraphicSprites.SPRITES_OBJECT, 'getThis' = function() { return this.that; } } Object with any additional data desired which can be any kind. If not provided, missing properties as default will use the value from the sprites group that it belongs to. It will always have a \"that\" property pointing to the CB_GraphicSprites.SPRITE_OBJECT object where it belongs to and a function in its \"getThis\" property returning the same value (added automatically). These properties (\"that\" and \"getThis\") cannot be overridden. subSprites array &lt;optional&gt; [] Numeric array containing CB_GraphicSprites.SUBSPRITE_OBJECT objects with the sub-sprites that this sprite uses. subSpritesByZIndex array Read-only property containing a numeric array of all the CB_GraphicSprites.SUBSPRITE_OBJECT objects of the sprite ordered by their z-index (\"zIndex\" property). It is updated automatically when the z-index of a sub-sprite is set with its \"setZIndex\" method (or when calling the CB_GraphicSprites#setZIndexSubSprite method) or when inserting/removing sub-sprites through the CB_GraphicSprites#insertSubSprites, CB_GraphicSprites#insertSubSprite, CB_GraphicSprites#removeSubSprite or CB_GraphicSprites#removeSubSpriteById methods. byReference boolean &lt;optional&gt; false If set to true, when inserting the sprite, its \"subSprites\" property will use exactly the object given for that property (without making a copy) and the same sprite itself (CB_GraphicSprites.SPRITE_OBJECT object) will be inserted internally directly without making a copy of itself. parent CB_GraphicSprites.SPRITES_OBJECT Read-only property pointing to its parent (CB_GraphicSprites.SPRITES_OBJECT object). container CB_GraphicSprites Read-only property pointing to the CB_GraphicSprites object which contains it. isSprite boolean Read-only property which is always set to true to help identify this type of object. type 'sprite' Read-only property indicating the type of object (always \"sprite\"). position integer Read-only property indicating the position of this sprite in the array which is set the \"sprites\" property of the sprites group parent (CB_GraphicSprites.SPRITES_OBJECT object). positionByZIndex integer Read-only property indicating the position of this sprite in the array which is set the \"spritesByZIndex\" property of the sprites group parent (CB_GraphicSprites.SPRITES_OBJECT object). time integer Property which stores the time in milliseconds when the sprite was started being pointed for the last time (time elapsed since the time origin which was obtained calling the CB_Device.getTiming function internally). Note that it could being not pointed anymore. If it has never being pointed before, it will be set to 0. setTime function Read-only property which is a method that updates the \"time\" property of the sprite (calls CB_GraphicSprites#setTime internally and returns its returning value). With only one parameter which belongs to the \"time\" parameter of the CB_GraphicSprites#setTime method. getTime function Read-only property which is a method that returns the \"time\" property of the sprite (calls CB_GraphicSprites#getTime internally and returns its returning value). With only one parameter which belongs to the \"returnValueOnFail\" parameter of the CB_GraphicSprites#getTime method. getTimeElapsed function Read-only property which is a method that returns how many milliseconds elapsed since the sprite was or will be pointed (checking its \"time\" property), comparing with the time given in milliseconds (time elapsed since the time origin which can be obtained calling the CB_Device.getTiming function) or with the current one if none is given (calls CB_GraphicSprites#getTimeElapsed internally and returns its returning value). With only one parameter which belongs to the \"timeToCompare\" parameter of the CB_GraphicSprites#getTimeElapsed method. removeAll function Read-only property which is a method that removes all the internal sub-sprites (CB_GraphicSprites.SUBSPRITE_OBJECT objects) from the sprite which are in the \"subSprites\" property (calls CB_GraphicSprites#removeSubSprites internally and returns its returning value). With no parameters. removeSubSprites function Alias for the \"removeAll\" method. insertSubSprites function Read-only property which is a method that inserts the given sub-sprites (CB_GraphicSprites.SUBSPRITE_OBJECT objects) in the sprite, adding them to the \"subSprites\" property (calls CB_GraphicSprites#insertSubSprites internally and returns its returning value). With only one parameter which belongs to the \"subSprites\" parameter of the CB_GraphicSprites#insertSubSprites method. remove function Read-only property which is a method that removes an internal sub-sprite (CB_GraphicSprites.SUBSPRITE_OBJECT object) by its index (position in the \"subSprites\" array) from the sprite, removing it from the \"subSprites\" property (calls CB_GraphicSprites#removeSubSprite internally and returns its returning value). With only one parameter which belongs to the \"index\" parameter of the CB_GraphicSprites#removeSubSprite method. removeById function Read-only property which is a method that removes an internal sub-sprite (CB_GraphicSprites.SUBSPRITE_OBJECT object) by its identifier from the sprite, removing it from the \"subSprites\" property (calls CB_GraphicSprites#removeSubSpriteById internally and returns its returning value). With only one parameter which belongs to the \"id\" parameter of the CB_GraphicSprites#removeSubSpriteById method. insert function Read-only property which is a method that inserts a given sub-sprite (CB_GraphicSprites.SUBSPRITE_OBJECT object) in the sprite, adding it to the \"subSprites\" property (calls CB_GraphicSprites#insertSubSprite internally and returns its returning value). With only one parameter which belongs to the \"subSprite\" parameter of the CB_GraphicSprites#insertSubSprite method. getAll function Read-only property which is a method that returns all the internal sub-sprites (CB_GraphicSprites.SUBSPRITE_OBJECT objects) in the sprite, getting them from the \"subSprites\" property (calls CB_GraphicSprites#getAll internally and returns its returning value). With two parameters (\"orderedByZIndex\" and \"returnValueOnFail\") which belong to the parameters with the same name of the CB_GraphicSprites#getAll method. getSubSprites function Alias for the \"getAll\" method. get function Read-only property which is a method that returns a sub-sprite (CB_GraphicSprites.SUBSPRITE_OBJECT object) by its index (position in the \"subSprites\" array) from the sprite, getting it from the \"subSprites\" property (calls CB_GraphicSprites#getSubSprite internally and returns its returning value). With two parameters (\"index\" and \"returnValueOnFail\") which belong to the parameters with the same name of the CB_GraphicSprites#getSubSprite method. getById function Read-only property which is a method that returns a sub-sprite (CB_GraphicSprites.SUBSPRITE_OBJECT object) by its identifier from the sprite, getting it from the \"subSprites\" property (calls CB_GraphicSprites#getSubSpriteById internally and returns its returning value). With two parameters (\"id\" and \"returnValueOnFail\") which belong to the parameters with the same name of the CB_GraphicSprites#getSubSpriteById method. getIndexById function Read-only property which is a method that returns the index (position in the \"subSprites\" array) of a sub-sprite (CB_GraphicSprites.SUBSPRITE_OBJECT object) by its identifier (calls CB_GraphicSprites#getSubSpriteIndexById internally and returns its returning value). With only one parameter which belongs to the \"id\" parameter of the CB_GraphicSprites#getSubSpriteIndexById method. executeFunctionAll function Read-only property which is a method that executes the desired function for each sub-sprite (CB_GraphicSprites.SUBSPRITE_OBJECT objects which are in the \"subSprites\" property) in the sprite (calls CB_GraphicSprites#executeFunctionAllSubSprites internally and returns its returning value). With five parameters (\"functionEach\", \"orderedByZIndex\", \"delayBetweenEach\", \"returnSetTimeoutsArray\", \"delayBetweenEachAffectsFirst\" and \"functionFinish\") which belong to the parameters with the same name of the CB_GraphicSprites#executeFunctionAllSubSprites method. executeAll function Alias for the \"executeFunctionAll\" method. forEach function Alias for the \"executeFunctionAll\" method. getZIndex function Read-only property which is a method that returns the z-index (\"z-index\" property) of the sprite (calls CB_GraphicSprites#getZIndexSprite internally and returns its returning value). With only one parameter which belongs to the \"returnValueOnFail\" parameter of the CB_GraphicSprites#getZIndexSprite method. setZIndex function Read-only property which is a method to set the z-index (\"z-index\" property) of the sprite (calls CB_GraphicSprites#setZIndexSprite internally and returns its returning value). With only one parameter which belongs to the \"zIndex\" parameter of the CB_GraphicSprites#setZIndexSprite method. isDisabled function Read-only property which is a method that tells whether the sprite is disabled or not (calls CB_GraphicSprites#isDisabledSprite internally and returns its returning value). With no parameters. A sprite is considered disabled if its sprites group parent is also disabled. setDisabled function Read-only property which is a method to disable or enable the sprite (calls CB_GraphicSprites#setDisabledSprite internally and returns its returning value). With four parameters (\"disabled\", \"affectSubSprites\", \"affectParent\" and \"affectParentChildren\") which belong to the parameters with the same name of the CB_GraphicSprites#setDisabledSprite method. getPointer function Read-only property which is a method that gets the current position of the pointer. It belongs to an index of the CB_GraphicSprites#spritesGroup.sprites array where a CB_GraphicSprites.SPRITE_OBJECT object is placed (containing a sprite). Internally, it uses the CB_GraphicSprites#pointer property. Calls CB_GraphicSprites#getPointer internally and returns its returning value. With no parameters. getCurrentPosition function Alias for the \"getPointer\" method. getPointerPrevious function Read-only property which is a method that gets the previous position of the pointer. Internally, it uses the CB_GraphicSprites#pointerPrevious property. Calls CB_GraphicSprites#getPointerPrevious internally and returns its returning value. With no parameters. getPreviousPosition function Alias for the \"getPointerPrevious\" method. setPointer function Read-only property which is a method that sets the pointer to the desired position (if possible). The position should belong to an index of the CB_GraphicSprites#spritesGroup.sprites array where a CB_GraphicSprites.SPRITE_OBJECT object is placed (containing a sprite). Internally, it modifies the CB_GraphicSprites#pointer property (if possible). If the position was updated, it will also reset the CB_GraphicSprites#time property (setting the current time in milliseconds). Calls CB_GraphicSprites#setPointer internally and returns the sprite (a CB_GraphicSprites.SPRITE_OBJECT object) which is being currently pointed (by the pointer set in the CB_GraphicSprites#pointer property). With two parameters (\"position\" and \"loop\") which belong to the parameters with the same name of the CB_GraphicSprites#setPointer method. setCurrentPosition function Alias for the \"setPointer\" method. getCurrent function Read-only property which is a method that gets the sprite (a CB_GraphicSprites.SPRITE_OBJECT object) which is being currently pointed (by the pointer set in the CB_GraphicSprites#pointer property). Calls CB_GraphicSprites#getCurrent internally and returns its returning value. With no parameters. current function Alias for the \"getCurrent\" method. now function Alias for the \"getCurrent\" method. getPrevious function Read-only property which is a method that gets the sprite which was previously pointed if any or returns null otherwise. It does not modify the CB_GraphicSprites#pointer property. Calls CB_GraphicSprites#getPrevious internally and returns its returning value. With no parameters. setPrevious function Read-only property which is a method that makes the pointer to go back to the previous position (if possible) and returns the sprite located there (if any). The position should belong to an index of the CB_GraphicSprites#spritesGroup.sprites array where a CB_GraphicSprites.SPRITE_OBJECT object is placed (containing a sprite) and it will be returned if found. Internally, it modifies the CB_GraphicSprites#pointer property (if possible). If the position was updated, it will update also the CB_GraphicSprites#time property (setting the current time in milliseconds). Calls CB_GraphicSprites#setPrevious internally and returns its returning value. With only one parameter which belongs to the \"loop\" parameter of the CB_GraphicSprites#setPrevious method. previous function Alias for the \"setPrevious\" method. setNext function Read-only property which is a method that makes the pointer to advance to the next position (if possible) and returns the sprite located there (if any). The position should belong to an index of the CB_GraphicSprites#spritesGroup.sprites array where a CB_GraphicSprites.SPRITE_OBJECT object is placed (containing a sprite) and it will be returned if found. Internally, it modifies the CB_GraphicSprites#pointer property (if possible). If the position was updated, it will also update the CB_GraphicSprites#time property (setting the current time in milliseconds). Calls CB_GraphicSprites#setNext internally and returns its returning value. With only one parameter which belongs to the \"loop\" parameter of the CB_GraphicSprites#setNext method. next function Alias for the \"setNext\" method. setPropertyCascade function Read-only property which is a method that sets the desired value of a given property name to the sprite itself and all of its sub-sprites (if any). Calls CB_GraphicSprites#setPropertyCascade internally and returns its returning value. With two parameters (\"propertyName\" and \"value\") which belong to the parameters with the same name of the CB_GraphicSprites#setPropertyCascade method. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 61 Example { //'my_sprite_1': id: \"my_sprite_1\", src: \"path/to/image.gif\", srcType: CB_GraphicSprites.SRC_TYPES.IMAGE, srcLeft: 10, srcTop: 20, srcWidth: 64, srcHeight: 32, left: 10, top: 20, width: 64, height: 32, disabled: false, data: { datum_1 : \"value_1\", datum_2 : 2, datum_3: [ \"a\", \"b\", \"c\" ] }, subSprites: [ //'my_subsprite_1': { id: \"my_subsprite_1\", srcLeft: 10, srcTop: 20, zIndex: 1 }, //'my_subsprite_2': { id: \"my_subsprite_2\", srcLeft: 20, srcTop: 40, zIndex: 2 } ] } SPRITES_OBJECT An object with the information that belongs to a group of graphic sprites. Type: Object Properties: Name Type Argument Default Description id string | * &lt;optional&gt; 'CB_GraphicSprites_' + CB_GraphicSprites._idUnique++ Identifier of the group of graphic sprites (also used as the CB_GraphicSprites.id property for the CB_GraphicSprites object). It should be unique. Recommended. It must be a value which evaluates to true. By default, it is generated automatically (with an internal counter). src * &lt;optional&gt; \"\" Source of origin. Can be a path or identifier of an image, text, bitmap, 3D object, etc. They can be used for any kind of source you may think of, including (but not limited to) one sprites sheet or more, one atlas or more, etc. or even a mix of all of them. srcType string &lt;optional&gt; CB_GraphicSprites.SRC_TYPES_DEFAULT Type of the source of origin. It should point to a property of the CB_GraphicSprites.SRC_TYPES object. You can use other values of the CB_GraphicSprites.SRC_TYPES object or create new ones. srcLeft number &lt;optional&gt; CB_GraphicSprites.LEFT_SOURCE_DEFAULT Left (horizontal) position in the original source (having in mind its real width and height). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from CB_GraphicSprites.LEFT_SOURCE_DEFAULT. srcTop number &lt;optional&gt; CB_GraphicSprites.TOP_SOURCE_DEFAULT Top (vertical) position in the original source (having in mind its real width and height). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from CB_GraphicSprites.TOP_SOURCE_DEFAULT. srcWidth number &lt;optional&gt; CB_GraphicSprites.WIDTH_SOURCE_DEFAULT Width of the original source. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from CB_GraphicSprites.WIDTH_SOURCE_DEFAULT. srcHeight number &lt;optional&gt; CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT Height of the original source. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT. left number &lt;optional&gt; CB_GraphicSprites.LEFT_DEFAULT Left (horizontal) position in the destiny. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from CB_GraphicSprites.LEFT_DEFAULT. top number &lt;optional&gt; CB_GraphicSprites.TOP_DEFAULT Top (vertical) position in the destiny. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from CB_GraphicSprites.TOP_DEFAULT. width number &lt;optional&gt; CB_GraphicSprites.WIDTH_DEFAULT Width of the destiny. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from CB_GraphicSprites.WIDTH_DEFAULT. height number &lt;optional&gt; CB_GraphicSprites.HEIGHT_DEFAULT Height of the destiny. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from CB_GraphicSprites.HEIGHT_DEFAULT. zIndex number &lt;optional&gt; CB_GraphicSprites.ZINDEX_DEFAULT The z-index for the destiny (only numeric values which are not zero (0) are allowed). Also used as the CB_GraphicSprites.zIndex property for the CB_GraphicSprites object. If not provided, as default it will use the value from CB_GraphicSprites.ZINDEX_DEFAULT. To change the value of this property, use the CB_GraphicSprites#setZIndex method (which will call the CB_GraphicSpritesScene#updateGraphicSpritesByZIndex method internally if there is a CB_GraphicSpritesScene parent object). disabled boolean &lt;optional&gt; false Tells whether this sprites group (and the CB_GraphicSprites object itself) is disabled or not. If not provided, as default it will be false (which means it is enabled). data object &lt;optional&gt; { 'that' : CB_GraphicSprites.SPRITES_OBJECT, 'getThis' = function() { return this.that; } } Object with any additional data desired which can be any kind. It will always have a \"that\" property pointing to the CB_GraphicSprites.SPRITES_OBJECT object where it belongs to and a function in its \"getThis\" property returning the same value (added automatically). These properties (\"that\" and \"getThis\") cannot be overridden. sprites array &lt;optional&gt; [] Numeric array containing CB_GraphicSprites.SPRITE_OBJECT objects with all the sprites that will be used. Recommended at least to provide one CB_GraphicSprites.SPRITE_OBJECT object in the first index. spritesByZIndex array Read-only property containing a numeric array of all the CB_GraphicSprites.SPRITE_OBJECT objects ordered by their z-index (\"zIndex\" property). It is updated automatically when the z-index of a sprite is set with its \"setZIndex\" method (or when calling the CB_GraphicSprites#setZIndexSprite method) or when inserting/removing sprites through the CB_GraphicSprites#insertSprites, CB_GraphicSprites#insertSprite, CB_GraphicSprites#removeSprite or CB_GraphicSprites#removeSpriteById methods. byReference_DEFAULT boolean &lt;optional&gt; false Default value to use as the \"byReference\" parameter for the constructor and for the CB_GraphicSprites#insertSprites method. If a boolean value is not provided, it will be parsed to boolean (resulting undefined to be false). parent * &lt;optional&gt; undefined|CB_GraphicSpritesScene Property pointing to or containing its parent (also used as the CB_GraphicSprites.parent property for the CB_GraphicSprites object). It could be a CB_GraphicSpritesScene object. container CB_GraphicSprites Read-only property pointing to the CB_GraphicSprites object which contains it. isSpritesGroup boolean Read-only property which is always set to true to help identify this type of object. type 'spritesGroup' Read-only property indicating the type of object (always \"spritesGroup\"). position integer &lt;optional&gt; Read-only property indicating the position of this CB_GraphicSprites object in the array which is set the \"items\" property inside the CB_GraphicSpritesScene#spritesGroups object which is in the CB_GraphicSpritesScene object parent (if any). positionByZIndex integer &lt;optional&gt; Read-only property indicating the position of this CB_GraphicSprites object in the array which is set the \"itemsByZIndex\" property inside the CB_GraphicSpritesScene#spritesGroups object which is in the CB_GraphicSpritesScene object parent (if any). Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 152 Example { //'my_sprites_1': id: \"my_sprites_1\", src: \"path/to/image.gif\", srcType: CB_GraphicSprites.SRC_TYPES.IMAGE, srcLeft: 10, srcTop: 20, srcWidth: 64, srcHeight: 32, left: 10, top: 20, width: 64, height: 32, data: { datum_1: \"value_1\", datum_2: 2, datum_3: [ \"a\", \"b\", \"c\" ] }, sprites: [ //'my_sprite_1': { id: \"my_sprite_1\", subSprites: [ //'my_subsprite_1': { id: \"my_subsprite_1\", srcLeft: 10, srcTop: 20, zIndex: 1 }, //'my_subsprite_2': { id: \"my_subsprite_2\", srcLeft: 20, srcTop: 40, zIndex: 2 } ] }, //'my_sprite_2': { id: \"my_sprite_2\", subSprites: [ //'my_subsprite_3': { id: \"my_subsprite_3\", srcLeft: 30, srcTop: 60, zIndex: 1 }, //'my_subsprite_4': { id: \"my_subsprite_4\", srcLeft: 40, srcTop: 80, zIndex: 2 } ] } ] } SUBSPRITE_OBJECT An object with the information that belongs to a sub-sprite (data which belongs to a certain source) used by a graphic sprite. Type: Object Properties: Name Type Argument Default Description id string | * &lt;optional&gt; 'CB_GraphicSprites.subSprite_' + CB_GraphicSprites._idSubSpriteUnique++ Identifier of the sub-sprite. It should be unique. It must be a value which evaluates to true. By default, it is generated automatically (with an internal counter). src * &lt;optional&gt; this.parent.src|\"\" Source of origin. Can be a path or identifier of an image, text, bitmap, 3D object, etc. They can be used for any kind of source you may think of, including (but not limited to) one sprites sheet or more, one atlas or more, etc. or even a mix of all of them. If not provided, as default it will use the value from the sprite that it belongs to. srcType string &lt;optional&gt; this.parent.srcType|CB_GraphicSprites.SRC_TYPES_DEFAULT Type of the source of origin. If not provided, as default it will use the value from the sprite that it belongs to. It should point to a property of the CB_GraphicSprites.SRC_TYPES object. You can use other values of the CB_GraphicSprites.SRC_TYPES object or create new ones. srcLeft number &lt;optional&gt; this.parent.srcLeft|CB_GraphicSprites.LEFT_SOURCE_DEFAULT Left (horizontal) position in the original source (having in mind its real width and height). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprite that it belongs to. srcTop number &lt;optional&gt; this.parent.srcTop|CB_GraphicSprites.TOP_SOURCE_DEFAULT Top (vertical) position in the original source (having in mind its real width and height). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprite that it belongs to. srcWidth number &lt;optional&gt; this.parent.srcWidth|CB_GraphicSprites.WIDTH_SOURCE_DEFAULT Width of the original source. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprite that it belongs to. srcHeight number &lt;optional&gt; this.parent.srcHeight|CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT Height of the original source. Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprite that it belongs to. left number &lt;optional&gt; CB_GraphicSprites.LEFT_DEFAULT Left (horizontal) position in the destiny (inside the sprite). Unit agnostic (only numeric values are allowed). top number &lt;optional&gt; CB_GraphicSprites.TOP_DEFAULT Top (vertical) position in the destiny (inside the sprite). Unit agnostic (only numeric values are allowed). width number &lt;optional&gt; this.parent.width|CB_GraphicSprites.WIDTH_DEFAULT Width of the destiny (inside the sprite). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprite that it belongs to. height number &lt;optional&gt; this.parent.height|CB_GraphicSprites.HEIGHT_DEFAULT Height of the destiny (inside the sprite). Unit agnostic (only numeric values are allowed). If not provided, as default it will use the value from the sprite that it belongs to. zIndex number &lt;optional&gt; this.parent.zIndex|CB_GraphicSprites.ZINDEX_DEFAULT The z-index for the destiny (inside the sprite). Only numeric values which are not zero (0) are allowed. If not provided, as default it will use the value from the sprite that it belongs to. To change the value of this property, use the \"setZIndex\" method of the sub-sprite or the CB_GraphicSprites#setZIndexSubSprite method (which will call the CB_GraphicSpritesScene#updateSubSpritesByZIndex method internally). disabled boolean &lt;optional&gt; this.parent.disabled|false Tells whether this sub-sprite is disabled or not. Regardless its value, it will be considered disabled if its sprite parent is also disabled. If not provided, as default it will use the value from the sprite that it belongs to. data object &lt;optional&gt; CB_combineJSON(this.parent.data, this.data)||this.parent.data||{ 'that' : CB_GraphicSprites.SPRITES_OBJECT, 'getThis' = function() { return this.that; } } Object with any additional data desired which can be any kind. If not provided, missing properties as default will use the value from the sprite that it belongs to. It will always have a \"that\" property pointing to the CB_GraphicSprites.SUBSPRITE_OBJECT object where it belongs to and a function in its \"getThis\" property returning the same value (added automatically). These properties (\"that\" and \"getThis\") cannot be overridden. byReference boolean &lt;optional&gt; false If set to true, when inserting the sub-sprite, the same sub-sprite itself (CB_GraphicSprites.SUBSPRITE_OBJECT object) will be inserted internally directly without making a copy of itself. parent CB_GraphicSprites.SPRITE_OBJECT Read-only property pointing to its parent (CB_GraphicSprites.SPRITE_OBJECT object). container CB_GraphicSprites Read-only property pointing to the CB_GraphicSprites object which contains it. isSubSprite boolean Read-only property which is always set to true to help identify this type of object. type 'subSprite' Read-only property indicating the type of object (always \"subSprite\"). position integer Read-only property indicating the position of this sub-sprite in the array which is set the \"subSprites\" property of the sprite parent (CB_GraphicSprites.SPRITE_OBJECT object). positionByZIndex integer Read-only property indicating the position of this sub-sprite in the array which is set the \"subSpritesByZIndex\" property of the sprite parent (CB_GraphicSprites.SPRITE_OBJECT object). time integer Property which stores the time in milliseconds when its parent sprite was started being pointed for the last time (time elapsed since the time origin which was obtained calling the CB_Device.getTiming function internally). Note that the parent could being not pointed anymore. If it has never being pointed before, it will be set to 0. It normally has the same value as the \"time\" property of its parent object but they can be modified independently. setTime function Read-only property which is a method that updates the \"time\" property of the sub-sprite (calls CB_GraphicSprites#setTime internally and returns its returning value). With only one parameter which belongs to the \"time\" parameter of the CB_GraphicSprites#setTime method. getTime function Read-only property which is a method that returns the \"time\" property of the sub-sprite (calls CB_GraphicSprites#getTime internally and returns its returning value). With only one parameter which belongs to the \"returnValueOnFail\" parameter of the CB_GraphicSprites#getTime method. If the \"time\" property of the sub-sprite is not found, it will use the \"time\" property from its sprite parent. getTimeElapsed function Read-only property which is a method that returns how many milliseconds elapsed since the sprite was or will be pointed (checking its \"time\" property), comparing with the time given in milliseconds (time elapsed since the time origin which can be obtained calling the CB_Device.getTiming function) or with the current one if none is given (calls CB_GraphicSprites#getTimeElapsed internally and returns its returning value). With only one parameter which belongs to the \"timeToCompare\" parameter of the CB_GraphicSprites#getTimeElapsed method. If the \"time\" property of the sub-sprite is not found, it will use the \"time\" property from its sprite parent. getZIndex function Read-only property which is a method that returns the z-index (\"z-index\" property) of the sub-sprite (calls CB_GraphicSprites#getZIndexSubSprite internally and returns its returning value). With only one parameter which belongs to the \"returnValueOnFail\" parameter of the CB_GraphicSprites#getZIndexSubSprite method. setZIndex function Read-only property which is a method to set the z-index (\"z-index\" property) of the sub-sprite (calls CB_GraphicSprites#setZIndexSubSprite internally and returns its returning value). With only one parameter which belongs to the \"zIndex\" parameter of the CB_GraphicSprites#setZIndexSubSprite method. isDisabled function Read-only property which is a method that tells whether the sub-sprite is disabled or not (calls CB_GraphicSprites#isDisabledSubSprite internally and returns its returning value). With no parameters. A sub-sprite is considered disabled if its sprite parent is disabled (a sprite is considered disabled if its sprites group parent is also disabled). setDisabled function Read-only property which is a method to disable or enable the sub-sprite (calls CB_GraphicSprites#setDisabledSubSprite internally and returns its returning value). With three parameters (\"disabled\", \"affectParents\" and \"affectParentsChildren\") which belong to the parameters with the same name of the CB_GraphicSprites#setDisabledSubSprite method. Source: CrossBase/audiovisual/image/CB_GraphicSprites.js, line 8 Example { id: \"my_subsprite_1\", src: \"path/to/image.gif\", srcType: CB_GraphicSprites.SRC_TYPES.IMAGE, srcLeft: 10, srcTop: 20, srcWidth: 64, srcHeight: 32, left: 10, top: 20, width: 64, height: 32, zIndex: 1, disabled: false, data: { datum_1: \"value_1\", datum_2: 2, datum_3: [ \"a\", \"b\", \"c\" ] } } × Search results Close "},"CB_GraphicSpritesScene.html":{"id":"CB_GraphicSpritesScene.html","title":"Class: CB_GraphicSpritesScene","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Class: CB_GraphicSpritesScene CB_GraphicSpritesScene Class to manage different groups of graphic sprites (2D or 3D). Internally, it manages CB_GraphicSprites objects. new CB_GraphicSpritesScene( [spritesGroups] [, byReference]) → {CB_GraphicSpritesScene} Class to manage different groups of graphic sprites (2D or 3D). Internally, it manages CB_GraphicSprites objects. Parameters: Name Type Argument Default Description spritesGroups CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT &lt;optional&gt; Object with the desired groups of sprites. The information will be used for the CB_GraphicSpritesScene#spritesGroups property. Used as the \"spritesGroups\" parameter when calling the CB_GraphicSpritesScene#insertSpritesGroups method internally. byReference boolean &lt;optional&gt; false This value will be used as the \"byReference\" parameter of the constructor when creating the new internal CB_GraphicSprites objects. If a boolean value is not provided, it will use the value of the CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT.byReference_DEFAULT property of the given CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT object (parsed to boolean). Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 127 To Do: Think about a \"createCopy\" parameter on different the insert methods (to insert sprites groups/graphic sprites objects, etc.) so it will make a copy of the object to avoid using/modifying the original one. If the \"createCopy\" is set to false, it should always use the object as reference (using/modifying it). Think about a method to remove a sprite group object when the same sprite group is received by parameter. The same to remove a CB_GraphicSprites object, receiving a CB_GraphicSprites object by parameter. The same to remove the sprites groups object, receiving a sprites groups object by parameter. Only remove them if they match exactly. Think about a method to insert CB_GraphicSprites object directly. The same with a method that inserts many CB_GraphicSprites objects (receiving an array with them). Returns: Returns a new CB_GraphicSpritesScene object. Type CB_GraphicSpritesScene Members &lt;readonly&gt; id :string|* Identifier of the sprites groups object (the \"id\" property of the CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT stored in the CB_GraphicSpritesScene#spritesGroups property) and the CB_GraphicSpritesScene object itself (same one). It should be unique. It must be a value which evaluates to true. By default, it is generated automatically (with an internal counter). Type: string | * Default Value: 'CB_GraphicSpritesScene_' + CB_GraphicSpritesScene._idUnique++ Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 140 &lt;constant&gt; isSpritesScene :boolean Property which is always set to true to help identify this type of object. Type: boolean Default Value: true Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 173 &lt;readonly&gt; parent :* Property pointing to or containing its parent. It is the same as the \"parent\" property of the CB_GraphicSprites.SPRITES_GROUPS_OBJECT stored in the CB_GraphicSprites#spritesGroups property. Type: * Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 149 &lt;readonly&gt; spritesGroups :SPRITES_GROUPS_OBJECT Object containing all the internally-created CB_GraphicSprites objects and their information. Type: SPRITES_GROUPS_OBJECT Default Value: {} Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 159 &lt;constant&gt; type :string Indicates the type of object (always \"spritesScene\"). Type: string Default Value: spritesScene Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 182 Methods destructor() Destroys the graphic sprites scene object (removing all the sprites groups and the internal CB_GraphicSprites objects, etc.) and frees memory. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 201 executeAll() Alias for CB_GraphicSpritesScene#executeFunctionAll. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 600 See: CB_GraphicSpritesScene#executeFunctionAll executeFunctionAll(functionEach [, orderedByZIndex] [, delayBetweenEach] [, graphicSpritesObjects] [, returnSetTimeoutsArray] [, delayBetweenEachAffectsFirst] [, functionFinish]) → {integer|array} Performs a desired action, using the provided function, on all the existing CB_GraphicSprites objects or on the desired ones (if provided). Calls the CB_Arrays.executeFunctionAll function internally and returns its returning value. Parameters: Name Type Argument Default Description functionEach CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK Function that will be called for each CB_GraphicSprites object. As the first parameter it receives the CB_GraphicSprites object of the \"graphicSpritesObjects\" being looped, as the second parameter the position of this CB_GraphicSprites object in the \"graphicSpritesObjects\" array provided (or, if not provided, in the array returned by the CB_GraphicSpritesScene#getGraphicSpritesAll method), the third parameter is the array being looped and the fourth parameter will be the \"delayBetweenEach\" being used, being \"this\" the CB_GraphicSprites object itself. orderedByZIndex boolean &lt;optional&gt; false If set to true, it will loop the CB_GraphicSprites sorted by their z-index (ascending order). delayBetweenEach number | CB_Arrays.executeFunctionAll_ON_LOOP_CALLBACK &lt;optional&gt; 0 If a value greater than zero is used, it will be used as the delay desired between each call to the \"functionEach\" function (calling them using the setTimeout function internally). If not provided or the value is 0 (zero) or lower, each call to the \"functionEach\" function will be performed immediately one after the other. If a function is provided, it will be called with the same parameters as the \"functionEach\" function and its returning value will be used as the delay (executed every loop for each CB_GraphicSprites object). graphicSpritesObjects array &lt;optional&gt; CB_GraphicSpritesScene#getGraphicSpritesAll() A numeric array containing the CB_GraphicSprites objects that we want to loop. It should contain only CB_GraphicSprites objects which are already in the current CB_GraphicSpritesScene object. If not provided, it will use all the CB_GraphicSprites objects contained in the CB_GraphicSpritesScene object. returnSetTimeoutsArray boolean &lt;optional&gt; false Defines whether we want the method to return an integer or a numeric array with information of each setTimeout call. Returning an array with information of each setTimeout call is only useful when the setTimeout function is called internally, which happens when the \"delayBetweenEach\" parameter is greater than 0 (zero). delayBetweenEachAffectsFirst boolean &lt;optional&gt; false If set to true, the desired delay (if any) will also affect the first call to the \"functionEach\" function. functionFinish CB_Arrays.executeFunctionAll_ON_FINISH_CALLBACK &lt;optional&gt; Function that will be called for when it has finished looping all the items. The first parameter will be the array which was looped, the second parameter will be the number of times that the \"functionEach\" callback was called (the most likely, matches the number of elements unless they are undefined or null), and the third parameter will be the maximum \"delay\" used, being \"this\" the array itself. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 628 To Do: Think about only allowing CB_GraphicSprites objects (in the \"graphicSpritesObjects\" parameter) which are already in the CB_GraphicSpritesScene (identify them by their ID), to avoid problems. Returns: If the \"returnSetTimeoutsArray\" parameter is set to false, it will return the number of calls to the \"functionEach\" function that were performed (which should be the same number as the CB_GraphicSprites objects given in the \"graphicSpritesObjects\" parameter). Otherwise, if the \"returnSetTimeoutsArray\" is set to true, it will return a numeric array with a CB_Arrays.executeFunctionAll_OBJECT object for each CB_GraphicSprites given. The length of this array will also be the number of calls to the \"functionEach\" function that were performed. Note that if a value greater than 0 (zero) for the \"delayBetweenEach\" parameter has been provided, perhaps not all calls of the \"functionEach\" function will have been performed yet when exiting this method because of the asynchronous nature of the setTimeout function. Type integer | array forEach() Alias for CB_GraphicSpritesScene#executeFunctionAll. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 605 See: CB_GraphicSpritesScene#executeFunctionAll forEachGraphicSprites() Alias for CB_GraphicSpritesScene#executeFunctionAll. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 610 See: CB_GraphicSpritesScene#executeFunctionAll get() Alias for CB_GraphicSpritesScene#getGraphicSprites. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 534 See: CB_GraphicSpritesScene#getGraphicSprites getAll() Alias for CB_GraphicSpritesScene#getGraphicSpritesAll. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 505 See: CB_GraphicSpritesScene#getGraphicSpritesAll getById() Alias for CB_GraphicSpritesScene#getGraphicSpritesById. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 555 See: CB_GraphicSpritesScene#getGraphicSpritesById getCopy( [avoidCopyingPointers] [, avoidCopyingTimes] [, clearReferences] [, filterProperties] [, propertiesToKeepObject]) → {CB_GraphicSpritesScene} Gets a new copy of this object with the same attributes (all sub-objects will be a copy, they will not the same reference). Parameters: Name Type Argument Default Description avoidCopyingPointers boolean &lt;optional&gt; false If set to true, it will not copy the CB_GraphicSprites#pointer property of each CB_GraphicSprites object. avoidCopyingTimes boolean &lt;optional&gt; false If set to true, it will not copy neither the CB_GraphicSprites#time property of each CB_GraphicSprites object nor the \"time\" property of each of their sprites (CB_GraphicSprites.SPRITE_OBJECT objects). clearReferences boolean &lt;optional&gt; false If set to true, it will not copy neither the \"container\" nor the \"parent\" nor the \"data.that\" nor the \"data.getThis\" properties of any element. Useful to be able to stringify the object preventing the \"TypeError: cyclic object value\" error. When set to true, calls the CB_GraphicSprites.clearReferences function internally. If set to true and the \"filterProperties\" parameter is also set to true, the CB_GraphicSprites.filterProperties will always be called before calling the CB_GraphicSprites.clearReferences function. filterProperties boolean &lt;optional&gt; false If set to true, it will call the CB_GraphicSprites.filterProperties function internally to filter the properties that we do not want to keep (using the given \"propertiesToKeepObject\" as the parameter to call it). When set to true, calls the CB_GraphicSprites.filterProperties function internally. If set to true and the \"clearReferences\" parameter is also set to true, the CB_GraphicSprites.filterProperties will always be called before calling the CB_GraphicSprites.clearReferences function. propertiesToKeepObject CB_GraphicSprites.filterProperties_propertiesToKeepObject_TYPE &lt;optional&gt; CB_GraphicSprites.filterProperties_DEFAULT_PROPERTIES The object with the properties that we want to keep. Only used when the \"filterProperties\" parameter is set to true, as the \"propertiesToKeepObject\" when calling the CB_GraphicSprites.filterProperties function internally. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 665 Returns: Returns a copy of this object with the same attributes (all sub-objects will be a copy, not the same reference). Type CB_GraphicSpritesScene getGraphicSprites( [index] [, returnValueOnFail]) → {CB_GraphicSprites|*} Gets a desired CB_GraphicSprites object through its index (its position in the CB_GraphicSpritesScene#spritesGroups.items array). Faster than getting it through its identifier with the CB_GraphicSpritesScene#getGraphicSpritesById method. Parameters: Name Type Argument Default Description index integer &lt;optional&gt; 0 The index where the desired CB_GraphicSprites object must be located (its position in the CB_GraphicSpritesScene#spritesGroups.items array). returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 546 Returns: Returns a CB_GraphicSprites object if found or the value of \"returnValueOnFail\" otherwise. Type CB_GraphicSprites | * getGraphicSpritesAll( [orderedByZIndex] [, returnValueOnFail]) → {array|*} Gets all the sprites graphic objects (the \"items\" property of the internal CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT object, if any). Parameters: Name Type Argument Default Description orderedByZIndex boolean &lt;optional&gt; false If set to true, it will return the CB_GraphicSprites objects sorted by their z-index (ascending order). returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 517 Returns: Returns an array with all the CB_GraphicSprites objects or the value of \"returnValueOnFail\" otherwise. Type array | * getGraphicSpritesById( [id] [, returnValueOnFail]) → {CB_GraphicSprites|*} Gets a desired CB_GraphicSprites object through its identifier. Slower than getting it through its index with the CB_GraphicSpritesScene#getGraphicSprites method. Parameters: Name Type Argument Description id string | * &lt;optional&gt; The identifier of the CB_GraphicSprites object that we want to get. returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 567 Returns: Returns a CB_GraphicSprites object if found or the value of \"returnValueOnFail\" otherwise. Type CB_GraphicSprites | * getGraphicSpritesIndexById( [id]) → {integer} Gets the index (the position in the CB_GraphicSpritesScene#spritesGroups.items array) of a desired CB_GraphicSprites object by its identifier. Parameters: Name Type Argument Description id string | * &lt;optional&gt; The identifier of the CB_GraphicSprites object whose index we want to get. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 586 To Do: Optimize it (perhaps using a cache matching the IDs with their position, maybe using the \"position\" or \"positionByZIndex\" properties). Returns: Returns the index (the position in the CB_GraphicSpritesScene#spritesGroups.items array) of the desired CB_GraphicSprites object or -1 if not found. Type integer getIndexById() Alias for CB_GraphicSpritesScene#getGraphicSpritesIndexById. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 574 See: CB_GraphicSpritesScene#getGraphicSpritesIndexById getSpritesGroups( [returnValueOnFail]) → {CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT|*} Gets the sprites groups object (the CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT object which is in the CB_GraphicSpritesScene#spritesGroups property), if any. Parameters: Name Type Argument Description returnValueOnFail * &lt;optional&gt; The value we want it to return in the case that no value is found. If not provided, undefined will be returned. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 499 Returns: Returns the sprites groups object (the CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT object which is in the CB_GraphicSpritesScene#spritesGroups property), if any, or the value of \"returnValueOnFail\" otherwise. Type CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT | * getSpritesGroupsAll() Alias for CB_GraphicSpritesScene#getSpritesGroups. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 488 See: CB_GraphicSpritesScene#getSpritesGroups insert() Alias for CB_GraphicSpritesScene#insertSpritesGroup. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 397 See: CB_GraphicSpritesScene#insertSpritesGroup insertSpritesGroup( [spritesGroup] [, avoidUpdatingGraphicSpritesByZIndex] [, byReference]) → {CB_GraphicSpritesScene.insertSpritesGroup_OBJECT} Adds the desired group of graphic sprites. Creates internal CB_GraphicSprites objects. Parameters: Name Type Argument Default Description spritesGroup CB_GraphicSprites.SPRITES_OBJECT &lt;optional&gt; Object with the desired sprites group. It will be stored in the \"CB_GraphicSpritesScene#spritesGroups.spritesGroups\" property and the CB_GraphicSprites object created internally will be stored in the \"CB_GraphicSpritesScene#spritesGroups.items\" property. avoidUpdatingGraphicSpritesByZIndex boolean &lt;optional&gt; false If set to true, it will not call the {CB_GraphicSpritesScene#updateGraphicSpritesByZIndex} method internally. Internal usage recommended only. byReference boolean &lt;optional&gt; false This value will be used as the \"byReference\" parameter of the constructor when creating the new internal CB_GraphicSprites objects. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 410 Returns: Returns an object whose \"spritesGroup\" property contains the CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT which has been inserted (it could have been modified/sanitized from the given one and some missing properties or those which were wrong could have been inherited) and was used to create the internal CB_GraphicSprites object when calling its constructor and the \"item\" property contains the CB_GraphicSprites object created and inserted. Type CB_GraphicSpritesScene.insertSpritesGroup_OBJECT insertSpritesGroups( [spritesGroups] [, byReference]) → {CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT} Adds the desired groups of graphic sprites. Calls the CB_GraphicSpritesScene#insertSpritesGroup and CB_GraphicSpritesScene#updateGraphicSpritesByZIndex methods internally. Parameters: Name Type Argument Default Description spritesGroups CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT &lt;optional&gt; Object with the desired sprites groups. They will be stored in the \"CB_GraphicSpritesScene#spritesGroups.spritesGroups\" property and the CB_GraphicSprites objects created internally will be stored in the \"CB_GraphicSpritesScene#spritesGroups.items\" property. byReference boolean &lt;optional&gt; !!CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT.byReference_DEFAULT This value will be used as the \"byReference\" parameter of the constructor when creating the new internal CB_GraphicSprites objects. If a boolean value is not provided, it will use the value of the CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT.byReference_DEFAULT property of the given CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT object (parsed to boolean). Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 238 Returns: Returns the CB_GraphicSpritesScene#spritesGroups property after updating it. Type CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT remove() Alias for CB_GraphicSpritesScene#removeSpritesGroup. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 323 See: CB_GraphicSpritesScene#removeSpritesGroup removeAll() Alias for CB_GraphicSpritesScene#removeSpritesGroups. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 211 See: CB_GraphicSpritesScene#removeSpritesGroups removeById() Alias for CB_GraphicSpritesScene#removeSpritesGroupById. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 355 See: CB_GraphicSpritesScene#removeSpritesGroupById removeGraphicSprites() Alias for CB_GraphicSpritesScene#removeSpritesGroup. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 328 See: CB_GraphicSpritesScene#removeSpritesGroup removeGraphicSpritesById() Alias for CB_GraphicSpritesScene#removeSpritesGroupById. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 360 See: CB_GraphicSpritesScene#removeSpritesGroupById removeSpritesGroup( [index]) → {boolean} Removes a sprites group and its CB_GraphicSprites object by its index (its position in the CB_GraphicSpritesScene#spritesGroups.items array). Calls the CB_GraphicSpritesScene#updateGraphicSpritesByZIndex method internally. Parameters: Name Type Argument Default Description index integer &lt;optional&gt; 0 The index where the CB_GraphicSprites object is located (its position in the CB_GraphicSpritesScene#spritesGroups.items array). Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 339 Returns: Returns true if the CB_GraphicSprites object has been deleted from the graphic sprites scene object or false otherwise. Type boolean removeSpritesGroupById( [id]) → {boolean} Removes a sprites group and its CB_GraphicSprites object by its identifier. Calls the CB_GraphicSpritesScene#updateGraphicSpritesByZIndex method internally. Parameters: Name Type Argument Description id string | * &lt;optional&gt; The identifier of the CB_GraphicSprites object. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 372 To Do: Optimize it (perhaps using a cache matching the IDs with their position, maybe using the \"position\" or \"positionByZIndex\" properties). Returns: Returns true if the CB_GraphicSprites object has been deleted from the graphic sprites scene object or false otherwise. Type boolean removeSpritesGroups() Removes all the sprites groups (and all the CB_GraphicSprites objects) by clearing the CB_GraphicSprites#spritesGroups property. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 225 removeSpritesGroupsAll() Alias for CB_GraphicSpritesScene#removeSpritesGroups. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 216 See: CB_GraphicSpritesScene#removeSpritesGroups setPropertyCascade(propertyName [, value] [, onlyCurrent]) → {integer} Sets the desired value of a given property name to the CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT object as well to its CB_GraphicSprites objects and their children (their CB_GraphicSprites.SPRITES_OBJECT object, including their CB_GraphicSprites.SPRITE_OBJECT and their CB_GraphicSprites.SUBSPRITE_OBJECT objects). Calls the CB_GraphicSprites#setPropertyCascade method internally. Parameters: Name Type Argument Default Description propertyName number The name of the property we want to affect. Also used as the \"propertyName\" parameter when calling the CB_GraphicSprites#setPropertyCascade method internally. value * &lt;optional&gt; The value desired for the given property. Also used as the \"value\" parameter when calling the CB_GraphicSprites#setPropertyCascade method internally. onlyCurrent boolean &lt;optional&gt; false If set to true, it will only affect the current sprite and its sub-sprites of each CB_GraphicSprites object (and also the CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT object and the CB_GraphicSprites.SPRITES_OBJECT object of each CB_GraphicSprites object). Used as the \"propertyName\" parameter when calling the CB_GraphicSprites#setPropertyCascade method internally. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 642 Returns: Returns the number of elements affected (counting the CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT object and the CB_GraphicSprites.SPRITES_OBJECT objects). Type integer updateGraphicSpritesByZIndex() → {array} Updates (sorts again) the \"itemsByZIndex\" property (which is an array with the CB_GraphicSprites objects ordered by z-index, whose data comes from the array in the \"items\" property of the CB_GraphicSpritesScene#spritesGroups object) of the CB_GraphicSpritesScene#spritesGroups object. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 300 Returns: Returns the \"itemsByZIndex\" array of the CB_GraphicSpritesScene#spritesGroups object after updating it. Returns null if the property could not be obtained or updated. Type array updateItemsByZIndex() Alias for CB_GraphicSpritesScene#updateGraphicSpritesByZIndex. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 290 See: CB_GraphicSpritesScene#updateGraphicSpritesByZIndex Type Definitions insertSpritesGroup_OBJECT Object used as the returning value of the CB_GraphicSpritesScene#insertSpritesGroup method. Type: Object Properties: Name Type Description spritesGroup CB_GraphicSprites.SPRITES_OBJECT The CB_GraphicSpritesScene.SPRITES_GROUPS_OBJECT which has been inserted (it could have been modified/sanitized from the given one and some missing properties or those which were wrong could have been inherited) and was used to create the internal CB_GraphicSprites object when calling its constructor. item CB_GraphicSprites The CB_GraphicSprites object created and inserted from the CB_GraphicSprites.SPRITES_OBJECT. Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 389 SPRITES_GROUPS_OBJECT An object with the information that belongs to a group of graphic sprites. Type: Object Properties: Name Type Argument Default Description id string | * &lt;optional&gt; 'CB_GraphicSpritesScene_' + CB_GraphicSpritesScene._idUnique++ Identifier of the sprites groups object and also for the graphic sprites scene (also used as the CB_GraphicSprites.id property for the CB_GraphicSpritesScene object). It should be unique. Recommended. It must be a value which evaluates to true. By default, it is generated automatically (with an internal counter). src * &lt;optional&gt; \"\" The value for the \"src\" property which will be used as default if not provided (or the provided one was wrong) in the given CB_GraphicSprites.SPRITES_OBJECT objects (in the \"spritesGroups\" property), when creating the internal CB_GraphicSprites objects. srcType string &lt;optional&gt; CB_GraphicSprites.SRC_TYPES_DEFAULT The value for the \"srcType\" property which will be used as default if not provided (or the provided one was wrong) in the given CB_GraphicSprites.SPRITES_OBJECT objects (in the \"spritesGroups\" property), when creating the internal CB_GraphicSprites objects. It should point to a property of the CB_GraphicSprites.SRC_TYPES object. You can use other values of the CB_GraphicSprites.SRC_TYPES object or create new ones. srcLeft number &lt;optional&gt; CB_GraphicSprites.LEFT_SOURCE_DEFAULT The value for the \"srcLeft\" property which will be used as default if not provided (or the provided one was wrong) in the given CB_GraphicSprites.SPRITES_OBJECT objects (in the \"spritesGroups\" property), when creating the internal CB_GraphicSprites objects. srcTop number &lt;optional&gt; CB_GraphicSprites.TOP_SOURCE_DEFAULT The value for the \"srcTop\" property which will be used as default if not provided (or the provided one was wrong) in the given CB_GraphicSprites.SPRITES_OBJECT objects (in the \"spritesGroups\" property), when creating the internal CB_GraphicSprites objects. srcWidth number &lt;optional&gt; CB_GraphicSprites.WIDTH_SOURCE_DEFAULT The value for the \"srcWidth\" property which will be used as default if not provided (or the provided one was wrong) in the given CB_GraphicSprites.SPRITES_OBJECT objects (in the \"spritesGroups\" property), when creating the internal CB_GraphicSprites objects. srcHeight number &lt;optional&gt; CB_GraphicSprites.HEIGHT_SOURCE_DEFAULT The value for the \"srcHeight\" property which will be used as default if not provided (or the provided one was wrong) in the given CB_GraphicSprites.SPRITES_OBJECT objects (in the \"spritesGroups\" property), when creating the internal CB_GraphicSprites objects. left number &lt;optional&gt; CB_GraphicSprites.LEFT_DEFAULT The value for the \"left\" property which will be used as default if not provided (or the provided one was wrong) in the given CB_GraphicSprites.SPRITES_OBJECT objects (in the \"spritesGroups\" property), when creating the internal CB_GraphicSprites objects. top number &lt;optional&gt; CB_GraphicSprites.TOP_DEFAULT The value for the \"top\" property which will be used as default if not provided (or the provided one was wrong) in the given CB_GraphicSprites.SPRITES_OBJECT objects (in the \"spritesGroups\" property), when creating the internal CB_GraphicSprites objects. width number &lt;optional&gt; CB_GraphicSprites.WIDTH_DEFAULT The value for the \"width\" property which will be used as default if not provided (or the provided one was wrong) in the given CB_GraphicSprites.SPRITES_OBJECT objects (in the \"spritesGroups\" property), when creating the internal CB_GraphicSprites objects. height number &lt;optional&gt; CB_GraphicSprites.HEIGHT_DEFAULT The value for the \"height\" property which will be used as default if not provided (or the provided one was wrong) in the given CB_GraphicSprites.SPRITES_OBJECT objects (in the \"spritesGroups\" property), when creating the internal CB_GraphicSprites objects. zIndex number &lt;optional&gt; CB_GraphicSprites.ZINDEX_DEFAULT The value for the \"zIndex\" property which will be used as default if not provided (or the provided one was wrong) in the given CB_GraphicSprites.SPRITES_OBJECT objects (in the \"spritesGroups\" property), when creating the internal CB_GraphicSprites objects. disabled boolean &lt;optional&gt; false The value for the \"disabled\" property which will be used as default if not provided (or the provided one was wrong) in the given CB_GraphicSprites.SPRITES_OBJECT objects (in the \"spritesGroups\" property), when creating the internal CB_GraphicSprites objects. data object &lt;optional&gt; { 'that' : CB_GraphicSprites.SPRITES_GROUPS_OBJECT, 'getThis' = function() { return this.that; } } Object with any additional data desired which can be any kind. It will always have a \"that\" property pointing to the CB_GraphicSprites.SPRITES_GROUPS_OBJECT object where it belongs to and a function in its \"getThis\" property returning the same value (added automatically). These properties (\"that\" and \"getThis\") cannot be overridden. The value given will also be used for the \"data\" property which will be used as default if not provided (or the provided one was wrong) in the given CB_GraphicSprites.SPRITES_OBJECT objects (in the \"spritesGroups\" property), when creating the internal CB_GraphicSprites objects. spritesGroups array &lt;optional&gt; [] Numeric array containing CB_GraphicSprites.SPRITES_OBJECT objects with all the sprites groups that are useful for creating the internal CB_GraphicSprites objects. Recommended at least to provide one CB_GraphicSprites.SPRITES_OBJECT object in the first index. parent * &lt;optional&gt; Property pointing to or containing its parent (also used as the CB_GraphicSpritesScene.parent property for the CB_GraphicSpritesScene object). items array Read-only numeric array containing CB_GraphicSprites objects created internally. Their \"parent\" property will be set to point the current CB_GraphicSpritesScene object which contains them. itemsByZIndex array Read-only property containing a numeric array of all the CB_GraphicSprites objects ordered by their z-index (\"zIndex\" property). It is updated automatically when the z-index of a sprite is set with its CB_GraphicSprites#setZIndex method or when inserting/removing CB_GraphicSprites objects through the CB_GraphicSpritesScene#insertSpritesGroups, CB_GraphicSpritesScene#insertSpritesGroup, CB_GraphicSpritesScene#removeSpritesGroup or CB_GraphicSpritesScene#removeSpritesGroupById methods. byReference_DEFAULT boolean &lt;optional&gt; false Default value to use as the \"byReference\" parameter for the constructor and for the CB_GraphicSpritesScene#insertSpritesGroups method. If a boolean value is not provided, it will be parsed to boolean (resulting undefined to be false). container CB_GraphicSpritesScene Read-only property pointing to the CB_GraphicSpritesScene object which contains it. isSpritesGroups boolean Read-only property which is always set to true to help identify this type of object. type 'spritesGroups' Read-only property indicating the type of object (always \"spritesGroups\"). Source: CrossBase/audiovisual/image/CB_GraphicSpritesScene.js, line 8 Example { //'my_sprites_scene_1': id: \"my_sprites_scene_1\", srcType: CB_GraphicSprites.SRC_TYPES.IMAGE, srcLeft: 10, srcTop: 20, srcWidth: 64, srcHeight: 32, left: 10, top: 20, width: 64, height: 32, data: { datum_1: \"value_1\", datum_2: 2, datum_3: [ \"a\", \"b\", \"c\" ] }, //Sprites groups: spritesGroups: [ //'my_sprites_1': { id: \"my_sprites_1\", src: \"path/to/image.gif\", sprites: [ //'my_sprite_1': { id: \"my_sprite_1\", subSprites: [ //'my_subsprite_1': { id: \"my_subsprite_1\", srcLeft: 10, srcTop: 20, zIndex: 1 }, //'my_subsprite_2': { id: \"my_subsprite_2\", srcLeft: 20, srcTop: 40, zIndex: 2 } ] }, //'my_sprite_2': { id: \"my_sprite_2\", subSprites: [ //'my_subsprite_3': { id: \"my_subsprite_3\", srcLeft: 30, srcTop: 60, zIndex: 1 }, //'my_subsprite_4': { id: \"my_subsprite_4\", srcLeft: 40, srcTop: 80, zIndex: 2 } ] } ] }, //'my_sprites_2': { id: \"my_sprites_2\", src: \"path/to/image2.gif\", sprites: [ //'my_sprite_3': { id: \"my_sprite_3\", subSprites: [ //'my_subsprite_1': { id: \"my_subsprite_5\", srcLeft: 10, srcTop: 20, zIndex: 1 }, //'my_subsprite_2': { id: \"my_subsprite_6\", srcLeft: 20, srcTop: 40, zIndex: 2 } ] }, //'my_sprite_4': { id: \"my_sprite_4\", subSprites: [ //'my_subsprite_3': { id: \"my_subsprite_7\", srcLeft: 30, srcTop: 60, zIndex: 1 }, //'my_subsprite_4': { id: \"my_subsprite_8\", srcLeft: 40, srcTop: 80, zIndex: 2 } ] } ] } ] } × Search results Close "},"CB_Keyboard.html":{"id":"CB_Keyboard.html","title":"Namespace: CB_Keyboard","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Keyboard CB_Keyboard Static class to manage the keyboard and other input devices that generate key codes. It will return itself if it is tried to be instantiated. Source: CrossBase/input/CB_Keyboard.js, line 11 Namespaces chars extended keys Members &lt;static, readonly&gt; keysDown :Object Object that will store the status for each key detected, using the key code as index and a boolean as their value (true when down or false when released). Type: Object Default Value: {} Source: CrossBase/input/CB_Keyboard.js, line 26 &lt;static, readonly&gt; keysPressed :array Array with the codes of the keys pressed recently (it will be cleared after the chosen milliseconds set with the CB_Keyboard.setKeysPressedExpiration function). Type: array Default Value: [] Source: CrossBase/input/CB_Keyboard.js, line 36 &lt;static, readonly&gt; typedString :string Stores the string typed recently (it will be cleared after the chosen milliseconds set with the CB_Keyboard.setTypedStringExpiration function). Type: string Source: CrossBase/input/CB_Keyboard.js, line 58 &lt;static, readonly&gt; typedStringCodes :array Array with the codes of the string typed recently (it will be cleared after the chosen milliseconds set with the CB_Keyboard.setTypedStringExpiration function). Type: array Default Value: [] Source: CrossBase/input/CB_Keyboard.js, line 48 Methods &lt;static&gt; clearKeysDown(keepPressed) Clears (empties totally or partially) the CB_Keyboard.keysDown object which contains the detected keys pressed or released. Parameters: Name Type Description keepPressed boolean If set to true, it will keep the pressed keys. Source: CrossBase/input/CB_Keyboard.js, line 3207 &lt;static&gt; clearKeysPressed(keepPressed) Clears (empties totally or partially) the CB_Keyboard.keysPressed array which contains the key codes pressed recently. Parameters: Name Type Description keepPressed boolean If set to true, it will keep the pressed keys (taken from the CB_Keyboard.keysDown object). Source: CrossBase/input/CB_Keyboard.js, line 3315 &lt;static&gt; clearTypedString(keepPressed) Clears (empties totally or partially) the CB_Keyboard.typedString string and the CB_Keyboard.typedStringCodes array. Parameters: Name Type Description keepPressed boolean If set to true, it will keep the values belonging to the currently-pressed keys (taken from the CB_Keyboard.keysDown object). Source: CrossBase/input/CB_Keyboard.js, line 3434 &lt;static&gt; getKeyCode(e [, avoidNormalize]) → {integer} Returns the key code that is contained in the given keyboard event. Parameters: Name Type Argument Default Description e Event Keyboard event object. avoidNormalize boolean &lt;optional&gt; false If it is not set to true, it will call the CB_Events.normalize function internally before. Source: CrossBase/input/CB_Keyboard.js, line 3159 To Do: Have in mind that keyCode is deprecated. Returns: Returns the key code. Type integer &lt;static&gt; getKeysDown() → {Object} Returns the CB_Keyboard.keysDown object which contains the detected keys pressed or released. Source: CrossBase/input/CB_Keyboard.js, line 3227 Returns: Returns the CB_Keyboard.keysDown object. Type Object &lt;static&gt; getKeysPressed() → {array} Returns the CB_Keyboard.keysPressed array which contains the key codes pressed recently (it will be cleared after the chosen milliseconds set with the CB_Keyboard.setKeysPressedExpiration function). Source: CrossBase/input/CB_Keyboard.js, line 3338 Returns: Returns the CB_Keyboard.keysPressed array. Type array &lt;static&gt; getKeysPressedExpiration() → {integer} Returns the milliseconds after which the CB_Keyboard.keysPressed array is always cleared (emptied). The time always starts counting from zero again when a key is pressed (onKeyDown event is fired). To define this amount of time, the CB_Keyboard.setKeysPressedExpiration method must be used. Source: CrossBase/input/CB_Keyboard.js, line 3368 Returns: Returns the milliseconds of expiration defined for the CB_Keyboard.keysPressed array. Type integer &lt;static&gt; getTypedString() → {string} Returns the CB_Keyboard.typedString string which contains the string typed recently (it will be cleared after the chosen milliseconds set with the CB_Keyboard.setTypedStringExpiration function). Source: CrossBase/input/CB_Keyboard.js, line 3485 Returns: Returns the CB_Keyboard.typedString string. Type string &lt;static&gt; getTypedStringCodes() → {array} Returns the CB_Keyboard.typedStringCodes array which contains the key codes pressed that belongs to the string typed recently (it will be cleared after the chosen milliseconds set with the CB_Keyboard.setTypedStringExpiration function). Source: CrossBase/input/CB_Keyboard.js, line 3496 Returns: Returns the CB_Keyboard.typedStringCodes array. Type array &lt;static&gt; getTypedStringExpiration() → {integer} Returns the milliseconds after which the CB_Keyboard.typedString string and the CB_Keyboard.typedStringCodes array are always cleared (emptied). The time always starts counting from zero again when a key is pressed (onKeyPress event is fired). To define this amount of time, the CB_Keyboard.setTypedStringExpiration method must be used. Source: CrossBase/input/CB_Keyboard.js, line 3526 Returns: Returns the milliseconds of expiration defined for the CB_Keyboard.typedString string and the CB_Keyboard.typedStringCodes array. Type integer &lt;static&gt; isKeyDown(keyCodes [, allPressed]) → {boolean} Returns whether the given key codes are being pressed (any of them or all at the same time, depending on the \"allPressed\" parameter). Parameters: Name Type Argument Default Description keyCodes integer | array | Object An integer with the key code or a numeric array with the key codes that we want to check. It can also be an array of arrays, being each element a numeric array with the key codes that we want to check. Although not recommended (for performance purposes), this parameter can also support an object whose indexes are the keycodes (it will be converted to a numeric array internally). allPressed boolean &lt;optional&gt; false If set true, the function will only return true in the case that all given key codes are currently being pressed. Otherwise, if set to false, the function will return true in the case that any of the given key codes is currently being pressed. When the \"keyCodes\" is an array of arrays with key codes, it will be considered that all keys are being pressed if each single array (all of them) has at least one of its key codes pressed. Source: CrossBase/input/CB_Keyboard.js, line 3240 Returns: If \"allPressed\" parameter is set to true, returns true in the case that all given key codes are currently being pressed. If \"allPressed\" parameter is set to false, returns true in the case that any of the given key codes is currently being pressed. In all other cases, it returns false. Type boolean &lt;static&gt; normalizeEvent(e) → {Event} Tries to return the given keyboard event with some properties normalized (since different clients can use different values) and perhaps some new properties added (in the case they were missing), when possible. The new attached methods and properties may include polyfills, etc. It also calls the CB_Events.normalize function internally. Some properties added or affected could be keyCode, location, ctrlKey, altKey, shiftKey, etc. Parameters: Name Type Description e Event Keyboard event object. If not provided, it will use the value of \"event\", \"window.event\", \"Event\" or an empty object (\"{}\"). Source: CrossBase/input/CB_Keyboard.js, line 3109 To Do: Calculate (if possible) the values for location, ctrlKey, altKey, etc. when added, to simulate the expected behaviour. Returns: Returns the keyboard event object normalized. Type Event &lt;static&gt; onKeyDown(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when a key is down (onKeyDown event) or removes it. Parameters: Name Type Argument Default Description callbackFunction CB_Keyboard.EVENT_CALLBACK | null The function (event listener) that we want to execute when the event is fired. The first parameter received for this function will be the event object (already normalized by the CB_Keyboard.normalizeEvent function) and the second one will be the key code associated. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Keyboard.js, line 3601 &lt;static&gt; onKeyPress(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when a key is pressed (onKeyPress event) or removes it. Parameters: Name Type Argument Default Description callbackFunction CB_Keyboard.EVENT_CALLBACK | null The function (event listener) that we want to execute when the event is fired. The first parameter received for this function will be the event object (already normalized by the CB_Keyboard.normalizeEvent function) and the second one will be the key code associated. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Keyboard.js, line 3587 &lt;static&gt; onKeyUp(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when a key is released (onKeyUp event) or removes it. Parameters: Name Type Argument Default Description callbackFunction CB_Keyboard.EVENT_CALLBACK | null The function (event listener) that we want to execute when the event is fired. The first parameter received for this function will be the event object (already normalized by the CB_Keyboard.normalizeEvent function) and the second one will be the key code associated. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Keyboard.js, line 3615 &lt;static&gt; preventF11Key(e) Tries to prevent the default behaviour that would produce the \"F11\" key of a given keyboard event when the client is compatible with the HTML5 Fullscreen API and uses it to toggle (enable or disable) the fullscreen mode. It calls the CB_Keyboard.normalizeEvent function internally. Parameters: Name Type Description e Event Keyboard event object. Source: CrossBase/input/CB_Keyboard.js, line 3537 &lt;static&gt; setKeysPressedExpiration(keysPressedExpiration) → {boolean} Sets the milliseconds after which the CB_Keyboard.keysPressed array is always cleared (emptied). The time always starts counting from zero when a key is pressed (onKeyDown event is fired). Parameters: Name Type Description keysPressedExpiration integer An integer greater than 0 (zero) representing the milliseconds after which we desire that the CB_Keyboard.keysPressed array is cleared (emptied), if no key is pressed during this time. Source: CrossBase/input/CB_Keyboard.js, line 3350 Returns: Returns true if the given time could be applied or false otherwise. Type boolean &lt;static&gt; setTypedStringExpiration(keysPressedExpiration) → {boolean} Sets the milliseconds after which the CB_Keyboard.typedString string and the CB_Keyboard.typedStringCodes array are always cleared (emptied). The time always starts counting from zero when a key is pressed (onKeyPress event is fired). Parameters: Name Type Description keysPressedExpiration integer An integer greater than 0 (zero) representing the milliseconds after which we desire that the CB_Keyboard.typedString string and the CB_Keyboard.typedStringCodes array are cleared (emptied), if no key is pressed during this time. Source: CrossBase/input/CB_Keyboard.js, line 3508 Returns: Returns true if the given time could be applied or false otherwise. Type boolean Type Definitions EVENT_CALLBACK(e, keyCode) Callback that is called before loading a file and should return true if we want to load the file or false otherwise. Parameters: Name Type Description e Event Keyboard event object. keyCode integer Key code which fired the event. Source: CrossBase/input/CB_Keyboard.js, line 3570 × Search results Close "},"CB_Keyboard.chars.html":{"id":"CB_Keyboard.chars.html","title":"Namespace: chars","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: chars CB_Keyboard. chars Object whose properties are aliases for char codes (each property can contain an array with one or more integers which belong to the char codes). Source: CrossBase/input/CB_Keyboard.js, line 2561 Members &lt;static&gt; 0 :array The \"0\" (zero) character. Type: array Default Value: [48] Source: CrossBase/input/CB_Keyboard.js, line 2568 &lt;static&gt; 1 :array The \"1\" character. Type: array Default Value: [49] Source: CrossBase/input/CB_Keyboard.js, line 2575 &lt;static&gt; 2 :array The \"2\" character. Type: array Default Value: [50] Source: CrossBase/input/CB_Keyboard.js, line 2582 &lt;static&gt; 3 :array The \"3\" character. Type: array Default Value: [51] Source: CrossBase/input/CB_Keyboard.js, line 2589 &lt;static&gt; 4 :array The \"4\" character. Type: array Default Value: [52] Source: CrossBase/input/CB_Keyboard.js, line 2596 &lt;static&gt; 5 :array The \"5\" character. Type: array Default Value: [53] Source: CrossBase/input/CB_Keyboard.js, line 2603 &lt;static&gt; 6 :array The \"6\" character. Type: array Default Value: [54] Source: CrossBase/input/CB_Keyboard.js, line 2610 &lt;static&gt; 7 :array The \"7\" character. Type: array Default Value: [55] Source: CrossBase/input/CB_Keyboard.js, line 2617 &lt;static&gt; 8 :array The \"8\" character. Type: array Default Value: [56] Source: CrossBase/input/CB_Keyboard.js, line 2624 &lt;static&gt; 9 :array The \"9\" character. Type: array Default Value: [57] Source: CrossBase/input/CB_Keyboard.js, line 2631 &lt;static&gt; a :array The \"a\" letter, lower case. Type: array Default Value: [97] Source: CrossBase/input/CB_Keyboard.js, line 2687 &lt;static&gt; A :array The \"A\" letter, upper case (capitalized). Type: array Default Value: [65] Source: CrossBase/input/CB_Keyboard.js, line 2680 &lt;static&gt; ASTERISK :array The \"*\" (asterisk) character. Type: array Default Value: [42] Source: CrossBase/input/CB_Keyboard.js, line 2652 &lt;static&gt; B :array The \"B\" letter, upper case (capitalized). Type: array Default Value: [66] Source: CrossBase/input/CB_Keyboard.js, line 2694 &lt;static&gt; b :array The \"b\" letter, lower case. Type: array Default Value: [98] Source: CrossBase/input/CB_Keyboard.js, line 2701 &lt;static&gt; c :array The \"c\" letter, lower case. Type: array Default Value: [99] Source: CrossBase/input/CB_Keyboard.js, line 2715 &lt;static&gt; C :array The \"C\" letter, upper case (capitalized). Type: array Default Value: [67] Source: CrossBase/input/CB_Keyboard.js, line 2708 &lt;static&gt; COMMA :array The \",\" (comma) character. Type: array Default Value: [44] Source: CrossBase/input/CB_Keyboard.js, line 2673 &lt;static&gt; D :array The \"D\" letter, upper case (capitalized). Type: array Default Value: [68] Source: CrossBase/input/CB_Keyboard.js, line 2722 &lt;static&gt; d :array The \"d\" letter, lower case. Type: array Default Value: [100] Source: CrossBase/input/CB_Keyboard.js, line 2729 &lt;static&gt; DOT :array The \".\" (dot) character. Type: array Default Value: [46] Source: CrossBase/input/CB_Keyboard.js, line 2666 &lt;static&gt; e :array The \"e\" letter, lower case. Type: array Default Value: [101] Source: CrossBase/input/CB_Keyboard.js, line 2743 &lt;static&gt; E :array The \"E\" letter, upper case (capitalized). Type: array Default Value: [69] Source: CrossBase/input/CB_Keyboard.js, line 2736 &lt;static&gt; f :array The \"f\" letter, lower case. Type: array Default Value: [102] Source: CrossBase/input/CB_Keyboard.js, line 2757 &lt;static&gt; F :array The \"F\" letter, upper case (capitalized). Type: array Default Value: [70] Source: CrossBase/input/CB_Keyboard.js, line 2750 &lt;static&gt; g :array The \"g\" letter, lower case. Type: array Default Value: [103] Source: CrossBase/input/CB_Keyboard.js, line 2771 &lt;static&gt; G :array The \"G\" letter, upper case (capitalized). Type: array Default Value: [71] Source: CrossBase/input/CB_Keyboard.js, line 2764 &lt;static&gt; h :array The \"h\" letter, lower case. Type: array Default Value: [104] Source: CrossBase/input/CB_Keyboard.js, line 2785 &lt;static&gt; H :array The \"H\" letter, upper case (capitalized). Type: array Default Value: [72] Source: CrossBase/input/CB_Keyboard.js, line 2778 &lt;static&gt; i :array The \"i\" letter, lower case. Type: array Default Value: [105] Source: CrossBase/input/CB_Keyboard.js, line 2799 &lt;static&gt; I :array The \"I\" letter, upper case (capitalized). Type: array Default Value: [73] Source: CrossBase/input/CB_Keyboard.js, line 2792 &lt;static&gt; J :array The \"J\" letter, upper case (capitalized). Type: array Default Value: [74] Source: CrossBase/input/CB_Keyboard.js, line 2806 &lt;static&gt; j :array The \"j\" letter, lower case. Type: array Default Value: [106] Source: CrossBase/input/CB_Keyboard.js, line 2813 &lt;static&gt; k :array The \"k\" letter, lower case. Type: array Default Value: [107] Source: CrossBase/input/CB_Keyboard.js, line 2827 &lt;static&gt; K :array The \"K\" letter, upper case (capitalized). Type: array Default Value: [75] Source: CrossBase/input/CB_Keyboard.js, line 2820 &lt;static&gt; l :array The \"l\" letter, lower case. Type: array Default Value: [108] Source: CrossBase/input/CB_Keyboard.js, line 2841 &lt;static&gt; L :array The \"L\" letter, upper case (capitalized). Type: array Default Value: [76] Source: CrossBase/input/CB_Keyboard.js, line 2834 &lt;static&gt; m :array The \"m\" letter, lower case. Type: array Default Value: [109] Source: CrossBase/input/CB_Keyboard.js, line 2855 &lt;static&gt; M :array The \"M\" letter, upper case (capitalized). Type: array Default Value: [77] Source: CrossBase/input/CB_Keyboard.js, line 2848 &lt;static&gt; MINUS :array The \"-\" (minus) character. Type: array Default Value: [45] Source: CrossBase/input/CB_Keyboard.js, line 2645 &lt;static&gt; N :array The \"N\" letter, upper case (capitalized). Type: array Default Value: [78] Source: CrossBase/input/CB_Keyboard.js, line 2862 &lt;static&gt; n :array The \"n\" letter, lower case. Type: array Default Value: [110] Source: CrossBase/input/CB_Keyboard.js, line 2869 &lt;static&gt; o :array The \"o\" letter, lower case. Type: array Default Value: [111] Source: CrossBase/input/CB_Keyboard.js, line 2883 &lt;static&gt; O :array The \"O\" letter, upper case (capitalized). Type: array Default Value: [79] Source: CrossBase/input/CB_Keyboard.js, line 2876 &lt;static&gt; P :array The \"P\" letter, upper case (capitalized). Type: array Default Value: [80] Source: CrossBase/input/CB_Keyboard.js, line 2890 &lt;static&gt; p :array The \"p\" letter, lower case. Type: array Default Value: [112] Source: CrossBase/input/CB_Keyboard.js, line 2897 &lt;static&gt; PLUS :array The \"+\" (plus) character. Type: array Default Value: [43] Source: CrossBase/input/CB_Keyboard.js, line 2638 &lt;static&gt; q :array The \"q\" letter, lower case. Type: array Default Value: [113] Source: CrossBase/input/CB_Keyboard.js, line 2911 &lt;static&gt; Q :array The \"Q\" letter, upper case (capitalized). Type: array Default Value: [81] Source: CrossBase/input/CB_Keyboard.js, line 2904 &lt;static&gt; R :array The \"R\" letter, upper case (capitalized). Type: array Default Value: [82] Source: CrossBase/input/CB_Keyboard.js, line 2918 &lt;static&gt; r :array The \"r\" letter, lower case. Type: array Default Value: [114] Source: CrossBase/input/CB_Keyboard.js, line 2925 &lt;static&gt; S :array The \"S\" letter, upper case (capitalized). Type: array Default Value: [83] Source: CrossBase/input/CB_Keyboard.js, line 2932 &lt;static&gt; s :array The \"s\" letter, lower case. Type: array Default Value: [115] Source: CrossBase/input/CB_Keyboard.js, line 2939 &lt;static&gt; SLASH :array The \"/\" (slash) character. Type: array Default Value: [47] Source: CrossBase/input/CB_Keyboard.js, line 2659 &lt;static&gt; T :array The \"T\" letter, upper case (capitalized). Type: array Default Value: [84] Source: CrossBase/input/CB_Keyboard.js, line 2946 &lt;static&gt; t :array The \"t\" letter, lower case. Type: array Default Value: [116] Source: CrossBase/input/CB_Keyboard.js, line 2953 &lt;static&gt; U :array The \"U\" letter, upper case (capitalized). Type: array Default Value: [85] Source: CrossBase/input/CB_Keyboard.js, line 2960 &lt;static&gt; u :array The \"u\" letter, lower case. Type: array Default Value: [117] Source: CrossBase/input/CB_Keyboard.js, line 2967 &lt;static&gt; V :array The \"V\" letter, upper case (capitalized). Type: array Default Value: [86] Source: CrossBase/input/CB_Keyboard.js, line 2974 &lt;static&gt; v :array The \"v\" letter, lower case. Type: array Default Value: [118] Source: CrossBase/input/CB_Keyboard.js, line 2981 &lt;static&gt; W :array The \"W\" letter, upper case (capitalized). Type: array Default Value: [87] Source: CrossBase/input/CB_Keyboard.js, line 2988 &lt;static&gt; w :array The \"w\" letter, lower case. Type: array Default Value: [119] Source: CrossBase/input/CB_Keyboard.js, line 2995 &lt;static&gt; X :array The \"X\" letter, upper case (capitalized). Type: array Default Value: [88] Source: CrossBase/input/CB_Keyboard.js, line 3002 &lt;static&gt; x :array The \"x\" letter, lower case. Type: array Default Value: [120] Source: CrossBase/input/CB_Keyboard.js, line 3009 &lt;static&gt; Y :array The \"Y\" letter, upper case (capitalized). Type: array Default Value: [89] Source: CrossBase/input/CB_Keyboard.js, line 3016 &lt;static&gt; y :array The \"y\" letter, lower case. Type: array Default Value: [121] Source: CrossBase/input/CB_Keyboard.js, line 3023 &lt;static&gt; z :array The \"z\" letter, lower case. Type: array Default Value: [122] Source: CrossBase/input/CB_Keyboard.js, line 3037 &lt;static&gt; Z :array The \"Z\" letter, upper case (capitalized). Type: array Default Value: [90] Source: CrossBase/input/CB_Keyboard.js, line 3030 × Search results Close "},"CB_Keyboard.extended.html":{"id":"CB_Keyboard.extended.html","title":"Namespace: extended","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: extended CB_Keyboard. extended Property that keeps extended key codes for different systems and platforms. Source: CrossBase/input/CB_Keyboard.js, line 66 Members &lt;static, constant&gt; AMAZON_FIRE_TV_GAME_CONTROLLER :Object Amazon Fire TV game controller key codes. Type: Object Properties: Name Type Description UP number UP button. DOWN number DOWN button. LEFT number LEFT button. RIGHT number RIGHT button. A number \"A\" button. B number \"B\" button. X number \"X\" button. Y number \"Y\" button. Source: CrossBase/input/CB_Keyboard.js, line 1023 &lt;static, constant&gt; AMAZON_FIRE_TV_REMOTE :Object Amazon Fire TV remote control key codes. Type: Object Properties: Name Type Description UP number UP button. DOWN number DOWN button. LEFT number LEFT button. RIGHT number RIGHT button. SELECT number SELECT button. PLAY_PAUSE number PLAY/PAUSE button. RW number RW (REWIND) button. FF number FF (FAST FORWARD) button. Source: CrossBase/input/CB_Keyboard.js, line 994 &lt;static, constant&gt; LG_SMART_TV_LINUX_35230 :Object LG Smart TV (Linux 35230) key codes. Type: Object Properties: Name Type Description _0 number 0 (zero) button. _1 number 1 button. _2 number 2 button. _3 number 3 button. _4 number 4 button. _5 number 5 button. _6 number 6 button. _7 number 7 button. _8 number 8 button. _9 number 9 button. 0 number Alias for CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._0. 1 number Alias for CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._1. 2 number Alias for CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._2. 3 number Alias for CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._3. 4 number Alias for CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._4. 5 number Alias for CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._5. 6 number Alias for CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._6. 7 number Alias for CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._7. 8 number Alias for CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._8. 9 number Alias for CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._9. FORWARD number FORWARD button. REWIND number REWIND button. PLAY number PLAY button. PAUSE number PAUSE button. Source: CrossBase/input/CB_Keyboard.js, line 1187 &lt;static, constant&gt; PS3 :Object Sony PlayStation 3 key codes. Type: Object Properties: Name Type Description UP number UP button. DOWN number DOWN button. LEFT number LEFT button. RIGHT number RIGHT button. CROSS number CROSS button. Source: CrossBase/input/CB_Keyboard.js, line 1095 &lt;static, constant&gt; PS4 :Object Sony PlayStation 4 key codes. Type: Object Properties: Name Type Description UP number D-PAD UP button. DOWN number D-PAD DOWN button. LEFT number D-PAD LEFT button. RIGHT number D-PAD RIGHT button. TRIANGLE number TRIANGLE button. SQUARE number SQUARE button. CIRCLE number CIRCLE button. L1 number L1 button. L2 number L2 button. R1 number R1 button. R2 number R2 button. LEFT_STICK_CLICK number LEFT STICK CLICK button. RIGHT_STICK_CLICK number RIGHT STICK CLICK button. OPTIONS number OPTIONS button. Source: CrossBase/input/CB_Keyboard.js, line 1120 &lt;static, constant&gt; PSVITA :Object Sony PlayStation Vita key codes. Type: Object Properties: Name Type Description UP number UP button. DOWN number DOWN button. LEFT number LEFT button. RIGHT number RIGHT button. Source: CrossBase/input/CB_Keyboard.js, line 1165 &lt;static, constant&gt; SAMSUNG_TIZEN_TV :Object Samsung Tizen TV key codes. Type: Object Properties: Name Type Description UP number UP button. DOWN number DOWN button. LEFT number LEFT button. RIGHT number RIGHT button. ENTER number ENTER button. MEDIA_PLAY_PAUSE number PLAY/PAUSE MEDIA button. MEDIA_REWIND number RW (REWIND) MEDIA button. MEDIA_FORWARD number FW (FORWARD) MEDIA button. MEDIA_PLAY number PLAY MEDIA button. MEDIA_PAUSE number PAUSE MEDIA button. MEDIA_STOP number STOP MEDIA button. RETURN number RETURN button. MEDIA_RECORD number RECORD MEDIA button. MEDIA_TRACK_PREVIOUS number PREVIOUS TRACK MEDIA button. MEDIA_TRACK_NEXT number NEXT TRACK MEDIA button. VOLUME_UP number VOLUME UP button. VOLUME_DOWN number VOLUME DOWN button. MUTE number MUTE button. _0 number 0 (zero) button. _1 number 1 button. _2 number 2 button. _3 number 3 button. _4 number 4 button. _5 number 5 button. _6 number 6 button. _7 number 7 button. _8 number 8 button. _9 number 9 button. 0 number Alias for CB_Keyboard.extended.SAMSUNG_TIZEN_TV._0. 1 number Alias for CB_Keyboard.extended.SAMSUNG_TIZEN_TV._1. 2 number Alias for CB_Keyboard.extended.SAMSUNG_TIZEN_TV._2. 3 number Alias for CB_Keyboard.extended.SAMSUNG_TIZEN_TV._3. 4 number Alias for CB_Keyboard.extended.SAMSUNG_TIZEN_TV._4. 5 number Alias for CB_Keyboard.extended.SAMSUNG_TIZEN_TV._5. 6 number Alias for CB_Keyboard.extended.SAMSUNG_TIZEN_TV._6. 7 number Alias for CB_Keyboard.extended.SAMSUNG_TIZEN_TV._7. 8 number Alias for CB_Keyboard.extended.SAMSUNG_TIZEN_TV._8. 9 number Alias for CB_Keyboard.extended.SAMSUNG_TIZEN_TV._9. RED number RED button. GREEN number GREEN button. YELLOW number YELLOW button. BLUE number BLUE button. INFO number INFORMATION button. EXIT number EXIT button. MINUS number MINUS button. CAPTION number CAPTION button. CH_UP number CHANNEL UP button. CH_DOWN number CHANNEL DOWN button. CH_PREVIOUS number PREVIOUS CHANNEL button. CH_LIST number CHANNEL LIST button. E_MANUAL number E-MANUAL button. SEARCH number SEARCH button. _3D number 3D button. 3D number Alias for CB_Keyboard.extended.SAMSUNG_TIZEN_TV._3D. GUIDE number GUIDE button. SOURCE number SOURCE button. PICTURE_SIZE number PICTURE SIZE button. EXTRA number EXTRA button. SOCCER number SOCCER button. MTS number MTS (Multichannel Television Sound) button. TELETEXT number TELETEXT button. MENU number MENU button. TOOLS number TOOLS button. Source: CrossBase/input/CB_Keyboard.js, line 245 &lt;static, constant&gt; SAMSUNG_TV :Object Samsung TV key codes. Type: Object Properties: Name Type Description TOOLS number TOOLS button. EMODE number EMODE button. DMA number DMA (Digital Media Adapter) button. SOURCE number SOURCE button. CHDOWN number CHANNEL DOWN button. CHUP number CHANNEL UP button. PANEL_CH_UP number CHANNEL UP PANEL button #1. PANEL_CH_DOWN number CHANNEL DOWN PANEL button #1. PANEL_CHUP number CHANNEL UP PANEL button #2. PANEL_CHDOWN number CHANNEL DOWN PANEL button #2. PIP_CHUP number CHANNEL UP PIP (Picture In Picture) button. PIP_CHDOWN number CHANNEL DOWN PIP (Picture In Picture) button. PRECH number PRE-CHANNEL (PREVIOUS CHANNEL) button. FAVCH number FAVOURITE CHANNEL button. CHLIST number CHANNEL LIST button. TTX_MIX number TELETEXT button. GUIDE number GUIDE button. ASPECT number ASPECT button. DOLBY_SRR number DOLBY SRR (SuRroundRight) button. MTS number MTS (Multichannel Television Sound) button. WHEELDOWN number WHEEL DOWN #1. WHEEL_DOWN number WHEEL DOWN #2. WHEELUP number WHEEL UP #1. WHEEL_UP number WHEEL UP #2. WHEELLEFT number WHEEL LEFT #1. WHEEL_LEFT number WHEEL LEFT #2. WHEELRIGHT number WHEEL RIGHT #1. WHEEL_RIGHT number WHEEL RIGHT #2. SMART number SMART TV button. EXIT number EXIT button. POWER number POWER button. PANEL_POWER number POWER PANEL button. POWEROFF number POWER OFF button. POWERON number POWER ON button. CONTENT number CONTENT button. WLINK number WLINK (Wiselink) button #1. W_LINK number WLINK (Wiselink) button #2. EMPTY number EMPTY button. CC number CC (Closed Captioning) button. REC number REC button. VOLUP number VOLUME UP button #1. VOL_UP number VOLUME UP button #2. VOLDOWN number VOLUME DOWN button #1. VOL_DOWN number VOLUME DOWN button #2. PANEL_VOLUP number PANEL VOLUME UP button #1. PANEL_VOL_UP number PANEL VOLUME UP button #2. PANEL_VOLDOW number PANEL VOLUME DOWN button #1. PANEL_VOLDOWN number PANEL VOLUME DOWN button #2. PANEL_VOL_DOWN number PANEL VOLUME DOWN button #3. MUTE number MUTE button. INFO number INFORMATION button. INFOLINK number INFOLINK button. MENU number MENU button. SUBTITLE number SUBTITLE button #1. SUB_TITLE number SUBTITLE button #2. PANEL_SOURCE number SOURCE PANEL button. _0 number 0 (zero) button. _1 number 1 button. _2 number 2 button. _3 number 3 button. _4 number 4 button. _5 number 5 button. _6 number 6 button. _7 number 7 button. _8 number 8 button. _9 number 9 button. _10 number 10 button. _11 number 11 button. _12 number 12 button. 0 number Alias for CB_Keyboard.extended.SAMSUNG_TV._0. 1 number Alias for CB_Keyboard.extended.SAMSUNG_TV._1. 2 number Alias for CB_Keyboard.extended.SAMSUNG_TV._2. 3 number Alias for CB_Keyboard.extended.SAMSUNG_TV._3. 4 number Alias for CB_Keyboard.extended.SAMSUNG_TV._4. 5 number Alias for CB_Keyboard.extended.SAMSUNG_TV._5. 6 number Alias for CB_Keyboard.extended.SAMSUNG_TV._6. 7 number Alias for CB_Keyboard.extended.SAMSUNG_TV._7. 8 number Alias for CB_Keyboard.extended.SAMSUNG_TV._8. 9 number Alias for CB_Keyboard.extended.SAMSUNG_TV._9. 10 number Alias for CB_Keyboard.extended.SAMSUNG_TV._10. 11 number Alias for CB_Keyboard.extended.SAMSUNG_TV._11. 12 number Alias for CB_Keyboard.extended.SAMSUNG_TV._12. RED number RED button. GREEN number GREEN button. YELLOW number YELLOW button. BLUE number BLUE button. CYAN number CYAN button. RW number RW (REWIND) button #1. REWIND number RW (REWIND) button #2. REWIND_ number RW (REWIND) button #3. FF number FF (FAST FORWARD) button #1. FF_ number FF (FAST FORWARD) button #2. PAUSE number PAUSE button. PLAY number PLAY button. STOP number STOP button. SEARCH number SEARCH button. UP number UP button. DOWN number DOWN button. LEFT number LEFT button. RIGHT number RIGHT button. CH_UP number CHANNEL UP button. CH_DOWN number CHANNEL DOWN button. DISC_MENU number DISC MENU button. _3D number 3D button. 3D number Alias for CB_Keyboard.extended.SAMSUNG_TV._3D. PIP_ONOFF number PIP (Picture In Picture) ON/OFF button. AD number AD (Audio Description) button. PMODE number PICTURE MODE button. SMODE number SOUND MODE button. SLEEP number SLEEP button. D_AUDIO number DIGITAL AUDIO button. D_FRONT_PLAY number DIGITAL FRONT PLAY button. D_VIEW_MODE number DIGITAL VIEW MODE button. STEP number STEP button. CALLER_ID number CALLED ID button. ANTENNA number ANTENNA button. ZOOM_MOVE number MOVE ZOOM button. ZOOM1 number ZOOM 1 button. ZOOM2 number ZOOM 2 button. ZOOM_IN number ZOOM IN button. ZOOM_OUT number ZOOM OUT button. RETURN number RETURN button. PANEL_RETURN number RETURN PANEL button. ENTER number ENTER button. PANEL_ENTER number ENTER PANEL button. PANEL_MENU number MENU PANEL button. ADDDEL number ADD/DEL button. PIP_SWAP number PIP (Picture In Picture) SWAP button. PLUS100 number SAMSUNG AUTO MOTION PLUS 100 HZ button. CAPTION number CAPTION button. PICTURE_SIZE number PICTURE SIZE button. PIP_SIZE number PIP (Picture In Picture) SIZE button. MAGIC_CHANNEL number MAGIC CHANNEL button. PIP_SCAN number PIP (Picture In Picture) SCAN button. DEVICE_CONNECT number DEVICE CONNECT button. HELP number HELP button. CONVERGENCE number CONVERGENCE button. AUTO_PROGRAM number AUTO PROGRAM button. FACTORY number FACTORY button. _3SPEED number 3SPEED button. 3SPEED number Alias for CB_Keyboard.extended.SAMSUNG_TV._3SPEED. RSURF number R.SURF button. TOPMENU number TOP MENU button. GAME number GAME button. QUICK_REPLAY number QUICK REPLAY button. STILL_PICTURE number STILL PICTURE button. DTV number DTV (Digital Television) button. INSTANT_REPLAY number INSTANT REPLAY button. LINK number LINK button. ANGLE number ANGLE button. RESERVED1 number RESERVED1 button. RESERVED5 number RESERVED5 button. PROGRAM number PROGRAM button. BOOKMARK number BOOKMARK button. PRINT number PRINT button. CLEAR number CLEAR button. VCHIP number V-CHIP button. REPEAT number REPEAT button. DOOR number DOOR button. OPEN number OPEN button. TURBO number TURBO button. DVR_MENU number DVR (Digital Video Recorder) MENU button. TTX_SUBFACE number Teletext Subface button. CH_LIST number CHANNEL LIST button. DNIe number DNIe (Digital Natural Image Engine) button. DNSe number DNSe (Digital Natural Sound Engine) button. SRS number SRS (Sound Retrieval System) button. CONVERT_AUDIO_MAINSUB number CONVERT AUDIO MAIN/SUB button. MDC number MDC button. SEFFECT number SOUND EFFECT button. DVR number DVR (Digital Video Recorder) button. DTV_SIGNAL number DTV (Digital Television) SIGNAL button. LIVE number LIVE button. PERPECT_FOCUS number PERPECT FOCUS button. HOME number HOME button. ESAVING number ENERGY SAVING button. CONTENTS number CONTENTS button. SCALE number SCALE button. CLOCK_DISPLAY number CLOCK DISPLAY button. SETUP_CLOCK_TIMER number SETUP CLOCK TIMER button. MAGIC_BRIGHT number MAGIC BRIGHT button. FM_RADIO number FM RADIO button. VCR_MODE number VCR MODE button. CATV_MODE number CATV (Community Antenna Television) MODE button. DSS_MODE number DSS MODE button. DVD_MODE number DVD MODE button. STB_MODE number STB (Set-Top Box) MODE button. PCMODE number PC MODE button. TV_MODE number TV MODE button. TV number TV button. AV1 number AV #1 button. AV2 number AV #2 button. AV3 number AV #3 button. SVIDEO1 number S-VIDEO (Separated-Video) #1 button. SVIDEO2 number S-VIDEO (Separated-Video) #2 button. SVIDEO3 number S-VIDEO (Separated-Video) #3 button. COMPONENT1 number COMPONENT #1 button. COMPONENT2 number COMPONENT #2 button. DVI number DVI (Digital Visual Interface) button. HDMI number HDMI button. HDMI1 number HDMI #1 button. HDMI2 number HDMI #2 button. HDMI3 number HDMI #3 button. HDMI4 number HDMI #4 button. DTV_LINK number DTVLINK (DIGITAL TELEVISION LINK) button. APP_LIST number APP LIST button. BACK_MHP number BACK MHP (Multimedia Home Platform) button. ALT_MHP number ALTERNATE MHP (Multimedia Home Platform) button. RSS number RSS button. ENTERTAINMENT number ENTERTAINMENT button. ID_INPUT number ID INPUT button. ID_SETUP number ID SETUP button. ANYNET number ANYNET button. ANYVIEW number ANYVIEW button. MS number MS button. MORE number MORE button. _4_3 number 4:3 button. 4_3 number Alias for CB_Keyboard.extended.SAMSUNG_TV._4_3. _16_9 number 16:9 button. 16_9 number Alias for CB_Keyboard.extended.SAMSUNG_TV._16_9. PANORAMA number PICTURE MODE PANORAMA button. DYNAMIC number PICTURE MODE DYNAMIC button. STANDARD number PICTURE MODE STANDARD button. MOVIE1 number PICTURE MODE MOVIE1 button. CUSTOM number PICTURE MODE CUSTOM button. AUTO_ARC_RESET number AUTO ARC (Audio Return Channel) RESET button. AUTO_ARC_LNA_ON number AUTO ARC (Audio Return Channel) LNA (Low Noise Amplifier) ON button. AUTO_ARC_LNA_OFF number AUTO ARC (Audio Return Channel) LNA (Low Noise Amplifier) OFF button. AUTO_ARC_ANYNET_MODE_OK number AUTO ARC (Audio Return Channel) ANYNET MODE OK button. AUTO_ARC_ANYNET_AUTO_START number AUTO ARC (Audio Return Channel) ANYNET AUTO START button. AUTO_ARC_CAPTION_ON number AUTO ARC (Audio Return Channel) CAPTION ON button. AUTO_ARC_CAPTION_OFF number AUTO ARC (Audio Return Channel) CAPTION OFF button. AUTO_ARC_PIP_DOUBLE number AUTO ARC (Audio Return Channel) PIP (Picture In Picture) DOUBLE button. AUTO_ARC_PIP_LARGE number AUTO ARC (Audio Return Channel) PIP (Picture In Picture) LARGE button. AUTO_ARC_PIP_SMALL number AUTO ARC (Audio Return Channel) PIP (Picture In Picture) SMALL button. AUTO_ARC_PIP_WIDE number AUTO ARC (Audio Return Channel) PIP (Picture In Picture) WIDE button. AUTO_ARC_PIP_LEFT_TOP number AUTO ARC (Audio Return Channel) PIP (Picture In Picture) LEFT TOP button. AUTO_ARC_PIP_RIGHT_TOP number AUTO ARC (Audio Return Channel) PIP (Picture In Picture) RIGHT TOP button. AUTO_ARC_PIP_LEFT_BOTTOM number AUTO ARC (Audio Return Channel) PIP (Picture In Picture) LEFT BOTTOM button. AUTO_ARC_PIP_RIGHT_BOTTOM number AUTO ARC (Audio Return Channel) PIP (Picture In Picture) RIGHT BOTTOM button. AUTO_ARC_PIP_CH_CHANGE number AUTO ARC (Audio Return Channel) PIP (Picture In Picture) CHANNEL CHANGE button. AUTO_ARC_PIP_SOURCE_CHANGE number AUTO ARC (Audio Return Channel) PIP (Picture In Picture) SOURCE CHANGE button. AUTO_ARC_AUTOCOLOR_SUCCESS number AUTO ARC (Audio Return Channel) AUTOCOLOR SUCCESS button. AUTO_ARC_AUTOCOLOR_FAIL number AUTO ARC (Audio Return Channel) AUTOCOLOR FAIL button. AUTO_ARC_C_FORCE_AGING number AUTO ARC (Audio Return Channel) C-FORCE AGING button. AUTO_ARC_USBJACK_INSPECT number AUTO ARC (Audio Return Channel) USB JACK INSPECT button. AUTO_ARC_JACK_IDENT number AUTO ARC (Audio Return Channel) JACK IDENT button. AUTO_ARC_CAPTION_KOR number AUTO ARC (Audio Return Channel) CAPTION KOREAN button. AUTO_ARC_CAPTION_ENG number AUTO ARC (Audio Return Channel) CAPTION ENGLISH button. AUTO_ARC_ANTENNA_AIR number AUTO ARC (Audio Return Channel) ANTENNA AIR button. AUTO_ARC_ANTENNA_CABLE number AUTO ARC (Audio Return Channel) ANTENNA CABLE button. AUTO_ARC_ANTENNA_SATELLITE number AUTO ARC (Audio Return Channel) ANTENNA SATELLITE button. AUTO_FORMAT number AUTO FORMAT button. DNET number D-NET button. NINE_SEPARATE number NINE SEPARATE button. MIC number MIC (MICROPHONE) button. EXT1 number EXT1 button. EXT2 number EXT2 button. EXT3 number EXT3 button. EXT4 number EXT4 button. EXT5 number EXT5 button. EXT6 number EXT6 button. EXT7 number EXT7 button. EXT8 number EXT8 button. EXT9 number EXT9 button. EXT10 number EXT10 button. EXT11 number EXT11 button. EXT12 number EXT12 button. EXT13 number EXT13 button. EXT14 number EXT14 button. EXT15 number EXT15 button. EXT16 number EXT16 button. EXT17 number EXT17 button. EXT18 number EXT18 button. EXT19 number EXT19 button. EXT20 number EXT20 button. EXT21 number EXT21 button. EXT22 number EXT22 button. EXT23 number EXT23 button. EXT24 number EXT24 button. EXT25 number EXT25 button. EXT26 number EXT26 button. EXT27 number EXT27 button. EXT28 number EXT28 button. EXT29 number EXT29 button. EXT30 number EXT30 button. EXT31 number EXT31 button. EXT32 number EXT32 button. EXT33 number EXT33 button. EXT34 number EXT34 button. EXT35 number EXT35 button. EXT36 number EXT36 button. EXT37 number EXT37 button. EXT38 number EXT38 button. EXT39 number EXT39 button. EXT40 number EXT40 button. EXT41 number EXT41 button. Source: CrossBase/input/CB_Keyboard.js, line 385 &lt;static, constant&gt; VK :Object Smart TV Alliance and virtual keyboard key codes. Type: Object Properties: Name Type Description ENTER number ENTER key. PAUSE number PAUSE key. PAGE_UP number PAGE UP key. PAGE_DOWN number PAGE DOWN key. LEFT number LEFT key. UP number UP key. RIGHT number RIGHT key. DOWN number DOWN key. _0 number 0 (zero) key. _1 number 1 key. _2 number 2 key. _3 number 3 key. _4 number 4 key. _5 number 5 key. _6 number 6 key. _7 number 7 key. _8 number 8 key. _9 number 9 key. 0 number Alias for CB_Keyboard.extended.VK._0. 1 number Alias for CB_Keyboard.extended.VK._1. 2 number Alias for CB_Keyboard.extended.VK._2. 3 number Alias for CB_Keyboard.extended.VK._3. 4 number Alias for CB_Keyboard.extended.VK._4. 5 number Alias for CB_Keyboard.extended.VK._5. 6 number Alias for CB_Keyboard.extended.VK._6. 7 number Alias for CB_Keyboard.extended.VK._7. 8 number Alias for CB_Keyboard.extended.VK._8. 9 number Alias for CB_Keyboard.extended.VK._9. REWIND number RW (REWIND) key. STOP number STOP key. PLAY number PLAY key. FAST_FWD number FF (FAST FORWARD) key. BACK number BACK key. PREV number PREVIOUS key. NEXT number NEXT key. INFO number INFORMATION key. RED number RED key. GREEN number GREEN key. YELLOW number YELLOW key. BLUE number BLUE key. SPACE number SPACE key. BACK_SPACE number BACK SPACE key. A number A key. B number B key. C number C key. D number D key. E number E key. F number F key. G number G key. H number H key. I number I key. J number J key. K number K key. L number L key. M number M key. N number N key. O number O key. P number P key. Q number Q key. R number R key. S number S key. T number T key. U number U key. V number V key. W number W key. X number X key. Y number Y key. Z number Z key. VOLUME_UP number VOLUME UP key. VOLUME_DOWN number VOLUME DOWN key. MUTE number MUTE key. PLAY_PAUSE number PLAY/PAUSE key. HELP number HELP key. SUBTITLE number SUBTITLE key. SEARCH number SEARCH key. AUDIODESCRIPTION number AUDIODESCRIPTION key. HD number HD (High Definition) key. Source: CrossBase/input/CB_Keyboard.js, line 72 To Do: Consider adding more (found in https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx and http://nehe.gamedev.net/article/msdn_virtualkey_codes/15009/) &lt;static, constant&gt; WII :Object Nintendo Wii (Wiimote) key codes. Type: Object Properties: Name Type Description UP number D-PAD UP button. DOWN number D-PAD DOWN button. LEFT number D-PAD LEFT button. RIGHT number D-PAD RIGHT button. A number \"A\" button. B number \"B\" button. MINUS number MINUS (\"-\") button. PLUS number PLUS (\"+\") button. ONE number \"1\" button. _1 number Alias for CB_Keyboard.extended.WII.ONE. 1 number Alias for CB_Keyboard.extended.WII.ONE. TWO number \"2\" button. _2 number Alias for CB_Keyboard.extended.WII.TWO. 2 number Alias for CB_Keyboard.extended.WII.TWO. HOME number HOME button. Source: CrossBase/input/CB_Keyboard.js, line 1052 × Search results Close "},"CB_Keyboard.keys.html":{"id":"CB_Keyboard.keys.html","title":"Namespace: keys","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: keys CB_Keyboard. keys Object whose properties are aliases for key codes (each property can contain an array with one or more integers which belong to the key codes). Source: CrossBase/input/CB_Keyboard.js, line 1255 Members &lt;static&gt; 0 :array The 0 (zero) key. Type: array Default Value: [48,96,\"CB_Keyboard.extended.VK._0\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV._0\",\"CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._0\"] Source: CrossBase/input/CB_Keyboard.js, line 1532 &lt;static&gt; 1 :array The 1 key. Type: array Default Value: [49,97,\"CB_Keyboard.extended.VK._1\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV._1\",\"CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._1\"] Source: CrossBase/input/CB_Keyboard.js, line 1552 &lt;static&gt; 2 :array The 2 key. Type: array Default Value: [50,98,\"CB_Keyboard.extended.VK._2\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV._2\",\"CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._2\"] Source: CrossBase/input/CB_Keyboard.js, line 1572 &lt;static&gt; 3 :array The 3 key. Type: array Default Value: [51,99,\"CB_Keyboard.extended.VK._3\",\"CB_Keyboard.extended.SAMSUNG_TV._3\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV._3\",\"CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._3\"] Source: CrossBase/input/CB_Keyboard.js, line 1592 &lt;static&gt; 4 :array The 4 key. Type: array Default Value: [52,100,\"CB_Keyboard.extended.VK._4\",\"CB_Keyboard.extended.SAMSUNG_TV._4\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV._4\",\"CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._4\"] Source: CrossBase/input/CB_Keyboard.js, line 1612 &lt;static&gt; 5 :array The 5 key. Type: array Default Value: [53,101,\"CB_Keyboard.extended.VK._5\",\"CB_Keyboard.extended.SAMSUNG_TV._5\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV._5\",\"CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._5\"] Source: CrossBase/input/CB_Keyboard.js, line 1632 &lt;static&gt; 6 :array The 6 key. Type: array Default Value: [54,102,\"CB_Keyboard.extended.VK._6\",\"CB_Keyboard.extended.SAMSUNG_TV._6\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV._6\",\"CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._6\"] Source: CrossBase/input/CB_Keyboard.js, line 1652 &lt;static&gt; 7 :array The 7 key. Type: array Default Value: [55,103,\"CB_Keyboard.extended.VK._7\",\"CB_Keyboard.extended.SAMSUNG_TV._7\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV._7\",\"CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._7\"] Source: CrossBase/input/CB_Keyboard.js, line 1672 &lt;static&gt; 8 :array The 8 key. Type: array Default Value: [56,104,\"CB_Keyboard.extended.VK._8\",\"CB_Keyboard.extended.SAMSUNG_TV._8\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV._8\",\"CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._8\"] Source: CrossBase/input/CB_Keyboard.js, line 1692 &lt;static&gt; 9 :array The 9 key. Type: array Default Value: [57,105,\"CB_Keyboard.extended.VK._9\",\"CB_Keyboard.extended.SAMSUNG_TV._9\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV._9\",\"CB_Keyboard.extended.LG_SMART_TV_LINUX_35230._9\"] Source: CrossBase/input/CB_Keyboard.js, line 1712 &lt;static&gt; _0 Alias for CB_Keyboard.keys.0. Source: CrossBase/input/CB_Keyboard.js, line 1522 See: CB_Keyboard.keys.0 &lt;static&gt; _1 Alias for CB_Keyboard.keys.1. Source: CrossBase/input/CB_Keyboard.js, line 1542 See: CB_Keyboard.keys.1 &lt;static&gt; _2 Alias for CB_Keyboard.keys.2. Source: CrossBase/input/CB_Keyboard.js, line 1562 See: CB_Keyboard.keys.2 &lt;static&gt; _3 Alias for CB_Keyboard.keys.3. Source: CrossBase/input/CB_Keyboard.js, line 1582 See: CB_Keyboard.keys.3 &lt;static&gt; _4 Alias for CB_Keyboard.keys.4. Source: CrossBase/input/CB_Keyboard.js, line 1602 See: CB_Keyboard.keys.4 &lt;static&gt; _5 Alias for CB_Keyboard.keys.5. Source: CrossBase/input/CB_Keyboard.js, line 1622 See: CB_Keyboard.keys.5 &lt;static&gt; _6 Alias for CB_Keyboard.keys.6. Source: CrossBase/input/CB_Keyboard.js, line 1642 See: CB_Keyboard.keys.6 &lt;static&gt; _7 Alias for CB_Keyboard.keys.7. Source: CrossBase/input/CB_Keyboard.js, line 1662 See: CB_Keyboard.keys.7 &lt;static&gt; _8 Alias for CB_Keyboard.keys.8. Source: CrossBase/input/CB_Keyboard.js, line 1682 See: CB_Keyboard.keys.8 &lt;static&gt; _9 Alias for CB_Keyboard.keys.9. Source: CrossBase/input/CB_Keyboard.js, line 1702 See: CB_Keyboard.keys.9 &lt;static&gt; A :array The \"A\" key. Type: array Default Value: [65,\"CB_Keyboard.extended.VK.A\"] Source: CrossBase/input/CB_Keyboard.js, line 1848 &lt;static&gt; ALT :array The Alt key. Type: array Default Value: [18] Source: CrossBase/input/CB_Keyboard.js, line 1360 &lt;static&gt; APP1 :array The App1 key. Type: array Default Value: [182] Source: CrossBase/input/CB_Keyboard.js, line 2377 &lt;static&gt; APP2 :array The App2 key. Type: array Default Value: [183] Source: CrossBase/input/CB_Keyboard.js, line 2384 &lt;static&gt; APPS :array The Apps (Applications) key. Type: array Default Value: [93] Source: CrossBase/input/CB_Keyboard.js, line 2100 &lt;static&gt; ASTERISK :array The \"*\" (asterisk) symbol key. NOTE: In some keyboards (for example in Spanish for Spain ones), you have to press PLUS (code 187) with SHIFT to access to \"*\". Type: array Default Value: [106] Source: CrossBase/input/CB_Keyboard.js, line 1752 &lt;static&gt; ATTN :array The Attn key. Type: array Default Value: [246] Source: CrossBase/input/CB_Keyboard.js, line 2391 &lt;static&gt; AUDIODESCRIPTION :array The Audio Description key. Type: array Default Value: [\"\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.CAPTION\"] Source: CrossBase/input/CB_Keyboard.js, line 2466 &lt;static&gt; B :array The \"B\" key. Type: array Default Value: [66,\"CB_Keyboard.extended.VK.B\"] Source: CrossBase/input/CB_Keyboard.js, line 1855 &lt;static&gt; BACKSPACE :array The Backspace key. Type: array Default Value: [8,127,\"CB_Keyboard.extended.VK.BACK_SPACE\"] Source: CrossBase/input/CB_Keyboard.js, line 1474 &lt;static&gt; BLUE :array The Blue colour button. Type: array Default Value: [\"CB_Keyboard.extended.VK.BLUE\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.BLUE\"] Source: CrossBase/input/CB_Keyboard.js, line 2536 &lt;static&gt; BROWSER_BACK :array The Browser's Back key. Type: array Default Value: [166,\"CB_Keyboard.extended.VK.PREV\",\"\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.RETURN\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_TRACK_PREVIOUS\",\"CB_Keyboard.extended.VK.BACK\"] Source: CrossBase/input/CB_Keyboard.js, line 2291 &lt;static&gt; BROWSER_FAVORITES :array The Browser's Favorites key. Type: array Default Value: [171] Source: CrossBase/input/CB_Keyboard.js, line 2346 &lt;static&gt; BROWSER_FORWARD :array The Browser's Forward key. Type: array Default Value: [167,\"CB_Keyboard.extended.VK.NEXT\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_TRACK_NEXT\"] Source: CrossBase/input/CB_Keyboard.js, line 2307 &lt;static&gt; BROWSER_HOME :array The Browser's Home key. Type: array Default Value: [172] Source: CrossBase/input/CB_Keyboard.js, line 2353 &lt;static&gt; BROWSER_REFRESH :array The Browser's Refresh (Reload) key. Type: array Default Value: [168] Source: CrossBase/input/CB_Keyboard.js, line 2319 &lt;static&gt; BROWSER_SEARCH :array The Browser's Search key. Type: array Default Value: [170,\"\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.SEARCH\"] Source: CrossBase/input/CB_Keyboard.js, line 2333 &lt;static&gt; BROWSER_STOP :array The Browser's Stop key. Type: array Default Value: [169] Source: CrossBase/input/CB_Keyboard.js, line 2326 &lt;static&gt; C :array The \"C\" key. Type: array Default Value: [67,\"CB_Keyboard.extended.VK.C\"] Source: CrossBase/input/CB_Keyboard.js, line 1862 &lt;static&gt; CAPS_LOCK :array The Caps Lock key. Type: array Default Value: [20] Source: CrossBase/input/CB_Keyboard.js, line 1504 &lt;static&gt; CLEAR :array The Clear key. Type: array Default Value: [12,254,\"\"] Source: CrossBase/input/CB_Keyboard.js, line 2044 &lt;static&gt; COMMA :array The \",\" (comma) symbol key. Type: array Default Value: [188] Source: CrossBase/input/CB_Keyboard.js, line 1784 &lt;static&gt; CRSEL :array The CrSel key. Type: array Default Value: [247] Source: CrossBase/input/CB_Keyboard.js, line 2398 &lt;static&gt; CTRL :array The Control key. Type: array Default Value: [17,162,163] Source: CrossBase/input/CB_Keyboard.js, line 1353 &lt;static&gt; CYAN :array The Cyan colour button. Type: array Default Value: [\"\"] Source: CrossBase/input/CB_Keyboard.js, line 2548 &lt;static&gt; D :array The \"D\" key. Type: array Default Value: [68,\"CB_Keyboard.extended.VK.D\"] Source: CrossBase/input/CB_Keyboard.js, line 1869 &lt;static&gt; DECIMAL :array The Decimal key (for numeric pads). NOTE: In some decimal systems, as in Spanish, it is a comma (\",\"). Normally, numeric keypads in Spanish for Spain keyboards show a dot (\".\") but others as German keyboards shows a comma (\",\"). Type: array Default Value: [110] Source: CrossBase/input/CB_Keyboard.js, line 2125 &lt;static&gt; DEL :array The Del (Delete) key. Type: array Default Value: [46] Source: CrossBase/input/CB_Keyboard.js, line 1841 &lt;static&gt; DOT :array The \".\" (dot) symbol key. Type: array Default Value: [190] Source: CrossBase/input/CB_Keyboard.js, line 1774 &lt;static&gt; DOWN :array The down arrow key. Type: array Default Value: [40,\"\",\"CB_Keyboard.extended.VK.DOWN\",\"CB_Keyboard.extended.SAMSUNG_TV.DOWN\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.DOWN\",\"CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE.DOWN\",\"CB_Keyboard.extended.AMAZON_FIRE_TV_GAME_CONTROLLER.DOWN\",\"CB_Keyboard.extended.PS3.DOWN\",\"CB_Keyboard.extended.PS4.DOWN\",\"CB_Keyboard.extended.PSVITA.DOWN\"] Source: CrossBase/input/CB_Keyboard.js, line 1400 &lt;static&gt; E :array The \"E\" key. Type: array Default Value: [69,\"CB_Keyboard.extended.VK.E\"] Source: CrossBase/input/CB_Keyboard.js, line 1876 &lt;static&gt; END :array The End key. Type: array Default Value: [35] Source: CrossBase/input/CB_Keyboard.js, line 1805 &lt;static&gt; ENTER :array The Enter (Return) key. Type: array Default Value: [13,\"CB_Keyboard.extended.VK.ENTER\",\"CB_Keyboard.extended.SAMSUNG_TV.ENTER\",\"CB_Keyboard.extended.SAMSUNG_TV.PANEL_ENTER\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.ENTER\",\"CB_Keyboard.extended.PS3.CROSS\",\"\"] Source: CrossBase/input/CB_Keyboard.js, line 1457 &lt;static&gt; EREOF :array The EREOF (Erase EOF) key. Type: array Default Value: [249] Source: CrossBase/input/CB_Keyboard.js, line 2412 &lt;static&gt; ESC :array The Escape (ESC) key. Type: array Default Value: [27] Source: CrossBase/input/CB_Keyboard.js, line 1262 &lt;static&gt; EXECUTE :array The Execute key. Type: array Default Value: [43] Source: CrossBase/input/CB_Keyboard.js, line 2081 &lt;static&gt; EXSEL :array The ExSel key. Type: array Default Value: [248] Source: CrossBase/input/CB_Keyboard.js, line 2405 &lt;static&gt; F :array The \"F\" key. Type: array Default Value: [70,\"CB_Keyboard.extended.VK.F\"] Source: CrossBase/input/CB_Keyboard.js, line 1883 &lt;static&gt; F1 :array The F1 key. Type: array Default Value: [112] Source: CrossBase/input/CB_Keyboard.js, line 1269 &lt;static&gt; F2 :array The F2 key. Type: array Default Value: [113] Source: CrossBase/input/CB_Keyboard.js, line 1276 &lt;static&gt; F3 :array The F3 key. Type: array Default Value: [114] Source: CrossBase/input/CB_Keyboard.js, line 1283 &lt;static&gt; F4 :array The F4 key. Type: array Default Value: [115] Source: CrossBase/input/CB_Keyboard.js, line 1290 &lt;static&gt; F5 :array The F5 key. Type: array Default Value: [116] Source: CrossBase/input/CB_Keyboard.js, line 1297 &lt;static&gt; F6 :array The F6 key. Type: array Default Value: [117] Source: CrossBase/input/CB_Keyboard.js, line 1304 &lt;static&gt; F7 :array The F7 key. Type: array Default Value: [118] Source: CrossBase/input/CB_Keyboard.js, line 1311 &lt;static&gt; F8 :array The F8 key. Type: array Default Value: [119] Source: CrossBase/input/CB_Keyboard.js, line 1318 &lt;static&gt; F9 :array The F9 key. Type: array Default Value: [120] Source: CrossBase/input/CB_Keyboard.js, line 1325 &lt;static&gt; F10 :array The F10 key. Type: array Default Value: [121] Source: CrossBase/input/CB_Keyboard.js, line 1332 &lt;static&gt; F11 :array The F11 key. Type: array Default Value: [122] Source: CrossBase/input/CB_Keyboard.js, line 1339 &lt;static&gt; F12 :array The F12 key. Type: array Default Value: [123] Source: CrossBase/input/CB_Keyboard.js, line 1346 &lt;static&gt; G :array The \"G\" key. Type: array Default Value: [71,\"CB_Keyboard.extended.VK.G\"] Source: CrossBase/input/CB_Keyboard.js, line 1890 &lt;static&gt; GREEN :array The Green colour button. Type: array Default Value: [\"CB_Keyboard.extended.VK.GREEN\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.GREEN\"] Source: CrossBase/input/CB_Keyboard.js, line 2512 &lt;static&gt; H :array The \"H\" key. Type: array Default Value: [72,\"CB_Keyboard.extended.VK.H\"] Source: CrossBase/input/CB_Keyboard.js, line 1897 &lt;static&gt; HD :array The HD (High Definition) key. Type: array Default Value: [\"\"] Source: CrossBase/input/CB_Keyboard.js, line 2490 &lt;static&gt; HELP :array The Help key. Type: array Default Value: [47,\"CB_Keyboard.extended.VK.HELP\",\"\"] Source: CrossBase/input/CB_Keyboard.js, line 2088 &lt;static&gt; HOME :array The Home key. Type: array Default Value: [36,\"\"] Source: CrossBase/input/CB_Keyboard.js, line 1794 &lt;static&gt; I :array The \"I\" key. Type: array Default Value: [73,\"CB_Keyboard.extended.VK.I\"] Source: CrossBase/input/CB_Keyboard.js, line 1904 &lt;static&gt; INFO :array The Info (Information) key. Type: array Default Value: [\"CB_Keyboard.extended.VK.INFO\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.INFO\"] Source: CrossBase/input/CB_Keyboard.js, line 2454 &lt;static&gt; INS :array The Ins (Insert) key. Type: array Default Value: [45] Source: CrossBase/input/CB_Keyboard.js, line 1834 &lt;static&gt; J :array The \"J\" key. Type: array Default Value: [74,\"CB_Keyboard.extended.VK.J\"] Source: CrossBase/input/CB_Keyboard.js, line 1911 &lt;static&gt; K :array The \"K\" key. Type: array Default Value: [75,\"CB_Keyboard.extended.VK.K\"] Source: CrossBase/input/CB_Keyboard.js, line 1918 &lt;static&gt; L :array The \"L\" key. Type: array Default Value: [76,\"CB_Keyboard.extended.VK.L\"] Source: CrossBase/input/CB_Keyboard.js, line 1925 &lt;static&gt; LEFT :array The left arrow key. Type: array Default Value: [37,\"\",\"CB_Keyboard.extended.VK.LEFT\",\"CB_Keyboard.extended.SAMSUNG_TV.LEFT\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.LEFT\",\"CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE.LEFT\",\"CB_Keyboard.extended.AMAZON_FIRE_TV_GAME_CONTROLLER.LEFT\",\"CB_Keyboard.extended.PS3.LEFT\",\"CB_Keyboard.extended.PS4.LEFT\",\"CB_Keyboard.extended.PSVITA.LEFT\"] Source: CrossBase/input/CB_Keyboard.js, line 1419 &lt;static&gt; M :array The \"M\" key. Type: array Default Value: [77,\"CB_Keyboard.extended.VK.M\"] Source: CrossBase/input/CB_Keyboard.js, line 1932 &lt;static&gt; MAIL :array The Mail key. Type: array Default Value: [180] Source: CrossBase/input/CB_Keyboard.js, line 2363 &lt;static&gt; MEDIA_FORWARD :array The Multimedia Forward key. Type: array Default Value: [176,228,\"CB_Keyboard.extended.LG_SMART_TV_LINUX_35230.FORWARD\",\"CB_Keyboard.extended.VK.FAST_FWD\",\"CB_Keyboard.extended.SAMSUNG_TV.FF_\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_FORWARD\",\"CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE.FF\"] Source: CrossBase/input/CB_Keyboard.js, line 2230 &lt;static&gt; MEDIA_PLAY_PAUSE :array The Multimedia Play/Pause key. Type: array Default Value: [179,\"CB_Keyboard.extended.VK.PLAY_PAUSE\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_PLAY_PAUSE\",\"CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE.PLAY_PAUSE\"] Source: CrossBase/input/CB_Keyboard.js, line 2278 &lt;static&gt; MEDIA_REWIND :array The Multimedia Rewind key. Type: array Default Value: [177,227,\"CB_Keyboard.extended.VK.REWIND\",\"CB_Keyboard.extended.LG_SMART_TV_LINUX_35230.REWIND\",\"CB_Keyboard.extended.SAMSUNG_TV.REWIND_\",\"\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_REWIND\",\"CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE.RW\"] Source: CrossBase/input/CB_Keyboard.js, line 2247 &lt;static&gt; MEDIA_SELECT :array The Select Media key. Type: array Default Value: [181] Source: CrossBase/input/CB_Keyboard.js, line 2370 &lt;static&gt; MEDIA_STOP :array The Multimedia Stop key. Type: array Default Value: [178,\"CB_Keyboard.extended.VK.STOP\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_STOP\"] Source: CrossBase/input/CB_Keyboard.js, line 2265 &lt;static&gt; MENU :array The Menu key. Type: array Default Value: [164,165,\"CB_Keyboard.extended.SAMSUNG_TV.MENU\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MENU\"] Source: CrossBase/input/CB_Keyboard.js, line 2132 &lt;static&gt; META :array The meta (Windows Start, Apple Command, etc.) key. Type: array Default Value: [91,92,219,220,224] Source: CrossBase/input/CB_Keyboard.js, line 1374 &lt;static&gt; MINUS :array The \"-\" (minus) symbol key. Type: array Default Value: [109,173,189,\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MINUS\"] Source: CrossBase/input/CB_Keyboard.js, line 1739 &lt;static&gt; MOUSE_LEFT_BUTTON :array The mouse's left button (for Windows' Virtual Keyboard). Type: array Default Value: [1] Source: CrossBase/input/CB_Keyboard.js, line 2146 &lt;static&gt; MOUSE_MIDDLE_BUTTON :array The mouse's middle button (for Windows' Virtual Keyboard). Type: array Default Value: [4] Source: CrossBase/input/CB_Keyboard.js, line 2153 &lt;static&gt; MOUSE_RIGHT_BUTTON :array The mouse's right button (for Windows' Virtual Keyboard). Type: array Default Value: [2] Source: CrossBase/input/CB_Keyboard.js, line 2160 &lt;static&gt; MOUSE_X1_BUTTON :array The mouse's X1 button (for Windows' Virtual Keyboard). Type: array Default Value: [5] Source: CrossBase/input/CB_Keyboard.js, line 2167 &lt;static&gt; MOUSE_X2_BUTTON :array The mouse's X2 button (for Windows' Virtual Keyboard). Type: array Default Value: [6] Source: CrossBase/input/CB_Keyboard.js, line 2174 &lt;static&gt; MUTE :array The Mute key. Type: array Default Value: [173,181,\"CB_Keyboard.extended.VK.MUTE\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MUTE\"] Source: CrossBase/input/CB_Keyboard.js, line 2181 &lt;static&gt; N :array The \"N\" key. Type: array Default Value: [78,\"CB_Keyboard.extended.VK.N\"] Source: CrossBase/input/CB_Keyboard.js, line 1939 &lt;static&gt; NUM_LOCK :array The Num Lock (Numeric Lock) key. Type: array Default Value: [144] Source: CrossBase/input/CB_Keyboard.js, line 1512 &lt;static&gt; O :array The \"O\" key. Type: array Default Value: [79,\"CB_Keyboard.extended.VK.O\"] Source: CrossBase/input/CB_Keyboard.js, line 1946 &lt;static&gt; P :array The \"P\" key. Type: array Default Value: [80,\"CB_Keyboard.extended.VK.P\"] Source: CrossBase/input/CB_Keyboard.js, line 1953 &lt;static&gt; PA1 :array The PA1 key. Type: array Default Value: [253] Source: CrossBase/input/CB_Keyboard.js, line 2447 &lt;static&gt; PAGE_DOWN :array The Page Down key. Type: array Default Value: [34,\"CB_Keyboard.extended.VK.PAGE_DOWN\"] Source: CrossBase/input/CB_Keyboard.js, line 1823 &lt;static&gt; PAGE_UP :array The Page Up key. Type: array Default Value: [33,\"CB_Keyboard.extended.VK.PAGE_UP\"] Source: CrossBase/input/CB_Keyboard.js, line 1812 &lt;static&gt; PAUSE :array The Pause key. Type: array Default Value: [19,\"CB_Keyboard.extended.VK.PAUSE\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_PAUSE\",\"CB_Keyboard.extended.LG_SMART_TV_LINUX_35230.PAUSE\"] Source: CrossBase/input/CB_Keyboard.js, line 2030 &lt;static&gt; PLAY :array The Play key. Type: array Default Value: [250,\"CB_Keyboard.extended.LG_SMART_TV_LINUX_35230.PLAY\",\"CB_Keyboard.extended.VK.PLAY\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.MEDIA_PLAY\"] Source: CrossBase/input/CB_Keyboard.js, line 2419 &lt;static&gt; PLUS :array The \"+\" (plus) symbol key. NOTE: In some keyboards (for example in Chinese ones), you have to press EQUAL (code 61) with SHIFT to access to \"+\". Type: array Default Value: [107,171,187] Source: CrossBase/input/CB_Keyboard.js, line 1727 &lt;static&gt; PRINT :array The Print key. Type: array Default Value: [42,\"\"] Source: CrossBase/input/CB_Keyboard.js, line 2063 &lt;static&gt; PRINT_SCREEN :array The Print Screen key. Type: array Default Value: [44] Source: CrossBase/input/CB_Keyboard.js, line 2074 &lt;static&gt; Q :array The \"Q\" key. Type: array Default Value: [81,\"CB_Keyboard.extended.VK.Q\"] Source: CrossBase/input/CB_Keyboard.js, line 1960 &lt;static&gt; R :array The \"R\" key. Type: array Default Value: [82,\"CB_Keyboard.extended.VK.R\"] Source: CrossBase/input/CB_Keyboard.js, line 1967 &lt;static&gt; RED :array The Red colour button. Type: array Default Value: [\"CB_Keyboard.extended.VK.RED\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.RED\"] Source: CrossBase/input/CB_Keyboard.js, line 2500 &lt;static&gt; RIGHT :array The right arrow key. Type: array Default Value: [39,\"\",\"CB_Keyboard.extended.VK.RIGHT\",\"CB_Keyboard.extended.SAMSUNG_TV.RIGHT\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.RIGHT\",\"CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE.RIGHT\",\"CB_Keyboard.extended.AMAZON_FIRE_TV_GAME_CONTROLLER.RIGHT\",\"CB_Keyboard.extended.PS3.RIGHT\",\"CB_Keyboard.extended.PS4.RIGHT\",\"CB_Keyboard.extended.PSVITA.RIGHT\"] Source: CrossBase/input/CB_Keyboard.js, line 1438 &lt;static&gt; S :array The \"S\" key. Type: array Default Value: [83,\"CB_Keyboard.extended.VK.S\"] Source: CrossBase/input/CB_Keyboard.js, line 1974 &lt;static&gt; SCROLL_LOCK :array The Scroll Lock key. Type: array Default Value: [145] Source: CrossBase/input/CB_Keyboard.js, line 1519 &lt;static&gt; SELECT :array The Select key (for Windows' Virtual keyboard). Type: array Default Value: [41] Source: CrossBase/input/CB_Keyboard.js, line 2056 &lt;static&gt; SEPARATOR :array The Separator key. Type: array Default Value: [108] Source: CrossBase/input/CB_Keyboard.js, line 2118 &lt;static&gt; SHIFT :array The Shift (left or right) key. Type: array Default Value: [16,160,161] Source: CrossBase/input/CB_Keyboard.js, line 1367 &lt;static&gt; SLASH :array The \"/\" (slash) symbol key. NOTE: In some keyboards (for example in Spanish for Spain ones), you have to press 7 (code 55) with SHIFT to access to \"/\". Type: array Default Value: [111] Source: CrossBase/input/CB_Keyboard.js, line 1764 &lt;static&gt; SLEEP :array The Sleep key. Type: array Default Value: [95,\"CB_Keyboard.extended.SAMSUNG_TV.SLEEP\"] Source: CrossBase/input/CB_Keyboard.js, line 2107 &lt;static&gt; SPACEBAR :array The Spacebar key. Type: array Default Value: [32,\"CB_Keyboard.extended.VK.SPACE\"] Source: CrossBase/input/CB_Keyboard.js, line 1486 &lt;static&gt; SUBTITLE :array The Subtitle key. Type: array Default Value: [\"CB_Keyboard.extended.VK.SUBTITLE\",\"CB_Keyboard.extended.SAMSUNG_TV.SUBTITLE\",\"CB_Keyboard.extended.SAMSUNG_TV.SUB_TITLE\"] Source: CrossBase/input/CB_Keyboard.js, line 2478 &lt;static&gt; T :array The \"T\" key. Type: array Default Value: [84,\"CB_Keyboard.extended.VK.T\"] Source: CrossBase/input/CB_Keyboard.js, line 1981 &lt;static&gt; TAB :array The Tabulator (Tab) key. Type: array Default Value: [9] Source: CrossBase/input/CB_Keyboard.js, line 1497 &lt;static&gt; U :array The \"U\" key. Type: array Default Value: [85,\"CB_Keyboard.extended.VK.U\"] Source: CrossBase/input/CB_Keyboard.js, line 1988 &lt;static&gt; UP :array The up arrow key. Type: array Default Value: [38,\"\",\"CB_Keyboard.extended.VK.UP\",\"CB_Keyboard.extended.SAMSUNG_TV.UP\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.UP\",\"CB_Keyboard.extended.AMAZON_FIRE_TV_REMOTE.UP\",\"CB_Keyboard.extended.AMAZON_FIRE_TV_GAME_CONTROLLER.UP\",\"CB_Keyboard.extended.PS3.UP\",\"CB_Keyboard.extended.PS4.UP\",\"CB_Keyboard.extended.PSVITA.UP\"] Source: CrossBase/input/CB_Keyboard.js, line 1381 &lt;static&gt; V :array The \"V\" key. Type: array Default Value: [86,\"CB_Keyboard.extended.VK.V\"] Source: CrossBase/input/CB_Keyboard.js, line 1995 &lt;static&gt; VOL_DOWN :array The Volume Down key. Type: array Default Value: [174,182,\"CB_Keyboard.extended.VK.VOLUME_DOWN\",\"\",\"CB_Keyboard.extended.SAMSUNG_TV.VOL_DOWN\",\"CB_Keyboard.extended.SAMSUNG_TV.PANEL_VOL_DOWN\",\"\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.VOLUME_DOWN\"] Source: CrossBase/input/CB_Keyboard.js, line 2212 &lt;static&gt; VOL_UP :array The Volume Up key. Type: array Default Value: [175,183,\"CB_Keyboard.extended.VK.VOLUME_UP\",\"\",\"CB_Keyboard.extended.SAMSUNG_TV.VOL_UP\",\"CB_Keyboard.extended.SAMSUNG_TV.PANEL_VOL_UP\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.VOLUME_UP\"] Source: CrossBase/input/CB_Keyboard.js, line 2195 &lt;static&gt; W :array The \"W\" key. Type: array Default Value: [87,\"CB_Keyboard.extended.VK.W\"] Source: CrossBase/input/CB_Keyboard.js, line 2002 &lt;static&gt; X :array The \"X\" key. Type: array Default Value: [88,\"CB_Keyboard.extended.VK.X\"] Source: CrossBase/input/CB_Keyboard.js, line 2009 &lt;static&gt; Y :array The \"Y\" key. Type: array Default Value: [89,\"CB_Keyboard.extended.VK.Y\"] Source: CrossBase/input/CB_Keyboard.js, line 2016 &lt;static&gt; YELLOW :array The Yellow colour button. Type: array Default Value: [\"CB_Keyboard.extended.VK.YELLOW\",\"\",\"CB_Keyboard.extended.SAMSUNG_TIZEN_TV.YELLOW\"] Source: CrossBase/input/CB_Keyboard.js, line 2524 &lt;static&gt; Z :array The \"Z\" key. Type: array Default Value: [90,\"CB_Keyboard.extended.VK.Z\"] Source: CrossBase/input/CB_Keyboard.js, line 2023 &lt;static&gt; ZOOM :array The Zoom key. Type: array Default Value: [251,\"CB_Keyboard.extended.SAMSUNG_TV.ZOOM1\",\"\",\"\"] Source: CrossBase/input/CB_Keyboard.js, line 2433 × Search results Close "},"CB_Modules.html":{"id":"CB_Modules.html","title":"Namespace: CB_Modules","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Modules CB_Modules Static class that contains all the modules and the tools to manage them. Source: CrossBrowdy.js, line 157 Members &lt;static&gt; modules :Object Contains all the modules, one per property. Type: Object Properties: Name Type Description name_of_the_module CB_Modules.MODULE Object that contains the module data. The property name must be the name of the module. Source: CrossBrowdy.js, line 242 &lt;static, readonly&gt; STATUSES :integer Enum which defines possible module statuses. Type: integer Properties: Name Type Default Description FAILED integer -1 The module has failed to load. UNKNOWN integer 0 The module has an unkwnown status. UNLOADED integer 1 The module is not loaded yet. Default status. LOADING integer 2 The module is being loading. LOADED integer 3 The module has loaded successfully (coudl be not ready yet). READY integer 4 The module has loaded successfully and it is ready to be used. Source: CrossBrowdy.js, line 166 Methods &lt;static&gt; addNeededFiles(moduleName, neededFiles) → {boolean} Attaches files to a module. Parameters: Name Type Description moduleName string Name of the module which will contain the new files. neededFiles CB_Modules.NEEDED_FILES The \"neededFiles\" parameter for the module. Source: CrossBrowdy.js, line 947 Returns: It will return true if succeeded or false otherwise. Type boolean &lt;static&gt; addNeededModule(moduleNameParent, moduleName, neededFiles) → {boolean} Attaches one module to another one. Parameters: Name Type Description moduleNameParent string Name of the parent module where the new child module will be attached to. moduleName string Name of the new child module which will be attached to the given parent. neededFiles CB_Modules.NEEDED_FILES The \"neededFiles\" parameter for the new child module. Source: CrossBrowdy.js, line 933 Returns: It will return true if succeeded or false otherwise. Type boolean &lt;static&gt; editProperty(moduleName, property, value [, type] [, iterateArray]) → {boolean} Modifies a desired property of a given module. Parameters: Name Type Argument Default Description moduleName string Name of the module which contains the property to modify. property string Name of the property to modify. value * Value desired for the property. type 'array' | 'object' | 'scalar' &lt;optional&gt; 'scalar' Type that the property uses. If it is \"array\", the given \"value\" will be attached at the end of the array (all in a new single index if the \"iterateArray\" parameter is set to false, or each value in a new index otherwise). If it is \"object\", the given \"value\" and the given \"property\" to modify will be treated as objects and the members of the \"value\" will be copied one by one (overwriting previous members in the case they existed). If it is \"scalar\" or any other, the given \"property\" value will be replaced with the given \"value\". iterateArray boolean &lt;optional&gt; false If is set to true and the given \"type\" is \"array\", the given \"value\" will be considered an array and will be iterated to copy each of its values to a new index in the destiny. Otherwise, if it is set to false and the given \"type\" is \"array\", the given \"value\" will be attached at the end of the array in a new single index. Source: CrossBrowdy.js, line 872 Returns: It will return true if succeeded or false otherwise. Type boolean &lt;static&gt; get(moduleName) → {CB_Modules.MODULE|null} Returns a CB_Modules.MODULE object for module management. Parameters: Name Type Description moduleName string Name of the desired module. Source: CrossBrowdy.js, line 828 Returns: If found, it will return the CB_Modules.MODULE object desired. Otherwise, it will return null. Type CB_Modules.MODULE | null &lt;static&gt; getProperty(moduleName, property) → {*|null} Gets the value of a desired module property (or returns null). Parameters: Name Type Description moduleName string Name of the desired module. property string Name of the desired property. Source: CrossBrowdy.js, line 846 Returns: If found, it will return the value of the desired module property. Otherwise, it will return null. Type * | null &lt;static&gt; setStatus(moduleName, status) → {boolean} Sets a status for a given module. Parameters: Name Type Description moduleName string Name of the module. status integer The desired status. Must be a value that exists in the CB_Modules.STATUSES enum. Source: CrossBrowdy.js, line 740 Returns: It will return true if succeeded or false otherwise. Type boolean Type Definitions CALLBACK(scriptPath) Callback for the different events of a module. Parameters: Name Type Description scriptPath string The value for the \"scriptPath\" parameter used by CB_init when it was called. Source: CrossBrowdy.js, line 219 MODULE Object that contains a module. Type: Object Properties: Name Type Description name string Name of the module. status CB_Modules.STATUSES Module status. onCall CB_Modules.CALLBACK Callback for when the module is called to be loaded. Being \"this\" the CB_Modules.MODULE object itself. onLoad CB_Modules.CALLBACK Callback for when the module loads successfully. Being \"this\" the CB_Modules.MODULE object itself. onReady CB_Modules.CALLBACK Callback for when the module is totally ready. Being \"this\" the CB_Modules.MODULE object itself. onFail CB_Modules.CALLBACK Callback for when the module fails to load. Being \"this\" the CB_Modules.MODULE object itself. NOT IMPLEMENTED YET. neededFiles CB_Modules.NEEDED_FILES Object containing the needed files. neededModules array Array of CB_Modules.NEEDED_MODULE objects, containing the needed modules. credits string Credits of the module. Source: CrossBrowdy.js, line 226 NEEDED_FILE Object that contains a needed file for a module. Type: Object Properties: Name Type Argument Default Description load boolean &lt;optional&gt; false Defines whether to load the file or not. mandatory boolean &lt;optional&gt; false Defines whether the file is mandatory. If the file is not mandatory, its module could be declared as loaded successfully before the file is loaded (and maybe never will). absolutePath boolean &lt;optional&gt; false Defines whether the path of the file is relative to the path of the main script or absolute. loadChecker CB_Modules.neededFile_LOAD_CHECKER &lt;optional&gt; Callback that will be called when the file tries to be loaded and should return true if the file needs to be loaded. id string &lt;optional&gt; Desired string to identify the file. requires array &lt;optional&gt; Array of strings with the IDs of the files that must be loaded before loading this file. The file will not be loaded until the required files are loaded first. Source: CrossBrowdy.js, line 191 NEEDED_FILES Object that contains the needed files for a module. Each property will represent a needed file. Type: Object Properties: Name Type Description path_to_the_file CB_Modules.NEEDED_FILE Object that contains a needed file for a module. The property name must be either the path to the file or a variable containing it. Tto use a variable, the name of the property must start with \"VALUEOF_\" and continue with the name of the variable. In the case that the variable is an object, each property must be separated by a dot (\".\"). Source: CrossBrowdy.js, line 203 NEEDED_MODULE Object that contains a needed module for a parent module. Type: Object Properties: Name Type Description name string Name of the module. neededFiles CB_Modules.NEEDED_FILES Object containing the needed files. Source: CrossBrowdy.js, line 211 neededFile_LOAD_CHECKER(filepath, neededFile) → {boolean} Callback that is called before loading a file and should return true if we want to load the file or false otherwise. Parameters: Name Type Description filepath string Filepath of the needed file (including the filename). neededFile CB_Modules.NEEDED_FILE Object that contains the needed file. Source: CrossBrowdy.js, line 182 Returns: Returns true if we want to load the file or false otherwise. Type boolean × Search results Close "},"CB_Mouse.html":{"id":"CB_Mouse.html","title":"Namespace: CB_Mouse","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Mouse CB_Mouse Static class to manage the mouse and related. It will return itself if it is tried to be instantiated. Source: CrossBase/input/CB_Mouse.js, line 12 Namespaces CursorImage Methods &lt;static&gt; getButtons() → {Object} Tells what mouse buttons are down (LEFT, MIDDLE and/or RIGHT buttons). Source: CrossBase/input/CB_Mouse.js, line 301 Returns: Returns an object using the following format (where \"true\" means that the button is being pressed): { LEFT : boolean, MIDDLE : boolean, RIGHT : boolean } Type Object &lt;static&gt; getLockElement( [avoidCache]) → {Element|null} Gets the lock element for the mouse pointer (if any) or null otherwise. More information: Pointer Lock API. Parameters: Name Type Argument Default Description avoidCache boolean &lt;optional&gt; false If set to false, the returning value will use the previously-cached value (updated when this function is called with this parameter set to true or the onPointerLockChange or analog event is fired or when the CB_Mouse.lock or CB_Mouse.unlock functions are called successfully). Source: CrossBase/input/CB_Mouse.js, line 691 Returns: Returns the lock element for the mouse pointer (if any) or null otherwise. Type Element | null &lt;static&gt; getX( [e] [, ignoreScroll] [, ignoreLock]) → {number} Gets and returns the X coordinate (horizontal position) of the mouse (relative to the window in desktop) in pixels. Parameters: Name Type Argument Default Description e Event &lt;optional&gt; Mouse event object. If not provided, the returning value will use the previously-cached value (updated the last time that the onMouseMove event was fired). ignoreScroll boolean &lt;optional&gt; false If set to true, the horizontal scroll position will not be added to the returning value. ignoreLock boolean &lt;optional&gt; false If set to true, it will ignore whether the cursor is being locked or not. Otherwise, if set to false and the cursor is locked, the returning value will only have in mind the position in the locking element. Source: CrossBase/input/CB_Mouse.js, line 315 Returns: Returns the X coordinate (horizontal position) of the mouse (relative to the window in desktop) in pixels. Type number &lt;static&gt; getXMovement( [e]) → {number} Returns the current X (horizontal) movement (useful when the mouse pointer is locked) in pixels. More information: MouseEvent.movementX. Parameters: Name Type Argument Description e Event &lt;optional&gt; Mouse event object. If not provided, the returning value will use the previously-cached value (updated the last time that the onMouseMove event was fired). Source: CrossBase/input/CB_Mouse.js, line 475 Returns: Returns the current X (horizontal) movement (useful when the mouse pointer is locked) in pixels. Type number &lt;static&gt; getXRelative(x [, ignoreScroll]) → {number} Gets and returns the current X coordinate (horizontal position) in pixels of the mouse relative to a given X position. The returning value uses the previously-cached value (updated the last time that the onMouseMove event was fired). Parameters: Name Type Argument Default Description x number The X coordinate (horizontal position) in pixels. The returning value will be calculated relatively to it. ignoreScroll boolean &lt;optional&gt; false If set to true, the horizontal scroll position will not be added to the returning value. Source: CrossBase/input/CB_Mouse.js, line 435 To Do: Think about allowing to define an \"e\" parameter with the mouse event object. Returns: Returns the current X coordinate (horizontal position) in pixels of the mouse relative to a given X position. Type number &lt;static&gt; getY( [e] [, ignoreScroll] [, ignoreLock]) → {number} Gets and returns the Y coordinate (vertical position) of the mouse (relative to the window in desktop) in pixels. Parameters: Name Type Argument Default Description e Event &lt;optional&gt; Mouse event object. If not provided, the returning value will use the previously-cached value (updated the last time that the onMouseMove event was fired). ignoreScroll boolean &lt;optional&gt; false If set to true, the vertical scroll position will not be added to the returning value. ignoreLock boolean &lt;optional&gt; false If set to true, it will ignore whether the cursor is being locked or not. Otherwise, if set to false and the cursor is locked, the returning value will only have in mind the position in the locking element. Source: CrossBase/input/CB_Mouse.js, line 375 Returns: Returns the Y coordinate (vertical position) of the mouse (relative to the window in desktop) in pixels. Type number &lt;static&gt; getYMovement( [e]) → {number} Returns the current Y (vertical) movement (useful when the mouse pointer is locked) in pixels. More information: MouseEvent.movementY. Parameters: Name Type Argument Description e Event &lt;optional&gt; Mouse event object. If not provided, the returning value will use the previously-cached value (updated the last time that the onMouseMove event was fired). Source: CrossBase/input/CB_Mouse.js, line 489 Returns: Returns the current Y (vertical) movement (useful when the mouse pointer is locked) in pixels. Type number &lt;static&gt; getYRelative(y [, ignoreScroll]) → {number} Gets and returns the current Y coordinate (vertical position) in pixels of the mouse relative to a given Y position. The returning value uses the previously-cached value (updated the last time that the onMouseMove event was fired). Parameters: Name Type Argument Default Description y number The Y coordinate (vertical position) in pixels. The returning value will be calculated relatively to it. ignoreScroll boolean &lt;optional&gt; false If set to true, the vertical scroll position will not be added to the returning value. Source: CrossBase/input/CB_Mouse.js, line 456 To Do: Think about allowing to define an \"e\" parameter with the mouse event object. Returns: Returns the current Y coordinate (vertical position) in pixels of the mouse relative to a given Y position. Type number &lt;static&gt; hide( [element] [, recursive]) Hides the mouse cursor in a given DOM element by changing its internal CSS code of the style.cursor property. Parameters: Name Type Argument Default Description element Element &lt;optional&gt; document.body If a DOM element is given, the mouse cursor will be hidden when it is over this DOM element. Otherwise, it will be hidden in the whole document (using document.body as element). recursive boolean &lt;optional&gt; true If it is set to true, all the child DOM elements will also be affected. Source: CrossBase/input/CB_Mouse.js, line 1009 To Do: Check whether the path used in the \"url\" is right or not (now it uses the CB_scriptPath variable). &lt;static&gt; isLocked( [avoidCache]) → {boolean} Tells whether the mouse pointer is locked or not. More information: Pointer Lock API. Parameters: Name Type Argument Default Description avoidCache boolean &lt;optional&gt; false Used as the parameter to call the CB_Mouse.getLockElement function internally. Source: CrossBase/input/CB_Mouse.js, line 655 Returns: Returns whether the mouse pointer is locked or not. Type boolean &lt;static&gt; isLockSupported() → {boolean} Tells whether mouse pointer lock is supported or not. More information: Pointer Lock API. Source: CrossBase/input/CB_Mouse.js, line 639 Returns: Returns whether mouse pointer lock is supported or not. Type boolean &lt;static&gt; isOverCircle(centreX, centreY, radius [, element]) → {boolean} Tells whether the mouse is over a given circle or not. Parameters: Name Type Argument Description centreX number The X coordinate (horizontal position) of the center of the circle in pixels. centreY number The Y coordinate (vertical position) of the center of the circle in pixels. radius number The radius of the circle in pixels. element Element &lt;optional&gt; If a DOM element is given, the mouse coordinates will be calculated relatively to the position of this DOM element. Source: CrossBase/input/CB_Mouse.js, line 957 Returns: Returns whether the mouse is over the given circle or not. Type boolean &lt;static&gt; isOverElement(element) → {boolean} Tells whether the mouse is over a given DOM element or not. Parameters: Name Type Description element Element The DOM element where we want to know whether the mouse is over or not. Source: CrossBase/input/CB_Mouse.js, line 853 Returns: Returns whether the mouse is over the given DOM element or not. Type boolean &lt;static&gt; isOverEllipse(centreX, centreY, radiusX, radiusY [, rotation] [, rotationUseDegrees]) → {boolean} Tells whether the mouse is over a given ellipse or not. Parameters: Name Type Argument Default Description centreX number The \"X\" coordinate of the center of the ellipse. centreY number The \"Y\" coordinate of the center of the ellipse. radiusX number The X (horizontal) radius of the ellipse. radiusY number The Y (vertical) radius of the ellipse. rotation number &lt;optional&gt; 0 The ellipse rotation. The value given will be considered either degrees or radians depending on the given \"rotationUseDegrees\" parameter (by default, it is considered radians). Not implemented yet! rotationUseDegrees boolean &lt;optional&gt; false Defines whether the \"rotation\" given should be considered degrees or not (radians). Not implemented yet! Source: CrossBase/input/CB_Mouse.js, line 985 Returns: Returns whether the mouse is over the given ellipse or not. Type boolean &lt;static&gt; isOverLine(lineX1, lineY1, lineX2, lineY2 [, tolerance] [, element]) → {boolean} Tells whether the mouse is over a given line (infinite line) or not. Parameters: Name Type Argument Default Description lineX1 number The X coordinate (horizontal position) of the first pixel of the line. lineY1 number The Y coordinate (vertical position) of the first pixel of the line. lineX2 number The X coordinate (horizontal position) of the second pixel of the line. lineY2 number The Y coordinate (vertical position) of the second pixel of the line. tolerance number &lt;optional&gt; 1 The amount of loss of precision we can tolerate to consider a collision. element Element &lt;optional&gt; If a DOM element is given, the mouse coordinates will be calculated relatively to the position of this DOM element. Source: CrossBase/input/CB_Mouse.js, line 871 To Do: Think about using a \"width\" parameter (apart from the \"tolerance\" parameter). Returns: Returns whether the mouse is over the given line (infinite line) or not. Type boolean &lt;static&gt; isOverRectangle(rectangleX, rectangleY, rectangleWidth, rectangleHeight [, element]) → {boolean} Tells whether the mouse is over a given rectangle or not. Parameters: Name Type Argument Description rectangleX number The X coordinate (horizontal position) of the first pixel of the rectangle (upper left corner). rectangleY number The Y coordinate (vertical position) of the first pixel of the rectangle (upper left corner). rectangleWidth number The width of the rectangle in pixels. rectangleHeight number The height of the rectangle in pixels. element Element &lt;optional&gt; If a DOM element is given, the mouse coordinates will be calculated relatively to the position of this DOM element. Source: CrossBase/input/CB_Mouse.js, line 931 Returns: Returns whether the mouse is over the given rectangle or not. Type boolean &lt;static&gt; isOverSegment(lineX1, lineY1, lineX2, lineY2 [, tolerance] [, element]) → {boolean} Tells whether the mouse is over a given line segment or not. Parameters: Name Type Argument Default Description lineX1 number The X coordinate (horizontal position) of the first pixel of the line segment. lineY1 number The Y coordinate (vertical position) of the first pixel of the line segment. lineX2 number The X coordinate (horizontal position) of the second pixel of the line segment. lineY2 number The Y coordinate (vertical position) of the second pixel of the line segment. tolerance number &lt;optional&gt; 1 The amount of loss of precision we can tolerate to consider a collision. element Element &lt;optional&gt; If a DOM element is given, the mouse coordinates will be calculated relatively to the position of this DOM element. Source: CrossBase/input/CB_Mouse.js, line 902 To Do: Think about using a \"width\" parameter (apart from the \"tolerance\" parameter). Returns: Returns whether the mouse is over the given line segment or not. Type boolean &lt;static&gt; lock( [target], callbackOk, callbackError) → {Element|null} Locks the mouse pointer (if possible). More information: Pointer Lock API. Parameters: Name Type Argument Default Description target Element &lt;optional&gt; document.body The DOM element that the mouse pointer will be locked to. callbackOk function Function callback that will be called (without parameters) if the mouse pointer could be locked successfully. callbackError function Function callback that will be called (without parameters) if the mouse pointer could not be locked successfully. Source: CrossBase/input/CB_Mouse.js, line 713 Returns: Returns the current lock element for the mouse pointer (if any) or null otherwise. Type Element | null &lt;static&gt; normalizeEvent(e) → {Event} Tries to return the given mouse event object with some properties normalized (since different clients can use different values) and perhaps some new properties added (in the case they were missing), when possible. The new attached methods and properties may include polyfills, etc. It also calls the CB_Events.normalize function internally. Some properties added or affected could be deltaX, deltaY, deltaZ, force, clientX, clientY, etc. Parameters: Name Type Description e Event Mouse event object. If not provided, it will use the value of \"event\", \"window.event\", \"Event\" or an empty object (\"{}\"). Source: CrossBase/input/CB_Mouse.js, line 128 To Do: Add more properties and methods to normalize (pageX, pageY, offsetX, offsetY, etc.). Returns: Returns the mouse event object normalized. Type Event &lt;static&gt; onButtonDown(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when a mouse button is down (onMouseDown event) or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the mouse event object (already normalized by the CB_Mouse.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Mouse.js, line 547 &lt;static&gt; onButtonUp(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when a mouse button is up (onMouseUp event) or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the mouse event object (already normalized by the CB_Mouse.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Mouse.js, line 561 &lt;static&gt; onClick(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when a click happens (onClick event) or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the mouse event object (already normalized by the CB_Mouse.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Mouse.js, line 519 &lt;static&gt; onDblClick(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when a click happens (onDblClick event) or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the mouse event object (already normalized by the CB_Mouse.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Mouse.js, line 533 &lt;static&gt; onLeave(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when a mouse leaves a DOM element (onMouseLeave event) or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the mouse event object (already normalized by the CB_Mouse.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; window The target where we want to attach the event listener. Source: CrossBase/input/CB_Mouse.js, line 575 &lt;static&gt; onLockChange(callbackFunction [, keepOldFunction] [, useCapture]) Sets a function to execute when the mouse pointer lock functionality changes its state (it has been either locked or unlocked, using pointerlockchange}, mozpointerlockchange or webkitpointerlockchange event) or removes it. More information: Pointer Lock API. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the mouse event object (already normalized by the CB_Mouse.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. Source: CrossBase/input/CB_Mouse.js, line 777 &lt;static&gt; onLockError(callbackFunction [, keepOldFunction] [, useCapture]) Sets a function to execute when the mouse pointer fails to either lock or unlock (using pointerlockerror, mozpointerlockerror or webkitpointerlockerror event) or removes it. More information: Pointer Lock API. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the mouse event object (already normalized by the CB_Mouse.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. Source: CrossBase/input/CB_Mouse.js, line 792 &lt;static&gt; onMove(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when a click happens (onMouseMove event) or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the mouse event object (already normalized by the CB_Mouse.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Mouse.js, line 505 &lt;static&gt; onOut(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when a mouse gets out of a DOM element (onMouseOut event) or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the mouse event object (already normalized by the CB_Mouse.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Mouse.js, line 603 &lt;static&gt; onOver(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when a mouse is over a DOM element (onMouseOver event) or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the mouse event object (already normalized by the CB_Mouse.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Mouse.js, line 589 &lt;static&gt; onWheel(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the mouse wheel is used (onWheel, onMouseWheel or DOMMouseScroll event) or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the mouse event object (already normalized by the CB_Mouse.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Mouse.js, line 617 &lt;static&gt; restore( [element] [, recursive]) Restores (unhides) the mouse cursor in a given DOM element by changing its internal CSS code of the style.cursor property to the default one (using \"default\" as the CSS code). Parameters: Name Type Argument Default Description element Element &lt;optional&gt; document.body If a DOM element is given, the mouse cursor will be restored (unhidden) when it is over this DOM element. Otherwise, it will be restored (unhidden) in the whole document (using document.body as the \"element\"). recursive boolean &lt;optional&gt; true If it is set to true, all the child DOM elements will also be affected. Source: CrossBase/input/CB_Mouse.js, line 1027 &lt;static&gt; setCSS( [CSS] [, element] [, recursive]) Sets the desired CSS code for the style.cursor property of the given DOM element. Parameters: Name Type Argument Default Description CSS string &lt;optional&gt; \"\" CSS code for the style.cursor property of the given DOM element. If not given, an empty string will be used. element Element &lt;optional&gt; document.body If a DOM element is given, the CSS code updated will affect the given DOM element. Otherwise, it will affect the whole document (using document.body as the \"element\"). recursive boolean &lt;optional&gt; true If it is set to true, all the child DOM elements will also be affected. Source: CrossBase/input/CB_Mouse.js, line 1050 &lt;static&gt; unlock() → {boolean} Unlocks the mouse pointer (if possible). More information: Pointer Lock API. Source: CrossBase/input/CB_Mouse.js, line 751 Returns: Returns true if the mouse pointer has been unlocked or false otherwise. Type boolean &lt;static&gt; wasLocked() → {boolean} Tells whether the mouse pointer was locked before or not when the CB_Mouse.isLocked function was called the last time. More information: Pointer Lock API. Source: CrossBase/input/CB_Mouse.js, line 679 Returns: Returns whether the mouse pointer was locked before or not when the CB_Mouse.isLocked function was called the last time. Type boolean × Search results Close "},"CB_Mouse.CursorImage.html":{"id":"CB_Mouse.CursorImage.html","title":"Namespace: CursorImage","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CursorImage CB_Mouse. CursorImage Property that keeps an object to manage the mouse cursor using a DOM element containing an image for clients that do not support changing the cursor image by CSS. Caution: Performance could be dramatically decreased while using this workaround. Source: CrossBase/input/CB_Mouse.js, line 28 Methods &lt;static&gt; get() → {Element} Gets the DIV element that contains the IMG element of the fake cursor (if any). Source: CrossBase/input/CB_Mouse.js, line 1191 Returns: Returns the DIV element that contains the IMG element of the fake cursor (if any). Type Element &lt;static&gt; getImage() → {Element} Gets the IMG element of the fake cursor (if any). Source: CrossBase/input/CB_Mouse.js, line 1202 Returns: Returns the IMG element of the fake cursor (if any). Type Element &lt;static&gt; hide( [showNormalCursor]) Hides the fake cursor image. Parameters: Name Type Argument Default Description showNormalCursor boolean &lt;optional&gt; true If set to true, restores (shows) the system cursor (calls the CB_Mouse.restore function internally). Source: CrossBase/input/CB_Mouse.js, line 1224 &lt;static&gt; isShowing() → {boolean} Tells whether the fake cursor is showing or not Source: CrossBase/input/CB_Mouse.js, line 1213 Returns: Returns whether the fake cursor is showing or not. Type boolean &lt;static&gt; move( [x] [, y]) Moves the fake cursor image (if it is not hidden). Automatically called when the onMouseMove event is fired. Parameters: Name Type Argument Default Description x number &lt;optional&gt; CB_Mouse.getX(null, false) The X coordinate (horizontal position) in pixels where the fake cursor image wants to be moved to. If not provided, it will use the value returned by calling CB_Mouse.getX(null, false) internally. y number &lt;optional&gt; CB_Mouse.getY(null, false) The Y coordinate (vertical position) in pixels where the fake cursor image wants to be moved to. If not provided, it will use the value returned by calling CB_Mouse.getY(null, false) internally. Source: CrossBase/input/CB_Mouse.js, line 1243 &lt;static&gt; set( [showCursorImage] [, cursorImage] [, cursorImageWidth] [, cursorImageHeight] [, hideNormalCursor] [, isSprite] [, numberOfFrames] [, framesMs] [, divElement] [, imageElement]) Uses an IMG element inside a DIV element (fakes the cursor) to simulate the mouse cursor (following its movements). If it was already called before and a fake cursor is already being used, the CB_Mouse.CursorImage.hide function must be called before in order to start using a different fake cursor image. Caution: Performance could be dramatically decreased while using this workaround. Parameters: Name Type Argument Default Description showCursorImage boolean &lt;optional&gt; true If set to true and a valid cursor image is given, the fake cursor functionality will be used. Otherwise, the fake cursor will stop being used. cursorImage string &lt;optional&gt; If a valid image path is given and \"showCursorImage\" is set to true, the fake cursor functionality will be used with the given image. Otherwise, the fake cursor will stop being used. cursorImageWidth number &lt;optional&gt; 32 Width in pixels of the cursor image. cursorImageHeight number &lt;optional&gt; 32 Height in pixels of the cursor image. hideNormalCursor boolean &lt;optional&gt; true If set to true, hides the system cursor (calls the CB_Mouse.hide function internally). Otherwise, shows the system cursor (calls the CB_Mouse.restore function internally). isSprite boolean &lt;optional&gt; false Defines whether the cursor will be animated (using sprites) or not. If so, the cursorImage must be an image containing sprites horizontally (their individual width is defined by the \"cursorImageWidth\" parameter). Once the last sprite is reached, it returns to the first one automatically and continues to the next one again (without stopping). numberOfFrames number &lt;optional&gt; 1 Number of frames (sprites) being used from the cursor image (\"cursorImage\" parameter). Used when the \"isSprite\" parameter is set to true. framesMs number &lt;optional&gt; 100 Number of milliseconds between each frame (between one sprite and next one). Used when the \"isSprite\" parameter is set to true. divElement Element &lt;optional&gt; CB_Elements.id('CB_fakeCursorImageDiv') The ID of the DIV element that will contain the image of the fake cursor (uses a DOM element with \"CB_fakeCursorImageDiv\" ID by default). imageElement Element &lt;optional&gt; CB_Elements.id('CB_fakeCursorImage') The ID of the IMG element that will contain the fake cursor (uses a DOM element with \"CB_fakeCursorImage\" ID by default). Source: CrossBase/input/CB_Mouse.js, line 1093 To Do: Allow defining an \"onMove\" parameter (a callback) to be able to call the \"move\" method with non-default parameters, etc. × Search results Close "},"CB_Net.html":{"id":"CB_Net.html","title":"Namespace: CB_Net","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Net CB_Net Static class to manage things related to the net. It will return itself if it is tried to be instantiated. Source: CrossBase/net/CB_Net.js, line 8 Namespaces Fetch REST Sockets XHR Methods &lt;static&gt; combineURIParameters() Alias for CB_combineURIParameters. Source: CrossBase/net/CB_Net.js, line 322 See: CB_combineURIParameters &lt;static&gt; combineURLParameters() Alias for CB_Net.combineURIParameters. Source: CrossBase/net/CB_Net.js, line 317 See: CB_Net.combineURIParameters &lt;static&gt; getHashParameters( [URI] [, exclude] [, includeOnly] [, includeIfNotExists] [, trim]) → {string} Gets all the hash parameters (names and their values) from a given URI or from the current URL. For example, if the URI provided is \"http://whatever.com/index.html?parameter1=value1&amp;parameter2=value2#hash_parameter1=hash_value1&amp;hash_parameter2=hash_value2\", it will return \"hash_parameter1=hash_value1&amp;hash_parameter2=hash_value2\" (using the default options). Parameters: Name Type Argument Default Description URI string &lt;optional&gt; window.location.href The URI that we want to work with. If not provided, it will try to use the current URL (by using window.location.href). exclude array &lt;optional&gt; A numeric array containing the name of the parameters that we want to exclude in the returned string. It will exclude them even if they are contained in the given \"includeOnly\" parameter (if any). includeOnly array &lt;optional&gt; A numeric array containing the name of the parameters that we want to include in the returned string. If provided, it will only include these ones to the returned string (unless they are included in the \"exclude\" parameter). includeIfNotExists boolean &lt;optional&gt; false If it is set to true and an array is given as the \"includeOnly\" parameter, it will add the parameters in the \"includeOnly\" array (with empty values) in the returned string even when they did not exist in the original URI provided. trim boolean &lt;optional&gt; true It will use this option when it calls the CB_Net.getURIParameters function internally. Source: CrossBase/net/CB_Net.js, line 216 Returns: An empty string will be returned if no parameters can be found. Type string &lt;static&gt; getHashValue(index [, trim] [, URI]) → {string} Gets the value of a specific hash (string after \"#\") parameter from the current URL or a desired URI. For example, if the URI provided is \"http://whatever.com/index.html?parameter1=value1&amp;parameter2=value2#hash_parameter1=hash_value1&amp;hash_parameter2=hash_value2\" and the index given is \"hash_parameter1\", it will return \"hash_value1\" (using the default options). Parameters: Name Type Argument Default Description index string The name of the parameter whose value we want to get. trim boolean &lt;optional&gt; true It will trim the value (using CB_Net.getParameter internally) before returning it. URI string &lt;optional&gt; window.location.href The URI that we want to work with. If not provided, it will try to use the current URL (by using window.location.href). Source: CrossBase/net/CB_Net.js, line 311 Returns: An empty string will be returned if the value of the given parameter cannot be found. Type string &lt;static&gt; getParameter(index [, trim] [, URI] [, firstDelimiter] [, lastDelimiter] [, concatenator] [, nameValueSeparator]) → {string} Gets the value of a specific URI parameter (query or hash), respecting GET/URL rules by default, from the current URL or a desired one (with the given delimiters). For example, if the URI provided is \"http://whatever.com/index.html?parameter1=value1&amp;parameter2=value2#hash_parameter1=hash_value1&amp;hash_parameter2=hash_value2\" and the index given is \"parameter1\", it will return \"value1\" (using the default options). Parameters: Name Type Argument Default Description index string The name of the parameter whose value we want to get. trim boolean &lt;optional&gt; true It will trim the value (using CB_trim internally) before returning it. URI string &lt;optional&gt; window.location.href The URI that we want to work with. If not provided, it will try to use the current URL (by using window.location.href). firstDelimiter string &lt;optional&gt; '?' The string that indicates where the parameters start. If it is not provided, it will be \"?\" as default. If not provided and \"lastDelimiter\" is not provided either, it will be \"?\" and \"lastDelimiter\" will be \"#\". lastDelimiter string &lt;optional&gt; undefined|'#' The string that indicates where the parameters end. If not provided and \"firstDelimiter\" is provided, it will stop at the end of the given URI. If it is not provided and \"firstDelimiter\" is not provided either, \"firstDelimiter\" will be \"?\" and \"lastDelimiter\" will be \"#\". concatenator string &lt;optional&gt; '&amp;' The string that joints the different parameters. nameValueSeparator string &lt;optional&gt; '=' The string that is the separator for the parameters and their values. Source: CrossBase/net/CB_Net.js, line 236 Returns: An empty string will be returned if the value of the given parameter cannot be found. Type string &lt;static&gt; getURIParameters( [URI] [, exclude] [, includeOnly] [, includeIfNotExists] [, trim] [, firstDelimiter] [, lastDelimiter] [, concatenator] [, nameValueSeparator]) → {string} Gets all the \"GET\" (query) parameters (names and their values) from a given URI or from the current URL. For example, if the URI provided is \"http://whatever.com/index.html?parameter1=value1&amp;parameter2=value2#hash_parameter1=hash_value1&amp;hash_parameter2=hash_value2\", it will return \"parameter1=value1&amp;parameter2=value2\" (using the default options). Parameters: Name Type Argument Default Description URI string &lt;optional&gt; window.location.href The URI that we want to work with. If not provided, it will try to use the current URL (by using window.location.href). exclude array &lt;optional&gt; A numeric array containing the name of the parameters that we want to exclude in the returned string. It will exclude them even if they are contained in the given \"includeOnly\" parameter (if any). includeOnly array &lt;optional&gt; A numeric array containing the name of the parameters that we want to include in the returned string. If provided, it will only include these ones to the returned string (unless they are included in the \"exclude\" parameter). includeIfNotExists boolean &lt;optional&gt; false If it is set to true and an array is given as the \"includeOnly\" parameter, it will add the parameters in the \"includeOnly\" array (with empty values) in the returned string even when they did not exist in the original URI provided. trim boolean &lt;optional&gt; true Defines whether we want to trim the spaces around the values or not. firstDelimiter string &lt;optional&gt; '?' The string that indicates where the parameters start. If it is not provided, it will be \"?\" as default. If not provided and \"lastDelimiter\" is not provided either, it will be \"?\" and \"lastDelimiter\" will be \"#\". lastDelimiter string &lt;optional&gt; undefined|'#' The string that indicates where the parameters end. If not provided and \"firstDelimiter\" is provided, it will stop at the end of the given URI. If it is not provided and \"firstDelimiter\" is not provided either, \"firstDelimiter\" will be \"?\" and \"lastDelimiter\" will be \"#\". concatenator string &lt;optional&gt; '&amp;' The string that joints the different parameters. nameValueSeparator string &lt;optional&gt; '=' The string that is the separator for the parameters and their values. Source: CrossBase/net/CB_Net.js, line 123 Returns: An empty string will be returned if no parameters can be found. Type string &lt;static&gt; getURIValue(index [, trim] [, URI]) → {string} Gets the value of a specific URI \"GET\" parameter (query) from the current URL or a desired URI. For example, if the URI provided is \"http://whatever.com/index.html?parameter1=value1&amp;parameter2=value2#hash_parameter1=hash_value1&amp;hash_parameter2=hash_value2\" and the index given is \"parameter1\", it will return \"value1\" (using the default options). Parameters: Name Type Argument Default Description index string The name of the parameter whose value we want to get. trim boolean &lt;optional&gt; true It will trim the value (using CB_Net.getParameter internally) before returning it. URI string &lt;optional&gt; window.location.href The URI that we want to work with. If not provided, it will try to use the current URL (by using window.location.href). Source: CrossBase/net/CB_Net.js, line 294 Returns: An empty string will be returned if the value of the given parameter cannot be found. Type string &lt;static&gt; URIDecode(URI) → {string} Encodes a given URI. Uses the native decodeURI function internally if available or fallbacks to the native unescape function otherwise. Parameters: Name Type Description URI string | number The URI that we want to decode. Normally, it should be either a string or a number. Source: CrossBase/net/CB_Net.js, line 100 To Do: Think about using another thing since unescape maybe is not a good fallback. Probably a polyfill to simulate the decodeURI function. Returns: Type string &lt;static&gt; URIEncode(URI) → {string} Encodes a given URI. Uses the native encodeURI function internally if available or fallbacks to the native escape function otherwise. Parameters: Name Type Description URI string | number The URI that we want to encode. Normally, it should be either a string or a number. Source: CrossBase/net/CB_Net.js, line 81 To Do: Think about using another thing since escape maybe is not a good fallback. Probably a polyfill to simulate the encodeURI function. Returns: Type string &lt;static&gt; URIValueDecode(value) → {string} Decodes a given URI value. Uses the native decodeURIComponent function internally if available or fallbacks to the native unescape function otherwise. Parameters: Name Type Description value string | number The value that we want to decode. Normally, it should be either a string or a number. Source: CrossBase/net/CB_Net.js, line 62 To Do: Think about using another thing since unescape maybe is not a good fallback. Probably a polyfill to simulate the decodeURIComponent function. Returns: Type string &lt;static&gt; URIValueEncode(value) → {string} Encodes a given URI value. Uses the native encodeURIComponent function internally if available or fallbacks to the native escape function otherwise. Parameters: Name Type Description value string | number The value that we want to encode. Normally, it should be either a string or a number. Source: CrossBase/net/CB_Net.js, line 43 To Do: Think about using another thing since escape maybe is not a good fallback. Probably a polyfill to simulate the encodeURIComponent function. Returns: Type string &lt;static&gt; URLDecode() Alias for CB_Net.URIDecode. Source: CrossBase/net/CB_Net.js, line 88 See: CB_Net.URIDecode &lt;static&gt; URLEncode() Alias for CB_Net.URIEncode. Source: CrossBase/net/CB_Net.js, line 69 See: CB_Net.URIEncode &lt;static&gt; URLValueDecode() Alias for CB_Net.URIValueDecode. Source: CrossBase/net/CB_Net.js, line 50 See: CB_Net.URIValueDecode &lt;static&gt; URLValueEncode() Alias for CB_Net.URIValueEncode. Source: CrossBase/net/CB_Net.js, line 31 See: CB_Net.URIValueEncode × Search results Close "},"CB_Net.Fetch.html":{"id":"CB_Net.Fetch.html","title":"Namespace: Fetch","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: Fetch CB_Net. Fetch Static class to manage things related to the Fetch API. It will return itself if it is tried to be instantiated. Source: CrossBase/net/fetch/CB_Net_Fetch.js, line 15 Methods &lt;static&gt; get(resource [, init]) → {Promise} Function that points to the fetch method. If the Fetch API is not supported natively, the fetch function will be a polyfill. Parameters: Name Type Argument Description resource string | Request First parameter of the fetch method. init Object &lt;optional&gt; Second parameter of the fetch method. Source: CrossBase/net/fetch/CB_Net_Fetch.js, line 41 Returns: Type Promise × Search results Close "},"CB_Net.REST.html":{"id":"CB_Net.REST.html","title":"Namespace: REST","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: REST CB_Net. REST Static class to manage REST services and related. It will return itself if it is tried to be instantiated. Source: CrossBase/net/REST/CB_Net_REST.js, line 14 To Do: Think about accepting an onAbort function as option (with also default and permanent). Members &lt;static&gt; actions :Object List of REST actions. Each property name is the name of the action and its value is a CB_Net.REST.actionProcess_ACTIONS object. Used by the CB_Net.REST.actionProcess function. Type: Object Default Value: {} Source: CrossBase/net/REST/CB_Net_REST.js, line 414 &lt;static&gt; allowedSuccessStatuses_DEFAULT :array Default \"allowedSuccessStatuses\", containing the statuses to considerer a successful REST action (must be a numeric array of integers). Used by the CB_Net.REST.actionProcess function. Type: array Default Value: [200,201,206] Source: CrossBase/net/REST/CB_Net_REST.js, line 272 &lt;static&gt; allowedSuccessStatuses_PERMANENT :array Permanent values for the \"allowedSuccessStatuses\" parameter, containing the statuses to considerer a successful REST action (must be a numeric array of integers). Used by the CB_Net.REST.actionProcess function. This is permanent for each REST action. Type: array Default Value: [] Source: CrossBase/net/REST/CB_Net_REST.js, line 263 &lt;static&gt; avoidProxy_DEFAULT :boolean Default value when the \"avoidProxy\" parameter is not available. Used by the CB_Net.REST.actionProcess function. NOTE: Edit the \"CB_proxy.config.php\" file to configure the default proxy (set by default in the value of the CB_Configuration.CrossBase.CB_Net_XHR_PROXY_URL property). Apart from configuring it, adding some security measures is highly recommended. Have in mind that, for safety reasons, the default proxy only allows to request the URLs defined in the \"$allowedURLs\" array in the \"CB_proxy.config.php\" file. Just edit it to allow other URLs. Type: boolean Source: CrossBase/net/REST/CB_Net_REST.js, line 37 &lt;static&gt; callbackBefore_DEFAULT :CB_Net.REST.actionProcess_CALLBACK_BEFORE Default \"callbackBefore\", containing a callback function before performing each REST action returning a boolean (to decide whether to do it or not). The function assigned by default returns true. Used by the CB_Net.REST.actionProcess function. Type: CB_Net.REST.actionProcess_CALLBACK_BEFORE Source: CrossBase/net/REST/CB_Net_REST.js, line 303 &lt;static&gt; callbackBefore_PERMANENT :CB_Net.REST.actionProcess_CALLBACK_BEFORE Permanent callback function before performing each REST action returning a boolean (to decide whether to do it or not). Executed before the default or the set \"callbackBefore\" function (if any). The function assigned by default returns true. Used by the CB_Net.REST.actionProcess function. This is permanent for each REST action. Type: CB_Net.REST.actionProcess_CALLBACK_BEFORE Source: CrossBase/net/REST/CB_Net_REST.js, line 290 &lt;static&gt; callbackError_DEFAULT :CB_Net.REST.actionProcess_CALLBACK_ERROR Default \"callbackError\", containing a callback function when an error happens processing the REST action. Used by the CB_Net.REST.actionProcess function. Type: CB_Net.REST.actionProcess_CALLBACK_ERROR Source: CrossBase/net/REST/CB_Net_REST.js, line 375 &lt;static&gt; callbackError_PERMANENT :CB_Net.REST.actionProcess_CALLBACK_ERROR Permanent callback function when an error happens processing any REST action. Used by the CB_Net.REST.actionProcess function. Executed before the default or the set \"callbackError\" function (if any). This is permanent for each REST action. Type: CB_Net.REST.actionProcess_CALLBACK_ERROR Source: CrossBase/net/REST/CB_Net_REST.js, line 362 &lt;static&gt; callbackOk_DEFAULT :CB_Net.REST.actionProcess_CALLBACK_OK Default \"callbackOk\", containing a callback function when the REST action has been successful. Used by the CB_Net.REST.actionProcess function. Type: CB_Net.REST.actionProcess_CALLBACK_OK Source: CrossBase/net/REST/CB_Net_REST.js, line 340 &lt;static&gt; callbackOk_PERMANENT :CB_Net.REST.actionProcess_CALLBACK_OK Permanent callback function when each REST action has been successful. Used by the CB_Net.REST.actionProcess function. Executed before the default or the set \"callbackOk\" function (if any). This is permanent for each REST action. Type: CB_Net.REST.actionProcess_CALLBACK_OK Source: CrossBase/net/REST/CB_Net_REST.js, line 327 &lt;static&gt; data_DEFAULT :CB_Net.REST.actionProcess_DATA Default \"data\" for REST actions (must return a string in URL/GET parameters format or a JSON format string). The function assigned by default returns an empty string (\"\"). Used by the CB_Net.REST.actionProcess function. The values returned by all functions that are mean to return the data should always return the same type of data (all strinngs or all objects) since CB_Net.REST.actionProcess will use the CB_combineAutomatically function to combine them. NOTE: remember to use CB_Net.URLValueEncode if needed. Type: CB_Net.REST.actionProcess_DATA Source: CrossBase/net/REST/CB_Net_REST.js, line 250 &lt;static&gt; data_PERMANENT :CB_Net.REST.actionProcess_DATA Permanent function (must return a string in URL/GET parameters format or a JSON format string) to execute the same way as the \"data\" parameter. The function assigned by default returns an empty string (\"\"). Used by the CB_Net.REST.actionProcess function. The values returned by all functions that are mean to return the data should always return the same type of data (all strinngs or all objects) since CB_Net.REST.actionProcess will use the CB_combineAutomatically function to combine them. This is permanent for each REST action. NOTE: remember to use CB_Net.URLValueEncode if needed. Type: CB_Net.REST.actionProcess_DATA Source: CrossBase/net/REST/CB_Net_REST.js, line 237 &lt;static&gt; dataURL_DEFAULT :CB_Net.REST.actionProcess_DATA_URL Default \"dataURL\" for REST actions (must return a string in URL/GET parameters format). The function assigned by default returns an empty string (\"\"). Used by the CB_Net.REST.actionProcess function. NOTE: remember to use CB_Net.URLValueEncode if needed. Type: CB_Net.REST.actionProcess_DATA_URL Source: CrossBase/net/REST/CB_Net_REST.js, line 215 &lt;static&gt; dataURL_PERMANENT :CB_Net.REST.actionProcess_DATA_URL Permanent function (must return a string in URL/GET parameters format) to execute the same way as the \"dataURL\" parameter. The function assigned by default returns an empty string (\"\"). Used by the CB_Net.REST.actionProcess function. The returning data will be placed in the beginning of the URL, followed by the rest of the \"dataURL\" desired (if any). NOTE: remember to use CB_Net.URLValueEncode if needed. This is permanent for each REST action. Type: CB_Net.REST.actionProcess_DATA_URL Source: CrossBase/net/REST/CB_Net_REST.js, line 202 &lt;static&gt; forceJSON_DEFAULT :boolean Tells whether to force JSON response by default or not. Used by the CB_Net.REST.actionProcess function when the REST action does not provided it and it is not null, as the \"forceJSON\" option. Type: boolean Default Value: true Source: CrossBase/net/REST/CB_Net_REST.js, line 99 &lt;static&gt; getHeaders_DEFAULT :boolean Tells whether get response HTTP headers by default or not. Used by the CB_Net.REST.actionProcess function when the REST action does not provided it and it is not null, as the \"getHeaders\" option. Type: boolean Source: CrossBase/net/REST/CB_Net_REST.js, line 108 &lt;static&gt; getHeadersOneDimension_DEFAULT :boolean Tells whether to get response HTTP headers in one-dimension array by default or not (needs \"getHeaders\" set to true). Used by the CB_Net.REST.actionProcess function when the REST action does not provided it and it is not null, as the \"getHeadersOneDimension\" option. Type: boolean Source: CrossBase/net/REST/CB_Net_REST.js, line 117 &lt;static&gt; getHeadersOneDimensionValues_DEFAULT :boolean Tells whether to get response HTTP headers values in one-dimension (just one value per key) by default or not (needs \"getHeaders\" set to true). Used by the CB_Net.REST.actionProcess function when the REST action does not provided it and it is not null, as the \"getHeadersOneDimensionValues\" option. Type: boolean Source: CrossBase/net/REST/CB_Net_REST.js, line 126 &lt;static&gt; headers_DEFAULT :CB_Net.REST.actionProcess_HEADERS Default \"headers\" for REST actions (must be a function returning a CB_Net.XHR.HEADERS object with the HTTP headers). The function assigned by default returns { \"Content-Type\" : \"application/x-www-form-urlencoded; charset=UTF-8\" }. Used by the CB_Net.REST.actionProcess function. Type: CB_Net.REST.actionProcess_HEADERS Source: CrossBase/net/REST/CB_Net_REST.js, line 160 &lt;static&gt; headers_PERMANENT :CB_Net.REST.actionProcess_HEADERS Permanent function (must be a function returning a CB_Net.XHR.HEADERS object with the HTTP headers) to execute the same way as the \"headers\" parameter. The function assigned by default returns { \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" }. Used by the CB_Net.REST.actionProcess function. This is permanent for each REST action. Type: CB_Net.REST.actionProcess_HEADERS Source: CrossBase/net/REST/CB_Net_REST.js, line 144 &lt;static&gt; method_DEFAULT :string Default \"method\" for REST actions. Used by the CB_Net.REST.actionProcess function. Type: string Default Value: GET Source: CrossBase/net/REST/CB_Net_REST.js, line 46 &lt;static&gt; responseType_DEFAULT :string Default \"responseType\" for REST actions when it is not provided and it is not null. Used by the CB_Net.REST.actionProcess function. Type: string Default Value: text Source: CrossBase/net/REST/CB_Net_REST.js, line 55 &lt;static&gt; routeWildcardData_DEFAULT :CB_Net.REST.actionProcess_ROUTE_WILDCARD_DATA Default \"routeWildcardData\" for REST actions (must be a function returning a JSON object or null if we do not want to modify the route). The function assigned by default returns null. Used by the CB_Net.REST.actionProcess function. Type: CB_Net.REST.actionProcess_ROUTE_WILDCARD_DATA Source: CrossBase/net/REST/CB_Net_REST.js, line 86 &lt;static&gt; routeWildcardData_PERMANENT :CB_Net.REST.actionProcess_ROUTE_WILDCARD_DATA Permanent function (must return a JSON object or null if we do not want to modify it) to execute the same way as the \"routeWildcardData\" parameter (if other \"routeWildcardData\" are provided or set, they will be executed before this one). The function assigned by default returns null. Used by the CB_Net.REST.actionProcess function. This is permanent for each REST action. Type: CB_Net.REST.actionProcess_ROUTE_WILDCARD_DATA Source: CrossBase/net/REST/CB_Net_REST.js, line 73 &lt;static&gt; SERVER_URL_DEFAULT :string Defines the URL for the default REST server to use when the \"serverURL\" parameter is not available. Used by the CB_Net.XHR.callREST function as the default \"serverURL\" parameter. Type: string Default Value: http://localhost/CrossBrowdy/tests/net/fake_rest_server/index.php Source: CrossBase/net/REST/CB_Net_REST.js, line 25 &lt;static&gt; transparentHeaders_DEFAULT :boolean Tells whether get HTTP headers transparently from the server by default or not. Used by the CB_Net.REST.actionProcess function when the REST action does not provided it and it is not null, as the \"transparentHeaders\" option. Type: boolean Default Value: true Source: CrossBase/net/REST/CB_Net_REST.js, line 184 &lt;static&gt; transparentStatus_DEFAULT :boolean Tells whether get status transparently from the server by default or not. Used by the CB_Net.REST.actionProcess function when the REST action does not provided it and it is not null, as the \"transparentStatus\" option. Type: boolean Default Value: true Source: CrossBase/net/REST/CB_Net_REST.js, line 175 Methods &lt;static&gt; actionAbort(XHR) → {boolean} Cancels a REST action (by its AJAX/XHR request associated) by executing the \"abort\" method of the given XHR object (if available) and sets its \"aborted\" property to true if succeeds. When a REST action is aborted, the callbackOk functions associated (if any) will not be called (unless they have been called already). Parameters: Name Type Description XHR Object The XHR object that we want to abort. Source: CrossBase/net/REST/CB_Net_REST.js, line 602 Returns: Returns true if the \"abort\" method of the given XHR object could be called and the \"aborted\" property was set to true. Otherwise, returns false. Type boolean &lt;static&gt; actionAbortCancel(XHR) → {boolean} Tries to revert the abortion of a REST action (by its AJAX/XHR request associated) by setting the \"aborted\" property of the given XHR object to false. If this function is called before the \"callbackOk\" functions associated to the REST action (if any) are called, they could finally be called perhaps (depending on each case, could be different). Have in mind that, after calling CB_Net.REST.actionAbort, the \"abort\" method of the XHR object was probably called already (if available). Parameters: Name Type Description XHR Object The XHR object whose abortion we want to cancel. Source: CrossBase/net/REST/CB_Net_REST.js, line 615 Returns: Returns true if the \"aborted\" property was set to false. Otherwise, returns false. Type boolean &lt;static&gt; actionIsAborted(XHR) → {boolean} Returns whether a REST action is aborted or not (by its AJAX/XHR request associated). Parameters: Name Type Description XHR Object The XHR object that we want to check. Source: CrossBase/net/REST/CB_Net_REST.js, line 628 Returns: Returns true if the \"aborted\" property is set to true. Otherwise, returns false. Type boolean &lt;static&gt; actionProcess(actionName [, additionalData] [, XHR] [, serverURL] [, avoidProxy]) → {Object|null} Processes a desired REST action (which must be previously defined in the CB_Net.REST.actions object) by its name. NOTE: Edit the \"CB_proxy.config.php\" file to configure the default proxy (set by default in the value of the CB_Configuration.CrossBase.CB_Net_XHR_PROXY_URL property). Apart from configuring it, adding some security measures is highly recommended. Have in mind that, for safety reasons, the default proxy only allows to request the URLs defined in the \"$allowedURLs\" array in the \"CB_proxy.config.php\" file. Just edit it to allow other URLs. Parameters: Name Type Argument Description actionName string The name of the REST action that we want to perform. It should be the name of an index defined in the CB_Net.REST.actions object whose value should be a CB_Net.REST.actionProcess_ACTIONS object. additionalData * &lt;optional&gt; Any additional data desired. It will be passed as a parameter when different callbacks are called internally, as their \"additionalData\" parameter. XHR Object &lt;optional&gt; Used for the \"XHR\" parameter of the CB_Net.XHR.callREST function when it is called internally. serverURL string &lt;optional&gt; Used for the \"serverURL\" parameter of the CB_Net.XHR.callREST function when it is called internally. If provided, the value defined in the \"serverURL\" parameter of the REST action being performed (if any) will be ignored. avoidProxy boolean &lt;optional&gt; Used for the \"avoidProxy\" parameter of the CB_Net.XHR.callREST function when it is called internally. If provided, the value defined in the \"avoidProxy\" parameter of the REST action being performed (if any) and the default one defined in CB_Net.REST.avoidProxy_DEFAULT (if any) will be both ignored. Source: CrossBase/net/REST/CB_Net_REST.js, line 445 Returns: Returns null if the CB_Net.XHR.callREST function is not called at all (because XHR is not supported or the REST action object cannot be found or the route is not well defined or the \"callbackBefore\" returns false, etc.). Otherwise, returns the same that the CB_Net.XHR.callREST function returns (called internally). Type Object | null Type Definitions actionProcess_ACTIONS Object that represents a REST action. Type: Object Properties: Name Type Argument Default Description route string The REST route (path). Belongs to the \"route\" parameter of the CB_Net.XHR.callREST function when it is called internally. It is mandatory. callbackBefore CB_Net.REST.actionProcess_CALLBACK_BEFORE &lt;optional&gt; CB_Net.REST.callbackBefore_DEFAULT Callback run before performing the REST action which will decide whether to continue with it or not. avoidProxy boolean &lt;optional&gt; CB_Net.REST.avoidProxy_DEFAULT Belongs to the \"avoidProxy\" parameter of the CB_Net.XHR.callREST function when it is called internally. routeWildcardData CB_Net.REST.actionProcess_ROUTE_WILDCARD_DATA &lt;optional&gt; CB_Net.REST.routeWildcardData_DEFAULT Callback returning an object that will be used for parsing the REST route. The object returned should follow the same rules as the \"JSONObject\" parameter of the CB_renderString function. dataURL CB_Net.REST.actionProcess_DATA_URL &lt;optional&gt; CB_Net.REST.dataURL_DEFAULT Belongs to the \"dataURL\" parameter of the CB_Net.XHR.callREST function when it is called internally. data CB_Net.REST.actionProcess_DATA &lt;optional&gt; CB_Net.REST.data_DEFAULT Belongs to the \"data\" parameter of the CB_Net.XHR.callREST function when it is called internally. headers CB_Net.REST.actionProcess_HEADERS &lt;optional&gt; CB_Net.REST.headers_DEFAULT Belongs to the \"headers\" parameter of the CB_Net.XHR.callREST function when it is called internally. allowedSuccessStatuses array &lt;optional&gt; CB_Net.REST.allowedSuccessStatuses_DEFAULT Belongs to the \"allowedSuccessStatuses\" parameter of the CB_Net.XHR.callREST function when it is called internally. callbackError CB_Net.REST.actionProcess_CALLBACK_ERROR &lt;optional&gt; CB_Net.REST.callbackError_DEFAULT Callback run when the REST action has not been performed successfully. callbackOk CB_Net.REST.actionProcess_CALLBACK_OK &lt;optional&gt; CB_Net.REST.callbackOk_DEFAULT Callback run when the REST action has been performed successfully. serverURL string &lt;optional&gt; CB_Net.REST.SERVER_URL_DEFAULT Belongs to the \"serverURL\" parameter of the CB_Net.XHR.callREST function when it is called internally. method string &lt;optional&gt; CB_Net.REST.method_DEFAULT Belongs to the \"method\" parameter of the CB_Net.XHR.callREST function when it is called internally. responseType string &lt;optional&gt; CB_Net.REST.responseType_DEFAULT Belongs to the \"responseType\" parameter of the CB_Net.XHR.callREST function when it is called internally and will be sent even it is null. If it is undefined, it will use the value of CB_Net.REST.responseType_DEFAULT instead. forceJSON boolean &lt;optional&gt; CB_Net.REST.forceJSON_DEFAULT Belongs to the \"forceJSON\" parameter of the CB_Net.XHR.callREST function when it is called internally and will be sent even it is null. If it is undefined, it will use the value of CB_Net.REST.forceJSON_DEFAULT instead. getHeaders boolean &lt;optional&gt; CB_Net.REST.getHeaders_DEFAULT Belongs to the \"getHeaders\" parameter of the CB_Net.XHR.callREST function when it is called internally and will be sent even it is null. If it is undefined, it will use the value of CB_Net.REST.getHeaders_DEFAULT instead. getHeadersOneDimension boolean &lt;optional&gt; CB_Net.REST.getHeadersOneDimension_DEFAULT Belongs to the \"getHeadersOneDimension\" parameter of the CB_Net.XHR.callREST function when it is called internally and will be sent even it is null. If it is undefined, it will use the value of CB_Net.REST.getHeadersOneDimension_DEFAULT instead. getHeadersOneDimensionValues boolean &lt;optional&gt; CB_Net.REST.getHeadersOneDimensionValues_DEFAULT Belongs to the \"getHeadersOneDimensionValues\" parameter of the CB_Net.XHR.callREST function when it is called internally and will be sent even it is null. If it is undefined, it will use the value of CB_Net.REST.getHeadersOneDimensionValues_DEFAULT instead. transparentStatus boolean &lt;optional&gt; CB_Net.REST.transparentStatus_DEFAULT Belongs to the \"transparentStatus\" parameter of the CB_Net.XHR.callREST function when it is called internally and will be sent even it is null. If it is undefined, it will use the value of CB_Net.REST.transparentStatus_DEFAULT instead. transparentHeaders boolean &lt;optional&gt; CB_Net.REST.transparentHeaders_DEFAULT Belongs to the \"transparentHeaders\" parameter of the CB_Net.XHR.callREST function when it is called internally and will be sent even it is null. If it is undefined, it will use the value of CB_Net.REST.transparentHeaders_DEFAULT instead. Source: CrossBase/net/REST/CB_Net_REST.js, line 382 actionProcess_CALLBACK_BEFORE(actionName, additionalData) → {boolean} Callback that will be run before performing a REST action and must return a boolean defining whether we want to continue performing the action (returning true) or not (returning false). Parameters: Name Type Description actionName string The name of the REST action being performed. It should be the name of an index defined in the CB_Net.REST.actions object whose value should be a CB_Net.REST.actionProcess_ACTIONS object. additionalData * Any additional data associated to the REST action being performed (belongs to the \"additionalData\" parameter used when the CB_Net.REST.actionProcess function was called). Source: CrossBase/net/REST/CB_Net_REST.js, line 275 Returns: It should return true in the case that we want to continue performing the current REST action or false otherwise. Type boolean actionProcess_CALLBACK_ERROR(actionName [, XHR], additionalData) Callback that will be run when the REST action has been performed successfully. Parameters: Name Type Argument Description actionName string The name of the REST action being performed. It should be the name of an index defined in the CB_Net.REST.actions object whose value should be a CB_Net.REST.actionProcess_ACTIONS object. XHR Object &lt;optional&gt; The XHR object that has been used to perform the REST action. additionalData * Any additional data associated to the REST action being performed (belongs to the \"additionalData\" parameter used when the CB_Net.REST.actionProcess function was called). Source: CrossBase/net/REST/CB_Net_REST.js, line 347 actionProcess_CALLBACK_OK(actionName [, XHR], callbackError, additionalData) Callback that will be run when the REST action has been performed successfully. Parameters: Name Type Argument Description actionName string The name of the REST action being performed. It should be the name of an index defined in the CB_Net.REST.actions object whose value should be a CB_Net.REST.actionProcess_ACTIONS object. XHR Object &lt;optional&gt; The XHR object that has been used to perform the REST action. callbackError CB_Net.REST.actionProcess_CALLBACK_ERROR The error callback function associated to the REST action being performed, just in case we want to call it. additionalData * Any additional data associated to the REST action being performed (belongs to the \"additionalData\" parameter used when the CB_Net.REST.actionProcess function was called). Source: CrossBase/net/REST/CB_Net_REST.js, line 311 actionProcess_DATA(actionName, additionalData) → {string|Object} Callback returning the data (string or object) which will be used as the \"data\" parameter when the CB_Net.XHR.callREST function is called internally by CB_Net.REST.actionProcess. The values returned by all functions that are mean to return the data should always return the same type of data (all strinngs or all objects) since CB_Net.REST.actionProcess will use the CB_combineAutomatically function to combine them. Parameters: Name Type Description actionName string The name of the REST action being performed. It should be the name of an index defined in the CB_Net.REST.actions object whose value should be a CB_Net.REST.actionProcess_ACTIONS object. additionalData * Any additional data associated to the REST action being performed (belongs to the \"additionalData\" parameter used when the CB_Net.REST.actionProcess function was called). Source: CrossBase/net/REST/CB_Net_REST.js, line 222 Returns: It should return a string or object containing the data. Return null or an empty string (recommended) in the case that we do not want to add anything. The value returned (if any) will be used as the \"data\" parameter of the CB_Net.XHR.callREST function when it is called by CB_Net.REST.actionProcess internally. Type string | Object actionProcess_DATA_URL(actionName, additionalData) → {string} Callback returning a string containing the URL (GET) data which will be used as the \"dataURL\" parameter when the CB_Net.XHR.callREST function is called internally by CB_Net.REST.actionProcess. Parameters: Name Type Description actionName string The name of the REST action being performed. It should be the name of an index defined in the CB_Net.REST.actions object whose value should be a CB_Net.REST.actionProcess_ACTIONS object. additionalData * Any additional data associated to the REST action being performed (belongs to the \"additionalData\" parameter used when the CB_Net.REST.actionProcess function was called). Source: CrossBase/net/REST/CB_Net_REST.js, line 187 Returns: It should return a string containing the URL (GET) data. Return an empty string in the case that we do not want to add anything. The string returned (if any) will be used as the \"dataURL\" parameter of the CB_Net.XHR.callREST function when it is called by CB_Net.REST.actionProcess internally. Type string actionProcess_HEADERS(actionName, additionalData) → {CB_Net.XHR.HEADERS|null} Callback returning an object containing the HTTP headers which will be used as the \"headers\" parameter when the CB_Net.XHR.callREST function is called internally by CB_Net.REST.actionProcess. Parameters: Name Type Description actionName string The name of the REST action being performed. It should be the name of an index defined in the CB_Net.REST.actions object whose value should be a CB_Net.REST.actionProcess_ACTIONS object. additionalData * Any additional data associated to the REST action being performed (belongs to the \"additionalData\" parameter used when the CB_Net.REST.actionProcess function was called). Source: CrossBase/net/REST/CB_Net_REST.js, line 129 Returns: It should return an object containing the HTTP headers. Return null in the case that we do not want to add anything. The object returned (if any) will be used as the \"headers\" parameter of the CB_Net.XHR.callREST function when it is called by CB_Net.REST.actionProcess internally. Type CB_Net.XHR.HEADERS | null actionProcess_ROUTE_WILDCARD_DATA(actionName, additionalData) → {Object|null} Callback returning an object that will be used for parsing the REST route. The object returned should follow the same rules as the \"JSONObject\" parameter of the CB_renderString function. Parameters: Name Type Description actionName string The name of the REST action being performed. It should be the name of an index defined in the CB_Net.REST.actions object whose value should be a CB_Net.REST.actionProcess_ACTIONS object. additionalData * Any additional data associated to the REST action being performed (belongs to the \"additionalData\" parameter used when the CB_Net.REST.actionProcess function was called). Source: CrossBase/net/REST/CB_Net_REST.js, line 58 Returns: It should return an object containing the wildcards that will be used to parse the REST route of the action being performed. Return null in the case that we do not want to modify anything. The object returned (if any) will be used as the \"JSONObject\" parameter of the CB_renderString function (the first parameter will be the route which should be a string) when it is called by CB_Net.REST.actionProcess internally. Type Object | null × Search results Close "},"CB_Net.Sockets.html":{"id":"CB_Net.Sockets.html","title":"Namespace: Sockets","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: Sockets CB_Net. Sockets Static class to manage sockets and related. It will return itself if it is tried to be instantiated. It uses SockJS-client. Source: CrossBase/net/sockets/CB_Net_Sockets.js, line 14 Namespaces SockJS × Search results Close "},"CB_Net.Sockets.SockJS.html":{"id":"CB_Net.Sockets.SockJS.html","title":"Namespace: SockJS","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: SockJS CB_Net.Sockets. SockJS Property that contains the functions and properties related with the SockJS client library. Source: CrossBase/net/sockets/CB_Net_Sockets.js, line 18 Members &lt;static, readonly&gt; websocketLast :Object|null Keeps the last SockJS created. Type: Object | null Source: CrossBase/net/sockets/CB_Net_Sockets.js, line 31 Methods &lt;static&gt; close( [websocket] [, onError]) → {undefined|false} Tries to close the websockets connection. Using the SockJS client library internally. Parameters: Name Type Argument Default Description websocket function &lt;optional&gt; CB_Net.Sockets.SockJS.websocketLast The SockJS object that we want to use. If not provided, it will try to use the last one created (if any) which is stored in CB_Net.Sockets.SockJS.websocketLast. onError function &lt;optional&gt; Function for the event \"onerror\" used by the SockJS object. If provided, it will replace the previous one (if any). Following the same rules as in the SockJS client library documentation. Source: CrossBase/net/sockets/CB_Net_Sockets.js, line 135 Returns: Returns undefined (the same as the \"close\" function of the SockJS object) if the SockJS has been used or false otherwise. Type undefined | false &lt;static&gt; listen(serverURL [, onOpen] [, onClose] [, onMessage] [, onError] [, options] [, protocols]) → {Object|null} Creates the websockets object and sets the listeners. Using the SockJS client library internally. Parameters: Name Type Argument Description serverURL string The URL of the SockJS server. This will be used as the first parameter when it calls the constructor of SockJS internally. Following the same rules as in the SockJS client library documentation (the parameter is called \"url\"). onOpen function &lt;optional&gt; Function for the event \"onopen\" used by the SockJS object. Following the same rules as in the SockJS client library documentation. onClose function &lt;optional&gt; Function for the event \"onclose\" used by the SockJS object. Following the same rules as in the SockJS client library documentation. onMessage function &lt;optional&gt; Function for the event \"onmessage\" used by the SockJS object. Following the same rules as in the SockJS client library documentation. onError function &lt;optional&gt; Function for the event \"onerror\" used by the SockJS object. Following the same rules as in the SockJS client library documentation. options Object &lt;optional&gt; The desired options for the SockJS object. This will be used as the third parameter when it calls the constructor of SockJS internally. Following the same rules as in the SockJS client library documentation (the parameter is called \"options\"). protocols array &lt;optional&gt; This will be used as the second parameter when it calls the constructor of SockJS internally. Following the same rules as in the SockJS client library documentation (the parameter is called \"_reserved\"). Source: CrossBase/net/sockets/CB_Net_Sockets.js, line 65 Returns: Returns a SockJS object. Read the SockJS client library documentation for more information. In the case of error, returns null. Type Object | null &lt;static&gt; open() Alias for CB_Net.Sockets.SockJS.listen. Source: CrossBase/net/sockets/CB_Net_Sockets.js, line 48 See: CB_Net.Sockets.SockJS.listen &lt;static&gt; send(message [, websocket] [, onError]) → {undefined|false} Sends a websockets message. Using the SockJS client library internally. Parameters: Name Type Argument Default Description message string The message that we want to send. This will be used as the first and unique parameter when it calls the \"send\" function of the SockJS object internally. Following the same rules as in the SockJS client library documentation. websocket function &lt;optional&gt; CB_Net.Sockets.SockJS.websocketLast The SockJS object that we want to use. If not provided, it will try to use the last one created (if any) which is stored in CB_Net.Sockets.SockJS.websocketLast. onError function &lt;optional&gt; Function for the event \"onerror\" used by the SockJS object. If provided, it will replace the previous one (if any). Following the same rules as in the SockJS client library documentation. Source: CrossBase/net/sockets/CB_Net_Sockets.js, line 102 Returns: Returns undefined (the same as the \"send\" function of the SockJS object) if the SockJS has been used or false otherwise. Type undefined | false × Search results Close "},"CB_Net.XHR.html":{"id":"CB_Net.XHR.html","title":"Namespace: XHR","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: XHR CB_Net. XHR Static class to manage XMLHttpRequest (XHR, AJAX) and related. It will return itself if it is tried to be instantiated. Source: CrossBase/net/XHR/CB_Net_XHR.js, line 15 To Do: Think about providing an easy way to abort XHR (AJAX) calls. Methods &lt;static&gt; call(URL [, method] [, data] [, headers] [, responseType] [, mimeType] [, callbackFunction] [, callbackFunctionOK] [, callbackFunctionError] [, allowedSuccessStatuses] [, asynchronous] [, XHR]) → {Object|null} Performs an AJAX (XHR) call. Parameters: Name Type Argument Default Description URL string The URL that we want to call. It can also contain URL (GET) parameters. method string &lt;optional&gt; 'POST' The HTTP method that will be used to perform the call (GET, POST, PUT, DELETE, etc.). data string | Object &lt;optional&gt; The data that we want to send. If a string is given and \"GET\" method is being used, it will assume they are GET (URL) parameters and will be attached at the end of the URL given. If something which is not a string is given, it will assume it is a JSON object and will try to convert it into a string (using the JSON.stringify function internally) before sending it. headers CB_Net.XHR.HEADERS &lt;optional&gt; Object containing the HTTP header names and their values that we want to send (used internally by the setRequestHeader method of the XHR object). responseType string &lt;optional&gt; If provided, it will be used for the responseType property of the XHR object (if available). mimeType string &lt;optional&gt; MIME type that will be used to override the default one returned by the server. Only used when the client supports the overrideMimeType method of the XHR object. callbackFunction function &lt;optional&gt; Function that will be used for the onreadystatechange property of the XHR object. The unique parameter that it will receive is the XHR object used by the request. If provided, the \"callbackFunctionOK\" and \"callbackFunctionError\" parameters will not be used even they were also provided. callbackFunctionOK function &lt;optional&gt; Function that will be called by an internally-created function used in the onreadystatechange property of the XHR object when the readyState property is 4 and the status property is included in the \"allowedSuccessStatuses\" desired. The first parameter it will receive is the XHR object used by the request and the second one will be the \"callbackFunctionError\" function provided (if any). It will not be used if the parameter \"callbackFunction\" is provided. callbackFunctionError function &lt;optional&gt; Function that will be called by an internally-created function used in the onreadystatechange property of the XHR object when the readyState property is 4 and the status property is not included in the \"allowedSuccessStatuses\" desired. The first parameter it will receive is the XHR object used by the request and the second one will be the \"callbackFunctionOk\" function provided (if any). It will not be used if the parameter \"callbackFunction\" is provided. allowedSuccessStatuses integer | array &lt;optional&gt; 200 An integer or a numeric array with a list of integers with the status or statuses that will be considered as a success call by the \"callbackFunctionOK\" function (only when it is used) when the response comes. asynchronous boolean &lt;optional&gt; true Defines whether to make a request asynchronously or not. It will be used for the third parameter of the method open of the XHR object. XHR Object &lt;optional&gt; The XHR object that we want to use for the call. If not provided, it will try to create a new one internally. Source: CrossBase/net/XHR/CB_Net_XHR.js, line 120 To Do: Think about providing a way to choose whether we want the \"data\" provided to be added to the URL when the \"GET\" method is used or not. Describe better what kind of XHR object will the different callbacks receive, as in some cases (as when using REST) they can contain some special properties with HTTP headers, etc. Returns: Returns null if the URL provided was empty or the AJAX (XHR) object provided is not a valid object or it could not be created a new one internally. Otherwise, it returns the AJAX (XHR) object used to try to perform the call (even that maybe it failed or will fail later). Type Object | null &lt;static&gt; callBinary(URL [, data] [, headers] [, blobOrArrayBuffer] [, callbackFunction] [, callbackFunctionOK] [, callbackFunctionError] [, allowedSuccessStatuses] [, XHR]) → {Object|null} Performs a standard XHR request for a binary file. Uses the CB_Net.XHR.call function internally with \"GET\" method, using \"text/plain; charset=x-user-defined\" for the \"mimeType\" parameter and asynchronously. Parameters: Name Type Argument Default Description URL string Used for the \"URL\" parameter of the CB_Net.XHR.call function when it is called internally. data string | Object &lt;optional&gt; Used for the \"data\" parameter of the CB_Net.XHR.call function when it is called internally. headers CB_Net.XHR.HEADERS &lt;optional&gt; { \"Content-Type\" : \"text/plain; charset=x-user-defined\", \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" } Object containing the HTTP header names and their values that we want to send. If not provided, it will use the default one. An empty object ({}) can be used if we do not want to send any HTTP headers at all. Used for the \"headers\" parameter of the CB_Net.XHR.call function when it is called internally. blobOrArrayBuffer 'arraybuffer' | 'blob' | '' &lt;optional&gt; 'arraybuffer' Used for the responseType parameter of the CB_Net.XHR.call function when it is called internally. If an empty string is provided, the responseType parameter will not be modified. callbackFunction function &lt;optional&gt; Used for the \"callbackFunction\" parameter of the CB_Net.XHR.call function when it is called internally. callbackFunctionOK function &lt;optional&gt; Used for the \"callbackFunctionOK\" parameter of the CB_Net.XHR.call function when it is called internally. callbackFunctionError function &lt;optional&gt; Used for the \"callbackFunctionError\" parameter of the CB_Net.XHR.call function when it is called internally. allowedSuccessStatuses integer | array &lt;optional&gt; 200 Used for the \"allowedSuccessStatuses\" parameter of the CB_Net.XHR.call function when it is called internally. XHR Object &lt;optional&gt; Used for the \"XHR\" parameter of the CB_Net.XHR.call function when it is called internally. Source: CrossBase/net/XHR/CB_Net_XHR.js, line 341 Returns: Returns the same that the CB_Net.XHR.call function returns (called internally). Type Object | null &lt;static&gt; callForm(URL [, data] [, headers] [, responseType] [, charset] [, callbackFunction] [, callbackFunctionOK] [, callbackFunctionError] [, allowedSuccessStatuses] [, XHR]) → {Object|null} Performs a standard XHR request to send form data by POST (no files). Uses the CB_Net.XHR.call function internally with \"POST\" method, asynchronously and \"mimeType\" parameter not provided. Parameters: Name Type Argument Default Description URL string Used for the \"URL\" parameter of the CB_Net.XHR.call function when it is called internally. data string | Object &lt;optional&gt; Used for the \"data\" parameter of the CB_Net.XHR.call function when it is called internally. headers CB_Net.XHR.HEADERS &lt;optional&gt; { \"Content-Type\" : \"application/x-www-form-urlencoded; charset=\" + charset, \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" } Object containing the HTTP header names and their values that we want to send. If not provided, it will use the default one that will include the charset defined by the \"charset\" parameter. An empty object ({}) can be used if we do not want to send any HTTP headers at all. Used for the \"headers\" parameter of the CB_Net.XHR.call function when it is called internally. responseType string &lt;optional&gt; Used for the responseType parameter of the CB_Net.XHR.call function when it is called internally. charset string &lt;optional&gt; 'UTF-8' The charset for the \"Content-Type\" HTTP header that will be sent by default only when no \"headers\" parameter is provided. callbackFunction function &lt;optional&gt; Used for the \"callbackFunction\" parameter of the CB_Net.XHR.call function when it is called internally. callbackFunctionOK function &lt;optional&gt; Used for the \"callbackFunctionOK\" parameter of the CB_Net.XHR.call function when it is called internally. callbackFunctionError function &lt;optional&gt; Used for the \"callbackFunctionError\" parameter of the CB_Net.XHR.call function when it is called internally. allowedSuccessStatuses integer | array &lt;optional&gt; 200 Used for the \"allowedSuccessStatuses\" parameter of the CB_Net.XHR.call function when it is called internally. XHR Object &lt;optional&gt; Used for the \"XHR\" parameter of the CB_Net.XHR.call function when it is called internally. Source: CrossBase/net/XHR/CB_Net_XHR.js, line 293 Returns: Returns the same that the CB_Net.XHR.call function returns (called internally). Type Object | null &lt;static&gt; callProxy(URL [, method] [, data] [, headers] [, responseType] [, forceJSON] [, getHeaders] [, headersForceOneDimension] [, headersForceOneDimensionValues] [, transparentStatus] [, transparentHeaders] [, callbackFunction] [, callbackFunctionOK] [, callbackFunctionError] [, allowedSuccessStatuses] [, XHR]) → {Object|null} Performs an AJAX (XHR) call through the proxy (made with PHP language and using cURL, so it will need a server which supports that) to avoid cross-domain request limitations of AJAX. Uses the CB_Net.XHR.callForm function (with \"headers\" and \"charset\" parameters not provided) internally to call the proxy. NOTE: Edit the \"CB_proxy.config.php\" file to configure the default proxy (set by default in the value of the CB_Configuration.CrossBase.CB_Net_XHR_PROXY_URL property). Apart from configuring it, adding some security measures is highly recommended. Have in mind that, for safety reasons, the default proxy only allows to request the URLs defined in the \"$allowedURLs\" array in the \"CB_proxy.config.php\" file. Just edit it to allow other URLs. Parameters: Name Type Argument Default Description URL string The URL that we want the proxy to call for us. It can also contain URL (GET) parameters. method string &lt;optional&gt; 'POST' The HTTP method (GET, POST, PUT, DELETE, etc.) that we want the proxy to use for us when performing the call. data string | Object &lt;optional&gt; The data that we want to send through the proxy to the final server. If something which is not a string is given, it will assume it is a JSON object and will try to convert it into a string (using the JSON.stringify function internally) before sending it. headers CB_Net.XHR.HEADERS &lt;optional&gt; Object (JSON format) containing the HTTP header names and their values that we want the proxy to send to the final server. Even if not provided, the proxy could end sending some HTTP headers depending on the cURL configuration used. responseType string &lt;optional&gt; Used for the responseType parameter of the CB_Net.XHR.callForm function when it is called internally. forceJSON boolean &lt;optional&gt; false If it is set to true, the response from the proxy will be a JSON object with the status property containing the HTTP status of the reply, the response property with the response content itself and the \"headers\" property (only when \"getHeaders\" parameters is set to true) with the HTTP headers of the reply, all belonging to the response from the final server. getHeaders boolean &lt;optional&gt; false If it is set to true, the proxy will answer including the HTTP headers from the final server. The HTTP headers will be included in the final response string at the beginning (before the response content) if the \"forceJSON\" parameter is not set to true or in the \"headers\" property of the JSON object that belongs to the response otherwise. headersForceOneDimension boolean &lt;optional&gt; false If it is set to true, the proxy will consider that the HTTP headers of the response from the final server are not multidimensional which means that the final server would never reply the same HTTP header repeated multiple times (with different values, normally) in different chunks separated by double new lines (\"\\r\\n\\r\\n\"). Default value (false) is recommended. Needs \"getHeaders\" set to true. headersForceOneDimensionValues boolean &lt;optional&gt; false If it is set to true, the proxy will only consider one value per HTTP header from the response from the final server. Default value (false) is recommended. Needs \"getHeaders\" set to true. transparentStatus boolean &lt;optional&gt; false If it is set to true, the proxy will reply us with the same status as the final server in its HTTP response. transparentHeaders boolean &lt;optional&gt; false If it is set to true, the proxy will reply us with the same HTTP headers as the final server in its HTTP response. callbackFunction function &lt;optional&gt; Used for the \"callbackFunction\" parameter of the CB_Net.XHR.callForm function when it is called internally. callbackFunctionOK function &lt;optional&gt; Used for the \"callbackFunctionOK\" parameter of the CB_Net.XHR.callForm function when it is called internally. callbackFunctionError function &lt;optional&gt; Used for the \"callbackFunctionError\" parameter of the CB_Net.XHR.callForm function when it is called internally. allowedSuccessStatuses integer | array &lt;optional&gt; 200 Used for the \"allowedSuccessStatuses\" parameter of the CB_Net.XHR.callForm function when it is called internally. XHR Object &lt;optional&gt; Used for the \"XHR\" parameter of the CB_Net.XHR.callForm function when it is called internally. Source: CrossBase/net/XHR/CB_Net_XHR.js, line 403 To Do: Document PHP proxy more. Returns: Returns the same that the CB_Net.XHR.callForm function returns (called internally). Type Object | null &lt;static&gt; callREST( [serverURL] [, route] [, dataURL] [, method] [, data] [, headers] [, responseType] [, avoidProxy] [, forceJSON] [, getHeaders] [, headersForceOneDimension] [, headersForceOneDimensionValues] [, transparentStatus] [, transparentHeaders] [, callbackFunctionOK] [, callbackFunctionError] [, allowedSuccessStatuses] [, XHR]) → {Object|null} Performs a REST call to a REST server. Uses the CB_Net.XHR.callProxy function (without \"callbackFunction\" parameter provided) internally if we do not want to avoid the proxy or uses the CB_Net.XHR.call function (asynchronously, with \"mimeType\" and \"callbackFunction\" parameters not provided) otherwise. Parameters: Name Type Argument Default Description serverURL string &lt;optional&gt; CB_Net.REST.SERVER_URL_DEFAULT The URL of the REST server that we want to call. It should not contain URL (GET) parameters. It can also contain the REST path (route), although it is recommended to set it in the \"route\" parameter. route string &lt;optional&gt; The REST path (route) we want to request. It can also contain URL (GET) parameters, although it is recommended to set them in the \"dataURL\" parameter. dataURL string &lt;optional&gt; The URL (GET) data that we want to send. method string &lt;optional&gt; 'POST' Used for the \"method\" parameter for the CB_Net.XHR.callProxy function or for the CB_Net.XHR.call function (if no proxy is allowed) when it is called internally. data string | Object &lt;optional&gt; Used for the \"data\" parameter of the CB_Net.XHR.callProxy function or of the CB_Net.XHR.call function (if no proxy is allowed) when it is called internally. headers CB_Net.XHR.HEADERS &lt;optional&gt; undefined|{ \"Content-Type\" : \"application/x-www-form-urlencoded; charset=UTF-8\", \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" } Used for the \"headers\" parameter of the CB_Net.XHR.callProxy function or of the CB_Net.XHR.call function (if no proxy is allowed) when it is called internally. If not provided and the CB_Net.XHR.call function is used (if no proxy is allowed), the default value will be: { \"Content-Type\" : \"application/x-www-form-urlencoded; charset=UTF-8\", \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" } responseType string &lt;optional&gt; Used for the responseType parameter of the CB_Net.XHR.callProxy function or of the CB_Net.XHR.call function (if no proxy is allowed) when it is called internally. avoidProxy boolean &lt;optional&gt; false If it is set to true, it will call the CB_Net.XHR.call internally. Otherwise, it will use the CB_Net.XHR.callProxy function internally. forceJSON boolean &lt;optional&gt; false Used for the \"forceJSON\" parameter of the CB_Net.XHR.callProxy function (if the proxy is allowed) when it is called internally. getHeaders boolean &lt;optional&gt; false Used for the \"getHeaders\" parameter of the CB_Net.XHR.callProxy function (if the proxy is allowed) when it is called internally. headersForceOneDimension boolean &lt;optional&gt; false Used for the \"headersForceOneDimension\" parameter of the CB_Net.XHR.callProxy function (if the proxy is allowed) when it is called internally. headersForceOneDimensionValues boolean &lt;optional&gt; false Used for the \"headersForceOneDimensionValues\" parameter of the CB_Net.XHR.callProxy function (if the proxy is allowed) when it is called internally. transparentStatus boolean &lt;optional&gt; false Used for the \"transparentStatus\" parameter of the CB_Net.XHR.callProxy function (if the proxy is allowed) when it is called internally. transparentHeaders boolean &lt;optional&gt; false Used for the \"transparentHeaders\" parameter of the CB_Net.XHR.callProxy function (if the proxy is allowed) when it is called internally. callbackFunctionOK function &lt;optional&gt; Used for the \"callbackFunctionOK\" parameter of the CB_Net.XHR.callProxy function or of the CB_Net.XHR.call function (if no proxy is allowed) when it is called internally. callbackFunctionError function &lt;optional&gt; Used for the \"callbackFunctionError\" parameter of the CB_Net.XHR.callProxy function or of the CB_Net.XHR.call function (if no proxy is allowed) when it is called internally. allowedSuccessStatuses integer | array &lt;optional&gt; 200 Used for the \"allowedSuccessStatuses\" parameter of the CB_Net.XHR.callProxy function or of the CB_Net.XHR.call function (if no proxy is allowed) when it is called internally. XHR Object &lt;optional&gt; Used for the \"XHR\" parameter of the CB_Net.XHR.callProxy function or of the CB_Net.XHR.call function (if no proxy is allowed) when it is called internally. Source: CrossBase/net/XHR/CB_Net_XHR.js, line 469 Returns: When using the proxy is allowed, returns the same that the CB_Net.XHR.callProxy function returns (called internally). Otherwise, it returns the same that the CB_Net.XHR.call function returns (called internally). Type Object | null &lt;static&gt; get() → {Object|null} Returns a new AJAX (XHR) object, if possible. Source: CrossBase/net/XHR/CB_Net_XHR.js, line 60 Returns: Returns a new AJAX (XHR) object if it has been possible to create it or null otherwise. Type Object | null &lt;static&gt; getResponseContent(response [, sanitize]) → {string|null} Returns the response content from an XHR object (from its responseText property) or from the JSON response generated by the \"getSslPage\" function used by the PHP proxy (response property). Useful to parse the response from the CB_Net.XHR.callProxy (or CB_Net.XHR.callREST and related) function when it has been called with the \"forceJSON\" parameter set to true. Parameters: Name Type Argument Default Description response Object | string The XHR object which contains the responseText property or the value of the responseText property (string) itself which should contain the JSON response generated by the \"getSslPage\" function used by the PHP proxy. If a string is provided, tries to parse it as a JSON object. The responseText property (or the response property as a fallback) will be tried to be returned from it. sanitize boolean &lt;optional&gt; true If it is set to true and neither the responseText nor the response properties are found, it will return an empty string (\"\") instead of returning null. Source: CrossBase/net/XHR/CB_Net_XHR.js, line 581 Returns: Returns the content of the responseText (or response) property if possible. If it is not possible, it will return null if the parameter \"sanitize\" is set to false or an empty string (\"\") otherwise. Type string | null &lt;static&gt; getResponseHeaders(response [, sanitize]) → {Object|null} Returns the HTTP headers (it should be an object) from the JSON response generated by the \"getSslPage\" function used by the PHP proxy (\"headers\" property). Useful to parse the response from the CB_Net.XHR.callProxy (or CB_Net.XHR.callREST and related) function when it has been called with the \"forceJSON\" parameter set to true. Parameters: Name Type Argument Default Description response Object | string The XHR object which contains the responseText property or the value of the responseText property (string) itself which should contain the JSON response generated by the \"getSslPage\" function used by the PHP proxy. If a string is provided, tries to parse it as a JSON object. The \"headers\" property will be tried to be returned from it. sanitize boolean &lt;optional&gt; true If it is set to true and the \"headers\" property is not found, it will return an empty object ({}) instead of returning null. Source: CrossBase/net/XHR/CB_Net_XHR.js, line 546 To Do: Consider adding the parameter \"headerNameFirst\". Returns: Returns the content of the \"headers\" property if possible (it should be a CB_Net.XHR.HEADERS object). If it is not possible, it will return null if the parameter \"sanitize\" is set to false or an empty object ({}) otherwise. Type Object | null &lt;static&gt; getStatusCode(response [, sanitize] [, statusDefault]) → {integer|*} Returns the HTTP status code from an XHR object (status property) or from the info array generated by the PHP's curl_getinfo function (\"http_code\" index) or from the JSON response generated by the \"getSslPage\" function used by the PHP proxy (status property). Useful to parse the response from the CB_Net.XHR.callProxy (or CB_Net.XHR.callREST and related) function when it has been called with the \"forceJSON\" parameter set to true. Parameters: Name Type Argument Default Description response Object | string The XHR object which contains the status property or the value of the responseText property (string) itself which should contain the JSON response generated by the \"getSslPage\" function used by the PHP proxy. If a string is provided, tries to parse it as a JSON object. The status property will be tried to be returned from it (or the \"http_code\" property as a fallback). sanitize boolean &lt;optional&gt; true If it is set to true and neither the \"status\" nor the \"http_code\" property are found (or is not a number), it will return the value of \"statusDefault\" instead of returning null. statusDefault boolean &lt;optional&gt; -1 Default value to return when the status cannot be found (or is not a number). Only used when the \"sanitize\" parameter is set to true. Source: CrossBase/net/XHR/CB_Net_XHR.js, line 563 Returns: Returns the content of the status (or \"http_code\") property if possible (it should be an integer). If it is not possible, it will return null if the parameter \"sanitize\" is set to false or the value of \"statusDefault\" otherwise. Type integer | * &lt;static&gt; supported() → {boolean} Returns whether AJAX (XHR) is available or not. Source: CrossBase/net/XHR/CB_Net_XHR.js, line 40 Returns: Returns true if XHR (AJAX) objects can be used. Type boolean Type Definitions HEADERS Object containing the HTTP headers and their values. Type: Object Properties: Name Type Description HTTPHeaderName Object Each property name is an HTTP header and its value is the desired one for this header. Source: CrossBase/net/XHR/CB_Net_XHR.js, line 92 Example { \"Content-Type\" : \"text/plain; charset=x-user-defined\", \"Cache-Control\" : \"no-cache\", \"Pragma\" : \"no-cache\" } × Search results Close "},"CB_Pointer.html":{"id":"CB_Pointer.html","title":"Namespace: CB_Pointer","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Pointer CB_Pointer Static class to manage the pointer, using the Pointer API if available and falling back to internal emulation otherwise. It will return itself if it is tried to be instantiated. Source: CrossBase/input/CB_Pointer.js, line 12 Methods &lt;static&gt; normalizeEvent(e) → {Event} Tries to return the given pointer event with some properties normalized (since different clients can use different values) and perhaps some new properties added (in the case they were missing), when possible. The new attached methods and properties may include polyfills, etc. It also calls the CB_Events.normalize function internally. Some properties added or affected could be \"POINTER_TYPE_TOUCH\", \"POINTER_TYPE_MOUSE\", \"POINTER_TYPE_PEN\", \"pointerId\", \"pointerType\", \"pressure\", \"tangentialPressure\", \"tiltX\", \"tiltY\", \"width\", \"height\", \"currentTarget\", \"isPrimary\", \"twist\", etc. Parameters: Name Type Description e Event Pointer event object. If not provided, it will use the value of \"event\", \"window.event\", \"Event\" or an empty object (\"{}\"). Source: CrossBase/input/CB_Pointer.js, line 80 To Do: Think about using Object.defineProperty with \"writable: true\" as option to prevent some web clients problems that have read only properties. Maybe e.width and e.height should be both 1 as default (?). Returns: Returns the pointer event object normalized. Type Event &lt;static&gt; onCancel(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the \"onPointerCancel\" event is fired or removes it. More information: Pointer events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Pointer.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Pointer.js, line 163 &lt;static&gt; onDown(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the \"onPointerDown\" event is fired or removes it. More information: Pointer events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Pointer.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Pointer.js, line 135 &lt;static&gt; onEnter(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the \"onPointerEnter\" event is fired or removes it. More information: Pointer events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Pointer.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Pointer.js, line 177 &lt;static&gt; onGotPointCapture(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the \"onGotPointerCapture\" event is fired or removes it. More information: Pointer events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Pointer.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Pointer.js, line 247 &lt;static&gt; onLeave(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the \"onPointerLeave\" event is fired or removes it. More information: Pointer events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Pointer.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Pointer.js, line 191 &lt;static&gt; onLostPointCapture(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the \"onLostPointerCapture\" event is fired or removes it. More information: Pointer events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Pointer.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Pointer.js, line 261 &lt;static&gt; onMove(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the \"onPointerMove\" event is fired or removes it. More information: Pointer events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Pointer.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Pointer.js, line 233 &lt;static&gt; onOut(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the \"onPointerOut\" event is fired or removes it. More information: Pointer events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Pointer.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Pointer.js, line 219 &lt;static&gt; onOver(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the \"onPointerOver\" event is fired or removes it. More information: Pointer events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Pointer.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Pointer.js, line 205 &lt;static&gt; onUp(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the \"onPointerUp\" event is fired or removes it. More information: Pointer events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Pointer.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Pointer.js, line 149 &lt;static&gt; setPointerEventsProperty(element, value [, important]) Sets the desired value for the CSS' style pointer-events property of a given element. Parameters: Name Type Argument Default Description element Element Element whose CSS' style \"pointer-events\" property we want to edit. value string CSS code for the CSS' style \"pointer-events\" property. important boolean &lt;optional&gt; false If set to true, it will add the \" !important\" text to the \"pointer-events\" property. Source: CrossBase/input/CB_Pointer.js, line 116 × Search results Close "},"CB_Screen.html":{"id":"CB_Screen.html","title":"Namespace: CB_Screen","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Screen CB_Screen Static class to manage the screen. It will return itself if it is tried to be instantiated. It can use detect-zoom and NoSleep.js. Source: CrossBase/audiovisual/image/CB_Screen.js, line 12 Methods &lt;static&gt; focus() Sets the focus to the main window (if possible). Source: CrossBase/audiovisual/image/CB_Screen.js, line 647 &lt;static&gt; getAvailableHeight() → {number} Gets the current available screen height (vertical resolution). Uses the window.screen.availHeight property internally, when possible. Source: CrossBase/audiovisual/image/CB_Screen.js, line 244 Returns: Returns the current available screen height (vertical resolution) in pixels. Type number &lt;static&gt; getAvailableHeightPrevious() → {number} Gets the previous available screen height (vertical resolution). Useful when the resolution (screen size and/or orientation) changed. Uses the window.screen.availHeight property internally, when possible. Source: CrossBase/audiovisual/image/CB_Screen.js, line 272 Returns: Returns the previous available screen height (vertical resolution) in pixels. Type number &lt;static&gt; getAvailableWidth() → {number} Gets the current available screen width (horizontal resolution). Uses the window.screen.availWidth property internally, when possible. Source: CrossBase/audiovisual/image/CB_Screen.js, line 228 Returns: Returns the current available screen width (horizontal resolution) in pixels. Type number &lt;static&gt; getAvailableWidthPrevious() → {number} Gets the previous available screen width (horizontal resolution). Useful when the resolution (screen size and/or orientation) changed. Uses the window.screen.availWidth property internally, when possible. Source: CrossBase/audiovisual/image/CB_Screen.js, line 260 Returns: Returns the previous available screen width (horizontal resolution) in pixels. Type number &lt;static&gt; getColorDepth() → {number} Gets the current color depth. Uses the window.screen.colorDepth property internally, when possible. Source: CrossBase/audiovisual/image/CB_Screen.js, line 354 Returns: Returns the current color depth. Type number &lt;static&gt; getHeight() → {number} Gets the current screen height (vertical resolution). Uses the window.screen.height property internally, when possible. Source: CrossBase/audiovisual/image/CB_Screen.js, line 188 Returns: Returns the current screen height (vertical resolution) in pixels. Type number &lt;static&gt; getHeightPrevious() → {number} Gets the previous screen height (vertical resolution). Calculated through the window.screen.height property internally, when possible. Useful when the resolution (screen size and/or orientation) changed. Source: CrossBase/audiovisual/image/CB_Screen.js, line 216 Returns: Returns the previous screen height (vertical resolution) in pixels. Type number &lt;static&gt; getOrientation() → {string} Gets the current orientation from the screen orientation object of the Screen Orientation API. Source: CrossBase/audiovisual/image/CB_Screen.js, line 1676 Returns: Returns a string with the current orientation from the screen orientation object of the Screen Orientation API. If cannot be found, it will return \"landscape-primary\" as default. Type string &lt;static&gt; getOrientationObject() → {Object} Gets the screen orientation object of the Screen Orientation API. Source: CrossBase/audiovisual/image/CB_Screen.js, line 1643 Returns: Returns the screen orientation object of the Screen Orientation API. Type Object &lt;static&gt; getPixelRatio() → {number} Gets the current pixel ratio of the screen (main window). Uses detect-zoom internally. Source: CrossBase/audiovisual/image/CB_Screen.js, line 467 To Do: Find a better and more-compatible way to detect pixel ratio which supports as many web clients as possible. Returns: Returns the current pixel ratio of the screen (main window). Default pixel ratio is 1 (one) even when it fails. Type number &lt;static&gt; getPixelRatioPrevious() → {number} Gets the previous pixel ratio of the screen (main window). Useful when the zoom/pixel-ratio changed. Uses detect-zoom internally. Source: CrossBase/audiovisual/image/CB_Screen.js, line 487 To Do: Find a better and more-compatible way to detect pixel ratio which supports as many web clients as possible. Returns: Returns the previous pixel ratio of the screen (main window). Default previous pixel ratio is 0 (zero) even when it fails. Type number &lt;static&gt; getScrollLeft() → {number|null} Gets the current scroll left position (horizontal scroll) of the screen (main window). Uses the CB_Elements.getScrollLeftById function internally. Source: CrossBase/audiovisual/image/CB_Screen.js, line 369 Returns: Returns the current scroll left position (horizontal scroll) of the screen (main window). It could return null if something fails. Type number | null &lt;static&gt; getScrollTop() → {number|null} Gets the current scroll top position (vertical scroll) of the screen (main window). Uses the CB_Elements.getScrollTopById function internally. Source: CrossBase/audiovisual/image/CB_Screen.js, line 402 Returns: Returns the current scroll top position (vertical scroll) of the screen (main window). It could return null if something fails. Type number | null &lt;static&gt; getWidth() → {number} Gets the current screen width (horizontal resolution). Uses the window.screen.width property internally, when possible. Source: CrossBase/audiovisual/image/CB_Screen.js, line 172 Returns: Returns the current screen width (horizontal resolution) in pixels. Type number &lt;static&gt; getWidthPrevious() → {number} Gets the previous screen width (horizontal resolution). Calculated through the window.screen.width property internally, when possible. Useful when the resolution (screen size and/or orientation) changed. Source: CrossBase/audiovisual/image/CB_Screen.js, line 204 Returns: Returns the previous screen width (horizontal resolution) in pixels. Type number &lt;static&gt; getWindowHeight() → {number} Gets the current window height (vertical resolution). Internally, uses the window.innerHeight if possible and fallbacks to document.documentElement.clientHeight or document.body.clientHeight property otherwise, when possible. Source: CrossBase/audiovisual/image/CB_Screen.js, line 307 Returns: Returns the current window height (vertical resolution) in pixels. Type number &lt;static&gt; getWindowHeightPrevious() → {number} Gets the previous window height (vertical resolution). Useful when the resolution (screen size and/or orientation) or window size changed. Internally, uses the window.innerHeight if possible and fallbacks to document.documentElement.clientHeight or document.body.clientHeight property otherwise, when possible. Source: CrossBase/audiovisual/image/CB_Screen.js, line 342 Returns: Returns the previous window height (vertical resolution) in pixels. Type number &lt;static&gt; getWindowWidth() → {number} Gets the current window width (horizontal resolution). Internally, uses the window.innerWidth if possible and fallbacks to document.documentElement.clientWidth or document.body.clientWidth property otherwise, when possible. Source: CrossBase/audiovisual/image/CB_Screen.js, line 284 Returns: Returns the current window width (horizontal resolution) in pixels. Type number &lt;static&gt; getWindowWidthPrevious() → {number} Gets the previous window width (horizontal resolution). Useful when the resolution (screen size and/or orientation) or window size changed. Internally, uses the window.innerWidth if possible and fallbacks to document.documentElement.clientWidth or document.body.clientWidth property otherwise, when possible. Source: CrossBase/audiovisual/image/CB_Screen.js, line 330 Returns: Returns the previous window width (horizontal resolution) in pixels. Type number &lt;static&gt; getZoom() → {number} Gets the current zoom level of the screen (main window). Uses detect-zoom internally. Source: CrossBase/audiovisual/image/CB_Screen.js, line 436 To Do: Find a better and more-compatible way to detect zoom which supports as many web clients as possible. Returns: Returns the current zoom level of the screen (main window). Default zoom level is 1 (one) even when it fails. Type number &lt;static&gt; getZoomPrevious() → {number} Gets the previous zoom level of the screen (main window). Useful when the zoom changed. Uses detect-zoom internally. Source: CrossBase/audiovisual/image/CB_Screen.js, line 455 Returns: Returns the previous zoom level of the screen (main window). Default previous zoom level is 0 (zero) even when it fails. Type number &lt;static&gt; isFocused() → {boolean} Tells whether the main window is focused or not. Source: CrossBase/audiovisual/image/CB_Screen.js, line 637 Returns: Returns whether the main window is focused or not. Type boolean &lt;static&gt; isFullScreen( [allowedWidthMarginPercentage] [, allowedHeightMarginPercentage]) → {boolean} Tells whether we are in full screen mode or not. Uses the Fullscreen API and fallbacks to other methods internally, including NW.js (formerly node-webkit) and Electron (Electron.js) ones, when not available. Parameters: Name Type Argument Default Description allowedWidthMarginPercentage number &lt;optional&gt; CB_Configuration.CrossBase.CB_Screen_isFullScreen_ALLOWED_WIDTH_MARGIN_PERCENTAGE Allowed width margin, in percentage, of the total screen available to detect whether it is in full screen or not. Needed by old web clients without Fullscreen API support, mainly. allowedHeightMarginPercentage number &lt;optional&gt; CB_Configuration.CrossBase.CB_Screen_isFullScreen_ALLOWED_HEIGHT_MARGIN_PERCENTAGE Allowed height margin, in percentage, of the total screen available to detect whether it is in full screen or not. Needed by old web clients without Fullscreen API support, mainly. Source: CrossBase/audiovisual/image/CB_Screen.js, line 1197 Returns: Returns whether we are in full screen mode or not. Type boolean &lt;static&gt; isFullScreenAPICompatible() → {boolean} Tells whether the web client is compatible with the FullScreen API or not. Source: CrossBase/audiovisual/image/CB_Screen.js, line 873 Returns: Returns whether the web client is compatible with the FullScreen API or not. Type boolean &lt;static&gt; isLandscape() → {boolean} Tells whether the screen (main window) is in landscape position. Source: CrossBase/audiovisual/image/CB_Screen.js, line 498 Returns: Returns whether the screen is in landscape position. Type boolean &lt;static&gt; isVisible() → {boolean} Tells whether the main window is visible or not. Source: CrossBase/audiovisual/image/CB_Screen.js, line 585 Returns: Returns whether the main window is visible or not. Type boolean &lt;static&gt; keepAwake( [callbackOk] [, callbackError]) → {boolean} Keeps the screen awake and prevents it from turning off. Uses different methods internally: Apache Cordova's Insomnia plugin, Standby API, Mozilla's Wake Lock API, new W3C's Wake Lock API, old W3C's Wake Lock API, NoSleep.js library (it should be activated by an event fired by the user as onclick or ontouchstart, etc.)... Parameters: Name Type Argument Description callbackOk function &lt;optional&gt; Function that will be called if the action has been performed successfully, without parameters. callbackError function &lt;optional&gt; Function that will be called if the action has not been performed successfully, without parameters. Source: CrossBase/audiovisual/image/CB_Screen.js, line 1798 To Do: Pay attention since many internal functions as the new W3C's Wake Lock API are still experimental and not well-tested. Returns: If it uses the new W3C's Wake Lock API internally, it will return a Promise. Otherwise, it will return a boolean depending on whether the internal method has been called successfully or not. The fact that the internal method has been called successfully does not mean that the action will perform successfully so it is recommended to relay on the \"callbackOk\" and \"callbackError\" functions and ignore this returning value. Type boolean &lt;static&gt; keepAwakeDisable( [callbackOk] [, callbackError]) → {boolean} Lets the screen sleep again and stops preventing it from turning off. Uses different methods internally: Apache Cordova's Insomnia plugin, Standby API, Mozilla's Wake Lock API, new W3C's Wake Lock API, old W3C's Wake Lock API, NoSleep.js library (it should be activated by an event fired by the user as onclick or ontouchstart, etc.)... Parameters: Name Type Argument Description callbackOk function &lt;optional&gt; Function that will be called if the action has been performed successfully, without parameters. callbackError function &lt;optional&gt; Function that will be called if the action has not been performed successfully, without parameters. Source: CrossBase/audiovisual/image/CB_Screen.js, line 1901 To Do: Pay attention since many internal functions as the new W3C's Wake Lock API are still experimental and not well-tested. Returns: If it uses the new W3C's Wake Lock API internally, it will return a Promise. Otherwise, it will return a boolean depending on whether the internal method has been called successfully or not. The fact that the internal method has been called successfully does not mean that the action will perform successfully so it is recommended to relay on the \"callbackOk\" and \"callbackError\" functions and ignore this returning value. Type boolean &lt;static&gt; lockOrientation(orientationMode [, onSuccess] [, onError]) → {boolean} Function that forces a desired screen orientation. Using the lock function and fallbacks to the lockOrientation function of the Screen Orientation API internally. Parameters: Name Type Argument Description orientationMode 'default' | 'any' | 'natural' | 'landscape' | 'portrait' | 'portrait-primary' | 'portrait-secondary' | 'landscape-primary' | 'landscape-secondary' Desired orientation. Internally, \"default\" and \"natural\" will be exchanged and \"any\" will be transformed to \"default\", depending on the internal function used. Values \"default\", \"any\" and \"natural\" are not recommended because they are not supported in all web clients. onSuccess function &lt;optional&gt; Callback function with no parameters that will be called if the orientation has been set successfully. onError function &lt;optional&gt; Callback function that will be called if the orientation has not been set successfully. Unique parameter received will be an error object (probably a DOMException, depending on the client) with the error. Source: CrossBase/audiovisual/image/CB_Screen.js, line 1563 To Do: Transform values of \"default\", \"any\" and \"natural\" to \"portrait\", \"landscape\", etc. when the web clients do not support it (calculating current orientation and trying to guess natural/default one, etc.). Returns: Returns the same Promise that the lock function returns, if available. Otherwise, returns the same boolean as the lockOrientation function (true if the locking action has been performed successfully), if available. Otherwise, returns false when the Screen Orientation API is not available. Type boolean &lt;static&gt; onFocusChange(callbackFunction [, keepOldFunction]) Sets a function to execute when the screen (main window) focus is changed or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. Source: CrossBase/audiovisual/image/CB_Screen.js, line 708 &lt;static&gt; onFullScreenChange(callbackFunction [, keepOldFunction]) Sets a function to execute when full screen mode is changed (enabled or disabled) or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. Source: CrossBase/audiovisual/image/CB_Screen.js, line 829 &lt;static&gt; onOrientationChange(callbackFunction [, keepOldFunction]) Sets a function to execute when the screen (main window) orientation is changed (portrait or landscape) or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. Source: CrossBase/audiovisual/image/CB_Screen.js, line 684 &lt;static&gt; onResize(callbackFunction [, keepOldFunction]) Sets a function to execute when the screen (main window) is resized (onResize event) or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. Source: CrossBase/audiovisual/image/CB_Screen.js, line 720 &lt;static&gt; onResizeOrZoom(callbackFunction [, keepOldFunction]) Sets a function to execute when the screen (main window) is resized or the zoom is changed, or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. Source: CrossBase/audiovisual/image/CB_Screen.js, line 817 &lt;static&gt; onScrollLeft(callbackFunction [, keepOldFunction]) Sets a function to execute when the left scroll position (horizontal scroll) is changed in the screen (main window) or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. Source: CrossBase/audiovisual/image/CB_Screen.js, line 660 &lt;static&gt; onScrollTop(callbackFunction [, keepOldFunction]) Sets a function to execute when the top scroll position (vertical scroll) is changed in the screen (main window) or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. Source: CrossBase/audiovisual/image/CB_Screen.js, line 672 &lt;static&gt; onVisibilityChange(callbackFunction [, keepOldFunction]) Sets a function to execute when the screen (main window) visibility is changed or removes it. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired, with no parameters. If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. Source: CrossBase/audiovisual/image/CB_Screen.js, line 696 &lt;static&gt; setFullScreen( [useFullScreen] [, element] [, allowReload]) Toggles between full screen and normal mode. Uses the Fullscreen API and fallbacks to other methods internally, including NW.js (formerly node-webkit) and Electron (Electron.js) ones, when not available. Recommended to be called through an event fired by the user as onclick or ontouchstart, etc. Parameters: Name Type Argument Default Description useFullScreen boolean &lt;optional&gt; true If set to true, it will try to enable full screen mode. Otherwise, it will try to enable normal mode. element Element &lt;optional&gt; document.documentElement|document.body Element which we want to use in full screen mode. By default uses the whole document body. Only used when the \"useFullScreen\" parameter is set to true. If an element is provided, it will use neither NW.js (formerly node-webkit) nor Electron (Electron.js) methods. allowReload boolean &lt;optional&gt; false If set to true and \"useFullScreen\" is set to true but it fails to enable full screen normally, it will try to reload the entire current document again in a new bigger window. Useful for very old web clients. Only used when the \"useFullScreen\" parameter is set to true. Source: CrossBase/audiovisual/image/CB_Screen.js, line 898 &lt;static&gt; setOrientation() Alias for CB_Screen.lockOrientation. Source: CrossBase/audiovisual/image/CB_Screen.js, line 1549 See: CB_Screen.lockOrientation &lt;static&gt; setViewport( [width] [, height] [, userScalable] [, initialScale] [, minimumScale] [, maximumScale] [, shrinkToFit] [, targetDensityDPI]) → {Node|null} Sets the Viewport meta tag dynamically with the desired options. If the Viewport meta tag already exists, it will be updated. Otherwise, it will create a new one (and append it to the HEAD tag, if found). Parameters: Name Type Argument Default Description width string | integer &lt;optional&gt; Desired value for the \"width\" parameter. height string | integer &lt;optional&gt; Desired value for the \"height\" parameter. userScalable string | boolean &lt;optional&gt; 'no' Desired value for the \"user-scalable\" parameter. initialScale number &lt;optional&gt; Desired value for the \"initial-scale\" parameter. minimumScale number &lt;optional&gt; Desired value for the \"minimum-scale\" parameter. maximumScale number &lt;optional&gt; Desired value for the \"maximum-scale\" parameter. shrinkToFit string &lt;optional&gt; Desired value for the \"shrink-to-fit\" parameter. targetDensityDPI string | number &lt;optional&gt; Desired value for the \"target-densitydpi\" parameter. Source: CrossBase/audiovisual/image/CB_Screen.js, line 1706 Returns: Returns the DOM element which belongs to the Viewport meta tag affected (it will have been just created if no one existed before). If a Viewport meta tag could not be created or modified, returns null. Type Node | null &lt;static&gt; unlockOrientation( [onError]) → {boolean} Function that unlocks the screen orientation. Using the unlock function and fallbacks to the unlockOrientation function of the Screen Orientation API internally. Parameters: Name Type Argument Description onError function &lt;optional&gt; Callback function that will be called if the orientation has not been unlocked successfully. Unique parameter received will be an error object (probably a DOMException, depending on the client) with the error. Source: CrossBase/audiovisual/image/CB_Screen.js, line 1465 Returns: Returns the same that the unlock function returns (undefined, normally), if available. Otherwise, returns the same boolean as the unlockOrientation function (true if the unlocking action has been performed successfully), if available. Otherwise, returns false when the Screen Orientation API is not available. Type boolean &lt;static&gt; unsetOrientation() Alias for CB_Screen.unlockOrientation. Source: CrossBase/audiovisual/image/CB_Screen.js, line 1454 See: CB_Screen.unlockOrientation × Search results Close "},"CB_Speaker.html":{"id":"CB_Speaker.html","title":"Namespace: CB_Speaker","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Speaker CB_Speaker Static class to manage the speaker or speakers. It will return itself if it is tried to be instantiated. It can also use timbre.js, Band.js and jsfx. Source: CrossBase/audiovisual/audio/CB_Speaker.js, line 14 To Do: Check whether the path used to play silent sounds as a workaround (through the internal \"_playBlankFilesSilently\" method) is right or not (now it uses the CB_scriptPath variable). getCopy and filterProperties methods (similar to the ones from CB_GraphicSprites and CB_GraphicSpritesScene). Methods &lt;static&gt; getAudioFileSpritesPool() → {CB_AudioFileSpritesPool|null} Returns the current CB_AudioFileSpritesPool object (if any). Source: CrossBase/audiovisual/audio/CB_Speaker.js, line 349 Returns: Returns the current CB_AudioFileSpritesPool object (if any) or null otherwise. Type CB_AudioFileSpritesPool | null &lt;static&gt; getBandJSObject() → {Object|null} Returns a new Band.js object (if possible). Useful for managing music composition. Source: CrossBase/audiovisual/audio/CB_Speaker.js, line 373 To Do: Band.js should have into account the CB_Speaker._volume Returns: Returns a new Band.js object (if possible) or null otherwise. Type Object | null &lt;static&gt; getJsfxObject() → {Object|null} Returns the jsfx object (if any). Useful for managing sound effects generation. Source: CrossBase/audiovisual/audio/CB_Speaker.js, line 385 To Do: jsfx should have into account the CB_Speaker._volume Returns: Returns the current jsfx object (if any) or null otherwise. Type Object | null &lt;static&gt; getTimbreJSObject() → {Object|null} Returns the timbre.js object (if any). Useful for functional processing and synthesizing audio. Source: CrossBase/audiovisual/audio/CB_Speaker.js, line 361 To Do: timbre.js should have into account the CB_Speaker._volume Returns: Returns the current timbre.js object (if any) or null otherwise. Type Object | null &lt;static&gt; getVolume( [avoidSanitize]) → {number} Tells the current volume. Parameters: Name Type Argument Default Description avoidSanitize boolean &lt;optional&gt; false If set to true, it will not call the CB_Speaker.sanitizeVolume function internally before returning the volume. Source: CrossBase/audiovisual/audio/CB_Speaker.js, line 320 Returns: Returns the current volume. Type number &lt;static&gt; mute( [avoidApplyingVolume] [, onMute] [, audioFiles]) → {number} Mutes the speaker. Calls the CB_Speaker.setVolume function internally, with 0 (zero) as the \"volume\" parmeter, null as the \"forceSetVolumeProperty\" parameter and true for both \"saveForUnmute\" and \"isMuteOrUnmute\" parameters. Parameters: Name Type Argument Default Description avoidApplyingVolume boolean &lt;optional&gt; false Used as a parameter to call the CB_Speaker.setVolume function internally. onMute function &lt;optional&gt; Used as as the \"functionToExecute\" parameter to call the CB_Speaker.setVolume function internally. audioFiles array &lt;optional&gt; Used as a parameter to call the CB_Speaker.setVolume function internally. Source: CrossBase/audiovisual/audio/CB_Speaker.js, line 288 To Do: Also affect BandJS, jsfx and timbre.js. Returns: Returns the result of the internal call to the CB_Speaker.setVolume function. Type number &lt;static&gt; sanitizeVolume( [volume] [, useSpeakerVolumeIfNaN]) → {number} Sanitizes the volume (it does not allow values greater than 100 or lower than 0). Parameters: Name Type Argument Default Description volume number &lt;optional&gt; CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME|CB_Speaker._volume The desired volume to be sanitized. If not given, it will use the current volume if the \"useSpeakerVolumeIfNaN\" parameter is set to true or the default volume otherwise. useSpeakerVolumeIfNaN boolean &lt;optional&gt; false If it is set to true and no valid volume is received in the \"volume\" parameter, it will use the current volume (CB_Speaker._volume). Otherwise, if it is set to false and no valid volume is received in the \"volume\" parameter, it will use the default volume which is set in the CB_Configuration.CrossBase.CB_Speaker_DEFAULT_VOLUME constant. Source: CrossBase/audiovisual/audio/CB_Speaker.js, line 243 Returns: Returns the volume sanitized (it does not allow values greater than 100 or lower than 0). Type number &lt;static&gt; setAudioFileSpritesPool(audioFileSpritesPool) → {CB_AudioFileSpritesPool|null} Sets the desired CB_AudioFileSpritesPool object. Parameters: Name Type Description audioFileSpritesPool CB_AudioFileSpritesPool The desired CB_AudioFileSpritesPool object to manage all audio files. Source: CrossBase/audiovisual/audio/CB_Speaker.js, line 333 Returns: Returns the current CB_AudioFileSpritesPool object after setting it (if any) or null otherwise. Type CB_AudioFileSpritesPool | null &lt;static&gt; setVolume( [volume] [, avoidApplyingVolume] [, forceSetVolumeProperty] [, functionToExecute] [, audioFiles] [, saveForUnmute] [, isMuteOrUnmute]) → {number} Sets the given volume. Parameters: Name Type Argument Default Description volume number &lt;optional&gt; CB_Speaker._volume The desired volume to be used (it will be sanitized internally by calling the CB_Speaker.sanitizeVolume function with the volume as the unique parameter). If not given, it will use the current volume. If the \"avoidApplyingVolume\" is set to false and the \"isMuteOrUnmute\" parameter is false, it will also be used as a parameter to call the CB_AudioFileSpritesPool#setVolumeAll method of the internal CB_AudioFileSpritesPool object defined in CB_Speaker._audioFileSpritesPool (if any). avoidApplyingVolume boolean &lt;optional&gt; false If it is set to true, the volume will not be applied (by calling the CB_Speaker._applyVolume internal function, which will also use the internal CB_AudioFileSpritesPool object defined in CB_Speaker._audioFileSpritesPool, if any) and just the CB_Speaker._volume internal property will be set. forceSetVolumeProperty boolean &lt;optional&gt; false If the \"avoidApplyingVolume\" is set to false and the \"isMuteOrUnmute\" parameter is false, it will be used as a parameter to call the CB_AudioFileSpritesPool#setVolumeAll method of the internal CB_AudioFileSpritesPool object defined in CB_Speaker._audioFileSpritesPool (if any). functionToExecute function &lt;optional&gt; A callback function. If the \"avoidApplyingVolume\" is set to false and the \"isMuteOrUnmute\" parameter is false, it will be used as the \"onSetVolume\" parameter to call the CB_AudioFileSpritesPool#setVolumeAll method of the internal CB_AudioFileSpritesPool object defined in CB_Speaker._audioFileSpritesPool (if any). If the \"avoidApplyingVolume\" is set to false and the \"isMuteOrUnmute\" parameter is true, it will be used as the \"onMute\" parameter to call the CB_AudioFileSpritesPool#muteAll method or as the \"onUnmute\" parameter to call the CB_AudioFileSpritesPool#unmuteAll method of the internal CB_AudioFileSpritesPool object defined in CB_Speaker._audioFileSpritesPool (if any). audioFiles array &lt;optional&gt; An array containing the CB_AudioFile objects that we want to affect (if not set and the \"avoidApplyingVolume\" is set to false, it will affect all the CB_AudioFile objects of the internal CB_AudioFileSpritesPool object defined in CB_Speaker._audioFileSpritesPool, if any). If the \"avoidApplyingVolume\" is set to false and the \"isMuteOrUnmute\" parameter is false, it will be used as the \"audioFiles\" parameter to call the CB_AudioFileSpritesPool#setVolumeAll method of the internal CB_AudioFileSpritesPool object defined in CB_Speaker._audioFileSpritesPool (if any). If the \"avoidApplyingVolume\" is set to false and the \"isMuteOrUnmute\" parameter is true, it will be used as the \"audioFiles\" parameter to call the CB_AudioFileSpritesPool#muteAll method or as the \"audioFiles\" parameter to call the CB_AudioFileSpritesPool#unmuteAll method of the internal CB_AudioFileSpritesPool object defined in CB_Speaker._audioFileSpritesPool (if any). saveForUnmute boolean &lt;optional&gt; false If it is set to true, the given volume will be saved to be restored later when the CB_Speaker.unmute method is called. isMuteOrUnmute boolean &lt;optional&gt; false If it is set to true and the volume given is zero, the action performed internally will be muting (by calling the CB_AudioFileSpritesPool#muteAll method of the internal CB_AudioFileSpritesPool object defined in CB_Speaker._audioFileSpritesPool, if any). Otherwise, if it is set to true and the volume given is not zero, the action performed internally will be unmuting (by calling the CB_AudioFileSpritesPool#unmuteAll method of the internal CB_AudioFileSpritesPool object defined in CB_Speaker._audioFileSpritesPool, if any). If it is set to false, the action performed will be set the volume given (by calling the CB_AudioFileSpritesPool#setVolumeAll method of the internal CB_AudioFileSpritesPool object defined in CB_Speaker._audioFileSpritesPool, if any). Source: CrossBase/audiovisual/audio/CB_Speaker.js, line 269 To Do: Also affect BandJS, jsfx and timbre.js. Returns: Returns the current volume being used after setting it. Type number &lt;static&gt; unmute( [avoidApplyingVolume] [, onUnmute] [, audioFiles] [, ignoreVolume]) → {number} Restores the audio volume after muting it. If the current volume is 0 (zero, muted) or the \"ignoreVolume\" parameter is set to true, calls the CB_Speaker.setVolume function internally, with the previously-saved volume before muting it as the \"volume\" parmeter, null as the \"forceSetVolumeProperty\" parameter, false for the \"saveForUnmute\" parameter and true for the \"isMuteOrUnmute\" parameter. Parameters: Name Type Argument Default Description avoidApplyingVolume boolean &lt;optional&gt; false Used as a parameter to call the CB_Speaker.setVolume function internally, if the \"ignoreVolume\" parameter is set to true. onUnmute function &lt;optional&gt; Used as as the \"functionToExecute\" parameter to call the CB_Speaker.setVolume function internally, if the \"ignoreVolume\" parameter is set to true. audioFiles array &lt;optional&gt; Used as a parameter to call the CB_Speaker.setVolume function internally, if the \"ignoreVolume\" parameter is set to true. ignoreVolume boolean &lt;optional&gt; false If set to true, it will try to perform the muting action even when the current volume is not 0 (zero, muted). Source: CrossBase/audiovisual/audio/CB_Speaker.js, line 304 To Do: Also affect BandJS, jsfx and timbre.js. Returns: Returns the current volume. Type number × Search results Close "},"CB_Touch.html":{"id":"CB_Touch.html","title":"Namespace: CB_Touch","body":" CrossBrowdy API documentation Namespaces CB_ArraysCB_AudioDetectorCB_baseSymbolsCB_ClientCB_CollisionsCB_ConfigurationCB_Configuration.CrossBaseCB_Configuration.CrossBrowdyCB_ControllersCB_Controllers_ProprietaryCB_Controllers_Proprietary.WIICB_Controllers_Proprietary.WII_UCB_DeviceCB_Device.AmbientLightCB_Device.BatteryCB_Device.LocationCB_Device.MotionCB_Device.OrientationCB_Device.ProximityCB_Device.VibrationCB_ElementsCB_EventsCB_KeyboardCB_Keyboard.charsCB_Keyboard.extendedCB_Keyboard.keysCB_ModulesCB_MouseCB_Mouse.CursorImageCB_NetCB_Net.FetchCB_Net.RESTCB_Net.SocketsCB_Net.Sockets.SockJSCB_Net.XHRCB_PointerCB_ScreenCB_SpeakerCB_Touch Classes CB_AudioFileCB_AudioFile_API.AAPICB_AudioFile_API.ACMPCB_AudioFile_API.SM2CB_AudioFile_API.WAAPICB_AudioFileCacheCB_AudioFileSpritesCB_AudioFileSpritesPoolCB_CanvasCB_GraphicSpritesCB_GraphicSpritesScene Global CB_addCreditsCB_BASE_NAMECB_baseToBaseCB_baseToIntCB_br2nlCB_brToNlCB_combineArraysOrObjectsCB_combineAutomaticallyCB_combineJSONCB_combineURIParametersCB_combineURLParametersCB_consoleCB_copyObjectCB_countDecimalDigitsCB_countDecimalPartCB_countDecimalsCB_countIntegerDigitsCB_countIntegerPartCB_creditsCB_CREDITS_DEFAULTCB_forceStringCB_forEachCB_getBase64StringObjectCB_getCookieCB_getDatumCB_getJSONPropertyValueCB_getLZStringObjectCB_getValueIndexCB_getValuePathCB_includeJSFileCB_indexOfCB_initCB_intToBaseCB_isArrayCB_isEmailCB_isFileLocalCB_isStringCB_lastIndexOfCB_ltrimCB_NAMECB_nl2brCB_nlToBrCB_numberFormatCB_numberOfDecimalDigitsCB_numberOfDecimalsCB_numberOfIntegerDigitsCB_OPTIONSCB_parseJSONCB_parseStringCB_regularExpressionStringCB_renderStringCB_replaceAllCB_rtrimCB_scriptPathCB_scriptPathCalculateCB_setCookieCB_setDatumCB_sizeofCB_sizeOfCB_stringifyJSONCB_symmetricCallCB_symmetricCallClearCB_thisCB_trimCB_VERSION Namespace: CB_Touch CB_Touch Static class to manage the touch events. It will return itself if it is tried to be instantiated. It can also use Pressure.js and Hammer.js. Source: CrossBase/input/CB_Touch.js, line 12 Members &lt;static, readonly&gt; DEFAULT_FORCE :number Default value for the force attribute if no one is detected. Type: number Default Value: 1 Source: CrossBase/input/CB_Touch.js, line 24 Methods &lt;static&gt; delay( [delayMs] [, index]) → {boolean} First time, this function will return true. Next calls, with same index, returns false during the previously-defined time set in the previous call and true after that delay. After the first call, next calls of this function with same index will be ignored (returning always false) until the delay provided expires. If it is called after a previous call with the same index and the delay of the previous call already expired, it will act as it was the first call again. Useful, for example, to prevent the onTouchStart event to fire twice or more when a layer (container) is closed and behind there is another one with also the onTouchStart event. Parameters: Name Type Argument Default Description delayMs integer &lt;optional&gt; CB_Touch._delayMsDefault Delay desired in milliseconds. For same indexes, this parameter will be ignored if there was a previous call to this function whose delay did not expire yet. index integer | string &lt;optional&gt; 0 Desired index to identify the process. Source: CrossBase/input/CB_Touch.js, line 344 Returns: First time, this function will return true. Next calls with the same index, returns false during the given time and true after that delay. After the first call, next calls with same index of this function will be ignored (returning always false) until the delay provided expires. If it is called after a previous call with the same index and the delay of the previous call already expired, it will act as it was the first call again. Type boolean &lt;static&gt; getData() → {Event|null} Returns the last touch event object (if any), processed by CB_Touch.normalizeEvent internally, which was used in the last touch event fired, if that touch event was touchstart, touchenter or touchmove. The touchend and touchleave events set it to \"null\". Source: CrossBase/input/CB_Touch.js, line 169 Returns: Returns the last touch event affected, if any. Type Event | null &lt;static&gt; getHammerJSObject() → {Object} Returns the Hammer.js object (if any). Useful for managing touch gestures. Source: CrossBase/input/CB_Touch.js, line 317 Returns: Returns the Hammer.js object (if any). Type Object &lt;static&gt; getMaxTouchPoints() → {integer|null} Returns the maximum of touch points supported by the device (if possible). Source: CrossBase/input/CB_Touch.js, line 180 Returns: Maximum touch points supported by the device (if possible). If it cannot be detected, returns null. Type integer | null &lt;static&gt; getPressureJSObject() → {Object} Returns the Pressure.js object (if any). Useful for managing Force Touch/3D Touch and Pointer Pressure features. Source: CrossBase/input/CB_Touch.js, line 328 Returns: Returns the Pressure.js object (if any). Type Object &lt;static&gt; normalizeEvent(e) → {Event} Tries to return the touch event object with some properties normalized (since different clients can use different values), when possible. It also calls the CB_Events.normalize and CB_Touch.normalizePoints functions internally. Some properties affected could be targetTouches, touches, changedTouches, etc. Parameters: Name Type Description e Event Touch event object. If not provided, it will use the value of \"event\", \"window.event\", \"Event\" or an empty object (\"{}\"). Source: CrossBase/input/CB_Touch.js, line 110 To Do: Add more properties and methods to normalize (if needed) Returns: Returns the touch event object normalized. Type Event &lt;static&gt; normalizeForce(force) → {Event} Normalizes the given \"force\" property value across different clients. The new attached methods and properties may include polyfills, etc. This function is called by CB_Touch.normalizePoint automatically. Parameters: Name Type Description force number Force value to be normalized. Source: CrossBase/input/CB_Touch.js, line 92 To Do: Not all web clients are the same, so not all should be normalized. Returns: Returns the force value normalized. Type Event &lt;static&gt; normalizePoint(point) → {Touch} Normalizes a given point. Calls CB_Touch.normalizeForce internally. This function is called by CB_Touch.normalizePoints automatically. Parameters: Name Type Description point Touch Touch object to be normalized. Source: CrossBase/input/CB_Touch.js, line 148 Returns: Returns the given point normalized. Type Touch &lt;static&gt; normalizePoints(points) → {TouchList|array} Normalizes a given list of points. Calls CB_Touch.normalizePoint internally. This function is called by CB_Touch.normalizeEvent automatically. Parameters: Name Type Description points TouchList | array TouchList or array with the points (Touch objects) to be normalized. Source: CrossBase/input/CB_Touch.js, line 131 Returns: Returns the given points normalized. Type TouchList | array &lt;static&gt; onCancel(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the onTouchCancel event is fired or removes it. More information: Touch events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Touch.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Touch.js, line 227 &lt;static&gt; onEnd(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the onTouchEnd event is fired or removes it. More information: Touch events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Touch.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Touch.js, line 213 &lt;static&gt; onEnter(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the onTouchEnter event is fired or removes it. More information: Touch events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Touch.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Touch.js, line 241 &lt;static&gt; onLeave(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the onTouchLeave event is fired or removes it. More information: Touch events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Touch.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Touch.js, line 255 &lt;static&gt; onMove(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the onTouchMove event is fired or removes it. More information: Touch events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Touch.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Touch.js, line 269 &lt;static&gt; onStart(callbackFunction [, keepOldFunction] [, useCapture] [, target]) Sets a function to execute when the onTouchStart event is fired or removes it. More information: Touch events. Parameters: Name Type Argument Default Description callbackFunction function | null The function (event listener) that we want to execute when the event is fired. The first and unique parameter received for this function will be the event object (already normalized by the CB_Touch.normalizeEvent function). If a null value is used, the event will be removed. keepOldFunction boolean &lt;optional&gt; true Defines whether we want to keep any possible previous event listener for the same target and event name or not. useCapture boolean &lt;optional&gt; 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 method and will be used as its third parameter. target Object &lt;optional&gt; document The target where we want to attach the event listener. Source: CrossBase/input/CB_Touch.js, line 199 × Search results Close "}}
11 </script>
12
13 <script type="text/javascript">
14 $(document).ready(function() {
15 Searcher.init();
16 });
17
18 $(window).on("message", function(msg) {
19 var msgData = msg.originalEvent.data;
20
21 if (msgData.msgid != "docstrap.quicksearch.start") {
22 return;
23 }
24
25 var results = Searcher.search(msgData.searchTerms);
26
27 window.parent.postMessage({"results": results, "msgid": "docstrap.quicksearch.done"}, "*");
28 });
29 </script>
30</body>
31</html>