/**
 * @author Joey Mazzarelli <mazzarelli+cookies@gmail.com>
 * @copyright Joey Mazzarelli
 * @license BSD license
 */

// Create a dispatcher
var Cookies = function (name, value, options) {
  // Case 1: no parameters supplied, dump the cookies.
  if (!name) {
    return Cookies.all();

  // Case 2: null value, delete cookie
  } else if (value === null) {
    return Cookies.remove(name);

  // Case 3: name supplied only, so get value
  } else if (value == undefined) {
    return Cookies.get(name);

  // Case 4: set a cookie with a value
  } else {
    return Cookies.set(name, value, options || {});
  }

}; // end dispatcher

$.extend(Cookies, (function () {

  // Create the private variables

  /**
   * Default options
   * @var object
   */
  var defaults = {
      path   : '/',
      expiry : null, // Days
      secure : (document.location.protocol == 'https:')
  };

  // Create the public methods
  //
  return {

    /**
     * Get the default options.
     * Not provided by dispatcher, must call explicitly.
     * @return object
     */
    defaults : function () {
      return defaults;
    },

    /**
     * Set a cookie
     * @param string name Name of cookie
     * @param string value Value of cookie
     * @param object options Options that override defaults
     * @return void
     */
    set : function (name, value, options) {
      var opts = {};
      jQuery.extend(opts, defaults, options || {});
      options = opts;

      if (options.expiry) {
        // convert number of days from now to string
        options.expiry = new Date(
          new Date().getTime() + (options.expiry * 86400000)
        ).toGMTString();
      }

      // Build the cookie string
      document.cookie = name + '=' + value +
          ((options.expiry)? '; expires=' + options.expiry: '') + '; ' +
          'path=' + options.path + ((options.secure)? '; secure=true': '');
    },

    /**
     * Get the value
     * @param string name Name of cookie
     * @return string Value of cookie
     */
    get : function (name) {
      return $.trim($.grep(document.cookie.split(';'), function (cookie) {
        return $.trim(cookie).substring(0, name.length) == name;
      })[0] || name + '=').substring(name.length + 1);
    },

    /**
     * Remove the cookie by name
     * @param string name
     * @return void
     */
    remove : function (name) {
      return Cookies.set(name, "", {expiry: -1});
    },

    /**
     * Get a list of the cookie
     * @return array
     */
    all : function () {
      return document.cookie.split(';').map($.trim);
    } 
  };

})()); // end extending Cookies

