$(function(){
	// Gallery Initializer
	$("div.ui-gallery").each(function(){
		var $this = $(this);
		
		var reverseDirection = ($this.attr('data-direction') == 'left');
		var timeout = $this.attr('data-timeout') || 5000;
		var animTimeout = $this.attr('data-anim') || 300;
		var step = $this.attr('data-step') || 1;
		var width = $this.width();
		
		var $list = $('ul.ui-items', $this);
		var $items = $('li', $list);
		
		var itemsCount = $items.length;
		var itemWidth = $items.outerWidth();
		
		var itemsDisplay = Math.floor(width/itemWidth);
		var enableGallery = (itemsCount > itemsDisplay);
		
		var $prev = $('.ui-prev[rel=#'+$this.attr('id')+']');
		var $next = $('.ui-next[rel=#'+$this.attr('id')+']');
		
		if(enableGallery){
			var timer;
			var currentIndex;
			
			var scrollToItem = function(index){
				clearTimeout(timer);
				currentIndex = index;
				
				$list.animate({
					left: (-index * itemWidth) + 'px'
				}, animTimeout);
				
				timer = setTimeout(function(){
					scrollToItem(getFollowingIndex(index, reverseDirection));			
				}, timeout);
			};
			
			function getFollowingIndex(index, reverse){
				var maxIndex = itemsCount - (itemsDisplay);
				if(reverse){
					if(index < step)
						return maxIndex;
					return index - step;
				}
				else{
					if(index == maxIndex)
						return 0;
					if(index+step > maxIndex)
						return maxIndex;
					return index+step;
				}
			}
			
	        $prev.click(function () {
	            scrollToItem(getFollowingIndex(currentIndex, true));
	            return false;
	        });
	
	        $next.click(function () {
	            scrollToItem(getFollowingIndex(currentIndex));
	            return false;
	        });
			
            $this.hover(function () { 
				clearTimeout(timer);
			 }, function () { 
			 	scrollToItem(currentIndex);
			 });
			 
			scrollToItem(0);
		}
		else{
			$prev.hide();
			$next.hide();
		}
	});
});
