(function ($) {
  $(function () {
    var $photoTags = $("#photo-tags"),
        $img       = $photoTags.prevAll('img'),
        imgOff     = $img.position(),
        $tags      = $photoTags.find('a');
    
    // Position the photoTags element directly over the
    // preceding image
    $photoTags.css({
      position: 'absolute',
      top:      imgOff.top  + 4,
      left:     imgOff.left + 4,
      width:    $img.width(),
      height:   $img.height(),
      display:  'block',
      opacity:  0
    }).hover(function () {
      // Fade in on hover, stoping any current animation
      $(this).stop(true).animate({opacity: 1}, 300);
    }, function () {
      // Fade out, do not cancel or stop animations
      $(this).animate({opacity: 0}, 300);
    }).add($("p.disclaimer")).click(function (e) {
      var $a = $(e.target).closest('a'), $target;
      // If one of the tags was clicked
      if ($a.length) {
        e.preventDefault();
        // Find the element this link targets
        $target = $($a.attr('href'));
        if ($target.length) {
          // Scroll the page to the targeted element
          $('html,body').animate({ scrollTop: $target.offset().top - 20 }, 600);
        }
      }
    });
    
    // Prep the tags
    $tags.each(function () {
      var $tag = $(this),
          pos  = $tag.attr('rel').split(','); // Get the position
      
      // Position the tag, and add helper HTML elements
      $tag.css({
        left: parseInt(pos[0], 10),
        top:  parseInt(pos[1], 10)
      }).wrapInner("<strong></strong>").append('<span><em></em></span>');
    });
  });
}(jQuery));
