$(function(){
	initGallery({
		holder:'.tabs-area',
		list:'.tab-holder',
		switcher:'#sidebar ul.tabset > li',
		autoRotation:8000,
		effect:'fade',
		autoHeight:true,
		prev:false,
		next:false
	});
});

function initGallery(option){
	var hold = jQuery(option.holder);
	var duration = option.autoRotation;
	var switcher = option.switcher || false;
	var autoHeight = option.autoHeight || false;
	var event = option.event || 'click';
	hold.each(function(){
		var _this = jQuery(this);
		var list = _this.find(option.list),
			count = list.children().length,
			w = list.parent().width(),
			_t,
			a = 0,
			r = a;

		if(option.prev && option.next){
			var prev = _this.find(option.prev).attr('rel', 'prev').click(animateSlide);
			var next = _this.find(option.next).attr('rel', 'next').click(animateSlide);
		}
		if(option.autoHeight){
			list.css({height:list.children().eq(a).height()});
		}
		if(option.switcher){
			switcher = _this.find(switcher);
			switcher.eq(r).removeClass('active');
			switcher.eq(a).addClass('active');
			switcher.bind(event, function(){
				var ind = switcher.index($(this));
				animateSlide(ind);
				return false;
			});
		}
		if(option.autoRotation) runTimer();
		if(option.effect == 'fade') {
			if($.browser.msie){
				list.children().hide();
				list.children().eq(a).addClass('active').show();
			}
			else {
				list.children().css('opacity', 0).hide();
				list.children().eq(a).css('opacity', 1).addClass('active').show();
			}
		}
		if(option.stopOnHover && _t){
			list.mouseenter(function(){
				clearTimeout(_t);
			}).mouseleave(runTimer);
		}
		function runTimer(){
			_t = setTimeout(function(){
				animateSlide('next');
			}, duration);
		}
		
		function animateSlide(e){
			r = a;
			if(typeof e == 'string' && e == 'next') a++;
			else if(typeof e == 'number') a=e;
			else{
				if(e.target.rel == 'next') a++;
				else if(e.target.rel == 'prev') a--;
			}
			if(_t) clearTimeout(_t);
			if(a == count) a=0;
			else if(a == -1) a=count-1;
			
			list.children().eq(r).removeClass('active');
			list.children().eq(a).addClass('active');
			
			if(option.switcher){
				switcher.eq(r).removeClass('active');
				switcher.eq(a).addClass('active');
			}
			if(option.effect == 'fade'){
				if($.browser.msie){
					list.children().css({'display':'none'});
					list.children().eq(a).css({'display':'block'});
					if(option.autoRotation) runTimer();
				}
				else{
					list.children().eq(r).animate({opacity:0}, {queue:false, duration:700});
					list.children().eq(a).show().animate({opacity:1}, {queue:false, duration:700, complete:function(){
						if(option.autoRotation) runTimer();
					}});
				}
				if(option.autoHeight){
					list.animate({height:list.children().eq(a).height()}, {queue:false, duration:700});
				}
			}
			else{
				list.animate({marginLeft:-w*a}, {queue:false, duration:700, complete:function(){
					if(option.autoRotation) runTimer();
				}});
			}
			return false;
		}
	});
};
