/**
 * @author Stéphane Roucheray 
 * @extends jquery
 */


jQuery.fn.carousel = function(previous, next, options){
	var sliderList = jQuery(this).children()[0];
	sliderListH = $(this).height();
	if (sliderList) {
		var increment = jQuery(sliderList).children().outerWidth("true"),
		elmnts = jQuery(sliderList).children(),
		numElmts = elmnts.length,
		sizeFirstElmnt = increment,
		shownInViewport = Math.round(jQuery(this).width() / sizeFirstElmnt),
		firstElementOnViewPort = 1,
		isAnimating = false;
		
		//controls drop-downs from individual items
		var subMenu = $(elmnts).children('.carousel-item-options')[0];
		if (subMenu) {
			$(elmnts)
				.each(function() {
					var subElmnts = $(this).children('.carousel-item-options'),
					subElmntsH = subElmnts.height();
					
					$(this).hover(function() {
						$(subElmnts).slideDown('normal');
						$(sliderList).parent().animate({height: sliderListH + subElmntsH});
					},
					function() {
						$(subElmnts).slideUp('fast');
					});
				})
				.parent().mouseleave(function(){
					$(sliderList).parent().animate({height: sliderListH});
				});
		}
		//prevents carousel from duplicating images 
		//if there are less than width of viewport
		if (numElmts <= shownInViewport) {
			jQuery(previous).addClass('hideCarouselArrow');
			jQuery(next).addClass('hideCarouselArrow');
		 return;
		}
		 
		for (i = 0; i < shownInViewport; i++) {
			jQuery(sliderList).css('width',(numElmts+shownInViewport)*increment + increment + "px");
			jQuery(sliderList).append(jQuery(elmnts[i]).clone());
		}
		
		jQuery(previous).click(function(event){
			if (!isAnimating) {
				if (firstElementOnViewPort == 1) {
					jQuery(sliderList).css('left', "-" + numElmts * sizeFirstElmnt + "px");
					firstElementOnViewPort = numElmts;
				}
				else {
					firstElementOnViewPort--;
				}
				
				jQuery(sliderList).animate({
					left: "+=" + increment,
					y: 0,
					queue: true
				}, "swing", function(){isAnimating = false;});
				isAnimating = true;
			}
			
		});
		
		jQuery(next).click(function(event){
			if (!isAnimating) {
				if (firstElementOnViewPort > numElmts) {
					firstElementOnViewPort = 2;
					jQuery(sliderList).css('left', "0px");
				}
				else {
					firstElementOnViewPort++;
				}
				jQuery(sliderList).animate({
					left: "-=" + increment,
					y: 0,
					queue: true
				}, "swing", function(){isAnimating = false;});
				isAnimating = true;
			}
		});
		
		
	}
};

