/**
 * JavaScript Cookie Cache 
 * by Jairo Luiz
 */
JSCookieCache = function(cacheId) {    
        
    function inTheCache(cacheId, cookieName) {
    	return cookieName.match("^" + cacheId + "(.*)");    	
    }    
        
    return {
    
    	cacheId: cacheId + "_Cache_",
    	
    	getAll: function() {    		
    		var cookiesMap = {};
    		var cookies = document.cookie.split(";");    		
    		for (var i = 0; i < cookies.length; i++) {
    			var cookie = cookies[i];
    			cookie = cookie.split("=");    			
    			// verifica se o cookie tem algum valor
    			if (cookie.length > 1 ) {
    				var cookieName = cookie[0].replace(/^\s+|\s+$/g, "");
    				
    				// verifica se o cookie é desse cache
    				if (inTheCache(this.cacheId, cookieName)) {
    					cookieName = cookieName.substring(this.cacheId.length);		
		    			var cookieValue = cookie[1].replace(/^\s+|\s+$/g, "");
		    			cookiesMap[cookieName] = unescape(cookieValue);
	    			}
    			}    			
    		}    		
    		return cookiesMap;
    	},     
    	     
		get: function(id) {
			var cookie = this.getAll()[id];
			return cookie ? cookie : null;            
        },
		
		getByType: function(type) {
			var cookies = this.getAll();
			var objs = [];
			for (var cookie in cookies) {
	    		if (typeof(cookies[cookie]) == type) {
	    			objs.push(cookies[cookie]);
	   			}
    		}    			
            return objs;
        },

		set: function(id, obj, ttl) {
            var oneDay = 1000 * 60 * 60 * 24; // 1 dia
            ttl = oneDay * (ttl || 365); // default é 1 ano				
			
			var date = new Date();
			date.setTime(date.getTime() + ttl);
			
			var expires = "; expires=" + date.toGMTString();
			document.cookie = this.cacheId + id + "=" + escape(obj) + expires + "; path=/";
			
            return (this.get(id)) ? true : false;
        },
        
    	add: function(id, obj, ttl) {            
            if (!this.get(id)) {
            	return this.set(id, obj, ttl);
            }
            return false;
        },
        
        remove: function(id) {
            document.cookie = this.cacheId + id + "=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/";            
            return (this.get(id)) ? false : true;
        },
		
        clear: function() {
        	var cookies = this.getAll();			
			for (var cookie in cookies) this.remove(cookies[cookie]);
        }
    }
}
