jQuery.fn.galletri = function(options) {
    var defaults = { TNL: "#" + $(this).attr("id"), attributes: "Picture1,Picture2,Picture3", Description: "#PictureDesc", fadeInterval: 400 };
    var opts = $.extend(defaults, options);
    var TNL = opts.TNL;
    var attributes = opts.attributes.split(",");
    var fadeInterval = opts.fadeInterval;
    var PictureDesc = opts.Description;


    $(TNL + " a").click(function() {
        var CurLink = $(this);
        $("#" + attributes[1]).addClass("loading");
        $(PictureDesc).fadeOut(300, function() {
            $(this).html('<p>' + $(CurLink).siblings(".referenceContainer").children(".referenceText").html() + '</p>');
            $(PictureDesc + " a:first").removeClass().addClass('redArrow');
            $("#PictureDesc a[rel*='lightbox']").lightBox();
            $(this).fadeIn(fadeInterval);
        });
        $("#PictureDesc2").fadeOut(300, function() {
            var ReferenceDesc = '<p>' + $(CurLink).siblings(".referenceContainer").children(".referenceDescription").text() + '</p>';
            $(this).empty();
            $(this).html(ReferenceDesc);
            $(this).fadeIn(fadeInterval);
        });

        for (var i in attributes) {
            NewPic("#" + attributes[i], $(this).siblings(".referenceContainer").children(".referenceImages").children("." + attributes[i]).text(), i * fadeInterval + fadeInterval);
        };
        return false;
    });

    function NewPic(id, src, fadeTime) {
        //hvis der ikke er noget billede:
        var blanksrc = "\/umbraco\/imagegen.aspx?height=240&image=";

        if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
            var Numb1 = Math.random() * 1001;
            var Numb2 = Math.random() * 10001;
            src += "&" + Numb1 + "=" + Numb2;
            blanksrc += "&" + Numb1 + "=" + Numb2;
        }

        pic = $(id + " img");
        if (pic.length) {
            $(id).append("<p id='fill'>&nbsp;</p>");
            pic.stop().fadeOut(300).remove();
        }
        if (src != blanksrc) {
            var largeImage = new Image();
            $(largeImage).attr("src", src)
             .load(function() {
                 if (!($(id + " img").length)) {
                     $(largeImage).hide();
                     $("#" + attributes[1]).removeClass("loading");
                     $(id).append(largeImage);
                     $(largeImage).fadeIn(fadeTime);
                     $("#fill").remove();
                 }
             });
        }
    }
    $(TNL + " a:first").click();
};
