﻿//-------------------------------------
// Cache - Image preload functions
//-------------------------------------
var CACHE_MAX = 20;

// add an item to the cache
function AddItem(myName, myItem) {
    if (this.items.length < CACHE_MAX) {
        this.names.push(myName);
        this.items.push(myItem);
        this.nextFree=this.items.length;
    } else {
        if (this.nextFree >= CACHE_MAX) {
            this.nextFree=0;
        }
        this.names[this.nextFree]=myName;
        this.items[this.nextFree]=myItem;
        this.nextFree++;
    }
}
// given a name, return an index
function ItemIndex(myName) {
    var i=0; 
    var result=-1;
    if (this.names) {
        if (this.names.length > 0) {
            while (i<this.names.length && this.names[i] != myName) {
                i++;
            }
            if (this.names[i] == myName) {
                result=i;
            }
        }
    }
    return result;
}
// remove an item from the cache
function RemoveItemByName(myName) {
    var result=-1;
    result = this.ItemIndex(myName);
    if (result >= 0) {
        this.items.splice(result,1);
        this.names.splice(result,1);
    }
    return result;
}
// remove an item from the cache by index
function RemoveItemByIndex(myIndex) {
    var result=-1;
    if (this.items.length > myIndex) {
        this.items.splice(myIndex,1);
        this.names.splice(myIndex,1);
        result=myIndex;
    }
    return result;
}
// get nexy item
function GetNextItem() {
    var result;
    if (this.nextItem < this.items.length) {
        result=this.items[this.nextItem];
        this.nextItem++;
        if (this.nextItem >= this.items.length) {
            this.nextItem=0;
        }
    } else {
        alert('GetNextItem - No items in cache');
    }
    return result;
}
// pre-load and add image to cache
function AddImage(myName, mySrc) {
    var myImage=new Image();
    myImage.src=mySrc;
    this.AddItem(myName, myImage);
}
// Cache object
function Cache() {
    this.nextFree=0;
    this.nextItem=0;
    this.names=[];
    this.items=[];
    this.AddItem=AddItem;
    this.ItemIndex=ItemIndex;
    this.RemoveItemByName=RemoveItemByName;
    this.RemoveItemByIndex=RemoveItemByIndex;
    this.GetNextItem=GetNextItem;
    this.AddImage=AddImage;
    this.loadStatus=-1;
}
