// vim: set fileencoding=utf-8 expandtab shiftwidth=4 tabstop=4 softtabstop=4:

function rotate(el, dir) {
    var that = this;
//    console.log($(el).attr('timeout_id'));
    if ($(el).attr('lock') == "1") {
        return;
    }
    $(el).attr('lock', 1);
    clearTimeout($(el).attr('timeout_id'));
    var tout = $(el).attr('slideshow_speed');
    var current = $($(el).children().filter(':not(.hidden)')[0]);
    var wybrany = parseInt($($(that).nextAll('div.przelacznik_elementow')[0]).find('.nr_elementu_wybranego').html());
    var next;
    if (dir>0) {
        next = current.next();
        wybrany++;
    } else {
        next = current.prev();
        wybrany--;
    }
    if (next.size() == 0) {
        var first;
        if (dir>0) {
            first = ':first';
            wybrany = 1;
        } else {
            first = ':last';
            wybrany = parseInt($($(that).nextAll('div.przelacznik_elementow')[0]).find('.ilosc_elementow').html());
        }
        next = $(el).children().filter(first);
    }
    if (!$.browser.msie) {
        current.animate({ 'opacity': 0.0 }, "slow");
    }
    current.queue(function() {
        current.addClass('hidden');
        //console.log(wybrany);
        $($(that).nextAll('div.przelacznik_elementow')[0]).find('.nr_elementu_wybranego').html(wybrany);
        if (!$.browser.msie) {
            next.css({ opacity: 0.0 });
            next.removeClass('hidden');
            next.animate({ 'opacity': 1.0 }, 'slow');
        } else {
            next.removeClass('hidden');
        }
        next.queue(function() {
            $(el).attr('timeout_id', setTimeout(function() { rotate(el, 1); }, tout));
            $(el).attr('lock', 0);
            $(this).dequeue();
        } );
        $(this).dequeue();
    });
/*
    current.fadeOut('slow', function() {
        //console.log(wybrany);
        $($(this).nextAll('div.przelacznik_elementow')[0]).find('.nr_elementu_wybranego').html(wybrany);
        next.fadeIn('slow', function() {
            $(el).attr('timeout_id', setTimeout(function() { rotate(el, 1); }, tout));
            $(el).attr('lock', 0);
        } );
    });
*/
}

$(function() {
    $('.slideshow').each(function(i) {
        if ($(this).children().size() < 2) {
            return;
        }
        $($(this).nextAll('div.przelacznik_elementow')[0]).find('.ilosc_elementow').html($(this).children().size());
        $($(this).nextAll('div.przelacznik_elementow')[0]).find('.nr_wybranego_elementu').html(1);
        var timeout = $(this).attr('slideshow_speed');
//        $(this).children().hide();
//        $(this).children().filter(':first').show();
        //$(this).css({width: this.offsetWidth, height: this.offsetHeight})
        var e = this;
        $(this).attr('timeout_id', setTimeout(function(e0) { return function() { rotate(e0, 1); } } (e), timeout));
    });
});
