X.createSingleton('BHG.GalleryBox',
	// Constructor
	function BHGGalleryBox()
	{
		this.data = null;
		this.$container = null;
		this.modal = null;
		
		this.containerMarkup = '<div class="gallery-box"><h2></h2><div class="gallery-box-page"></div><a class="btn-close" href="#">Close</a><div class="gallery-box-image-view"></div><ul class="carousel jcarousel-skin-bhg"></ul></div>';
	},
	// Prototype Members
	{
		open: function(data, index)
		{
			// If data is the same, do not re-instantiate. Just open existing one.
			if (this.data == data)
			{
				this.modal.show();
				return;
			}
			
			this.data = data;
			this.$container = jQuery(this.containerMarkup);
			index = index ? index : 0;
			
			var settings =
			{
				wrapperClasses: ['gallery-box-modal'],
				fixed: true,
				createHandler: this.onModalCreate.delegate(this)
			};
			this.modal = X.ModalFactory.create(this.$container.get(0), settings);
			
			this.$container.find('ul.carousel').jcarousel(
			{
				size: this.data.length,
				scroll: 4,
				visible: 4,
				itemLoadCallback:
				{
					onBeforeAnimation: this.onCarouselBeforeAnimation.delegate(this, index)
				}
		    })
			.find('li a').live('click', this.onThumbClick.delegate(null, this));
			
			this.$container.find('h2').html(this.data[index].title);
			this.$container.find('.gallery-box-image-view').html('<img src="' + this.data[index].imageURL + '"/>');
			this.$container.find('.gallery-box-page').html('Image ' + (index + 1) + ' of ' + this.data.length);
		},
		onModalCreate: function(modal)
		{
			this.$container.find('.btn-close').click(this.onModalCloseBtnClick.delegate(this, modal));
		},
		onModalCloseBtnClick: function(e, modal)
		{
			e.preventDefault();
			modal.hide();
		},
		onCarouselBeforeAnimation: function(carousel, state, event, index)
		{
			for (var i = carousel.first, activeClass; i <= carousel.last; i++)
			{
		        if (carousel.has(i))
				{
		            continue;
		        }

		        if (i > this.data.length)
				{
		            break;
		        }

				activeClass = (index == i - 1) ? ' class="active"' : "";

		        carousel.add(i, '<a' + activeClass + ' href="' + this.data[i-1].imageURL + '" title="' + this.data[i-1].title + '"><img src="' + this.data[i-1].thumbURL + '" width="129" height="75" alt="" /></a>');
		    }
		},
		onThumbClick: function(e, query, galleryBox)
		{
			e.preventDefault();
			$this = jQuery(this);
			var index = galleryBox.$container.find('ul.carousel li a').index(this);
			
			galleryBox.$container.find('ul.carousel li a.active').removeClass('active');
			galleryBox.$container.find('h2').html($this.attr('title'));
			galleryBox.$container.find('.gallery-box-page').html('Image ' + (index + 1) + ' of ' + galleryBox.data.length);
			galleryBox.$container.find('.gallery-box-image-view').html('<img src="' + $this.attr('href') + '"/>');
			
			$this.addClass('active');
		}
	}
);
