/**
 * define GA tracker support functions
 */
jQuery.fn.extend({
  init_tracker: function(tracker) {
    var ignoredOrganics = [
      "onsip",
      "onsip.com",
      "onsip.org",
      "www.onsip.com",
      "http://www.onsip.com",
      "junction networks onsip",
      "admin.onsip.com",
      "junction networks",
      "junction voip",
      "junction networks voip",
      "junctionnetworks.com"
    ];

    $(ignoredOrganics).each(function(i) {
      tracker._addIgnoredOrganic(this);
    });

    tracker._setAllowLinker(true);
    tracker._setDomainName("none");
    tracker._trackPageview();

    $(this).attach_all_trackers(tracker);
  },

  attach_tracker: function(tracker, loc) {
    var loc_key = 'ga_loc',
      tracker_key = 'ga_tracker',
      bound_key = 'ga_bound';

    if(!$(this).data) return false;

    var is_bound = !!$(this).data(bound_key);

    var reg =  new RegExp("^((http[s]?://" + location.host + ")|\/)(.*)$"); 

    if (!$(this).attr('href') || $(this).attr('href').match(reg) || !tracker) return false;

    loc = loc ? loc : $(this).attr('href');

    $(this).data(tracker_key, tracker);
    $(this).data(loc_key, loc);

    if (!is_bound) {
      $(this).click(function() {
        var tracker = $(this).data(tracker_key);
        var loc = $(this).data(loc_key);

        if (!tracker || !loc || !tracker['_link']) return true;

        tracker._link(loc);
        return false;
      });
      $(this).data(bound_key, true);
      $(this).addClass('_ga-domain-tracked');
    }

    return $(this).data(bound_key);
  },

  attach_all_trackers: function(pageTracker) {
    var domains = [
      'www.onsip.com',
      'admin.onsip.com',
      'signup.onsip.com',
      'www.junctionnetworks.com',
      'wiki.junctionnetworks.com',
      'pstn.junctionnetworks.com'
    ]

    $(domains).map(function(i) {
      return (this == location.host) ? null : this
    }).each(function(i) {
      var domain = this;
      $('a').map(function(j) {
        var href = $(this).attr('href');
        var pattern = new RegExp("^(http[s]?://" + domain + ")(.*)$");
        return (href && (href.match(pattern))) ? this : null
      }).each(function(j) {
        $(this).attach_tracker(pageTracker); 
      })
    })
  }
});
