/*
* Google Analytics event tracking
*
*/
(function($){

  $.gact = function(func_name) {
    $.isFunction(func_name) ? func_name.call() : null
  };

  $.gact.regex = {
    download: /(?:http(?:s|)\:\/\/(?:www\.|)originenergy.com.au|)(?:\/news|)(\/files\/.+)/im,
    outgoing: /(http(?:s|)\:\/\/(?!(?:www\.|)originenergy.com.au).*)/im,
    location_href: /\/\/.*?(\/.*)/i
  }

  $.gact.downloads = [];

  $.gact.gactClickHandler = function(event) {
    // No tracking for right-clicks
    //
    if (event.which == 3) {
      return;
    }
    var href = $(this).attr('href');

    if ($(this).hasClass("gact-download")) {
      $.gact.trackEvent('Downloads', href.match($.gact.regex.download)[1], 'From : ' + $.gact.getDocumentLocation());
    }
    if ($(this).hasClass("gact-outgoing")) {
      $.gact.trackEvent('Outgoing', href.match($.gact.regex.outgoing)[1], 'From : ' + $.gact.getDocumentLocation());
    }
    if ($(this).hasClass("gact-atom")) {
      $.gact.trackEvent('Atoms', $(this).closest(".atom_item").find(".atom_item_info").text(), 'From : ' + $.gact.getDocumentLocation() + ' To : ' + href);
    }
  }

  $.gact.trackEvent = function(category, action, label) {
    if (typeof category == 'undefined' || category.length <= 0 || typeof action == 'undefined' || action.length <= 0) {
      return;
    }
    _gaq.push(['_trackEvent', category, action, label]);
  }

  $.gact.getDocumentLocation = function() {
    return document.location.href.match($.gact.regex.location_href)[1];
  }

  $.gact.run = function() {
    $("a").each(function(){
      var href = $(this).attr('href');
      if (typeof href == 'undefined' || href.length == 0) {
        return;
      }
      if (href.match($.gact.regex.download)) {
        $(this).addClass("gact gact-download");
      }
      if (href.match($.gact.regex.outgoing)) {
        $(this).addClass("gact gact-outgoing");
      }
    });

    $(".atom_item a").addClass("gact gact-atom");

    $(".gact").live('click', $.gact.gactClickHandler);
  }

  $(document).ready(function() {
    $.gact.run();
  });

})(jQuery);
