/* Copyright (c) 2009 Michal Charemza */

// Mild hack to make sure there is no single pixel jump at end
/*Array.implement({
	round: function() {
		return this.map(function(number) {return Math.round(number)});
	}
});

Fx.Scroll.implement({
	set: function(){
		var now = Array.flatten(arguments).round();
		this.element.scrollTo(now[0], now[1]);
	}
});*/

var LinkScroll = new Class({
	Implements: [Options],
	
	options: {
		fxOptions: {
			wheelStops: false,
			link: 'chain'
		}
	},
	
	initialize: function(links, targets, pane, options) {
		this.setOptions(options);
		this.scrollFx = this.createFx(pane);
		
		this.coords = [];
		this.anchors = [];
		this.links = links;
		this.targets = targets;
		this.at = 0;
		
		this.setCoords();
		this.setAnchors();
		this.initLinks();
		this.at = this.coords.indexOf(pane.getScroll().x);
		this.at = (this.at != -1) ? this.at : 0;
	},
	
	initLinks: function() {
		this.links.each(function(link, i) {this.initLink(link, i)}, this);
	},
	
	initLink: function(link, i) {
		link.addEvent('click', (function() {this.onClick(link, i); return false;}).bind(this));
	},
	
	onClick: function(link, i) {
		this.toAnchor(i);
		return false;
	},
	
	createFx: function(pane, options) {
		return new Fx.Scroll(pane, $merge(options, this.options.fxOptions, {wheelStops: false, link:'chain', onComplete: this.onComplete.bind(this)})); // Prefer if setOptions merged
	},
	
	setAnchors: function() {
		this.targets.each(this.setAnchor.bind(this));
	},
	
	setAnchor: function(target, i) {
		this.anchors[i] = target.get('id');
	},
	
	setCoords: function() {
		this.targets.each(function(target, i) {this.setCoord(i)}, this);
	},
	
	setCoord: function(i) {
		this.coords[i] = (i > 0) ? this.coords[i-1] + this.getSize(i) : 0;	
	},

	getSize: function(i) {
		return this.targets[i-1].getSize().x + this.targets[i-1].getStyle('margin-right').toInt();
	},
	
	toAnchor: function(i, immediate) {
		this.at = i;
		this.scrollFx[(immediate) ? 'set' : 'start'](this.coords[i], 0);
		!immediate || this.onComplete();
	},
	
	onComplete: function() {
	}
});