$(document).ready(function(){
  // grab all captions
  var $captions = $('.caption');
  // perform the following on all captions
  $captions.each(function(){
    // see if the caption has an image inside (versus a swf)
    if ($(this).has('img').length > 0) {
      // grab the image
      var $image = $(this).find('img');
      // remove image's width attributes
      $image.one('load', function(){
        $image.removeAttr('width')
              .removeAttr('min-width')
              .css('width','');
        // grab the real width
        var img_width = $image.width();
        // check whether the parent anchor has a class that contains 'swf'
        if ($image.parent('a[class*="swf"]').size() > 0) {
          // locate the swf image's p caption
          var $caption = $image.parentsUntil('.caption').parent();
          var $para = $caption.find('p');
        } else {
          // locate a normal image's p caption
          var $para = $image.siblings('p:first');
        }
        // fire a function to find the width of the paragraph minus padding
        var adjusted_width = adjustedWidth($para, img_width);
        // give the caption paragraph the adjusted width to match the image
        $para.width(adjusted_width);
      }).each(function(){
        // make sure the above function fires after the image is loaded into the dom
        if (this.complete) $(this).trigger('load');
      });
    } else {
      // grab the swf
      var $swf_wrap = $(this).find('div');
      // explode malte's swf class into an array
      var $swf_class = $swf_wrap.attr('class').split('_');
      // grab the width and the height from the array
      var swf_width = $swf_class[1];
      var swf_height = $swf_class[2];
      // find the paragraph caption
      var $para = $(this).find('p:first');
      // fire a function to find the width of the paragraph minus padding
      var adjusted_width = adjustedWidth($para, swf_width);
      // give the caption paragraph the adjusted width to match the image
      $para.width(adjusted_width);
    }
  });
});

// finds the width of a paragraph minus its padding
function adjustedWidth($para, width) {
  var para_pad_left = parseInt($para.css('padding-left'));
  var para_pad_right = parseInt($para.css('padding-left'));
  var calculated_width = (width - (para_pad_left + para_pad_right));
  return calculated_width;
}