jQuery.fn.glebsn_carousel = function(){
	var carousel_items = $("#carousel-list").find("li").length;
	var item_width = $("#carousel-list").find("li").width();
	var carousel_width = item_width*carousel_items;
	var clip_width = $("#carousel-clip").width();
	var carousel_list = $("#carousel-list");
	var first_delta = -19;
	var last_delta = 19;
	var current = $('#current').length ? $('#current').attr('value'):0;
	var speed = 2000;
	
	

	var can_move = (clip_width) < (carousel_width-first_delta + last_delta);
	
	/* we can move if carousel width minus deltas is bigger than carousel clip */
	if (current && can_move) {
		move_carousel_to_position(current);
	}
	
	/* functions */
	
	$("#next").mouseover( function() {
		if(can_move) {
			var desctination = -carousel_width+clip_width+last_delta;
			var current_speed = change_speed(desctination);
			carousel_list.animate({"left": desctination},current_speed, function() {$("#next img").attr("src","/i/next_dis.gif"); } );
			$("#prev img").attr("src","/i/prev.gif");
		}
	});
		
	$("#prev").mouseover( function() {
		if(can_move) {
			var current_speed = change_speed(first_delta);
			carousel_list.animate({"left": first_delta},current_speed, function() {$("#prev img").attr("src","/i/prev_dis.gif");} );
			$("#next img").attr("src","/i/next.gif"); 
		}
	});
	
	$("#prev").mouseout( function() {
		carousel_list.stop();
	});
	
	$("#next").mouseout( function() {
		carousel_list.stop();
	});
	
	/* controls */
	
	$("#carousel-control > span.number").click( function() { 
		var el = $(this);
		var number = parseInt(el.html());
		
		$("#carousel-control span").removeClass("selected");
		el.addClass("selected");

		if(can_move) move_carousel_to_position(number);
	});
	
	
	/* this function moves carousel list to the defined position */
	function move_carousel_to_position(number) {
		var dis_next = '';
		var dis_prev = '';
		var delta = ((clip_width-item_width)/2) - (item_width*(number-1)) + first_delta;
		
		if (delta > first_delta) {
			delta = first_delta;
			dis_prev = '_dis';
		}
		
		var right_border = delta + carousel_width - last_delta;
		
		if (right_border < clip_width) {
			delta = clip_width-carousel_width+last_delta;
			dis_next = '_dis';
		}
		
		$("#next img").attr("src","/i/next" + dis_next + ".gif");
		$("#prev img").attr("src","/i/prev" + dis_prev + ".gif");
		
		//var current_speed = change_speed(delta);
		
		carousel_list.animate({"left": delta}, "fast");
	}
	
	function change_speed(destination) {
		var current_left = parseInt(carousel_list.css("left"));
		var distance = Math.abs(destination-current_left);
		
		var current_speed = parseInt(speed * Math.pow(distance / parseInt(item_width), 1/1.3) );
		//current_speed = current_speed < 2000 ? 2000:current_speed;
		
		current_speed = Math.round(current_speed/1000)*1000;
		
		
		return current_speed; 
	}
};