// Give up trying any more flickr API calls if we hit a max number of failures.
var flickrFailures = 0;
var maxFlickrFailures = 10;

window.onload = function()
{
    loadFlickrImages();

    // 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(decodeURIComponent(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 && (flickrFailures <= maxFlickrFailures))
    {
        setTimeout(loadFlickrImages, 10000);
    }
}

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")
    {
        flickrFailures++;
        if (data["code"] == 1)
        {
            // Image not found. This is unrecoverable, so no point annoying the user with warnings.
        }
        else
        {
            alert("Error getting images: " + data["message"]);
        }
      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);
        }
    }
}

