var animateLeft = 0;
var animateMax = 0;
var page = 0;
var num_pages = 0;

function gallery_slider() {
    // wrap all galleries
    $("#content ul.gallery").wrap('<div class="gallery_wrapper"></div>');
    
    $("#content ul.gallery").each(function (i) {
        animateMax = -($("li", this).length-1) * 250;
        num_pages = $("li", this).length;
        if (num_pages > 1) {
            // add navigation
            $(this).css("position", "absolute");
            $(this).parent().after('<ul class="gallery_nav"><li><a href="#" class="previous" title="Previous"><img src="/static/images/left_orange.gif" alt="Previous" /></a></li><li><a href="#" class="next" title="Next"><img src="/static/images/right_orange.gif" alt="Next" /></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 () {
                    animateLeft += 250;
                    page--;
                    if (animateLeft > 0) {
                        animateLeft = 0;
                        page = 0;
                    }
                    $("#gallery_"+i).animate({ left: animateLeft }, "normal");
                    update_info(i, page);
                    return false;
                });
                $("a.next", this).click(function () {
                    animateLeft -= 250;
                    page++;
                    if (animateLeft < animateMax) {
                        animateLeft = animateMax;
                        page = num_pages-1;
                    }
                    $("#gallery_"+i).animate({ left: animateLeft }, "normal");
                    update_info(i, page);
                    return false;
                });
            });
            update_info(i, page);
        }
    }).css("width", num_pages * 250 + "px");
}

function update_info(i, page) {
    $("#gallery_"+i).parent().next().each(function () {
        $("li.info", this).text('Slide '+(page+1)+'/'+num_pages);
    })
}

$(document).ready(function(){
    gallery_slider();
});