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;
        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 asdfasdf = 0;
    function setPosition(obj, h, w)
    {
        h = h || 82 - $(obj).height();
        w = w || 110 - $(obj).width();

        var l = w/2,
            t = h/2;

        if (!t) {
            t = 0;
        }
        $(obj)
            .css('top', t + 'px')
            .css('left', l + 'px')
            .css('position', 'absolute');
    }

    var start_wait = 2000;

    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];

        setPosition(orig);

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

        $(this).css('position', 'relative');

        dupe.onload = function() {
            var h = 82 - $(dupe).height(),
                w = 110 - $(dupe).width();

            var l = w/2,
                t = h/2;

            setPosition(dupe);

            $(orig).fadeOut(2000).css('position', 'absolute');
            $(dupe).fadeIn(2000, function() {
                orig.src = dupe.src;
                setPosition(orig, h, w);
                setTimeout(function() {
                    $(dupe).hide();
                    $(orig).show();
                }, 400);
                setTimeout( function() { swapMe(a, dupe, orig); }, 10000 );
            });
        };
    });
};

jQuery.fn.adsRoll.defaults = {shuffle: true, images: []};
