/**
 * Crumb plugin (for jQuery)
 * version: 1.0 (03/24/2010)
 * @requires jQuery Cookie Plugin (http://plugins.jquery.com/node/1387)
 *
 * Licensed under the MIT licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright (c) 2010 Derek DeVries (derek@maintainable.com)
 */

/**
 * Create a crumb (cookie substring) with the given name and value and other optional parameters.
 *
 *
 * @example $.crumb('the_cookie', 'the_crumb');
 * @desc Get the value of a crumb.
 * 
 * @example $.crumb('the_cookie', 'the_crumb', 'the_value');
 * @desc Set the value of a crumb.
 * 
 * @example $.crumb('the_cookie', 'the_crumb', null);
 * @desc 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.
 *
 * @param String name The name of the cookie.
 * @param String name The name of the crumb.
 * @param String value The value of the crumb.
 * 
 * @author Derek DeVries/derek@maintainable.com
 */

/**
 * Get the value of a crumb with the given name.
 *
 * @example $.cookie('tabs', 'search');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the crumb.
 * @return The value of the crumb.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.crumb = function(cookie_name, name, value) {
  if (typeof value != 'undefined') {
    // Delete crumb
    if (value === null) {
      var cookie = $.cookie(cookie_name);
      var crumbs = _splitValues(cookie);
      delete crumbs[name];
      return _setCrumbValues(cookie_name, crumbs);
      
    // Set crumb
    } else {
      var cookie = $.cookie(cookie_name);
      var crumbs = _splitValues(cookie);
      crumbs[name] = value || '';
      return _setCrumbValues(cookie_name, crumbs);
    }

  // Get crumb
  } else {
    var cookie = $.cookie(cookie_name);
    if (!cookie == null) {return null;}
    var crumbs = _splitValues(cookie);
    return crumbs[name] || null;
  }

  function _setCrumbValues(cookie_name, crumbs) {
    var values = [];
    for (var i in crumbs) {
      var value = crumbs[i] + ''; // to_s
      values.push(i+"="+value.replace('=', '^^'));
    }
    $.cookie(cookie_name, values.join('|'));
  }

  function _splitValues(string, escaped) {
    if (string == null || string == "") {return {}; }
    var pairs = string.split("|");
    var values = {};
    for (var i = 0, l = pairs.length; i < l; i++) {
      var keyval = pairs[i].split('=', 2);
      var key = keyval[0] ? _strip(keyval[0]) : null; 
      var val = keyval[1] ? _strip(keyval[1]) : null;
      if (key && val) {
        var value = (escaped ? unescape(val) : val.replace('^^', '='));
        if (value && value != 'null') { values[key] = value; }
      }
    }
    return values;
  }

  function _strip(str) {
    return str.replace(/^\s+/, '').replace(/\s+$/, '');
  }

};

