﻿function GaPushEvents($) {
    /* Largely taken from here: http://www.carronmedia.com/extend-google-analytics-with-jquery/ */
    var filetypes = /\.(pdf|doc*|xls*|ppt*)$/i;
    $('a').each(function() {
        var href = $(this).attr('href');
        //alert(href);
        if (!(typeof href === "undefined")) {
            if ((href.match(/^https?\:/i)) && (!href.match(document.domain))) {
                //alert(href);
                $(this).click(function() {
                    var extLink = href.replace(/^https?\:\/\//i, '');
                    recordOutboundLink(href, 'External', extLink, $(location).attr('href'));
                    //pageTracker._trackEvent('External', 'Click', extLink);
                });
            }
            else if (href.match(/^mailto\:/i)) {
                $(this).click(function() {
                    var mailLink = href.replace(/^mailto\:/i, '');
                    recordOutboundLink(href, 'Email', mailLink, $(location).attr('href'));
                    //pageTracker._trackEvent('Email', 'Click', mailLink);
                });
            }
            else if (href.match(filetypes)) {
                $(this).click(function() {
                    var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                    var filePath = href.replace(/^https?\:\/\/(www.)mydomain\.com\//i, '');
                    recordOutboundLink(href, 'Download', filePath, $(location).attr('href'));
                    //pageTracker._trackEvent('Download', 'Click - ' + extension, filePath);
                });
            }
            else {
                var rel = $(this).attr('rel');
                if (!(typeof rel === "undefined")) {
                    if (rel.match(/^Document\: /i)) {
                        $(this).click(function() {
                            recordOutboundLink(href, 'Download', rel, $(location).attr('href'));
                        });
                    }
                }
            }
        }
    });
}

function recordOutboundLink(originalLink, category, action, label) {
    try {

        //vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
        //THIS WORKS: 
        var myTracker = _gat._getTracker("UA-XXXXXXX-X");
        myTracker._trackEvent(category, action, label);
        //But would like to avoid using the analytics id in order to keep it generic
        //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        //_gaq.push(['_trackEvent', category, action, label]);
        setTimeout('document.location = "' + originalLink + '"', 100)
    } catch (err) { }
}
