var gallery = 
{
	el: null,
	index: 0,
	nextIndex: -1,
	count: 0,
	page: 0,
	pages: 0,
	busy: false,
	
	init: function() 
	{
		this.el = $('#fancybox-content #gallery');
		if (this.el.length == 0)
			return;
		
		this.index = $('.item:visible', this.el).index();
		this.count = $('.item', this.el).length;
		this.page = 0;
		this.pages = Math.ceil(this.count / 4);
		this.updateArrows();
		
		$('.left').click(function() { gallery.setPage(gallery.page - 1); } );
		$('.right').click(function() { gallery.setPage(gallery.page + 1); } );
		$('li').mousedown(function(e) { gallery.navigate($(e.currentTarget).index()); return false; });
		
		this.navigate(this.index);
	},
	
	updateArrows: function()
	{
		(this.page > 0) ? $('.left', this.el).show() : $('.left', this.el).hide();
		(this.page < this.pages - 1) ? $('.right', this.el).show() : $('.right', this.el).hide();
	},
	
	navigate: function(index)
	{
		$('li', this.el).removeClass('active');
		$('li:nth-child(' + (index + 1) + ')', this.el).addClass('active');
		
		
		if (index != this.index)
		{
			if (this.busy)
			{
				this.nextIndex = index;
				return;
			}
			
			this.busy = true;
			
			var oldItem = $('.item:nth-child(' + (this.index + 1) + ')', this.el);
			var newItem = $('.item:nth-child(' + (index + 1) + ')', this.el);

			this.index = index;
			
			$('.item', this.el).css('z-index', 1);			
			newItem.css('z-index', 2).show().fadeOut(0).fadeIn(600);
			$('.caption', this.el).html($('div', newItem).html());
			
			setTimeout(function() 
			{
				oldItem.hide();
				gallery.busy = false;
				if (gallery.nextIndex != -1)
				{
					gallery.navigate(gallery.nextIndex);
					gallery.nextIndex = -1;
				}
			}, 600);
		}
	},
	
	setPage: function(page) 
	{
		page = Math.max(0, Math.min(this.pages - 1, page));
		if (page == this.page)
			return;
		this.page = page;
		$('ul', this.el).animate({left: (-this.page * 400) + 'px'}, {duration: 300, complete: function() { gallery.updateArrows(); }} );
	}
	
};
