;(function( $ ){
	
	
	
	// layout
	jQuery.fn.layout = function()
	{
		var w = 0;
		this.find('img').each
		(
			function()
			{
				$(this).css('position', 'absolute');
				$(this).css('top', '0');
				$(this).css('width', 'auto');
				$(this).css('height', 'auto');
				var ih = $(this).height();
				var iw = $(this).width();
				$(this).css('height', '100%');
				var ratio = $(this).height() / ih;
				$(this).css('width', Math.round(iw * ratio) + 'px');
				$(this).css('left', Math.round(w) + 'px');
				w += Math.round($(this).width());
			}
		);
		
		var ul = this.find('ul');
		
		ul.width(w);
		
		this.imageIndex(this.imageIndex(), false);
		
	}
	
	
	
	// fwd
	jQuery.fn.fwd = function()
	{
		this.imageIndex(this.imageIndex() + 1);
	}
	
	
	
	
	// rev
	jQuery.fn.rev = function()
	{
		this.imageIndex(this.imageIndex() - 1);
	}
	
	
	
	
	
	//imageIndex
	jQuery.fn.imageIndex = function(n, animate)
	{
		if(n != undefined)
		{
			// set imageIndex property
			n = Math.max(0, n);
			n = Math.min(this.find('img').length - 1, n);
			this.attr('imageIndex', n);
			
			// enable or disable rev/fwd buttons
			if(n == 0) { this.find('a.rev').addClass('disabled'); } else { this.find('a.rev').removeClass('disabled'); }
			if(n == this.find('img').length - 1) { this.find('a.fwd').addClass('disabled'); } else { this.find('a.fwd').removeClass('disabled'); }
				
			// scroll to the image
			var img = this.find('img:eq(' + n + ')');
			var imgx = img.position().left;
			var imgw = img.width();
			var winw = this.width();
			var x = -imgx + (winw / 2) - (imgw / 2);
			x = Math.max(x, winw - this.find('ul').width());
			x = Math.min(x, 0);
			x = Math.round(x);
			if(animate != false)
			{
				this.find('ul').stop();
				this.find('ul').animate({'left':x}, 800, 'easeOutQuad');
			}
			else
			{
				this.find('ul').css('left',x);
			}
			
		}
		
		// find index of selected image (there must be a better way to do this!)
		if(this.attr('imageIndex') == undefined) { this.attr('imageIndex', 0); }
		return parseInt(this.attr('imageIndex'));
	}
	
	
	
	
	//init
	jQuery.fn.imageScroller = function()
	{	
		// initialise
		this.addClass('image-scroller-initialised');
		
		
		// do layout
		this.layout();	
		$(window).bind('resize', function(){ $('.image-scroller-initialised').layout(); } );
		$('.image-scroller-initialised img').load( function(){ $('.image-scroller-initialised').layout(); } );
		
		
		// click navigation
		this.append('<div class="revfwd"><a class="rev"></a><a class="fwd"></a></div>');
		this.find('.revfwd').mouseFollow(true);
		
		this.mouseleave( function() { this.find('.revfwd').mouseFollow(false); } );
		this.mouseleave( function() { this.find('.revfwd').mouseFollow(true); } );
		
		this.find('a.rev').click
		( 
			function()
			{ 
				$(this).parent().parent().rev();
			} 
		);
		this.find('a.fwd').click
		( 
			function()
			{ 
				$(this).parent().parent().fwd();
			} 
		);
		
	}
	
	
	
	

})( jQuery );
