/**
 * Slider - alterne des blocs avec une transition
 *
 * NB : le 1e clic sur la flèche va déterminer le sens que préfère l'internaute
 *
 * @version		1.0
 *
 * @license		MIT-style license
 * @author		Guilhem Achikbache <guilhem [at] answeb.net>
 * @copyright	Author
 */

var Slider = new Class({

	Implements: Options,

	options: {
		container: 'slider',		// ID du conteneur des éléments
		elements: '#slider > div',	// Selcteur CSS des éléments
		arrows: true,				// Afficher les flèches ou non
		arrows_class: 'pages',		// Class CSS du div contenant les flèches
		arrow_up: '↑',				// Fleche haut (html ok)
		arrow_down: '↓'				// Fleche bas (html ok)
	},

	initialize: function(options) {
		this.setOptions(options);
		this.clicked = false;
		this.inverted = false;
		this.container = $(this.options.container);
		this.current = 0;
		if (this.container) {
			this.items = document.getElements(this.options.elements);
			if (this.items.length < 2) return;
			this.totalheight = 0;
			var maxheight = 0;
			this.items.each(function(el) {
				var newheight = el.getSize().y.toInt();
				if (maxheight < newheight) maxheight = newheight;
				this.totalheight += newheight;
			}, this);
			this.container.setStyles({
				'height': maxheight+'px',
				'overflow': 'hidden'
			});
			this.slider = new Fx.Scroll(this.container);
			if (this.options.arrows) {
				var u = new Element('a', { 'href': '#', 'class': 'u' }).set('html', this.options.arrow_up);
				u.addEvent('click', function(ev) {
					if (this.clicked == false) {
						this.clicked = true;
						// Le premier clic s'est fait sur la flèche up, on utilise le comportement normal
						this.inverted = false;
					}
					if (this.inverted) this.scrollDown();
					else this.scrollUp();
					ev.stop();
				}.bind(this));
				var d = new Element('a', { 'href': '#', 'class': 'd' }).set('html', this.options.arrow_down);
				d.addEvent('click', function(ev) {
					if (this.clicked == false) {
						this.clicked = true;
						// Le premier clic s'est fait sur la flèche down, on utilise le comportement inversé
						this.inverted = true;
					}
					if (this.inverted) this.scrollUp();
					else this.scrollDown();
					ev.stop();
				}.bind(this));
				var pages = new Element('div', { 'id': this.container.get('id')+'-pages', 'class': this.options.arrows_class});
				pages.adopt([u, d]).injectBefore(this.container);
			}
		}
	},

	scrollDown: function() {
		this.current--;
		if (this.items[this.current]) {
			this.slider.toElement(this.items[this.current]);
		} else {
			this.current++;
		}
	},

	scrollUp: function() {
		this.current++;
		if (this.items[this.current]) {
			this.slider.toElement(this.items[this.current]);
			if (this.container.getScroll().y.toInt() > this.totalheight) {
				// Bloquer au dernier
				this.current--;
			}
		} else {
			this.current--;
		}
	}

});

