$(function(){
 // Loop through all the sets of before and after pics
 $(".beforeafter").each(function(){
  // Set the container's size to the size of the image
  var $before = $(this).find("img[rel=before]"),
   $after = $(this).find("img[rel=after]");
  if ($before.length === 1 && $after.length === 1) {
   $(this)
    .width($before.width())
    .height($before.height())
    .append("<div class='after'></div><div class='before'></div><div class='help'>Hover over the image to toggle.</div>")
    // Convert the images into background images on layered divs
    // and a helpful message
    .find(".after")
     .css("background-image", "url(" + $after.attr("src") + ")")
     .width($after.width())
     .height($after.height())
     .end()
    .find(".before")
     .css("background-image", "url(" + $before.attr("src") + ")")
     .width($before.width())
     .height($before.height())
     .end()
    .find("img")
     .remove() // Remove the original images
     .end()
    // Event handler for the mouse moving over the image
    .mousemove(function(event){
     // Need to know the X position of the parent as people may have their browsers set to any width
     var offset = $(this).offset().left;
     // Don't let the reveal go any further than 5 pixels less than the width of the image
     // or 5 pixels on the left hand side
     if ((event.clientX - offset) < ($(this).find(".after").width() - 3) && (event.clientX - offset) > 3) {
      // Adjust the width of the top image to match the cursor position
      $(this)
       .find(".before")
        .width(event.clientX - offset);
     }
    })
    // Fade out the help message after the first hover
    .hover(function(){
     $(this)
      .find(".help")
       .animate({"opacity": 0}, 400, function(){
        $(this).find(".help").remove();
       });
    });
  }
 });
});