var ImageSwapper = function(options) {

	var $ = jQuery, current, init, show, foci, thumbs, scroll, button, scrollable, width, height;

	// optional hack for zero-size thumb problem in fancybox
	width = options.width || 0;
	height = options.height || 0;

	if(typeof pngfix === 'function') pngfix(options.focus + ' img');
			
	$(function () {
		show = function (index) {
			var i;
			
			i = 0;
			foci.each(function () {
				if (index === i) {
					$(this).css({display: 'block'});
				} else {
					$(this).css({display: 'none'});
				}
				i += 1;
			});
		};
		
		scroll = function (index) {
			current = index;
			$(options.hand).animate({
				left: 0 - current * width
			});
			
			if (current === scrollable) {
				$(options.nextFade).animate({
					opacity: .25
				});
			} else {
				$(options.nextFade).animate({
					opacity: 1
				});
			}
			
			if (current === 0) {
				$(options.previousFade).animate({
					opacity: .25
				});
			} else {
				$(options.previousFade).animate({
					opacity: 1
				});
			}
		};
		
		button = function (selector, action) {
			$(selector).css({
				cursor: 'pointer'
			}).click(action);
		};

		init = function () {
			var i;

			// the slider position
			current = 0;

			// style all the focus nodes
			foci = $(options.focus).css({
				position: 'absolute',
				top: 0,
				left: 0,
				display: 'none'
			});
			
			// style and position the thumbs, and make them clickable
			i = 0;
			thumbs = $(options.thumbs).css({
				cursor: 'pointer',
				float: 'none',
				position: 'absolute',
				top: 0
			}).each(function () {
				var self;
					self = $(this);
					if (!width) {
						width = self.width();
						height = self.height();
					}
				(function (i) {
					self.click(function () {
						show(i);
					}).css({
						left: i * width
					});
				})(i);
				i += 1;
			});
			
			// position the swatch (the viewport for the sliding thumbs)
			scrollable = thumbs.length - options.visibleCount;
			$(options.swatch).css({
				overflow: 'hidden',
				position: 'relative',
				top: 0,
				left: 0,
				width: options.visibleCount * width,
				height: height
			});
			
			// position the "hand" (the group of thumbs that slides inside the swatch)
			$(options.hand).css({
				position: 'absolute',
				top: 0,
				left: 0,
				width: thumbs.length * width,
				height: height
			});
			
			if (scrollable > 0) {
				// set up the previous and next buttons
				button(options.previous, function () {
					scroll(Math.max(0, current - options.visibleCount));
				});
				button(options.next, function () {
					scroll(Math.min(scrollable, current + options.visibleCount));
				});
			} else {
				$(options.previous + " div").css({display: 'none'});
				$(options.next + " div").css({display: 'none'});
			}

			// set initial state
			show(0);
			scroll(0);
		};

		init();
		
	});
};