(function($) {

//$.fnはプラグイン専用のオブジェクト(参考:魔法の鎖のつなぎ方(2) )
$.fn.lavaLamp = function(o) {

  //引数oがあれば、lavaLampメンバーのデフォルト値を上書きして変数oを作成します。
  o = $.extend({ fx: "linear", speed: 500, click: function(){} },o ||{});

  //jQueryのセレクタで検索された要素を順番にeachで回し処理して
  // メソッドチェーンへつなぎます。
  return this.each(function() {

          //カレント要素
      var me = $(this), 
          //何もしない関数
          noop = function(){},
          //背景ブロックをカレント要素へ追記
          $back=$('<li class="back"><div class="left"></div>')
                    .appendTo(me),
          //カレント要素内のli要素s
          $li = $("li", this), 
          curr = $("li.current", this)[0] ||
                 $($li[0]).addClass("current")[0];

      //背景ボックスにhoverしたらmove関数を実行
      $li.not(".back").hover(function() {
          move(this);
      }, noop);

      //検索された要素にhoverしてもmove関数を実行
      $(this).hover(noop, function() {
          move(curr);
      });

      //li要素がクリックされたらカレント要素のセット
      $li.click(function(e) {
          setCurr(this);
          return o.click.apply(this, [e, this]);
      });

      setCurr(curr);

      //カレント要素のセット
      function setCurr(el) {
        $back.css({
           "left": el.offsetLeft+"px",
           "width": el.offsetWidth+"px"
        });
        curr = el;
      };

      ///背景ボックスアニメーション
      function move(el) {
          $back.each(function() {
              $(this).dequeue(); }
          ).animate({
              width: el.offsetWidth,
              left: el.offsetLeft
          }, o.speed, o.fx);
      };

  });
};
})(jQuery);
