﻿$(function () {
    $("[data-photo-id]").each(function () {
        var photoId = $(this).attr("data-photo-id");
        Flickr.ExtraTexts.push(Flickr.ResolveCaption($(this)));
        Flickr.ShowLoading(photoId);
        Flickr.ShowPhoto(photoId, "Medium");
    });
});

var Flickr = {

    ResolveCaption: function (div) {
        var caption = div.attr("data-photo-caption");
        if (caption != undefined)
            return caption;
        return "";
    },

    ExtraTexts: new Array(),

    Logo: "<a href=\"http://www.flickr.com\" class=\"flickrLogo\"><img src=\"http://www.connemara.net/Content/Images/SocialMedia/flickr.png\" alt=\"Flickr\" /></a>",

    ShowLoading: function (id) {
        $('[data-photo-id="' + id + '"]').html(Flickr.Logo + "{ Loading photo... }");
    },

    ShowPhoto: function (id, size) {
        $.ajax({
            data: { id: id, size: size },
            dataType: "jsonp",
            jsonpCallback: "Flickr.ParseCallback",
            url: "http://www.connemara.net/services/Flickr/FlickrClient.ashx" // "/services/flickr/FlickrClient.ashx"
        });
    },

    ParseCallback: function (json) {
        // show the photo!
        Flickr.GetHTML({ "json": json });
    },

    GetHTML: function (params) {
        var json = params["json"];
        var id = json.id;
        var html = "<a href=\"" + json.link + "\"><img src=\"" + json.source + "\" alt=\"Flickr photo\"></a><br /><span class\"flickrText\">" + Flickr.Logo + "\"<a href=\"" + json.link + "\">" + json.title + "</a>\", by " + json.photographer;

        // get any extra text already in place
        var extraText = Flickr.ExtraTexts.shift(); // remove first element
        if (extraText != "")
            html += ". " + extraText;
        html += "</span>";

        // render HTML
        $('[data-photo-id="' + id + '"]').html(html);
    }
};
