function rndNum(c) {return Math.floor(Math.random()*c+1)-1;}

function fadeGallery(){
	var _swichTime = 5000;
	var _d = 1000;
	jQuery('.img-holder').each(function(){
		var _this = jQuery(this);
		var _list = jQuery('> img', _this);
		var _a = rndNum(_list.length);
		if(_swichTime) _swichTime +=_d;
		if(_a == -1) _a = 0;
		_list.removeClass('active').css('opacity', 0).eq(_a).addClass('active').css('opacity', 1).css('opacity', 'auto');
		var _t;
		if (_swichTime){
			_t = setTimeout(function(){
				if(_a < _list.length - 1) changeEl(_a + 1);
				else changeEl(0);
			}, _swichTime);
		}
		function changeEl(_ind){
			if(_t) clearTimeout(_t);
			if(_ind != _a){
				_list.eq(_a).removeClass('active').css({display:'block'}).animate({opacity: 0}, {queue:false, duration:_d});
				_list.eq(_ind).addClass('active').animate({opacity: 1}, {queue:false, duration:_d});
				_a = _ind;
			}
			if (_swichTime){
				_t = setTimeout(function(){
					if(_a < _list.length - 1) changeEl(_a + 1);
					else changeEl(0);
				}, _swichTime);
			}
		}
	});
}

jQuery(function(){
	fadeGallery();
})