xref: /dokuwiki/lib/scripts/cookie.js (revision 40be5e7a38c9cf92c115534a77437c3fda53379e)
1/**
2* Handles the cookie used by several JavaScript functions
3*
4* Only a single cookie is written and read. You may only save
5* simple name-value pairs - no complex types!
6*
7* You should only use the getValue and setValue methods
8*
9* @author Andreas Gohr <andi@splitbrain.org>
10* @author Michal Rezler <m.rezler@centrum.cz>
11*/
12var DokuCookie = {
13    data: {},
14    name: 'DOKU_PREFS',
15
16    /**
17     * Save a value to the cookie
18     *
19     * @author Andreas Gohr <andi@splitbrain.org>
20     */
21    setValue: function(key,val){
22        var text = [],
23            _this = this;
24        this.init();
25        val = val + "";
26        this.data[key] = val;
27
28        //save the whole data array
29        jQuery.each(_this.data, function (key, val) {
30            if (_this.data.hasOwnProperty(key)) {
31                text.push(encodeURIComponent(key)+'#'+encodeURIComponent(val));
32            }
33        });
34        jQuery.cookie(this.name, text.join('#'), {expires: 365, path: DOKU_COOKIE_PARAM.path, secure: DOKU_COOKIE_PARAM.secure});
35    },
36
37    /**
38     * Get a Value from the Cookie
39     *
40     * @author Andreas Gohr <andi@splitbrain.org>
41     */
42    getValue: function(key){
43        this.init();
44        return this.data[key];
45    },
46
47    /**
48     * Loads the current set cookie
49     *
50     * @author Andreas Gohr <andi@splitbrain.org>
51     */
52    init: function(){
53        var text, parts, i;
54        if(!jQuery.isEmptyObject(this.data)) {
55            return;
56        }
57        text = jQuery.cookie(this.name);
58        if(text){
59            parts = text.split('#');
60            for(i = 0; i < parts.length; i += 2){
61                this.data[decodeURIComponent(parts[i])] = decodeURIComponent(parts[i+1]);
62            }
63        }
64    }
65};
66