/* Author by Le Yang */

var CarouselScroll = {
	
	index : 1,
	
	init : function(obj, offset){
		
		//get list length
		var sum = obj.find('ul').children('li').length;
		CarouselScroll.autoScroll(obj, offset, sum);
		
		// modify the whole width
		var width = (sum + 1) * obj.outerWidth();
		obj.find('ul').css('width', width);
	
		obj.find('.pagination').find('.prev').click(function(){
			CarouselScroll.prevHandler(obj, offset);
			return false;
		});
		
		obj.find('.pagination').find('.next').click(function(){
			CarouselScroll.nextHandler(obj, offset, sum);
			return false;
		});
		
		obj.find('.pagination').find('a').not('.prev, .next').click(function(){
			var self = $(this);
			CarouselScroll.gotoPage(obj, offset, self);
			return false;
		})
	},
	
	prevHandler : function(obj, offset){
		var ul_obj = obj.find('ul');
		ul_obj.stop(true, true);
		
		if (CarouselScroll.index > 1){
			ul_obj.animate({left: '+=' + offset}, 700);
			CarouselScroll.index --;
			obj.find('.pagination').find('a').not('.prev, .next').removeClass('current');
			obj.find('.pagination').find('a').not('.prev, .next').eq(CarouselScroll.index - 1).addClass('current');
		}
	},
	
	gotoPage : function(obj, offset, self){
		var ul_obj = obj.find('ul');
		var index = self.html();
		obj.find('.pagination').find('a').not('.prev, .next').removeClass('current');
		self.addClass('current');
		ul_obj.stop(true, true);
		ul_obj.animate({left: -1 * offset * (index - 1)}, 700);
		CarouselScroll.index = index;
	},
	
	
	nextHandler : function(obj, offset, sum){
		var ul_obj = obj.find('ul');
		ul_obj.stop(true, true);
		
		if (CarouselScroll.index < sum){
			
			ul_obj.animate({left: '-=' + offset}, 700);
			CarouselScroll.index ++;
			obj.find('.pagination').find('a').not('.prev, .next').removeClass('current');
			obj.find('.pagination').find('a').not('.prev, .next').eq(CarouselScroll.index - 1).addClass('current');
		}
	},
	
	autoScroll : function(obj, offset, sum){
		obj.find('.pagination').find('a.current').animate({opacity: 1},10000, function(){
			if($(this).next().hasClass('next')){
				CarouselScroll.gotoPage(obj, offset, $(this).parent().children('.prev').next());
			}else{
				CarouselScroll.nextHandler(obj, offset, sum);
			}
			CarouselScroll.autoScroll(obj, offset, sum);
		})
	}
	
	
	
}
if ($('body.supported').length > 0){
	CarouselScroll.init($('.carousel-widget'), 889);
}
else {
	CarouselScroll.init($('.carousel-widget'), 952);
}

