function imgLoadManager() {
    var _ = this;

    _.loaders = [];
    
    //Add and start new image loader
    _.addImgLoader = function(camdivid, camid, waitid, inter) {
        var loadSet = {
            'index' : _.loaders.length,
            'camdiv': document.getElementById(camdivid),
            'camimg': document.getElementById(camid),
            'waitimg' : document.getElementById(waitid),
            'inter' : inter
        }
        var loader = new imageLoader(loadSet);
        _.loaders[_.loaders.length] = loader;
        loader.loopBack();                                      //Start loader
    }
    
    //Image loading timed out
    _.loaderTimeout = function(index) {
        window.clearTimeout(_.loaders[index].loadHandle);       // Stop loading
        _.loaders[index].loopBack();                            // Restart loader
    }
}


function imageLoader(loadSet) {
    var _ = this;

    _.index = loadSet['index'];
    _.camdiv = loadSet['camdiv'];
    _.camimg = loadSet['camimg'];
    _.waitimg = loadSet['waitimg'];
    _.inter = loadSet['inter'];
    _.origsrc = _.camimg.src;
    _.loadHandle = null;
    _.timeoutHandle = null;
    _.count = 0;

    _.loadImage = function() {
        _.loading = true;

        var img = document.createElement('img');
        img.id = _.camimg.id;

        img.onload = function(evt) {
            //Clear timeout thread
            window.clearTimeout(_.timeoutHandle);

            //Refresh image
            this.width = _.camimg.width;
            this.height = _.camimg.height;
            _.camdiv.replaceChild(this, _.camimg);
            _.camimg = this;
            _.waitimg.style.display = 'none';
            _.waitimg.style.visibility = 'hidden';
            _.count++;

            //Set next load timeout
            window.setTimeout('_imgLoadMng.loaders[' + _.index + '].loopBack()', _.inter);
        }

        //Ensure image source is not cached
        d = new Date();
        img.src = _.origsrc + '?ts=' + d.getFullYear() + d.getMonth() + d.getDay() + d.getHours() + d.getMinutes() + d.getSeconds() + d.getMilliseconds();
    }

    _.loopBack = function() {
        //Show loading image - should execute before the loadImage thread is started
        _.waitimg.style.display = 'list-item';
        _.waitimg.style.visibility = 'visible';
        _.timeoutHandle = window.setTimeout('_imgLoadMng.loaderTimeout(' + _.index + ')', 60000);
        _.loadHandle = window.setTimeout('_imgLoadMng.loaders[' + _.index + '].loadImage()', 1);
    }
}

var _imgLoadMng = new imgLoadManager();