$(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[alt=before]"),
   $after = $(this).find("img[alt=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 and move your pointer left and right to fade between images.Tap if using a touch interface.</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 10 pixels less than the width of the image
     // or 10 pixels on the left hand side
     if ((event.clientX - offset) < ($(this).find(".after").width() - 4) && (event.clientX - offset) > 4) {
      // 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();
       });
    });
  }
 });
});