(function($){
  $.fn.extend({

    collage: function(){
      return $(this).children("a")
        .css("position", "absolute")
        // Randomly position images.
        .each(function(){
          $(this).css({
            top: Math.floor(Math.random() * ($(this).parent().height() - $(this).height())),
            left: Math.floor(Math.random() * ($(this).parent().width() - $(this).width()))
          });
        })
        .hover(
          function(){
            // Bring to front, and reset z-index of siblings.
            $(this).css("z-index", 10)
              .siblings("a")
                .css("z-index", "")
                .children("img")
                  .stop()
                  .animate({ opacity: .6 }, "fast")
          },
          function(){
            $(this).siblings("a").children("img").stop().animate({ opacity: 1 }, "fast");
          }
        );
    },

    draggable: function(){
      var moving = (function(obj, offset){
        return function(e){
          $(obj).css({ left: e.pageX + offset.x, top: e.pageY + offset.y });
        }
      });
      return $(this)
        .mousedown(function(e){
          var pos = $(this).position();
          var clone = $("<div>").css($.extend({}, pos, { zIndex: 11, height: 125, width: 125, background: "red", position: "absolute", opacity: .2 }));
          var that = this;
          $(this).hide().before(clone);
          $(document)
            .mousemove(moving(clone, { x: pos.left - e.pageX, y: pos.top - e.pageY }))
            .mouseup(function(){
              $(document).unbind("mousemove mouseup");
              $(that).css($(clone).position());
              $(that).show().css("z-index", 10).siblings("a").stop().css("z-index", "");
              $(clone).before(that).remove();
            })
          return false;
        });
    }
  });

})(jQuery);

