﻿
Object.extend = function(destination, source) {
    for (var property in source)
        destination[property] = source[property];
    return destination;
};

var Cookie = {
    data: {},
    options: { expires: 1, domain: "", path: "/", secure: false },

    init: function(options, data) {
        Cookie.options = Object.extend(Cookie.options, options || {});
        Cookie.data = Cookie.retrieve();
    },
    getData: function(key) {
        return Cookie.data[key];
    },
    setData: function(key, value) {
        Cookie.data[key] = value;
    },
    removeData: function(key) {
        delete Cookie.data[key];
    },
    retrieve: function() {
        var cookies = document.cookie.toString();
        var data = {};

        var expr = new RegExp(Cookie.options.name + '=(.*?)(;|$)', 'gi');
        var match = expr.exec(cookies);

        if (match && match[1]) {
            var values = match[1].split(/&/);
            for (var i = 0; i < values.length; i++) {
                var kv = values[i].split(/=/);
                data[kv[0]] = (kv[1]) ? kv[1] : null;
            }
        }
        return data;
    },
    store: function() {
        var expires = '';
        if (Cookie.options.expires) {
            var today = new Date();
            var date = new Date(today.getTime() + Cookie.options.expires * 86400000);
            expires = ';expires=' + date.toGMTString();
        }

        var cookie = '';
        for (var k in Cookie.data) {
            var v = Cookie.data[k];
            cookie += (cookie == '' ? '' : '&') + k + (v ? '=' + v : '');
        }

        document.cookie = Cookie.options.name + '=' + cookie +
            Cookie.getOptions() + expires;
    },
    erase: function() {
        document.cookie = Cookie.options.name + '=' + Cookie.getOptions() +
            ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
    },
    getOptions: function() {
        return (Cookie.options.path ? ';path=' + Cookie.options.path : '') +
            (Cookie.options.domain ? ';domain=' + Cookie.options.domain : '') +
            (Cookie.options.secure ? ';secure' : '');
    }
};

