/* Cookie plugin
------------------------------------------------------------------------------------------------ */

// Create a cookie with the given name and value and other optional parameters.

// $.cookie('the_cookie', 'the_value'); -> Set the value of a cookie
// $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); -> Create a cookie with all available options.
// $.cookie('the_cookie', null); -> Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain used when the cookie was set.

$.cookie = function(name, value, options) {

    if (typeof value != 'undefined') {
        options = options || {};

        if (value === null) {
            value           = '';
            options.expires = -1;
        }

        var expires = '';

        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;

            if (typeof options.expires == 'number'){
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            }
            else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }

        var path    = options.path ? '; path=' + (options.path) : '',
            domain  = options.domain ? '; domain=' + (options.domain) : '',
            secure  = options.secure ? '; secure' : '';

        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    }
    else {
        var cookieValue = null;

        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            $(cookies).each(function() {
                var cookie = $.trim(this);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    return;
                }
            });
        }
        return cookieValue;
    }
};
