document.observe("dom:loaded", function() {

    var bysshe = new Bysshe(new Cookie(document));
    
    // Save the region id into a cookie, so that the analytics code
    // can figure out what region was clicked on.
    
    document.observe('click', function(v) {
        
        // See if we're dealing with a click on an <a>.  Note that if the
        // HTML source is <a><img></a>, then this code is triggered on the 
        // <img> element.

        var e = v.element();
                
        if (e.tagName.toLowerCase() != "a") {
            e = e.up("a");
        }
        
        if (!e) { 
            // A click happened, but it doesn't seem to be a click
            // on a <a>.
            return;
        }
        
        // "pathname" is a "magic" property of <a> elements. 
        
        var pathname = e.pathname;
        
        // Find the first ancestor with an id. 
        
        while (e.id === "" && e != document.body) {
            e = e.parentNode;
        }
        
        bysshe.setPathnameData(pathname, new Date().getTime(), e.id);
        
    });
    
    new Ajax.Request("/api/visit/", {
        method: "POST",
        parameters: bysshe.getInfo(),
        onSuccess: function(res) {
            var t = new Template([
                '<h2>Stats</h2>',
                '<ul class="flat">',
                  '<li>Views last month: <strong>#{hits}</strong></li>',
                  '<li>Last viewed: #{last_hit}</li>',
                  '<li><img src="#{sparkline.url}" width="#{sparkline.width}" height="#{sparkline.height}" alt="Hits over last 28 days" title="Hits over last 28 days" id="sparkline"/></li>',
                '</ul>'
            ].join("\n"));
            res.responseJSON.last_hit = res.responseJSON.last_hit.replace(/^(\d+)/, '<strong>$1</strong>');
            if ($("stats")) {
                $("stats").update(t.evaluate(res.responseJSON));
                //$("stats").show();
            }
        }
    });

});

