$(function() {
    function toAge(n) {
        if (n < 0) {
            return Math.abs(n) + "BC"
        } else if (n > 0) {
            return Math.abs(n) + "AD"
        } else {
            return n;
        }
    }
    function round(n, dp) {
        return Math.round(n * (10 * dp)) / (10 * dp);
    }
    function toSlug(str) {
        return str.toLowerCase().replace(/\W/g, "-");
    }
    function toScore(civ) {
        // is this an integer?
        return Math.log(civ.p);
    }
    
    var civs = [];
    var continents = {};
    $("table tbody tr")
        .each(function() {
            var name = $(this).find("th a");
            var info = $(this).find("td");
            var civ = {
                n: $(name).text(),
                l: $(name).attr("href"),
                b: parseInt($(info[0]).text(), 10),
                e: parseInt($(info[1]).text(), 10),
                p: parseInt($(info[2]).text(), 10),
                o: $(info[3]).text()
            };
            civs.push(civ);
            continents[$(info[3]).text()] = 1;
        })
        .sort(function(a, b) {
            if (a.b < b.b) return 1;
            if (a.b > b.b) return -1;
            return 0;
         });
         
    var min_year = null;
    var max_year = null;
    var min_popularity = null;
    var max_popularity = null;
    $.each(
        civs,
        function() {
            if (min_year == null || this.b < min_year) {
                min_year = this.b;
            }
            if (max_year == null || this.e > max_year) {
                max_year = this.e;
            }

            if (min_popularity == null || toScore(this) < min_popularity) {
                min_popularity = toScore(this);
            }
            if (max_popularity == null || toScore(this) > max_popularity) {
                max_popularity = toScore(this);
            }
        }
    );
    
    $("table").hide();
    var timeline = $("<div />").attr("id", "timeline").insertAfter("table");
    var key = $("<div />").attr("id", "key").appendTo(timeline);
    var graph = $("<div />").attr("id", "graph").appendTo(timeline);
    
    var period = Math.abs(min_year) + Math.abs(max_year);
    var top = 0;
    // var height = round((100 / civs.size()), 2);
    var height = 42;
    var index = 0;
    $.each(
        civs,
        function() {
            var civ = this;
            
            var left = ((civ.b - min_year) / period) * 100;
            var width = ((civ.e - this.b) / period) * 100;
            var opacity = (toScore(civ) / max_popularity);
            
            $("<div />")
                .width(width + "%")
                .css({
                    left: left + "%",
                    top: top + "px",
                    height: height + "px",
                    zIndex: index,
                    opacity: opacity
                })
                .addClass(toSlug(civ.o))
                .html("<span />")
                .tooltip({ 
                    bodyHandler: function() { 
                        var title = "The <strong>" + civ.n + "</strong> lot were big from " + toAge(civ.b) + " to " + toAge(civ.e) + " in " + civ.o + " and left " + civ.p + " results in Google.";
                        return title;
                    }, 
                    delay: 1000,
                    showURL: false,
                    fade: 200
                })
                .appendTo(graph);
            
            var truncated_title = civ.n.length > 11 ? civ.n.substring(0, 10) + "..." : civ.n;
            $("<div />")
                .css({
                    top: top + "px",
                    height: height + "px"
                })
                .html("<a href=\"" + civ.l + "\">" + truncated_title + "<small>" + toAge(civ.b) + " &rarr; " + toAge(civ.e) + "</small></a>")
                .appendTo(key);

            $("<div />")
                .addClass("line")
                .css({
                    top: top + "px"
                })
                .appendTo(timeline);
            top = top + height;
            index = index + 1;
        });
    
    var cheatsheet = $("<ul />").appendTo(timeline);
    $.each(
        continents,
        function(name) {
            // (100/continents.length)
            $("<li />")
                .css({width: 20 + "%"})
                .html("<img class='" + toSlug(name) + "' src='/trans.gif'/> " + name)
                .appendTo(cheatsheet);
        });
    
    $("<div />")
        .addClass("line")
        .css({
            top: top + "px"
        })
        .appendTo(timeline);
});
