$.memoryMenu = {};
$.memoryMenu.data = {};
$.memoryMenu.save = function() {
  $.cookie('memory-menu', $.toJSON($.memoryMenu.data), { path: '/' })
};

$.memoryMenu.load = function(namespace) {
  var data = $.evalJSON($.cookie('memory-menu'));
  if (data) {
    $.memoryMenu.data = data;
    if (data[namespace]) {
      return data[namespace];
    }
  }
  return {};
};

$.memoryMenu.hide = function(namespace, which) {
  $.memoryMenu.toggle(namespace, which, false);
};

$.memoryMenu.show = function(namespace, which) {
  $.memoryMenu.toggle(namespace, which, true);
};

$.memoryMenu.toggle = function(namespace, which, show) {
  $.memoryMenu.ensureNamespace(namespace);
  $.memoryMenu.data[namespace][which] = show;
  $.memoryMenu.save();
};

$.memoryMenu.ensureNamespace = function(namespace) {
  if (!$.memoryMenu.data[namespace]) {
    $.memoryMenu.data[namespace] = {};
  }
};

$.fn.memoryMenu = function(options) {
  options = $.extend({
    speed: 250
  }, options);

  var namespace = $(this).attr('id');
  var data = $.memoryMenu.load(namespace);

  $(this).find('a').each(function() {
    if (!$(this).attr('href')) {
      var link = $(this);
      var direction = data[$(link).text()] ? 'show' : 'hide';
      $(this).attr('href', '#').click(function() {
        $(this).next().slideToggle(options.speed, function() {
          var direction = $(this).is(':visible') ? 'show' : 'hide';

          $.memoryMenu[direction](namespace, link.text());

          if (options[direction]) { $.proxy(options[direction], link)(); }
        });
        return false;
      }).next()[direction]();
      if (options[direction]) { $.proxy(options[direction], link)(); }
    }
  });

  return this;
};

