// runsummary.js
// 
// Runs through a table of information about runs and generates information about them
// such as: total mileage; personal bests; average weekly mileage and monthly mileage.
// 
// The (function () {} ()); pattern is an immediate function that will run as soon as it 
// has been parsed. We can use this instead of addEvent(....) to run on document load.
// Since the function is anonymous we don't add anything to the global namespace. In
// addition all the helper functions are internal as well so they don't become global.
// 
// Have run through JSLint with the following options:
// jslint - browser: true, sloppy: true, plusplus: true, maxerr: 50, indent: 4 

(function () {
    var runSumCount = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        runCount = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
        t,
        d = document,
        pbCount = 0,
        curDate = new Date(),
        curYear = curDate.getYear(),
        inCurYear = false,
        dateVal,
        dateArray,
        curNode,
        tabNode,
        sum = 0,
        sumMax = 0,
        weeks = 52,
        yearStart,
        dist = 0,
        mult,
        text = "",
        content = "",
        len,
        i,
        r,
        n;

    // If we aren't a modern browser then quit
    if (!d.getElementById || !d.createElement || !d.createTextNode) {
        return;
    }
    t = d.getElementById('runs');
    if (!t) {
        return;
    }

    //  Internal helper functions.
    function hasClass(obj) {
        var res = false;
        if (obj.getAttributeNode("class") !== null) {
            res = obj.getAttributeNode("class").value;
        }
        return res;
    }

    function checkRowClass(t, r, c) {
        return hasClass(t.rows[r]) === c;
    }

    function getCellValue(obj) {
        var c;
        if (typeof obj === 'string') {
            c = d.getElementById(obj);
        } else {
            c = obj;
        }

        c.normalize();
        if (c.firstChild.nodeType === 3) {
            return c.firstChild.nodeValue;
        } else if (c.firstChild.nodeType === 1) {
            return c.firstChild.firstChild.nodeValue;
        } else {
            return '';
        }
    }

    function dateToDays(t) {
        return t.getTime() / (1000 * 60 * 60 * 24);
    }

    // OK, on with the show ...
    if (curYear < 1900) {
        curYear += 1900;
    }

    yearStart = new Date(curYear, 0, 1);

    if (d.getElementById('top2').innerHTML.indexOf(curYear) !== -1) {
        weeks = Math.ceil((dateToDays(curDate) - dateToDays(yearStart)) / 7);
    }

    len = t.rows.length;
    for (r = 0; r < len; r += 1) {
        dist = parseFloat(getCellValue(t.rows[r].cells[1]));
        pbCount += checkRowClass(t, r, "pbest") ? 1 : 0;
        if (!isNaN(dist)) {
            sum += dist;
            dateVal = getCellValue(t.rows[r].cells[0]);
            dateArray = dateVal.split(' ');

            for (i = 0; i < 12; i += 1) {
                if (dateArray[1] === monthNames[i]) {
                    runSumCount[i] += dist;
                    runCount[i] += 1;
                }
            }
        }
    }

    if (d.getElementById('top2').innerHTML.indexOf(curYear) !== -1) {
        inCurYear = true;
    }

    // A bit of text about personal bests, totals and averages.
    content =  (inCurYear ? "So far this year I have " : "This year I achieved ");
    if (pbCount) {
        content += "achieved personal bests in " + pbCount + ((pbCount > 1) ? " events." : " event.");
    } else {
        content += "no personal bests.";
    }

    curNode = d.getElementById("mileage");
    n = d.createElement('p');
    n.appendChild(d.createTextNode("Total mileage this year is " + Math.round(sum * 100) / 100 + " miles. "));
    curNode.appendChild(n);
    n = d.createElement('p');
    n.appendChild(d.createTextNode("Average weekly mileage is " + Math.round((sum / weeks) * 100) / 100 + " miles. "));
    curNode.appendChild(n);
    n = d.createElement("p");
    n.appendChild(d.createTextNode(content));
    curNode.appendChild(n);

    tabNode = d.getElementById("monTot");

    if (tabNode) {
        for (i = 0; i < 12; i += 1) {
            if (runSumCount[i] > sumMax) {
                sumMax = runSumCount[i];
            }
        }
        // Chose 200 as it's roughly 50 miles per week which is probably my upper limit.
        mult = 200 / sumMax;

        text = "<table id='monTab'><caption>Monthly totals:</caption><tbody> <tr>";
        for (i = 0; i < 12; i += 1) {
            if (runSumCount[i] > 0) {
                text += "<td><img src='..\/pictures\/red.gif' width='25' height='" + (mult * runSumCount[i]) + "'></td>";
            } else {
                text += "<td></td>";
            }
        }
        text += "</tr><tr>";
        for (i = 0; i < 12; i += 1) {
            if (runSumCount[i] > 0) {
                text += "<td>(" + runSumCount[i] + ")</td>";
            } else {
                text += "<td>&nbsp;</td>";
            }
        }
        text += "</tr><tr>";
        for (i = 0; i < 12; i += 1) {
            text += "<td>" + monthNames[i] + "</td>";
        }
        text += "</tr></tbody></table>";
        tabNode.innerHTML = text;
    }
}());
// End of file



