window.onload = function()
{
    loadFlickrImages();
    if(document.location.href.match(/Expense.*Tally/)) tallyExpenses();

    // Create breadcrumbs.
    var path = document.location.href.split("/");
    path.shift(); // http:
    path.shift(); // [blank]
    path.shift(); // (www.)?tylerkaraszewski.com
    path.pop();   // file name
    var mainTitle = document.getElementsByTagName("h1")[0];
    var lastSubpath = "";
    for(var i = 0; i < path.length; i++)
    {
        var link = document.createElement("a");
        lastSubpath += "/" + path[i];
        link.href = lastSubpath;
        link.appendChild(document.createTextNode(path[i]));
        mainTitle.appendChild(document.createTextNode(" \u25B8 "));
        mainTitle.appendChild(link);
    }

    // Sets up comments to work on any page that's included the comments script.
    if(window.commentScript) initComments();
}

function loadFlickrImages()
{
    var links = document.getElementById("main").getElementsByTagName("a");
    var parser = new RegExp(/^flickr(Medium)?[iI]mg(\d+)$/);
    var matches;
    var checkAgain = false;
    for(var i = 0; i < links.length; i++)
    {
        if(links[i].id && (matches = parser.exec(links[i].id)))
        {
            if(!links[i].lookupComplete)
            {
                flickrSizeLookup(matches[2]);
                checkAgain = true;
            }
        }
    }

    if(checkAgain)
    {
        setTimeout(loadFlickrImages, 10000);
    }
}

function tallyExpenses()
{
    var lis = document.getElementById("main").getElementsByTagName("li");
    var matcher = /\$((\d|,)+\.\d+)$/;
    var total = 0;
    var result;
    for(var i = 0; i < lis.length; i++)
    {
        if(result = matcher.exec(lis[i].innerHTML))
        {
            total += parseFloat(result[1].replace(/,/g, ""));
        }
    }
    total = Math.round(total * 100)/100; // Yay floating point rounding errors.
    if(total > 1000)
    {
        total = total.toString().replace(/(\d\d\d\.)/, ",$1");
    }
    // if(total > 1000000) ... // I should have got a nicer boat for this kind of cash.
    document.getElementById("main").innerHTML += ("<div>Total to date: $" + total + "</div>");
}

function flickrSizeLookup(imgid)
{
    var url = "http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key=" +
        "6af57450424a006cc948dbf76d1e2fdd&photo_id=" + imgid + "&format=json";
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = url;
    document.getElementsByTagName("head")[0].appendChild(s);
    setTimeout(function(){s.parentNode.removeChild(s)}, 10000);
}

function jsonFlickrApi(data)
{
    if(data["stat"] != "ok")
    {
        alert("Error getting images: " + data["stat"]);
        return;
    }
    // Handle the (only case so far) case where we want to get the URL for particular-sized images.
    // TODO: This breaks if we have the same image included twice on one page. Fix that.
    if(data["sizes"]){
        var list = data["sizes"]["size"];

        // Nothing we can do here, but it shouldn't ever actually happen.
        if(!list.length) return;

        var src = "";
        var href = "";
        var width = 0;
        var height = 0;
        
        // we need the image ID, which isn't provided ,but is part of the provided URL.
        imgid = list[0]["url"].replace(/^\D*(\d+)\/sizes.*$/, "$1");

        // The size we want for this image is part of its link's id.
        var useSize = "Small";
        var link = document.getElementById("flickrimg" + imgid);
        if(!link)
        {
            link = document.getElementById("flickrMediumImg" + imgid);
            useSize = "Medium";
        }

        // If we found a link for this image, insert the appropriate graphic and href tag.
        if(link)
        {
            for(var i = 0; i < list.length; i++)
            {
                if(list[i]["label"] == useSize)
                {
                    src = list[i]["source"];
                    width = list[i]["width"];
                    height = list[i]["height"];
                }
                // And link to the large sized image.
                if(list[i]["label"] == "Large")
                {
                    href = list[i]["url"];
                    imgid = href.replace(/^\D*(\d+)\/sizes.*$/, "$1");
                }
                // If there is no 'large' size, try the original size.
                if(list[i]["label"] == "Original" && href === "")
                {
                    href = list[i]["url"];
                    imgid = href.replace(/^\D*(\d+)\/sizes.*$/, "$1");
                }
            }
            link.href = href;
            link.lookupComplete = true;
            var img = document.createElement("img");
            img.src = src;
            img.setAttribute("width", width + "px");
            img.setAttribute("height", height + "px");
            img.alt = "";
            link.appendChild(img);
        }
    }
}
