// filter the list of elements given only returning the 
// ones that link to external resources (via href)
jQuery.fn.external_links = function() {
  return $($.grep(this, function(element){
    var href = $(element).attr('href');  
    if (href == null) return false; // no href

    var protocol_match = href.match(/(\w+):.*/);
    if (protocol_match == null) return false; // doesn't start with abc:

    var protocol = protocol_match[1];
    if (protocol == null) return false; // just incase (doesn't start with abc:)

    if (protocol == 'http' || protocol == 'https') {
      if (window.location.host == '') return true; // can't be relative to nothing
      var is_relative = new RegExp("https?://" + window.location.host).test(href);
      return ! is_relative; // not relative
    } else {
      return true; // if it's not http || https, it can't be a relative link
    }
  }));
}

// track all clicks on the elements given
jQuery.fn.trackpageview = function() {
  return this.each(function(){
    $(this).click(function(){
      trackpageview.track(this);
    });
  });
}

var trackpageview = {

  // if you want to track all external links on the page, 
  // call trackpageview.track_all_external_links();
  // from inside your $(document).ready function
  track_all_external_links: function(){
    $('a').external_links().trackpageview();
  },

  // if you want to override what actually happens 
  // when one of these links gets clicked, 
  // override this function
  track: function(element_clicked) {
    var href = $(element_clicked).attr('href');
    if (href != null) {
      pageTracker._trackPageview(href);
    }
  }

};

$(function(){
  
  // by default, track page views on all links with the class 'trackpageview'
  $('a.trackpageview').trackpageview();

});

