
/*
Bare bones cookie persistance dict.
d

- depends: jquery.class.js
- depends: json2.js

Things to note:
---------------
- Order of items in baset is not sigificant
- Items are schema-less
- Basket.get acts as constructor
- Must call store() to persist any mutations


Example: Create/Resurrect, add and item, and finally persist:
--------------------------------------------------------------
(creates new basket if 'my_basket' is unknown)
>> Acm.Basket.get('my_basket').add(...).store() <-- 


PDict.get('test')

*/


// if(!window.Acm) {
//     Acm = {};
// };

var Persistable = Class.extend({
    // API
    init: function(name) {
        // initializer for new objects
        if(!name)
            throw "A Persistable must have a name."
        this.name = name
    },
    __setstate__: function(state) {
        // called when resurrecting from cookie
        for(var name in state)
            this[name] = state[name]
    },
    store: function() {
        Persistable.cookie(this.name, escape(JSON.stringify(this)), { expires: 365, path: '/' })
        return this
    },
    destroy: function() {
        Persistable.cookie(this.name, '', { expires: -1, path: '/' });
    }

});
Persistable._memory = {}
Persistable.get = function(name) {
    if(!name)
        throw "Missing name"

    if(Persistable._memory[name]){
        // in-memory
        return Persistable._memory[name]
    }
    else if(Persistable.cookie(name)) {
        // resurrect from cookie
        var b = new this('resurrect')
        b.__setstate__(JSON.parse(unescape(Persistable.cookie(name))))
    }
    else {
        // create new
        var b = new this(name)
    }
    Persistable._memory[name] = b    
    return b
}
// jquery.cookie
Persistable.cookie = function(B,I,L){if(typeof I!="undefined"){L=L||{};if(I===null){I="";L.expires=-1}var E="";if(L.expires&&(typeof L.expires=="number"||L.expires.toUTCString)){var F;if(typeof L.expires=="number"){F=new Date();F.setTime(F.getTime()+(L.expires*24*60*60*1000))}else{F=L.expires}E="; expires="+F.toUTCString()}var K=L.path?"; path="+(L.path):"";var G=L.domain?"; domain="+(L.domain):"";var A=L.secure?"; secure":"";document.cookie=[B,"=",encodeURIComponent(I),E,K,G,A].join("")}else{var D=null;if(document.cookie&&document.cookie!=""){var J=document.cookie.split(";");for(var H=0;H<J.length;H++){var C=jQuery.trim(J[H]);if(C.substring(0,B.length+1)==(B+"=")){D=decodeURIComponent(C.substring(B.length+1));break}}}return D}};







