﻿(function ($)
{
    var idleTime = 5000;
    var rowLength = 5;
    var numberOfRows = 0;

    $.fn.imageScroller = function (o, p)
    {
        var defaults =
        {
            domain: "http://www.dhf.dk/",
            feed: "http://www.dhf.dk/Frontend/DHF/DHF.Widget.Gallery.Small/Server/DHF.Widget.Gallery.Small.ashx?galleryID=60d08165-4379-4aa4-b910-985f079437a5",
            target: "gallery-teaser-slideshow"
        };

        if (typeof o == "string" && typeof p != "undefined")
        {
            defaults[o] = p;
            o = {};
        }
        else if (typeof p == "function")
        {
            defaults.callAfter = p;
        }

        o = $.extend(defaults, o || {});

        $.ajax(
        {
            type: "GET",
            url: o.feed,
            dataType: "xml",
            success: function (xml)
            {
                $(xml).find('item').each(function (i, val)
                {
                    var id = $(this).attr('id');
                    var thumb = $(this).attr('thumb');
                    var url = $(this).attr('url');
                    var caption = $(this).find('name').text();

                    var row = Math.ceil((i + 1) / rowLength);
                    var div = $('<div class="image round-' + row + '" id="link_' + id + '"></div>');

                    if (((i + 1) % rowLength) == 0)
                    {
                        div.addClass('last');
                    }

                    if (i == 0 || (i % rowLength == 0))
                    {
                        div.addClass('first');
                        numberOfRows++;
                    }

                    if (caption.length > 14)
                    {
                        caption = caption.substr(0, 14) + ' ...';
                    }

                    div.html('<a href="' + o.domain + url + '"><img src="' + o.domain + thumb + '"></a><a class="caption" href="' + o.domain + url + '">' + caption + '</a>').appendTo('#' + o.target);

                    if ((i + 1) > rowLength)
                    {
                        displayBatch(1);
                    }
                });
            }
        });
    };

    function displayBatch(row)
    {
        if (row > numberOfRows) row = 1;

        $(".image").each(function ()
        {
            $(this).hide();
        });

        $(".round-" + row).each(function ()
        {
            $(this).fadeIn();
        });

        setTimeout(function () { displayBatch(row + 1); }, idleTime);
    }
})(jQuery);
