/*
* AJAXCache 1.0
*
* (c) 2007 Jaroslaw Kostrz
* e-mail: jkostrz@gmail.com
* www:  http://ajaxcache.ajaxin.pl/
*       http://ajaxin.pl/
* http://creativecommons.org/licenses/by/2.5/pl/
* W przypadku użycia komercyjnego proszę o informację o tym fakcie.
* In case of commercial use please inform me about that fact.
*/

function AJAXCache() {

	this.garbage = [];
	
	this._getIndexById = function(id) {
		for (var i = this.garbage.length-1; i >= 0; i--) 
		{
			if (this.garbage[i][0] == id)
			return i;
		}
		return -1;
	};
	
	this._getNewItemId = function() {
		return this.garbage.length;
	};
	
	this._add = function(i, id, t, o) {	
		if (o == null)
            o = {};
		if (o.expiration)
		{
			var to = new Date(new Date().getTime()+o.ttl*1000).getTime();
			var x = this;
			setTimeout(function(){x.remove(i)}, o.expiration*1000);
		}
		this.garbage[i] = [id, t, to];
	};
	
	this.save = function(id, t, o) {
		var i = this._getIndexById(id);
		if (i >= 0) {
		  if (this._isExpired(i) || o.overwrite) {
			this._add(i, id, t, o);
		  }  
		}
		else {	
			this._add(this._getNewItemId(), id, t, o);
		}
	};
	
	this.get = function(id) {
		var i = this._getIndexById(id);
		if (i < 0 || this._isExpired(i)) {
			return null;
		}
		else {
			return this.garbage[i][1];
		}
	};

	this.remove = function(i) {
		if (this.garbage[i])
		 this.garbage[i].splice(0, 2);
	};
	
	this.flush = function() {
		this.garbage.splice(0, 2);
	};

	this._isExpired = function(i) {
		var now = new Date().getTime();
		if (!this.garbage[i][2] || (this.garbage[i][2] - now) > 0) {		
			return 0;	
		}
		return 1;
	};
}
