/*
 * JavaScript Cache 
 * by Jairo Luiz
 */
JSCache = function() {
    var cache = [];
        
    return {    
    	     
    	getAll: function() {
    		var objs = [];
    		for (var id in cache) {
    			if (cache[id] && (typeof(cache[id]) != 'function')) objs.push(cache[id]);
    		}    		
    		return objs;
    	},     
    	     
		get: function(id) {			
			return cache[id] ? cache[id] : null;            
        },
		
		getByType: function(type) {
			var objs = [];
			for (var id in cache) {
	    		if (typeof(cache[id]) == type) {
	    			objs[id] = cache[id];
	   			}
    		}    			
            return objs;
        },

		set: function(id, obj) {
            if (cache[id]) delete(cache[id]);
            cache[id] = obj;
            if (arguments[2]){
                var ttl = arguments[2].ttl || null;
                if (ttl) var self = this, to = setTimeout(function() { self.remove(id); }, ttl);
            }
            return (cache[id]) ? true : false;
        },
        
		add: function(id, obj) {
            if (!cache[id]) {
                cache[id] = obj;
                if (arguments[2]){
                    var ttl = arguments[2].ttl || null;
                    if (ttl) var self = this, to = setTimeout(function() { self.remove(id); }, ttl);
                }
                return (cache[id]) ? true : false;
            }
        },
		
        remove: function(id) {
            cache[id] = null;            
            return (cache[id]) ? false : true;
        },
		
        clear: function() {
            cache = {};
        }
    }
}
