/* lightbox cache functions */

/* externals: get(imgid)
 *            put(imgid, w, h, fname)
 *            constructor
 *            store()		** must be called on unload
 * internals: load()
 *
 * requires: cookie.js
*/

var LbCache_cookieName = "markb-photo-cache";

// constructor
function LbCache() {
	this.load();
}

LbCache.prototype.put = function(imgid, w, h, fname) {
	// create a new entry if one does not already exist
	if (!(this.entry[imgid])) {
		this.entry[imgid] = new Object;
		this.nentries++;
	}
	// store the values
	this.entry[imgid].w      = w;
	this.entry[imgid].h      = h;
	this.entry[imgid].fname  = fname;
	this.entry[imgid].remove = false;
}


LbCache.prototype.get = function(imgid) {
	var a = this.entry[imgid];
	if (a) {
		a.remove = false;
		return new Array(a.w, a.h, a.fname);
	}
	return null;
}


LbCache.prototype.remove = function(imgid) {
	var a = this.entry[imgid];
	if (a) {
		a.remove = true;
	}
}


LbCache.prototype.store = function() {
	// serialise
	var a = new Array;
	var i = 0;
	for (var j in this.entry) {	// iterate over keys
		var e = this.entry[j];
		if (!(e.remove)) {	// only store data not flagged for removal
			a[i++] = j + ':' + e.w + ':' + e.h + ':' + e.fname;
		}
	}
	// stash the value in the cache
	writeSessionCookie(LbCache_cookieName, i > 1 ? a.join('+') : i==1 ? a[0] : '');
}


LbCache.prototype.load = function() {
	this.entry = new Object;		// initialise to empty
						// (hope any old content gets garbage collected)
	this.nentries = 0;
	var s = getCookieValue(LbCache_cookieName);	// serialised string
	if (!s) {
		return;
	}

	// unserialise
	var a = s.split('+');
	var n = a.length;
	for (var j=0; j<n; j++) {
		var b = a[j].split(':');
		var c = new Object;
		c.w = b[1];
		c.h = b[2];
		c.fname = b[3];
		this.entry[b[0]] = c;
		this.nentries++;
	}
}

/* end */
