(function($){

	var list;
	var orgWidth;
	var animation = false;
	
	$.fn.FWGaleria = function(){
		return this.each(function(i){
			list = $('ul', this);
			orgWidth = $('li', this).width();
			var imgsCount = $('li', this).length;
			var ulWidth = imgsCount * parseInt( orgWidth );
			list.width( ulWidth );
			$('.prev, .next', this).click(function(){
				if( !animation ) switchImg( $(this).attr('class') );
				return false;
			});
		});
	}
	
	function switchImg(mode){
		animation = true;		
		var toHide = mode == 'prev' ? $('li', list).last() : $('li', list).first();		
        var tmpLeft = list.css('left');
		var tmpLeft = tmpLeft == 'auto' ? 0 : parseInt(tmpLeft);
		if( mode == 'prev' ){
			toHide.prependTo(list);
			list.css({ left: tmpLeft-orgWidth });
		}
		list.animate({
			left: (mode == 'prev' ? '+=' : '-=' ) + orgWidth+'px'
		},{
			queue: true,
			duration: 500,
			complete: function(){
				if( mode == 'next' ){
					list.css('left', tmpLeft + 'px');
					toHide.appendTo(list);
				}
				animation = false;
			}
		});
		return false;
	}

})(jQuery);
