1 var jaws = (function(jaws) {
  2   /**
  3    * @fileOverview jaws.assets properties and functions
  4    * 
  5    * Loads and processes image, sound, video, and json assets
  6    * (Used internally by JawsJS to create <b>jaws.assets</b>)
  7    * 
  8    * @class Jaws.Assets
  9    * @constructor
 10    * @property {boolean}    bust_cache              Add a random argument-string to assets-urls when loading to bypass any cache
 11    * @property {boolean}    fuchia_to_transparent   Convert the color fuchia to transparent when loading .bmp-files
 12    * @property {boolean}    image_to_canvas         Convert all image assets to canvas internally
 13    * @property {string}     root                    Rootdir from where all assets are loaded
 14    * @property {array}      file_type               Listing of file postfixes and their associated types
 15    * @property {array}      can_play                Listing of postfixes and (during runtime) populated booleans 
 16    */
 17   jaws.Assets = function Assets() {
 18     if (!(this instanceof arguments.callee))
 19       return new arguments.callee();
 20 
 21     var self = this;
 22 
 23     self.loaded = [];
 24     self.loading = [];
 25     self.src_list = [];
 26     self.data = [];
 27 
 28     self.bust_cache = false;
 29     self.image_to_canvas = true;
 30     self.fuchia_to_transparent = true;
 31     self.root = "";
 32 
 33     self.file_type = {};
 34     self.file_type["json"] = "json";
 35     self.file_type["wav"] = "audio";
 36     self.file_type["mp3"] = "audio";
 37     self.file_type["ogg"] = "audio";
 38     self.file_type['m4a'] = "audio";
 39     self.file_type['weba'] = "audio";
 40     self.file_type['aac'] = "audio";
 41     self.file_type['mka'] = "audio";
 42     self.file_type['flac'] = "audio";
 43     self.file_type["png"] = "image";
 44     self.file_type["jpg"] = "image";
 45     self.file_type["jpeg"] = "image";
 46     self.file_type["gif"] = "image";
 47     self.file_type["bmp"] = "image";
 48     self.file_type["tiff"] = "image";
 49     self.file_type['mp4'] = "video";
 50     self.file_type['webm'] = "video";
 51     self.file_type['ogv'] = "video";
 52     self.file_type['mkv'] = "video";
 53 
 54     var audioTest = new Audio();
 55     var videoTest = document.createElement('video');
 56     self.can_play = {};
 57     self.can_play["wav"] = !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '');
 58     self.can_play["ogg"] = !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '');
 59     self.can_play["mp3"] = !!audioTest.canPlayType('audio/mpeg;').replace(/^no$/, '');
 60     self.can_play["m4a"] = !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, '');
 61     self.can_play["weba"] = !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '');
 62     self.can_play["aac"] = !!audioTest.canPlayType('audio/aac;').replace(/^no$/, '');
 63     self.can_play["mka"] = !!audioTest.canPlayType('audio/x-matroska;').replace(/^no$/, '');
 64     self.can_play["flac"] = !!audioTest.canPlayType('audio/x-flac;').replace(/^no$/, '');
 65     self.can_play["mp4"] = !!videoTest.canPlayType('video/mp4;').replace(/^no$/, '');
 66     self.can_play["webm"] = !!videoTest.canPlayType('video/webm; codecs="vorbis"').replace(/^no$/, '');
 67     self.can_play["ogv"] = !!videoTest.canPlayType('video/ogg; codecs="vorbis"').replace(/^no$/, '');
 68     self.can_play["mkv"] = !!videoTest.canPlayType('video/x-matroska;').replace(/^no$/, '');
 69 
 70     /**
 71      * Returns the length of the resource list
 72      * @public
 73      * @returns {number}  The length of the resource list
 74      */
 75     self.length = function() {
 76       return self.src_list.length;
 77     };
 78 
 79     /**
 80      * Set root prefix-path to all assets
 81      *
 82      * @example
 83      *   jaws.assets.setRoot("music/").add(["music.mp3", "music.ogg"]).loadAll()
 84      *
 85      * @public
 86      * @param   {string} path-prefix for all following assets
 87      * @returns {object} self
 88      */
 89     self.setRoot = function(path) {
 90       self.root = path
 91       return self
 92     }
 93  
 94     /**
 95      * Get one or more resources from their URLs. Supports simple wildcard (you can end a string with "*").
 96      *
 97      * @example
 98      *   jaws.assets.add(["song.mp3", "song.ogg"])
 99      *   jaws.assets.get("song.*")  // -> Will return song.ogg in firefox and song.mp3 in IE
100      *
101      * @public
102      * @param   {string|array} src The resource(s) to retrieve 
103      * @returns {array|object} Array or single resource if found in cache. Undefined otherwise.
104      */
105     self.get = function(src) {
106       if (jaws.isArray(src)) {
107         return src.map(function(i) {
108           return self.data[i];
109         });
110       }
111       else if (jaws.isString(src)) {
112         // Wildcard? song.*, match against asset-srcs, make sure it's loaded and return content of first match.
113         if(src[src.length-1] === "*") {
114           var needle = src.replace("*", "")
115           for(var i=0; i < self.src_list.length; i++) {
116             if(self.src_list[i].indexOf(needle) == 0 && self.data[self.src_list[i]]) 
117               return self.data[self.src_list[i]];
118           }
119         }
120         
121         // TODO: self.loaded[src] is false for supported files for some odd reason.
122         if (self.data[src]) { return self.data[src]; } 
123         else                { jaws.log.warn("No such asset: " + src, true); }
124       }
125       else {
126         jaws.log.error("jaws.get: Neither String nor Array. Incorrect URL resource " + src);
127         return;
128       }
129     };
130 
131     /**
132      * Returns if specified resource is currently loading or not
133      * @public 
134      * @param {string} src Resource URL
135      * @return {boolean|undefined} If resource is currently loading. Otherwise, undefined. 
136      */
137     self.isLoading = function(src) {
138       if (jaws.isString(src)) {
139         return self.loading[src];
140       } else {
141         jaws.log.error("jaws.isLoading: Argument not a String with " + src);
142       }
143     };
144 
145     /** 
146      * Returns if specified resource is loaded or not
147      * @param src Source URL
148      * @return {boolean|undefined} If specified resource is loaded or not. Otherwise, undefined.
149      */
150     self.isLoaded = function(src) {
151       if (jaws.isString(src)) {
152         return self.loaded[src];
153       } else {
154         jaws.log.error("jaws.isLoaded: Argument not a String with " + src);
155       }
156     };
157 
158     /**
159      * Returns lowercase postfix of specified resource
160      * @public
161      * @param {string} src Resource URL
162      * @returns {string} Lowercase postfix of resource
163      */
164     self.getPostfix = function(src) {
165       if (jaws.isString(src)) {
166         return src.toLowerCase().match(/.+\.([^?]+)(\?|$)/)[1];
167       } else {
168         jaws.log.error("jaws.assets.getPostfix: Argument not a String with " + src);
169       }
170     };
171 
172     /**
173      * Determine type of file (Image, Audio, or Video) from its postfix
174      * @private
175      * @param {string} src Resource URL
176      * @returns {string} Matching type {Image, Audio, Video} or the postfix itself
177      */
178     function getType(src) {
179       if (jaws.isString(src)) {
180         var postfix = self.getPostfix(src);
181         return (self.file_type[postfix] ? self.file_type[postfix] : postfix);
182       } else {
183         jaws.log.error("jaws.assets.getType: Argument not a String with " + src);
184       }
185     }
186 
187     /**
188      * Add URL(s) to asset listing for later loading
189      * @public
190      * @param {string|array|arguments} src The resource URL(s) to add to the asset listing
191      * @example
192      * jaws.assets.add("player.png")
193      * jaws.assets.add(["media/bullet1.png", "media/bullet2.png"])
194      * jaws.assets.add("foo.png", "bar.png")
195      * jaws.assets.loadAll({onload: start_game})
196      */
197     self.add = function(src) {
198       var list = arguments;
199       if(list.length == 1 && jaws.isArray(list[0])) list = list[0];
200       
201       for(var i=0; i < list.length; i++) {
202         if(jaws.isArray(list[i])) {
203           self.add(list[i]);
204         }
205         else {
206           if(jaws.isString(list[i]))  { self.src_list.push(list[i]) }
207           else                        { jaws.log.error("jaws.assets.add: Neither String nor Array. Incorrect URL resource " + src) }
208         }
209       }
210 
211       return self;
212     };
213 
214     /**
215      * Iterate through the list of resource URL(s) and load each in turn.
216      * @public
217      * @param {Object} options Object-literal of callback functions
218      * @config {function} [options.onprogress] The function to be called on progress (when one assets of many is loaded)
219      * @config {function} [options.onerror] The function to be called if an error occurs
220      * @config {function} [options.onload] The function to be called when finished 
221      */
222     self.loadAll = function(options) {
223       self.load_count = 0;
224       self.error_count = 0;
225 
226       if (options.onprogress && jaws.isFunction(options.onprogress))
227         self.onprogress = options.onprogress;
228 
229       if (options.onerror && jaws.isFunction(options.onerror))
230         self.onerror = options.onerror;
231 
232       if (options.onload && jaws.isFunction(options.onload))
233         self.onload = options.onload;
234 
235       self.src_list.forEach(function(item) {
236         self.load(item);
237       });
238 
239       return self;
240     };
241 
242     /** 
243      * Loads a single resource from its given URL
244      * Will attempt to match a resource to known MIME types.
245      * If unknown, loads the file as a blob-object.
246      * 
247      * @public
248      * @param {string} src Resource URL
249      * @param {Object} options Object-literal of callback functions
250      * @config {function} [options.onload] Function to be called when assets has loaded
251      * @config {function} [options.onerror] Function to be called if an error occurs
252      * @example
253      * jaws.load("media/foo.png")
254      * jaws.load("http://place.tld/foo.png")
255      */
256     self.load = function(src, options) {
257       if(!options) options = {};
258 
259       if (!jaws.isString(src)) {
260         jaws.log.error("jaws.assets.load: Argument not a String with " + src);
261         return;
262       }
263 
264       var asset = {};
265       var resolved_src = "";
266       asset.src = src;
267       asset.onload = options.onload;
268       asset.onerror = options.onerror;
269       self.loading[src] = true;
270       var parser = RegExp('^((f|ht)tp(s)?:)?//');
271       if (parser.test(src)) {
272         resolved_src = asset.src;
273       } else {
274         resolved_src = self.root + asset.src;
275       }
276       if (self.bust_cache) {
277         resolved_src += "?" + parseInt(Math.random() * 10000000);
278       }
279 
280       var type = getType(asset.src);
281       if (type === "image") {
282         try {
283           asset.image = new Image();
284           asset.image.asset = asset;
285           asset.image.addEventListener('load', assetLoaded);
286           asset.image.addEventListener('error', assetError);
287           asset.image.src = resolved_src;
288         } catch (e) {
289           jaws.log.error("Cannot load Image resource " + resolved_src +
290                   " (Message: " + e.message + ", Name: " + e.name + ")");
291         }
292       } 
293       else if (self.can_play[self.getPostfix(asset.src)]) {
294         if (type === "audio") {
295           try {
296             asset.audio = new Audio();
297             asset.audio.asset = asset;
298             asset.audio.addEventListener('error', assetError);
299             asset.audio.addEventListener('canplay', assetLoaded); // NOTE: assetLoaded can be called several times during loading.
300             self.data[asset.src] = asset.audio;
301             asset.audio.src = resolved_src;
302             asset.audio.load();
303           } catch (e) {
304             jaws.log.error("Cannot load Audio resource " + resolved_src +
305                     " (Message: " + e.message + ", Name: " + e.name + ")");
306           }
307         } 
308       else if (type === "video") {
309           try {
310             asset.video = document.createElement('video');
311             asset.video.asset = asset;
312             self.data[asset.src] = asset.video;
313             asset.video.setAttribute("style", "display:none;");
314             asset.video.addEventListener('error', assetError);
315             asset.video.addEventListener('canplay', assetLoaded);
316             document.body.appendChild(asset.video);
317             asset.video.src = resolved_src;
318             asset.video.load();
319           } catch (e) {
320             jaws.log.error("Cannot load Video resource " + resolved_src +
321                     " (Message: " + e.message + ", Name: " + e.name + ")");
322           }
323         }
324       }
325       
326       //Load everything else as raw blobs...
327       else {
328         // ... But don't load un-supported audio-files.
329         if(type === "audio" && !self.can_play[self.getPostfix(asset.src)]) {
330           assetSkipped(asset);
331           return self;
332         }
333 
334         try {
335           var req = new XMLHttpRequest();
336           req.asset = asset;
337           req.onreadystatechange = assetLoaded;
338           req.onerror = assetError;
339           req.open('GET', resolved_src, true);
340           if (type !== "json")
341             req.responseType = "blob";
342           req.send(null);
343         } catch (e) {
344           jaws.log.error("Cannot load " + resolved_src +
345                   " (Message: " + e.message + ", Name: " + e.name + ")");
346         }
347       }
348       
349       return self;
350     };
351 
352     /** 
353      * Initial loading callback for all assets for parsing specific filetypes or
354      *  optionally converting images to canvas-objects.
355      * @private
356      * @param {EventObject} event The EventObject populated by the calling event
357      * @see processCallbacks()
358      */
359     function assetLoaded(event) {
360       var asset = this.asset;
361       var src = asset.src;
362       var filetype = getType(asset.src);
363       
364       try {
365         if (filetype === "json") {
366           if (this.readyState !== 4) {
367             return;
368           }
369           self.data[asset.src] = JSON.parse(this.responseText);
370         }
371         else if (filetype === "image") {
372           var new_image = self.image_to_canvas ? jaws.imageToCanvas(asset.image) : asset.image;
373           if (self.fuchia_to_transparent && self.getPostfix(asset.src) === "bmp") {
374             new_image = fuchiaToTransparent(new_image);
375           }
376           self.data[asset.src] = new_image;
377         }
378         else if (filetype === "audio" && self.can_play[self.getPostfix(asset.src)]) {
379           self.data[asset.src] = asset.audio;
380         }
381         else if (filetype === "video" && self.can_play[self.getPostfix(asset.src)]) {
382           self.data[asset.src] = asset.video;
383         } else {
384           self.data[asset.src] = this.response;
385         }
386       } catch (e) {
387         jaws.log.error("Cannot process " + src +
388                   " (Message: " + e.message + ", Name: " + e.name + ")");
389         self.data[asset.src] = null;
390       }
391 
392       /*
393       * Only increment load_count ONCE per unique asset.
394       * This is needed cause assetLoaded-callback can in certain cases be called several for a single asset...
395       * ..and not only Once when it's loaded.
396       */
397       if( !self.loaded[src]) self.load_count++;
398 
399       self.loaded[src] = true;
400       self.loading[src] = false;
401 
402       processCallbacks(asset, true, event);
403     }
404     
405     /** 
406      * Called when jaws asset-handler decides that an asset shouldn't be loaded
407      * For example, an unsupported audio-format won't be loaded.
408      *
409      * @private
410     */
411     function assetSkipped(asset) {
412       self.loaded[asset.src] = true;
413       self.loading[asset.src] = false;
414       self.load_count++;
415       processCallbacks(asset, true);
416     }
417 
418     /**
419      * Increases the error count and calls processCallbacks with false flag set
420      * @see processCallbacks()
421      * @private 
422      * @param {EventObject} event The EventObject populated by the calling event
423      */
424     function assetError(event) {
425       var asset = this.asset;
426       self.error_count++;
427       processCallbacks(asset, false, event);
428     }
429 
430     /** 
431      * Processes (if set) the callbacks per resource
432      * @private
433      * @param {object} asset The asset to be processed
434      * @param {boolean} ok If an error has occured with the asset loading
435      * @param {EventObject} event The EventObject populated by the calling event
436      * @see jaws.start() in core.js
437      */
438     function processCallbacks(asset, ok, event) {
439       var percent = parseInt((self.load_count + self.error_count) / self.src_list.length * 100);
440 
441       if (ok) {
442         if(self.onprogress)
443           self.onprogress(asset.src, percent);
444         if(asset.onprogress && event !== undefined)
445           asset.onprogress(event);
446       }
447       else {
448         if(self.onerror)
449           self.onerror(asset.src, percent);
450         if(asset.onerror && event !== undefined)
451           asset.onerror(event);
452       }
453 
454       if (percent === 100) {
455         if(self.onload) self.onload();
456 
457         self.onprogress = null;
458         self.onerror = null;
459         self.onload = null;
460       }
461     }
462 
463     /**
464      * Displays the progress of asset handling as an overall percentage of all loading
465      * (Can be overridden as jaws.assets.displayProgress = function(percent_done) {})
466      * @public
467      * @param {number} percent_done The overall percentage done across all resource handling
468      */
469     self.displayProgress = function(percent_done) {
470 
471       if (!jaws.isNumber(percent_done))
472         return;
473 
474       if (!jaws.context)
475         return;
476 
477       jaws.context.save();
478       jaws.context.fillStyle = "black";
479       jaws.context.fillRect(0, 0, jaws.width, jaws.height);
480 
481       jaws.context.fillStyle = "white";
482       jaws.context.strokeStyle = "white";
483       jaws.context.textAlign = "center";
484 
485       jaws.context.strokeRect(50 - 1, (jaws.height / 2) - 30 - 1, jaws.width - 100 + 2, 60 + 2);
486       jaws.context.fillRect(50, (jaws.height / 2) - 30, ((jaws.width - 100) / 100) * percent_done, 60);
487 
488       jaws.context.font = "11px verdana";
489       jaws.context.fillText("Loading... " + percent_done + "%", jaws.width / 2, jaws.height / 2 - 35);
490 
491       jaws.context.font = "11px verdana";
492       jaws.context.fillStyle = "#ccc";
493       jaws.context.textBaseline = "bottom";
494       jaws.context.fillText("powered by www.jawsjs.com", jaws.width / 2, jaws.height - 1);
495 
496       jaws.context.restore();
497     };
498   };
499 
500   /** 
501    * Make Fuchia (0xFF00FF) transparent (BMPs ONLY)
502    * @private
503    * @param {HTMLImageElement} image The Bitmap Image to convert
504    * @returns {CanvasElement} canvas The translated CanvasElement 
505    */
506   function fuchiaToTransparent(image) {
507     if (!jaws.isDrawable(image))  
508       return;
509 
510     var canvas = jaws.isImage(image) ? jaws.imageToCanvas(image) : image;
511     var context = canvas.getContext("2d");
512     var img_data = context.getImageData(0, 0, canvas.width, canvas.height);
513     var pixels = img_data.data;
514     for (var i = 0; i < pixels.length; i += 4) {
515       if (pixels[i] === 255 && pixels[i + 1] === 0 && pixels[i + 2] === 255) { // Color: Fuchia
516         pixels[i + 3] = 0; // Set total see-through transparency
517       }
518     }
519 
520     context.putImageData(img_data, 0, 0);
521     return canvas;
522   }
523 
524   jaws.assets = new jaws.Assets();
525   return jaws;
526 })(jaws || {});
527 
528