/* ImagePreloader.js - schedules images to be preloaded
 *
 * The author of this program, Safalra (Stephen Morley), irrevocably releases
 * all rights to this program, with the intention of it becoming part of the
 * public domain. Because this program is released into the public domain, it
 * comes with no warranty either expressed or implied, to the extent permitted
 * by law.
 *
 * For more public domain JavaScript code by the same author, visit:
 * http://www.safalra.com/web-design/javascript/
 */

// create the ImagePreloader
var ImagePreloader =
    new function(){

      // initialise the array of preloaded images to the empty array
      var images = [];

      /* Schedules the specified image to be preloaded with the specified
       * priority. Once the page has loaded images will be preloaded in priority
       * order. The scheduling is handled by OnloadScheduler - see the
       * documentation for that object for details of priorities. The parameters
       * are:
       *
       * url      - the URL of the image to be preloaded
       * priority - the priority to use when scheduling the preloading
       * onload   - a function to call if the image has loaded successfully - if
       *            this parameter is not specified or is not a function, no
       *            function will be called when the image has loaded
       *            successfully
       * onerror  - a function to call if the image has failed to load - if this
       *            parameter is not specified or is not a function, no function
       *            will be called when the image has failed to load
       */
      this.schedule = function(url, priority, onload, onerror){

        // schedule the image to be preloaded
        OnloadScheduler.schedule(
            createPreloadClosure(url, onload, onerror),
            priority);

      };

      /* Returns a function that preloads the specified image. The parameters
       * are:
       *
       * url     - the URL of the image to be preloaded, as described above
       * onload  - the onload function, as described above
       * onerror - the onerror function, as described above
       */
      function createPreloadClosure(url, onload, onerror){

        // return the preloading function
        return function(){

          // create a new image
          var image = new Image();

          // if an onload function was specified, attach it to the image
          if (onload instanceof Function){
            image.onload = onload();
          }

          // if an onerror function was specified, attach it to the image
          if (onerror instanceof Function){
            image.onerror = onerror();
          }

          // set the URL of the image
          image.src = url;

          // add the image to the array of preloaded images
          images.push(image);

        };

      }

    }();
