﻿// ==== GoogleAnalytics ====
document.onclick = function (event) {
    //debugger;
    event = event || window.event;
    var target = event.target || event.srcElement;
    var targetElement = target.tagName.toLowerCase();
    if (targetElement == "span") {
        target = target.parentElement;
        targetElement = target.tagName.toLowerCase();
    }
    if (targetElement == "a") {
        var href = target.getAttribute("href");
        if (href != null) {
            if (IsExternalLink(href)) {
                if (!TrackDownloadableFileType(href)) {
                    GA_Track_External_Click_Event(href);
                }
            } else if (IsMailtoLink(href)) {
                GA_Track_Mailto_Click_Event(href.substr(7));
            } else {
                TrackDownloadableFileType(href)
            }
        }
    }
};

function IsExternalLink(href) {
    if (href == null) return false;
    var urlHost = document.domain.replace(/^www\./i, "");
    return href.match(/^https?\:/i) && !href.match("^(?:https?:)?\/\/(?:(?:www)\.)?" + urlHost + "\/?");
}

function IsMailtoLink(href) {
    if (href == null) return false;
    return href.match(/^mailto\:/i);
}

function TrackDownloadableFileType(href) {
    if (href == null) return false;
    var fileExtensionsToTrack = /^.*\.(pdf|jpg|png|gif|zip|mp3|txt|doc|rar|js|py|reg|exe)$/i;
    var fileType = fileExtensionsToTrack.exec(href);
    if (fileType) {
        GA_Track_Download_Click_Event(href, fileType[1]);
        return true;
    }
    return false;
}

function GA_Track_Mailto_Click_Event(email) {
    GA_TrackEvent('Mailto', 'click', email);
};

function GA_Track_Download_Click_Event(href, fileType) {
    GA_TrackEvent('Download', fileType, href, fileType);
};

function GA_Track_External_Click_Event(href) {
    GA_TrackEvent('External', 'click', href);
};

function GA_TrackEvent(eventCategory, action, value) {
    //alert('GA_TrackEvent: ' + eventCategory + '_' + action + '\n' + value);
    if (_gaq != null) {
        if (value != null) {
            _gaq.push(['_trackEvent', eventCategory, action, value]);
        }
        else {
            _gaq.push(['_trackEvent', eventCategory, action]);
        }
    }
};
