$(document).ready(function() {
  // Break up the callback URL so that httrack doesn't rewrite it.
  var callback = '/'+'replace'+'/'+'replace'+'.'+'php';

  // Define some local aliases so that this script can be better minified.
  var url = document.location.href;
  var ref = document.referrer;
  var urlencode = encodeURIComponent;

  // Find all the ad blocks on the current page.
  var ids = new Array();
  var i = 0;
  $('.haclient-target').each(function() {
    ids[i++] = this.id;
  });

  // Post the current location and referrer to the PHP script.
  $.post(callback, {
    'location': url,
    'referrer': ref,
    'blocks[]': ids
  }, function(data, textStatus) {
    // The script returns an array of ads keyed by jquery selectors.
    for (var target in data) {
      // Replace the targeted element with the appropriate ad.
      $('.haclient-target#' + target).html(data[target].content);

      // The content has been replaced. Next we want to fiddle with the links.
      // First, we remove the .haclient-target class from all HTML ads, so that
      // their links are not rewritten (they are e.g. adsense/adbutler/etc.)
      $('.haclient-target .html-advertisement').parent('.haclient-target').removeClass('haclient-target');

      // We want to replace all links in the ad with local links back to our
      // redirection script.  We do this by attaching a click handler to each
      // link.  To ensure that each click handler sends the correct selector
      // back to the script, we create a closure by calling an outer function
      // with the selector as a parameter, which returns a reference to the
      // handler function.  At least that's how I *think* it works.
      $('.haclient-target#' + target + ' a[href]').click(function(ad) {
        return function() {
          var destination = callback;
          destination += '?click=' + urlencode(this);
          destination += '&location=' + urlencode(url);
          destination += '&referrer=' + urlencode(ref);
          destination += '&ad=' + urlencode(ad);
          destination += '&aid=' + urlencode(data[ad].aid);
          location.href = destination;

          // Prevent the click from being handled normally, just in case.
          return false;
        }
      }(target));

      // Now, for the flash.
      $('.haclient-target#' + target + ' a.flashembed').each(function() {
        $(this).flashembed(
          this.title, {
            clk: this.href,
            loc: url,
            ref: ref,
            ad: target,
            aid: data[target].aid
          }
        );
        // This little hack is apparently only needed on my personal copy of
        // Firefox and not anywhere else in the world.  So let's remove it when
        // finished testing.
        // $(this).find('object').attr('data', this.title);
      });
    }
  }, 'json');
});
