var ads_x = false;

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

function swapMe(a, dupe, orig)
{
    var type = a.id.split('-')[0];
    var next = ads.splice(0,1)[0];
    ads.push(next);
    dupe.src = "/thumbnail.php?max_w=180&max_h=75&img=/banners/" + next.filename;
    a.href = next.link;
}

$(document).ready(function() {
    /* Poll */
    poll = PollAjax.construct('#poll-container');
    if(poll)
        poll.load();

    /* Meny */
    $("li.sec-menuitem").mouseover(function() {
        $(this).addClass('sfHover');
    });
    $("li.sec-menuitem").mouseout(function() {
        $(this).removeClass('sfHover');
    });

    /* Ads */
    var start_wait = 5000;
    shuffle($(".swappable")).each(function() {
        if(!ads_x) {
            ads_x = getPosition( this, 'x' );
        }

        var a = this;
        var dupe = $(".imgdupe", a)[0];
        var orig = $(".orig", a)[0];

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

        dupe.onload = function() {
            var new_left = ads_x + ((180 - $(dupe).width())/2);
            $(dupe).css('left', new_left);
            $(orig).fadeOut(2000);
            $(dupe).fadeIn(2000, function() {
                orig.src = dupe.src;
                $(orig).show();
                $(dupe).hide();
                setTimeout( function() { swapMe(a, dupe, orig); }, 10000 );
            });
        };
    });
});
