﻿var mpTrackerGif = 'http://localhost/most-popular/images/tracker.gif';

//On window load...
window.onload = function() {    
    //...retrieve accordion data in JSON-P format
    new Asset.javascript('http://www.nejm.org/most-popular/accordion-data.aspx');
}

//Called when the data is loaded
fillAccordion = function(data) {
    //Create a <dl> to store accordion data in.
    accordion = new Element('dl').injectAfter($('mpHead'));
    accordion.className = 'accordion';
    
    //Add a <dt> (title) and <dd> (content) for each category in the accordion data 
    accordion.innerHTML = buildString(data.categories, function(cat) {
        return '<dt>' + cat.name + '</dt><dd><ol>' + 
                getListItems(cat.links) + '</ol><p class="moreLink">' + 
                '<a href="' + cat.link + '">more &gt;</a></p></dd>';
    });
    
    //Apply mootools accordion script to all <dl>s with a class of accordion
    $$('dl.accordion').each(function(el) {
        new Accordion(el.getElements("dt"), el.getElements("dd"), { show: 0 });
    });
    
    //Add hover behavior to <dt>s
    $$('dl.accordion dt').each(function(el) {
        el.onmouseover = function(e) { el.addClass('hover') };
        el.onmouseout = function(e) { el.removeClass('hover') };
        el.addEvent('click', function(e) { trackAction(el, 'expand'); });
    });
    
    $$('dl.accordion dd a').each(function(a) { 
        a.addEvent('click', function(e) {
            e = new Event(e);
            var el = e.target.getParent().getParent().getParent().getPrevious();
            trackAction(el, 'clickLink');
            e.stop();
            (function() { document.location.href = e.target.href; }).delay(500);
        });
    });
};

trackAction = function(el, action) {
    var section = $pick(el.innerText, el.textContent);
    var randomNum = new Date().getTime() + '' + Math.floor(Math.random()*1000000);
    new Asset.image(mpTrackerGif + '?action=' + action + '&section=' + section + '&rnd=' + randomNum);      
}

//Construct a link for each link in this category
getListItems = function(links) {
    return buildString(links, function(link) {
        return '<li><a href="' + unescape(link.url) + '">' + unescape(link.title) + '</a></li>'
    });
};

//Returns the concatenation of the results of running fn on each item in arr
buildString = function(arr, fn) {
    str = '';
    arr.each(function(item) { str += fn(item) });
    return str;
};