$.fn.accordion = function() {
  return this.each(function() {
    $container = $(this);

    // Hijack handles.
    $container.find("a.acc").each(function() {
      var $header = $(this);
      var $selected = $header.nextAll('div:first');
	  var $selUl = $selected.children();
      
    $header
        .click(function() {  
          if ($selected.is(":visible")) {
            $selected
              .animate({ height: 0 }, { duration: 900, complete: function() {
                $(this).hide();
              }
            });
          } else {
            $unselected = $container.find("div:visible");
			$unselUl = $unselected.children();
            $selected.show();
            var newHeight = heights[$selected.attr("id")];
            var oldHeight = heights[$unselected.attr("id")];
        
            $('<span>').animate({ height : 1 }, {
              duration  : 900,
              step      : function(now) {
                var stepSelectedHeight = Math.round(newHeight * now);
				var stepSelMarginTop = (-newHeight/2)*(1-now);
				var stepUnselMarginTop = (-oldHeight/2)*now;
				$selUl.css('margin-top', stepSelMarginTop);
				$unselUl.css('margin-top', stepUnselMarginTop);
                $selected.height(stepSelectedHeight);
				//console.log($selected.height());
                $unselected.height(oldHeight + Math.round((newHeight - oldHeight) * now) - Math.round(newHeight * now));
              },
              complete  : function() {
                $unselected
                  .hide()
                  .css({ height : 0 });
                }
            });
          }
          return false;
        });
    });

    // Iterate over panels, save heights, hide all.
    var heights = {};
    $container.find(".out").each(function() {

      var $this = $(this);
      var $next = $this.children();
	  $next.css('margin-top', -$next.height()/2);
      $this.css("overflow", "hidden");
      heights[$this.attr("id")] = $next.height()+14;
      $this
        .hide()
        .css({ height : 0 });
    });
  });
};

$(document).ready(function() {
  $("#inav").accordion();
});
