// a JS class that hopefully supports image caching/load on demand

function ImageCache_delElement(ename, child) {
    var ni = document.getElementById(ename);
    ni.removeChild(child);
}

function ImageCache_addElement(ename, child) {
    var ni = document.getElementById(ename);
    ni.appendChild(child);
}

function ImageCache_reset() {
    this.cachetime = -1;
    for (img in this.imgset) {
        delete this.imgset[img];
    }
    delete this.imgset;
    this.imgset = new Object();

    return true;
}

function ImageCache_setTime(when) {
    if (arguments.length == 0) {
        this.cachetime = -1;
    } else {
        this.cachetime = when - 0;
    }
    
    if (this.cachetime <= 0) {
        var now = new Date();
        this.cachetime = Math.floor(now.getTime() / 1000);
    }

    return true;
}

function ImageCache_markMissing(){
    var start = this.src.indexOf('?c=');
    var cachetime = this.src.substring(start);
    this.src = this.missing + cachetime;
}

function ImageCache_getImg(path, parent_id, missing) {
    if (this.imgset[path]) {
        var start = this.imgset[path].src.indexOf('c=') + 2;
        var when = this.imgset[path].src.substring(start);
        if (when != this.cachetime) {
            // window.alert('reloading ' + path);
            var cachepath = path + '?c=' + this.cachetime;
            this.imgset[path].src = cachepath;
        } else {
            // window.alert('already loaded ' + path);
        }
    } else {
        // window.alert('loading ' + path);
        var cachepath = path + '?c=' + this.cachetime;
        this.imgset[path] = document.createElement('img');
        if (arguments.length > 2) {
            this.imgset[path].missing = missing;
            this.imgset[path].onerror = ImageCache_markMissing;
        }
        this.imgset[path].src = cachepath;
        this.imgset[path].parentId = "";
    }

    if (arguments.length > 1) {
        if (this.imgset[path].parentId != parent_id) {
            if (this.imgset[path].parentId != "") {
                ImageCache_delElement(parent_id, this.imgset[path]);
            }
            ImageCache_addElement(parent_id, this.imgset[path]);
        }
    }

    return this.imgset[path];
}

function ImageCache() {
    this.imgset = new Object();
    this.cachetime = -1;
    this.reset = ImageCache_reset;
    this.setTime = ImageCache_setTime;
    this.getImg  = ImageCache_getImg;

    return true;
}
