var firstElementOnViewPort;

jQuery.fn.simplecarousel = function(previous, next, options){
	var sliderList = jQuery(this).children()[0];
	
	if (sliderList) {
		var increment = jQuery(sliderList).children().outerWidth("true"),
		elmnts = jQuery(sliderList).children(),
		numElmts = elmnts.length,
		sizeFirstElmnt = increment,
		shownInViewport = 4;// Math.round(jQuery(this).width() / sizeFirstElmnt),
		firstElementOnViewPort = 1,
		isAnimating = false;
		
	
		for (i = 0; i < shownInViewport; i++) {
			jQuery(sliderList).css('width',(numElmts+shownInViewport)*increment + increment + "px");
			
			var clone = jQuery(elmnts[i]).clone(true);
		
			var containerId  = jQuery(clone).find('.carousel-container').attr('id');
			
			var nextId  = jQuery(clone).find('.simpleNext').attr('id');
			var prevId  = jQuery(clone).find('.simplePrevious').attr('id');
			var viewportId    = jQuery(clone).find('.viewport').attr('id');
						
			jQuery(clone).find('.carousel-container').attr('id','clone_of_' + containerId);
			
			jQuery(clone).find('.simplePrevious').attr('id','clone_of_' + prevId);
			jQuery(clone).find('.simpleNext').attr('id','clone_of_' + nextId);
			jQuery(clone).find('.viewport').attr('id','clone_of_' + viewportId);
			
			
			jQuery(sliderList).append(clone);
			//clonedArray.push(id);
		}
		
		jQuery(previous).click(function(event){
			if (!isAnimating){
				if (firstElementOnViewPort == 1) {
					jQuery(sliderList).css('left', "-" + numElmts * sizeFirstElmnt + "px");
					firstElementOnViewPort = numElmts;	}
				else {
					firstElementOnViewPort--;
				}
				
				jQuery('#simplePrevious').animate({opacity:0}, 50);
				jQuery('#simpleNext').animate({opacity:0}, 50);
				
				jQuery(sliderList).animate({
					left: "+=" + increment,
					y: 0,
					queue: true
				}, "swing", function(){
					jQuery('#simplePrevious').animate({opacity:1}, 200);
					jQuery('#simpleNext').animate({opacity:1}, 200);
					isAnimating = false;
					});
				isAnimating = true;
			}
			
		});
		
		jQuery(next).click(function(event){
			if (!isAnimating) {
				if (firstElementOnViewPort > numElmts) {
					firstElementOnViewPort = 2;
					jQuery(sliderList).css('left', "0px");
				}
				else {
					firstElementOnViewPort++;
				}
				
				jQuery('#simplePrevious').animate({opacity:0}, 50);
				jQuery('#simpleNext').animate({opacity:0}, 50);
				
				jQuery(sliderList).animate({
					left: "-=" + increment,
					y: 0,
					queue: true
				}, "swing", function(){
					jQuery('#simplePrevious').animate({opacity:1}, 200);
					jQuery('#simpleNext').animate({opacity:1}, 200);
					isAnimating = false;
				});
				isAnimating = true;
			}
		});
	}
};
