var curLeft = 0;
var maxLeft = 0;

function buttonInit() {

    // add click to right button
    $('.photos_go_right').click(function() {
        if (curLeft > maxLeft) {
            var newLeft = curLeft - parseInt($('.photos').css('width').replace('px', ''));
            $('.photos_slider').animate({ left: newLeft + 'px' }, { duration: 500 });
            curLeft = newLeft;
        }
        return false;
    });

    // add click to left button
    $('.photos_go_left').click(function() {
        if (curLeft < 0) {
            var newLeft = curLeft + parseInt($('.photos').css('width').replace('px', ''));
            $('.photos_slider').animate({ left: newLeft + 'px' }, { duration: 500 });
            curLeft = newLeft;
        }
        return false;
    });

}

function galleryInit() {

    // set width of .photos_slider to allow side to side scrolling
    var photoCount = $('.photos_slider .photo').size();
    var photoSliderWidth = (parseInt($('.photos_slider .photo').css('width').replace('px', '')) + 40) * (Math.ceil(photoCount / 4) * 2) ;
    $('.photos_slider').css('width', photoSliderWidth + 'px');

    // get the limit so we don't scroll too far
    maxLeft = ((Math.ceil(photoCount / 4) * 2) - 2) * (parseInt($('.photos_slider .photo').css('width').replace('px', '')) + 40) * -1;
    $('.photos_slider').css('left', '0');
    curLeft = parseInt($('.photos_slider').css('left').replace('px', ''));

    $(".viewer img").attr("src", $(".photos_slider .photo").first().addClass("viewing"));
    $(".viewer img").attr("src", $(".photos_slider .photo img").first().attr("src").replace("-thumbs", ""));

    $(".photos_slider .photo").click(function() {
        $(".viewer img").removeAttr("src");
        $(".viewer img").attr("src", $(this).children("img").attr("src").replace("-thumbs", ""));
        $(".photo").removeClass("viewing");
        $(this).addClass("viewing");
    });

}

$(document).ready(function() {

    buttonInit();

    // load first gallery
    $.get('image_gallery.php?opg=2009-mlb-all-star-game&ppg=4', function(data) {
        $('.photos_slider').html(data);
        galleryInit();
    }, "html");

    $('.gallery_link').click(function() {
        var dir = $(this).attr('rel');
        $.get('image_gallery.php?opg=' + dir + '&ppg=4', function(data) {
            $('.photos_slider').html(data);
            galleryInit();
        }, "html");
        $('.gallery_link').removeClass("viewing");
        $(this).addClass("viewing");
        return false;
    });

});