/*
*	Dependencies:
*		MooTools 1.2.1
*		MooTools Plugin: Fx.Scroll
*/

var ThumbScroller = new Class({
	Implements: Options,
	options: {
		active: 1,
		perGroup: 4,
		next: '.next',
		prev: '.prev',
		transition: Fx.Transitions.Expo.easeOut
	},
	initialize: function(container, options){
		this.setOptions(options);
		this.container = $(container) || false;
		this.thumbs = this.container.getElements('li') || false;
		this.togglerPrev = $$(this.options.prev);
		this.togglerNext = $$(this.options.next);
		this.count = this.thumbs.length;
		this.groups = Math.ceil(this.count / this.options.perGroup);
		this.setup();
	},
	setup: function(){
		this.getActive();
		this.getPositions(this.groups);
		this.Scroll = new Fx.Scroll(this.container, {transition: this.options.transition, wheelStops: false, link: 'cancel', onStart: function(){this.locked = true}.bind(this), onComplete: function(){this.locked = false}.bind(this)});
		this.thumbs[this.active - 1].addClass('active');
		this.currentGroup = this.findGroup(this.active);
		this.scrollTo(this.currentGroup);
		this.togglerPrev.addEvent('click', this.prevGroup.bindWithEvent(this));
		this.togglerNext.addEvent('click', this.nextGroup.bindWithEvent(this));
		this.container.addEvent('mousewheel', function(e){
			e.stop();
			if(this.locked) return false;
			if(e.wheel < 0 && (this.currentGroup != this.groups)) this.nextGroup();
			if(e.wheel > 0 && (this.currentGroup != 1)) this.prevGroup();
		}.bind(this));
	},
	scrollTo: function(group){
		this.currentGroup = group;
		this.Scroll.start(0, this.positions[group].y);
		(this.currentGroup == 1) ? this.togglerPrev.addClass('disable') : this.togglerPrev.removeClass('disable');
		(this.currentGroup == this.groups) ? this.togglerNext.addClass('disable') : this.togglerNext.removeClass('disable');
	},
	prevGroup: function(e){
		if(e) e.stop();
		if(e && e.target.hasClass('disable')) return false;
		(this.currentGroup > 1 ) ? this.currentGroup -= 1 : this.currentGroup = 1;
		this.scrollTo(this.currentGroup);
	},
	nextGroup: function(e){
		if(e) e.stop();
		if(e && e.target.hasClass('disable')) return false;
		(this.currentGroup < this.groups ) ? this.currentGroup += 1 : this.currentGroup = this.groups;
		this.scrollTo(this.currentGroup);
	},
	findGroup: function(pos){
		return Math.ceil(pos / this.options.perGroup);
	},
	findGroupLead: function(group){
		return (group * this.options.perGroup - this.options.perGroup);
	},
	getActive: function(){
		this.active = this.options.active;
		this.thumbs.each(function(el, i){
			if(el.hasClass('active')) this.active = (i + 1);
		}.bind(this));
	},
	getPositions: function(groups){
		this.positions = {};
		for(var i = 1; i <= groups; i++){
			this.positions[i] = this.thumbs[this.findGroupLead(i)].getPosition(this.container);
		}
	}
});
