// IGA.linktagger.js
// Logs outbound links in Google Analytics

(function($) {
    window._gaq = window._gaq || [];

    setInterval(function() {
        $("a").not(".echo-gallery-container a").not(".ts_buttonlink").not(".linktagged").each(function() {
            $(this).addClass("linktagged");
            var href = this.href;
            var target = this.target;
            var rex = /^http:\/\/([^\/\?\#]+)((?:\/(?=[^#\?]))?.*?)\/?([#\?]|$)/i;
            var matches = rex.exec(href);
            if (matches && matches[1] != window.location.hostname) {
                $(this).click(function(e) {
                    var pageView = '/outgoing/' + matches[1] + matches[2];
                    _gaq.push(['_trackPageview', pageView]);
                    if (!target || target == "_top") {
                        setTimeout(function() {
                            navigate(href, target);
                        }, 100);
                        e.preventDefault();
                    }
                });
            }
        });
    }, 1000);
    
    // Navigate to the given link, preserving the referer
    function navigate(link, target) {
        var cheatForm = $('<form method="get"></form>').attr({action: link, target: target}).appendTo(document.body);
        
        // rebuild query string if necessary
        var qrex = /\?(.+)$/;
        var matches = qrex.exec(link);
        if (matches) {
            var params = matches[1].split("&");
            for (var n=0; n < params.length; n++) {
                var parts = params[n].split("=");
                $('<input type="hidden" />').attr({name: decodeURIComponent(parts[0]), value: decodeURIComponent(parts[1])}).appendTo(cheatForm);
            }
        }
        
        cheatForm[0].submit();
    }
})(jQuery);
