(function() {
	$.fn.portfolioCarousel = function() {
		function repeat(str, n) {
			return new Array(n+1).join(str);	
		}
		return this.each(function() {
			var 	$wrapper = $('> div',this).css('overflow','hidden'),
					$slider = $wrapper.find('> ul').width(9999),
					$items = $slider.find('> li'),
					$single = $items.filter(':first')
										
					singleWidth = $single.outerWidth(),
					visible = Math.ceil($wrapper.innerWidth() / singleWidth),
					currentPage = 1,
					pages = Math.ceil($items.length / visible);
									
			if($items.length % visible != 0) {
				$slider.append(repeat('<li class="empty" />',visible - ($items.length % visible)));	
				$items = $slider.find('> li');
			}
			
			$items.filter(':first').before($items.slice(-visible).clone().addClass('cloned'));
			$items.filter(':last').after($items.slice(0,visible).clone().addClass('cloned'));
			$items = $slider.find('> li');
			
			$wrapper.scrollLeft(singleWidth * visible);
			
			function gotoPage(page) {
				var dir = page < currentPage ? -1 : 1,
					n = Math.abs(currentPage - page),
					left = singleWidth * dir * visible * n;
					
				$wrapper.filter(':not(:animated)').animate({
					scrollLeft : '+=' + left
					}, 500, function() {
						if(page > pages) {
							$wrapper.scrollLeft(singleWidth * visible); 
							page = 1;
						} else if(page == 0) {
							page = pages;
							$wrapper.scrollLeft(singleWidth * visible * pages);
						}
					   
					   currentPage = page;
				});
			}
			
			$wrapper.after('<a href="#" class="scrollLeft">&lt;</a><a href="#" class="scrollRight">&gt;</a>');
			
			$('a.scrollLeft',this).click(function() {
				gotoPage(currentPage - 1);
				return false;
			});
			
			$('a.scrollRight',this).click(function() {
				gotoPage(currentPage + 1);
				return false;
			});
			
			autoRotate = setInterval(function(){gotoPage(currentPage + 1)}, 5000);
			
			$(this).hover(function() {
				clearInterval(autoRotate);
			}, function() {
				autoRotate = setInterval(function(){gotoPage(currentPage + 1)}, 5000);
			});
		});
	};
})(jQuery);

function slideSwitch(element) {
	var $active = $(element + ' img.active');

	if ( $active.length == 0 ) $active = $(element + ' img:last');

	var $next =  $active.next().length ? $active.next() : $(element + ' img:first');

	$active.addClass('last-active');

	$next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 1000, function() {
		$active.animate({opacity: 0.0}, 1000).removeClass('active last-active');
	});
}

$(function() {
	//
	setInterval( "slideSwitch('#photoList')", 7000 );
	$('.portfolioCarousel').portfolioCarousel();
	$('#portfolio li:not(".cloned") a').lightBox();
});
