
(function($){

  $(document).ready(function(){

    var simplebox = $('#simplebox');
    var overlay   = $('.overlay', simplebox);
    var box       = $('.box', simplebox);
    var img       = $('img', simplebox);
    var caption   = $('.caption', simplebox);
    var captionText = $('.caption p', simplebox);

    var currentCaption;

    box.mouseenter(function(){
      if(!currentCaption) return;
      caption.stop(true, true).hide().fadeIn(200);
    });

    box.mouseleave(function(){
      if(!currentCaption) return;
      caption.stop(true, true).show().fadeOut(200);
    });

    img.load(function(){
      var width = img.width();
      var height = img.height();
      box.width(width);
      box.height(height);
      var marginLeft = width / -2;
      var marginTop  = height / -2;
      box.css({ 'margin-left': marginLeft, 'margin-top': marginTop });
      box.hide().fadeIn(200);
      box.removeClass('loading');
    });

    overlay.click(function(){
      simplebox.hide();
    });

    $('a[rel=simplebox]').click(function(){
      var link = $(this);
      var url   = link.attr('href');
      currentCaption = link.attr('title');
      simplebox.show();
      box.addClass('loading');
      img.attr('src', ''); // Webkit requires this to reload cached images.
      img.attr('src', url);
      captionText.text(currentCaption);
      return false;
    });
  });

})(jQuery);

