jQuery.noConflict();

jQuery(function(){
	initGallery({
		holder:'.gallery',
		list:'div.gallery-holder ul',
		switcher:'ul.switcher > li',
		autoRotation:5000,
		prev:'a.previous',
		next:'a.next'
	});
});

function initGallery(option){
	var hold = jQuery(option.holder);
	var duration = option.autoRotation;
	var switcher = option.switcher || 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.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') {
			list.children().css('opacity', 0);
			list.children().eq(a).css('opacity', 1).addClass('active');
		}
		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'){
				list.children().eq(r).animate({opacity:0}, {queue:false, duration:700});
				list.children().eq(a).animate({opacity:1}, {queue:false, duration:700, complete:function(){
					if(option.autoRotation) runTimer();
				}});
			}
			else{
				list.animate({marginLeft:-w*a}, {queue:false, duration:700, complete:function(){
					if(option.autoRotation) runTimer();
				}});
			}
			return false;
		}
	});
};
