$(document).ready(function() {
   
    initializeAnalytics();
    countriesMenu();
    
});

function countriesMenu() {
    $('div#countries a.toggle').click(function() {
       $('ul#countries_menu').slideToggle(200);
        return false;
    });
}

var rxExternalURL = /(^http:\/\/.*$)|(^https:\/\/.*$)/;
var rxLocalURL = /(^$)|(^#.*$)|(^\/.*$)/;
var rxMailURL = /^mailto:(.*)$/;
var rxDocURL = /^.+\.(pdf|doc|docx|xls|xlsx|ppt|pptx|txt)$/i;

var genericLinkHandler = function() {
    var href = $(this).attr('href');
    
    // If it's marked as an external link, do it.
    if ($(this).hasClass('external_link')) {
        $(this).attr('target', '_blank');
    }
    
    // If it's an external link:
    if (rxExternalURL.test(href)) {
        _gaq.push(['_trackEvent', 'External Link', 'Click', href]);
    }
    // If it's an email link:
    else if (rxMailURL.test(href)) {
        _gaq.push(['_trackEvent', 'Email Link', 'Click', href]);
    }
    
    // If it's an internal (implied) document link:
    if (rxDocURL.test(href)) {
        _gaq.push(['_trackEvent', 'Document Link', 'Click', href]);
    }
}

var countryLinkHandler = function() {
    _gaq.push(['_trackEvent', 'Country Link', 'Click', $(this).attr('href')]);
}

var billboardLinkHandler = function() {
    _gaq.push(['_trackEvent', 'Billboard', 'Click', $(this).attr('href')]);
}

// This can be run multiple times! Especially when introducing new elements on
// the page.
function registerAnalytics() {
    
    // Regardless of the link's type, we'll attach an intelligent handler
    // to it that will assess the link's intentions when it's clicked.
    $('a').each(function() {
        // Remove the event handler if it's already there.
        try {
            $(this).unbind('click', genericLinkHandler);
        } catch (e) {}
        // Reregister that same handler.
        $(this).bind('click', genericLinkHandler);
    });

}

// This should only be run once, at page load.
function initializeAnalytics() {
    
    // This can be run multiple times, but should be run initially too.
    registerAnalytics();
    
    // Unregister the COUNTRY MENU's events and replace it with a better one.
    $('#countries_menu li a').each(function() {
        // Remove the standard onclick handler.
        try {
            $(this).unbind('click', genericLinkHandler);
        } catch (e) {}
        // Add the more specific country handler.
        $(this).bind('click', countryLinkHandler);
    });
    
    // Unregister the BILLBOARDS' events and replace it with a better one.
    $('.audience-slide-content a.learn-more').each(function() {
        // Remove the standard onclick handler.
        try {
            $(this).unbind('click', genericLinkHandler);
        } catch (e) {}
        // Add the more specific country handler.
        $(this).bind('click', billboardLinkHandler);
    });
    
}


