window.addEvent('domready', function(){
    $$('.photobox').each(function(box){
        new Photobox(box);
    });
});

var Photobox = new Class({

    initialize: function(container)
    {
        this.container = $(container);
        
        this.availSpace = this.container.getElement('.images').getSize();
        this.currentImage = 0;
        this.images = this.container.getElements('.images img');
        this.imageCount = this.images.length;
        this.build();
        this.images.each(function(img){
            this.center(img);
        }, this);
        this.show();
    },
    
    build: function()
    {
        // caption
        if(!this.container.getElement('.caption'))
        {
            var caption = new Element('div').addClass('caption').inject(this.container, 'bottom')
            //this.container.insert({ 'bottom': caption });
        }        
        var target = this.container.getElement('.caption');
       
        // nav
        var nav = new Element('div').addClass('nav').inject(this.container, 'top');
        //this.container.insert({ 'top': nav });
        
        // prev
        new Element('a', {
			'class': 'prev',
			events: {
				'click': function(e) {
					e.stop();
					this.prev();
				}.bind(this)
			},
			href: '#'
		}).inject(nav);
        //nav.insert(p);

        // next
		new Element('a', {
			'class': 'next',
			events: {
				'click': function(e) {
					e.stop();
					this.next();
				}.bind(this)
			},
			href: '#'
		}).inject(nav);
        //nav.insert(n);

        // count
        new Element('span', {
			'class': 'count'
		}).inject(nav);

        // title        
        new Element('span').inject(target);

        this.setTitle();        
    },
    
    setTitle: function()
    {
        this.container.getElement('.caption span').set('text', this.images[this.currentImage].title);
    },
    
    setCount: function()
    {
        var c = this.container.getElement('.nav span');
        c.set('text', (this.currentImage+1)+' / '+(this.imageCount));
    },
    
    center: function(img)
    {
        var dim = img.getSize();
        if(dim.x < this.availSpace.x)
        {
            img.setStyle('marginLeft', Math.round((this.availSpace.x-dim.x)/2, 0)+'px');
        }
        if(dim.y < this.availSpace.y)
        {
            img.setStyle('marginTop', Math.round((this.availSpace.y-dim.y)/2, 0)+'px');
        }
    },
    
    prev: function()
    {
        var p = this.currentImage - 1 < 0 ? this.imageCount-1 : this.currentImage - 1;
        this.currentImage = p;
        this.show();
    },
    
    next: function()
    {
        var n = this.currentImage + 1 >= this.imageCount? 0 : this.currentImage + 1;
        this.currentImage = n;
        this.show();
    },
    
    show: function()
    {
        this.images.each(function(img, i){
            img.setStyle('display', i == this.currentImage ? '' : 'none');
        }, this);
        this.setTitle();
        this.setCount();
    }
    
});
