
var Gallery = function(el)
{
    this.el = $(el);

    this.current_image = 0;
    this.num_images = $('.image img', this.el).length;

    this.bindEvents();
    this.go(0, 1);
};
Gallery.prototype.go = function(offs, num)
{
    var cur = this.current_image;
    var next;

    if (num)
        next = parseInt(num);
    else
        next = cur + offs;

    if (next > this.num_images)
        next = 1;
    if (next < 1)
        next = this.num_images;

    this.show('image');

    if (cur == next)
        return;

    // TODO: transitions

    // hide current image
    $('.image img[name=image_'+cur+']', this.el).hide();
    // hide current caption
    $('.caption[name=caption_'+cur+']', this.el).hide();
    // deselect current thumb
    $('.thumb[name=thumb_'+cur+']', this.el).removeClass('selected');

    // show next image
    $('.image img[name=image_'+next+']', this.el).show();
    // show next caption
    $('.caption[name=caption_'+next+']', this.el).show();
    // select next thumb
    $('.thumb[name=thumb_'+next+']', this.el).addClass('selected');

    this.current_image = next;

    var counter = this.current_image + '/' + this.num_images;
    $('.counter', this.el).text(counter);
};
Gallery.prototype.show = function(view)
{
    var $img = $('.image, .captions, .viewalbum, .counter', this.el)
    var $thb = $('.thumbnails', this.el)
    if (view == 'image')
    {
        $thb.hide();
        $img.show();
    }
    if (view == 'thumbnails')
    {
        $img.hide();
        $thb.show();
    }
};
Gallery.prototype.bindEvents = function()
{
    var self = this;
    
    $('.controls a', this.el).click(function()
    {
        self.go( $(this).is('.next')?1:-1 );
    });

    $('.thumb', this.el).click(function()
    {
        var num = $(this).attr('name').substr('thumb_'.length);
        self.go(null, num);
    });

    $('.viewalbum', this.el).click(function()
    {
        self.show('thumbnails');
    });

};

