(function($){
	$.fn.jGallery = function(options) {
		var defaults = {
			elWidth        : 131,
			minPos         : 0,
			carousel       : '.carousel',
			viewport       : '.carousel .carousel-wrap',
			animSpeed      : 'fast',
			lArrClass      : 'arr-l',  
			rArrClass      : 'arr-r',
			loaderClass    : 'loader',
			viewerClass    : 'viewer'
		};
		var options = $.extend(defaults, options);
		
		var obj       = $(this);
		var carousel  = $(options.carousel);
		var list      = carousel.find('ul');
		var allCount  = list.children('li').size();
		var cWidth    = allCount * options.elWidth;
		var viewport  = $(options.viewport);

		
		var active;
	
		list.width(cWidth);	

		var rArr      = $('<div></div>').addClass(options.rArrClass);
		var lArr      = $('<div></div>').addClass(options.lArrClass);		
		carousel.append(rArr);
		carousel.append(lArr);		
		
		var loader    = $('<div></div>').addClass(options.loaderClass);
		var loaded    = true;
				
		var viewer    = $('<div><img /></div>').addClass(options.viewerClass);
		
		viewer.append(loader);
		obj.append(viewer);		
		
		viewer.children('img').load(function() {
			loader.hide();											 
			$(this).fadeIn(options.animSpeed);	
			startScroll();
			loaded = true;
		});
		
		viewer.click(function() {
			if(loaded) {							  
				active = null;							  
				$(this).fadeOut(options.animSpeed);
				restartScroll();
			}
		});
		
		list.click(function(e) {
			var link = $(e.target).parent();					
			var li   = link.parent('li');
			if(li.size() && !viewer.is(':animated') && loaded) {
				
				active  = li;	
				loaded  = false;
				var img = viewer.children('img');

				if(viewer.is(':visible')) {
					img.fadeOut(options.animSpeed, function() {
						loader.show();														
						img.attr('src', link.attr('href'));							
					});
				} else {
					img.attr('src', '');
					loader.show();		
					viewer.show();
					img.attr('src', link.attr('href'));	
				}

				var elPos = getElmInViewportPos(li);
				if(elPos == 0) {
					stepOn(-1);	
				} else if(elPos >= displayCount() -1) {
					stepOn(1);
				} else {
					stopScroll();
				}

			}
			e.preventDefault();
		});
		
		rArr.click(function(){
			if(loaded) {							
				viewer.hide();
				active = null;
				stepOn( displayCount());
			}
		});
		
		lArr.click(function(){	
			if(loaded) {							
				viewer.hide();
				active = null;	
				stepOn( -displayCount());
			}												 
		});
		
		function stepOn(steps) {
			if (!list.is(':animated') && steps != 0) {
				var pos    = list.position();
				var tWidth = touchWidth(steps);
				var newPos;
				if(steps > 0) {
					newPos = pos.left - tWidth;
					var scrollCount = scrolledCount(newPos);
					
					if(allCount - displayCount() < scrollCount) {
						var maxPos = getMaxPos();
						if(allCount - displayCount() == scrolledCount(pos.left)) {
							newPos   = options.minPos;
							if(active) {
								active = list.children().first();
							}
						} else {
							newPos   = maxPos;
						}
					}
				} else if(steps < 0) {
					newPos = pos.left + tWidth;
					if(newPos > options.minPos) {
						if(Math.abs(pos.left) == options.minPos) {
							newPos   = getMaxPos();
							if(active) {
								active = list.children().last();
							}
						} else {
							newPos   = options.minPos;
						}
					}
				}
				list.animate({
					'left': newPos +'px'				  
				},400);				
				if(loaded) {
					restartScroll();
				}
			}
		}
		
		function displayCount() {
			return Math.floor(viewport.width() /options.elWidth);
		}
		
		function scrolledCount(pos) {
			return Math.abs(pos /options.elWidth);
		}
		
		function touchWidth(steps) {
			return Math.abs(steps * options.elWidth);
		}
		
		function getMaxPos() {
			return -(allCount - displayCount()) * options.elWidth;
		}
		
		function getElmInViewportPos(el) {
			return ($(el).position().left + list.position().left) /options.elWidth;
		}
		
		function scrollIn() {
			if(!loaded) {
				stopScroll();
				return;					
			}
			if(!list.is(':animated')) {
				stepOn(1);
				if(active) {
					var next = active.next();
					if(next.size()) {
						active.next().children().children().click();
					} else {
						viewer.click();
					}
				}
			}
		}
		
		var interval;
		function startScroll() {
			if(interval) {
				stopScroll();
			}
			interval = setInterval(scrollIn, 4000);	
		}	
		
		function stopScroll() {
			if(interval) {
				clearInterval(interval);
				interval = null;
			}
		}
		
		function restartScroll() {
			stopScroll(); 
			startScroll();
		}
                startScroll();
	}		  
})(jQuery);




