/// Prototype-based Fancy Menu
/// File: fancyMenu.js
/// Date: 02/08/2007
/// Author: David Georges - Globule Bleu

var SlideList = Class.create();

SlideList.Transitions = 
{
  backIn: function(p)
  {
    return Math.pow(p, 2) * ((1.618 + 1) * p - 1.618);
  },
  
  backOut: function(p)
  {
    return (1 - (Math.pow(1-p, 2) * ((1.618 + 1) * (1-p) - 1.618)));
  },
  
  elasticIn: function(p)
  {
    return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI / 3);
  },
  
  elasticOut: function(p)
  {
    p = (1-p);
    return 1 - (Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI / 3));
  }
}

SlideList.prototype = {
	
	options: null,
	
	// Constructeur de la classe SlideList.
	initialize: function(menu, options) {
		this.options = Object.extend(this.getOptions(), options);

		this.menu = $(menu);
		this.current = this.menu.getElementsBySelector('li.current').reduce();
		
		this.menu.getElementsBySelector('li').each(function(item){
			Event.observe(item, 'mouseover', function(){ this.moveBg(item); }.bind(this));
			Event.observe(item, 'mouseout', function(){ this.moveBg(this.current); }.bind(this));
			Event.observe(item, 'click', function(evt){ this.clickItem(evt, item); }.bind(this));
		}.bind(this));
				
		this.back = Builder.node('li',{className:'background'},[Builder.node('div',{className:'left'})]);
		this.menu.appendChild(this.back);

		this.setCurrent(this.current);
	},
	
	setOptions: function(options) {
		Object.extend(this.options, options);
	},
	
	// Méthode qui sélectionne un MenuItem + effet.
	setCurrent: function(el) {
		if(this.current) {
			$(this.back).setStyle({left: (el.offsetLeft)+'px', width: (el.offsetWidth)+'px'});
			this.current = el;
		} else $(this.back).hide();
	},
	
	// Récupère les options par défaut.
	getOptions: function(){
		return {
			transition: SlideList.Transitions.backOut,
			duration: 0.5
		};
	},

	// Méthode appellée lors du click sur un MenuItem.
	clickItem: function(evt, item) {
		if(!this.current) this.setCurrent(item);
		this.current = item;
	},
	
	// Méthode qui gère le déplacement de l'élément de fond.
	moveBg: function(to) {
		if(to) {
			if(this.currentEffect) this.currentEffect.cancel();
			
			Object.extend(this.options, {
					style: {
						left: (to.offsetLeft)+'px',
						width: (to.offsetWidth)+'px'
					}, 
					afterFinish: function() {
						this.currentEffect = null;
					}.bind(this)
			});
			
			$(this.back).show();
			
			this.currentEffect = new Effect.Morph(this.back, this.options);
		} else $(this.back).hide();
	}
};