var animateTop = 0;
var animateMax = 0;
var page = 0;
var num_pages = 0;

function gallery_slider() {
    // wrap all galleries
    $("#main_content > ul.gallery").wrap('<div class="gallery_wrapper"></div>');
    
    $("#main_content ul.gallery").each(function (i) {
        // calculate max slide x
        var divide = $("li", this).length / 6;
        if (Math.floor(divide) == divide) {
            // ni ostanka
            animateMax = -Math.floor(divide-1) * 320;
        }
        else {
            animateMax = -Math.floor(divide) * 320;
        }
        num_pages = Math.ceil(divide);
        if (num_pages > 1) {
            // add navigation
            $(this).css("position", "absolute");
            $(this).parent().after('<ul class="gallery_nav"><li><a href="#" class="previous" title="Nazaj">Nazaj</a></li><li><a href="#" class="next" title="Naprej">Naprej</a></li><li class="info"></li></ul>');
            
            // set up sliding for up/down links
            $("#gallery_"+i).parent().next().each(function () {            
                $("a.previous", this).click(function () {
                    animateTop += 320;
                    page--;
                    if (animateTop > 0) {
                        animateTop = 0;
                        page = 0;
                    }
                    $("#gallery_"+i).animate({ top: animateTop }, "normal");
                    update_info(i, page);
                    return false;
                });
                $("a.next", this).click(function () {
                    animateTop -= 320;
                    page++;
                    if (animateTop < animateMax) {
                        animateTop = animateMax;
                        page = num_pages-1;
                    }
                    $("#gallery_"+i).animate({ top: animateTop }, "normal");
                    update_info(i, page);
                    return false;
                });
            });
            update_info(i, page);
        }
    });
}

function update_info(i, page) {
    $("#gallery_"+i).parent().next().each(function () {
        $("li.info", this).text('Stran '+(page+1)+'/'+num_pages);
    })
}

$(document).ready(function(){
    gallery_slider();
});