(function($){

	$.fn.imageCycler = function(params){
	
		// give the imgopts their default value
		imgopts = $.extend({
			innerUL: '.portfolioThumbs',
			imageLoader: '#imgLoader',
			select: ':first-child',
			speed:500
		}, params);
		
		var imgLoader = $(imgopts.imageLoader+' img');
		
		// plugin actions
		$(this).each(function(){
			$listobj = $(this).find(imgopts.innerUL);
			hasSelection = false;
			
			$listobj.find( 'li a.current').each(function(){
				hasSelection = true;
				$first = $(this);
				$listobj.firstSrc = $(this).attr('href');
			});
			
			if(hasSelection == false){
				$first = $listobj.find('li:first a');
				$listobj.firstSrc = $first.attr('href');
				$first.addClass('current');
			}
			
			
			if( typeof($listobj.firstSrc) != 'undefined'){
				$(imgLoader).animate({ opacity:"hide" }, imgopts.speed, function(){
					$(imgLoader).attr('src', $listobj.firstSrc).load(function(){
						imgLoader.animate({ opacity:"show" }, imgopts.speed );
						$(imgLoader).unbind( 'load' ); // have to unbind to avoid repeating this callback on clicks
					});
					$first.siblings().animate({ opacity:"show" }, imgopts.speed );
				});
			}
				
				
			
			$listobj.find('a').unbind('click');
			
			$listobj.find('a').click(function(){
				$newObj = $(this);
				src = $newObj.attr('href');
				
				if( $(imgLoader).attr('src') !== src){
					$oldObj = $listobj.find('li a.current');
					$oldObj.removeClass('current');
					$oldObj.siblings().hide();
					
					$(imgLoader).animate({ opacity:"hide" }, imgopts.speed, function(){
						$newObj.addClass('current');
						$(imgLoader).attr('src', src).load(function(){
							$(imgLoader).animate({ opacity:"show" }, imgopts.speed );
						});
						$newObj.siblings().animate({ opacity:"show" }, imgopts.speed );
					});
				}
		
				return false;
				
			});
			
		});
		
		return this; // keeps jquery chaining going
	
	}
	
})(jQuery);
