/**
 * Create the header gallery
 * See page: Bikes & Equipment > Any bike...
 */
jQuery.fn.headerGallery = function() {
	var _currentSlide = 0;
	var _width = 717;
	var _totalSlides = 0;

	/**
	 * Slide to a particular image
	 */
	function slideTo (slide)
	{
		imageContainer.stop(true, true); // Stop the current animation
		slide = slide >= _totalSlides ? 0 : (slide < 0 ? _totalSlides-1 : slide);
		_currentSlide = slide;
		imageContainer.animate({left:-(_currentSlide * _width)});
		setColor();
	}

	/**
	 * Slide to another color
	 */
	function setColor ()
	{
		image = jQuery(images[_currentSlide]);
		fullscreenButton.attr('href', image.parent().attr('href'));
		MagicThumb.refresh( jQuery('.fullscreen').attr('id') );
		colorText.html(
			jQuery(
				'.box-gallery-colors .' + image.attr('class')
			).attr('alt')
		);
	}

	var fullscreenButton = jQuery('.fullscreen').click(function(){});
	var colorText = jQuery('.box-gallery-color', this);
	var imageContainer = jQuery('.box-gallery-image-container', this);
	var controllerNext = jQuery('.box-gallery-control-next', this)
		.click(function(){slideTo(_currentSlide+1)});
	var controllerPrevious = jQuery('.box-gallery-control-previous', this)
		.click(function(){slideTo(_currentSlide-1)});
	var images = jQuery('.box-gallery-image-container a > img', this).each(function(n, image){
			image = jQuery(image);
			imageContainer.width( imageContainer.width() + image.width() );
			_width = image.width();
			_totalSlides++;
		});
	var colors = jQuery('.box-gallery-colors img', this)
		.css({cursor:'pointer'})
		.click(function(){
				slideTo(
						images.index(
							jQuery('.' + jQuery(this).attr('class') + ':first', imageContainer)
						)
					);
			});
}


jQuery(window).load(function(){
	jQuery('div.box.box-gallery .box-gallery').headerGallery();
});
