(function($){
	var position = 0;
	var w = 0 ;
	var items = [];
	var count = 0;
	var settings = {};
	$.fn.r = function (opts) {
		var $this = $(this);
		settings = $.extend({
			minOpacity : 1.1,
			maxOpacity : 0
		}, opts);
		items = $(' > div', $this);
		count = items.length;
		w = $this.width();
		position = Math.ceil(count / 2) - 1;
		updateView();
		$('.next', items).bind('click', function(){next()});
		$('.prev', items).bind('click', function(){prev()});
		for (var i=0;i < count; i++) {
			$(items[i]).attr('i', i);
			$('div.shadow', items[i]).attr('index', i);
			$('div.shadow', items[i]).bind('click', function(){
				toIndex($(this).attr('index'));
			});
		}
	};
	
	function getPositionCoef (position, index) {
		var c = 0;
		if (position == index) {
			c =  0.5;
		}
		else if (position - index == 1) {
			c = 0.25;
		}
		else if (position - index == -1) {
			c = 0.75;
		}
		else if (position - index == 2) {
			c = 0.1;
		}
		else if (position - index == -2) {
			c =  0.9;
		}
		else if (position + count - index == 2) {
			c =  0.1;
		}
		else if (position + count - index == 1) {
			c =  0.25;
		}
		else if (position - count + index == -2 || (position - count + index) == 0) {
			c = 0.9;
		}
		else if (position - count + index == -1 && index < count / 2) {
			c = 0.75;
		}
		//console.log("position : " + position + ";index:" + index + ";c:" + c);
		return c;
	};
	
	function updateView () {
		for (i = 0; i <count; i++) {
			var pc = getPositionCoef(position, i);
			//console.log("index : " + i + " pc = " + pc + " pos = " + position);
			updateItem(items[i], pc, position == i);
		}
	};
	
	function updateItem (item, pc, current) {
		var $item = $(item);
		var z = (pc > 0.5 ? 1 - pc : pc) * 100;
		var o= 0;
		if (current) {
			o = settings.maxOpacity;
		}
		else {
			o = settings.minOpacity - Math.abs((pc > 0.5 ?  1 - pc : pc) * 2);
		}
		$item.css({
			position:"absolute",
			top : 0,
			"z-index" : parseInt(z)
		});
		var left = 0;
		if (current) {
			left =  w * 0.5 - $item.width() / 2;
		}
		else {
			if (pc == 0.25) {
				left = w * 0.5 - $item.width() - $item.width() / 2;
			}
			if (pc == 0.1){
				left = w * 0.5 - 2 * $item.width() - $item.width() / 2 ;
			}
			if (pc == 0.75) {
				left = w * 0.5 + $item.width() / 2;
			}
			if (pc == 0.9) {
				left = w * 0.5 + $item.width()  + $item.width() / 2;
			}
		}
		$item.animate({left : left});
		$('.shadow', $item).animate({opacity : o});
		if (current) {
			$('.next,.prev,.text', $item).fadeIn(500);
		}
		else {
			$('.next,.prev,.text', $item).fadeOut(500);
		}
	};
	
	function next () {
		position++;
		if (count<=position) {
			position = 0;
		}
		updateView();
	};
	
	function prev () {
		position--;
		if (position < 0) {
			position = count - 1;
		}
		updateView();
	};
	
	function toIndex (i) {
		if (position != i) {
			position = i;
			updateView();
		}
	}
	
})(jQuery);
