(function($){

	$.fn.jBoxTape = function(o){
		var defaults = {
			'easing' : 'easeInBack'
		};
		var options = $.extend(defaults, o);
		
		return this.each(function(){
			var $box = $(this), $list = $box.find('ol:first');
			if (!$list.size()) $list = $box.find('ul:first');
			var $curr = $list.find('> li.s');
			var pos = 0, i = 0;
			$list.find('> li').each(function(){
				if ($(this).attr('value')==$curr.attr('value')) pos = i;
				i++;
			});
			var picWidth = $list.find('> li:first').width();
			var len = $list.find('> li').size();
			var step = 1;
			
			$list.each(function(){
				if (this.tagName=='UL'){
					picWidth += 6; // 5 sometimes. do not remember where.
					step = 3;
					return false;
				}
			});
			var ulWidth = picWidth*len;

			var $prev = $box.find('a.prev:first'), $next = $box.find('a.next:first');
			lockedTape = false;
			
			function _checkButtons(){
				$list.width(ulWidth);
				$prev.show();
				$next.show();
				if (pos*step-step<0) $prev.hide();
				if (pos*step+step>=len) $next.hide();
			}
			
			function _rollBox(dir){
				if (lockedTape) return false;
				pos += dir;
				_checkButtons();
				var left = -(picWidth * pos * step), boxWidth = $list.parent().width(),
					cnt = parseInt(boxWidth / picWidth, 10);
				if (left + $list.width() < cnt * picWidth){
					// out of right border
					left = -(picWidth * ($list.find('> li').size() - cnt));
					pos = Math.floor(len / cnt);
				}
				if (left > 0){
					// out of left border
					pos -= dir;
					return false;
				}
				lockedTape = true;
				if (dir) $list.animate({"left" : left}, 750, options.easing, function(){
					lockedTape = false;
				});
			}
			
			$prev.click(function(){
				_rollBox(-1);
				return false;
			});
			$next.click(function(){
				_rollBox(1);
				return false;
			});
			
			if (typeof $.fn.mousewheel == 'function'){
				$list.parent().mousewheel(function(event, delta){
					if (delta < 0) $prev.click(); else $next.click();
					return false;
				});
			}
			
			_checkButtons();
		});
	}
	
})(jQuery)

