// The document has to be loaded before the links can be selected.
// This line tells jQuery to run the function only after the document has loaded.
$(document).ready(function(){

    // This line uses a jQuery attribute selector to find every link containing "/visit/".
    // It then binds a click event to each link, which runs this anonymous function when clicked.
    $("a[href*='/visit/']").click(function(){
    
        //This line uses the jQuery attribute function to get the url (href) of the link.
        // $(this) refers the current element. In this case, it's the link that was clicked.
        var url = $(this).attr('href'); 
        
        //This line uses the Javascript String function "replace" to change any substring "../" in the url into an empty substring "".
        // The first parameter is a regular expression that finds '../'. The "g" makes it find all matches instead of the first one.
        // The periods have to be escaped with backward slashes because they are special characters in regular expressions.
        url = url.replace(/\.\.\//g, ""); 
        
        //This line uses the Javascript String function "match" to check if the url has "http", "https", or "www" at the start.
        // Again, the function parmeter is a regular expression. The caret (^) refers to the start of the string.
        if (url.match(/^(http|https|www)/) == null) {
        
            // If those substrings are not present, this line adds the forward slash at the start if it's missing
            if (url.match(/^\//) == null) url = '/' + url;
        }
        
        //Finally, the corrected link is sent off to PageTracker.
        pageTracker._trackPageview(url);
    });
});
