﻿///
/// Singleton ImagePrefetcher (_imagePrefetcher is defined at the bottom of this js file)
///
/// Prefetch Images in the background.
///
/// input: URL string or URL array String
///
/// Example: 
/// 1. _imagePrefetcher.prefetchImage("http://www.google.com/intl/en_ca/images/logo.gif");
/// 2. _imagePrefetcher.prefetchImages(["http://www.google.com/intl/en_ca/images/logo.gif", "http://l.yimg.com/us.yimg.com/i/ca/ww/ca_logo_232x58.gif"]);
/// 3. _imagePrefetcher.clearAfterComplete(2000);

function ImagePrefetcher () {    
}

ImagePrefetcher.prototype = {   

    //public Methods
    prefetchImage : function (imageURL) {
        this.fetchToMemory(imageURL);
    },    
    prefetchImages : function (imageURLArray) {
        for (var i = 0; i < imageURLArray.length; i++)
        {
            this.fetchToMemory(imageURLArray[i]);
        }
    },      
    clearAfterComplete : function (interval) {
        if (this.isCompleted())
        {
            this.clear();
        }
        else
        {
            setTimeout("_imagePrefetcher.clearAfterComplete("+interval+");", interval);
        }
    },
    
    //private attributes
    imageObjects: [],
    
    //private methods
    clear : function () {
        this.imageObjects = [];
    },    
    fetchToMemory : function (URL) {                
        var oImage = new Image;
        oImage.src = URL;
        oImage.isLoaded = false;      
        oImage.onload = ImagePrefetcher.prototype.imageObjectonload;
        
        if (!oImage.complete)        
            this.imageObjects.push(oImage);
    },    
    isCompleted: function() {
        for (var i = 0; i < this.imageObjects.length; i++)
        {
            if (!this.imageObjects[i].isLoaded)
            {
                return false;
            }
        }
        return true;
    },     
    imageObjectonload: function() {
        this.isLoaded = true;
    }
};

//Singleton Pattern
//A page can have at most one prefetcher.
var _imagePrefetcher = new ImagePrefetcher();