(function($) {
	$.fn.gallery = function() {
		var _obj = this,
			_active = $('.active', this),
			defaults = {
				container : $('.gallery .image')	
			},
			_opts = $.extend(defaults, _opts);
		
		this.setImage = function($el) {
			var $link = $('a', $el),
				$img = $('img', $el).hide(),
				$new = $(new Image()),
				_src = $img.attr('src').replace(/\/sq\//, '/l/');
				
			$new.load(function() {
				
				$link.click(function(e) {
					e.preventDefault();
					if(!$link.parent().hasClass('active')) {
						$('#overlay .shift').unbind('click');
						_obj.displayImage($new);
						_active = $link.parent().addClass('active');
						_active.siblings('.active').removeClass('active');
					}
				});
				
				$img.fadeIn('slow');
				
			}).attr('src', _src).css({position: 'absolute', left: '50%', top: 0, display: 'none'});			
		}
		
		this.displayImage = function($new) {
			$('img', _opts.container).fadeOut('slow', function() { $(this).remove(); });
			_opts.container.append($new);
			$new.css('margin-left', -($new.width()/2)).fadeIn('slow', function() { 
				$('#overlay .shift').bind('click', _obj.move); 
			});
		}
		
		this.move = function(e) {  
			$(e.target).hasClass('prev')? _obj.prev() : _obj.next();
		}
		
		this.prev = function() {
			_active.is(':first-child') ? _active.siblings(':last-child').children('a').trigger('click') : _active.prev().children('a').trigger('click');
		}
		
		this.next = function() {
			_active.is(':last-child') ? _active.siblings(':first-child').children('a').trigger('click') : _active.next().children('a').trigger('click');
		}
				
		return this.each(function() {
			var _width = $('ul li', _obj).length * $('ul li', _obj).outerWidth(true);
			if(_width > $(this).width()) {
				$('ul', _obj).width(_width).hoverscroll({width: _obj.width(), height: $(this).height(), arrows: false});
			}
			
			$('ul li', _obj).each(function() { _obj.setImage($(this)); });
			$('#overlay .shift').bind('click', _obj.move);
		});
	}
})(jQuery);