(function(){ // Must be loaded after DOMReady

var
// Q: Wut?
// A:
//   1. Compressor will minify references to the local names but not the globals;
//      also, this means the the code doesn't have to be filled with var w = window.
//   2. `var undefined` protects us from context pollution.
//   3. `var _window = window` et al are necessary to avoid blowing up the world;
//      you can't safely `var window = window` (or document), ever, in any context. 
//      It will silently halt execution.
//   3a. Except location. `var location = window.location` means "Welcome to 
//      Infinite Loopville, population you!" in some languages.
undefined,
_window = window,
_document = _window.document,
_location = _window.location,

// Constants
CDN_TRACKING_URL       = '//l.addthiscdn.com/ds/mg.gif',
VL_ENDPOINT            = 'http://api.viglink.com/api/click?key=3d00fd2a504d751a33437eff75f92710&format=jsonp&',
VL_TIMEOUT             = 350,
PING_WAIT              = 150,

basename = function (path, sep){
    return (path || '').split(sep || '/').pop();
},

dirname = function (path, sep){
    return (path || '').split(sep || '/').slice(0,-1).join(sep || '/');
},

/**
 * Given we're on https://zooshock.com/favourites/ then:
 * 
 * canonicalize(url) :: url =
 *    http://www.addthis.com/get-you-one    -> http://www.addthis.com/get-you-one
 * |  //www.addthis.com/get-you-one         -> https://www.addthis.com/get-you-one
 * |  /lol/dongs                            -> https://zooshock.com/lol/dongs
 * |  share?with=mom@willmeyer.com          -> https://zooshock.com/favourites/share?with=mom@willmeyer.com
 * |                                        -> https://zooshock.com/favourites/
 * 
 * TODO: Unit test this. It is a gordian knot of branching.
 */
canonicalize = function(url){
    if (!url)
        return ''+_location;
    if ( !(/^(https?:)?\/\//).test(url) )
        url = [
                '//', 
                _location.hostname,
                ( url.indexOf('/') !== 0
                    ? dirname(_location.pathname)+'/'+url
                    : url )
            ].join('');
    return ( url.indexOf('//') === 0
            ? _location.protocol+url
            : url );
},

// fqdn --> sld.tld
extractDomain = function(url){
    return canonicalize(url)
        .replace(EXTRACT_DOMAIN_PATTERN, '$1')
        .split('.')
        .slice(-2)
        .join('.');
},
EXTRACT_DOMAIN_PATTERN = (/^(?:https?:)?\/\/([^\/:]+)(?:\:\d*)?(\/.*)?$/),
ON_DOMAIN_HOST = extractDomain(),

viglinkApi = function(url, callback){
    var
    cb_name = 'addthis_jsonp_cb_' + _ate.cuid(),
    s = _document.createElement('script');
    
    // if jsonp returns first, clear jsonp callback turd
    // and execute real callback.
    _window[cb_name] = function(){
        _window[cb_name] = undefined;
        callback.apply(_window, arguments);
    };
    
    s.type = 'text/javascript';
    s.src = VL_ENDPOINT + _ate.toKV({
        jsonp : cb_name,
        out   : url,
        loc   : ''+_location
    });
    _document.body.appendChild(s);
    
    // if we timeout, make sure we don't double-invoke the callback
    // and ensure the cleanup occurs when/if the request comes back.
    setTimeout(function(){
        if ( !_window[cb_name] ) return;
        
        _window[cb_name] = function(){ _window[cb_name] = undefined; };
        callback(url, 1);
    }, VL_TIMEOUT);
},
imgz = [],
// t: timeout occurred
// w: wait time
// s: scavenged URL
ping = function(data){
    var i = new Image();
    imgz.push(i);
    i.src = CDN_TRACKING_URL+'?'+_ate.toKV(data);
},

okUrl = function(url){
    url = canonicalize(url);
    return (url &&
        ON_DOMAIN_HOST !== extractDomain(url) &&
        url.indexOf('/bookmark.php') < 0);
},
okLink = function(el){
    if (!el || !el.href )
        return false;
    return okUrl(el.getAttribute('href'));
},
scavenge = function(link, evt, oc_return){
    var url = canonicalize(link.href);
    
    // we ain't goin' anywhere if:
    //   - no event
    //   - publisher's onclick handler returned false
    //   - target URL is on-domain (relative to current page)
    //   - link wants to open in another frame (FIXME)
    //   - user is attempting to open in a new window (TODO)
    if ( !evt || oc_return === false || !okLink(link) || link.target )
        return oc_return;
    
    var start = new Date().getTime();
    viglinkApi(url, function(taggedUrl, isTimeout){
        var wait = new Date().getTime() - start;
        
        // Analytics
        if ( isTimeout )
            ping({ 'w':wait, 't':1 });
        else if ( url === taggedUrl )
            ping({ 'w':wait });
        else
            ping({ 'w':wait, 's':taggedUrl });
        
        // Gogogogo!
        setTimeout(function(){
            _window.location = taggedUrl;
        }, PING_WAIT);
    });
    
    // Stop link navigation
    if (evt.preventDefault)
        evt.preventDefault();
    evt.returnValue = false;
    return false;
};

// Process all links on the page
_ate.reduce( _document.getElementsByTagName('a'),
    function( _, link ){
        
        if ( !okLink(link) ) return;
        
        // Use closure to capture return value and pass it around
        var oc = link.onclick, oc_return;
        if( typeof oc === 'function' )
            link.onclick = function(){
                oc_return = oc.apply(this, arguments);
                return oc_return;
            };
        
        _ate.listen(link, 'click', function(evt){
            
            var r = scavenge(link, evt || _window.event, oc_return);
            
            // Reset return so we don't accidentally reuse it
            oc_return = undefined;
            return r;
        });
    });

})();

