/* Copyright 2009 Monsternett AS */

jQuery.fn.adsRoll = function(providedOptions)
{
    var opts = $.extend({}, jQuery.fn.adsRoll.defaults, providedOptions);

    if (opts.images.lenght < 1)
        return;

    function swapMe(a, dupe, orig)
    {
        var next = opts.images.splice(0,1)[0];
        opts.images.push(next);

        dupe.src = next.logo;

        if (a.tagName === 'A')
        {
            a.href = next.link;
        }
    }

    function shuffle(o) 
    {
        for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
        return o;
    };

    function getPosition(obj, dir) {
        var pos = (dir == 'x') ? obj.offsetLeft : obj.offsetTop;
        var tmp = obj.offsetParent;

        while(tmp != null) {
            pos += (dir == 'x') ? tmp.offsetLeft : tmp.offsetTop;
            tmp = tmp.offsetParent;
        }

        return pos;
    }

    var start_wait = opts.time_delta;

    var elements = this;
    if (opts.shuffle)
    {
        elements = shuffle(elements);
    }

    return elements.each(function()
    {
        var a = this;
        var dupe = $(".dupe", a)[0];
        var orig = $(".orig", a)[0];

        setTimeout( function() { swapMe(a, dupe, orig); }, start_wait );

        start_wait += opts.time_delta;

        if (opts.auto_height)
        {
            $(orig).css('top', opts.auto_height($(orig).height()) + 'px');
        }

        dupe.onload = function() {
            if (opts.auto_height)
            {
                $(dupe).css('top', opts.auto_height($(dupe).height()) + 'px');
            }

            $(orig).fadeOut(opts.fade_speed);
            $(dupe).fadeIn(opts.fade_speed, function() {
                orig.src = dupe.src;

                setTimeout(function() {
                    if (opts.auto_height)
                    {
                        $(orig).css('top', opts.auto_height($(orig).height()) + 'px');
                    }
                    $(dupe).hide();
                    $(orig).show();
                }, 400);

                setTimeout( function() { swapMe(a, dupe, orig); }, opts.swap_timeout);
            });
        };
    });
};

jQuery.fn.adsRoll.defaults = {
    shuffle: false,
    images: [],
    auto_height: false,
    swap_timeout: 10000,
    time_delta: 10000,
    fade_speed: 6000
};

