(function($) {
	$.fn.ElementsCycle = function(options){
		var defaults = {
			elementContainer: '#productlistarea',
			prevElement: '.arrow_left',
			nextElement: '.arrow_right',
			speed: 200,
			containerWidth: false,
			showCount: 3
		};
		
		var options = $.extend(defaults, options);  
				
		this.each(function() {
			// GET ELEMENTS
			var totalElements = $(this).find(".productone");
			var maxIndex = totalElements.length - 1;
			
			// WORK OUT START INDEX
			// assumes that total elements is greater then the slice
			var startIndex = Math.floor((maxIndex - options.showCount) / 2);
			var elementWidth = $(this).find(".productone").outerWidth(true);
			var margin = ((startIndex + 1) * elementWidth) * -1;
			var lowerIndex = startIndex + 1;
			var upperIndex = startIndex + options.showCount;
			var parent = $(this);
			
			// SORT OUT STYLES
			$(this).find(options.elementContainer).css({
				'width': (options.containerWidth) ? options.containerWidth : elementWidth * options.showCount,
				'overflow': 'hidden'
			});
			$(this).find("#productlistarea2").css({
				'width': (maxIndex + 1) * elementWidth,
				'padding': '0'
			});
			
			// INIT
			cycle("load");
			
			// CLICK
			$(options.nextElement).click(function(){ cycle("next"); return false; });
			$(options.prevElement).click(function(){ cycle("prev"); return false; });	
			
			// CYCLE
			function cycle(dir){			
				switch(dir){
					case "next":
						if(upperIndex <= maxIndex) {
							$(options.prevElement).show();
							margin = margin - elementWidth;
							upperIndex = upperIndex + 1;
							lowerIndex = lowerIndex + 1;
							$("#productlistarea2",parent).animate({
									marginLeft: margin
								},options.speed);
								
							if((upperIndex + 1) > maxIndex) {
								$(options.nextElement).hide();
							}
						}					
						break;	
					case "prev":
						if(lowerIndex >= 0) {
							$(options.nextElement).show();	
							upperIndex = upperIndex - 1;
							lowerIndex = lowerIndex - 1;
							margin = margin + elementWidth;
							$("#productlistarea2",parent).animate({
								marginLeft: margin
							}, options.speed);
							if((lowerIndex-1) < 0) {
								$(options.prevElement).hide();
							}
						}
						break;
						
					case "load": {
						$("#productlistarea2",parent).animate({
							marginLeft: margin
						}, options.speed);
						break;
					}
					default:
						break; 
				};													
			};
		}); 
	};
})(jQuery);




