var MorphList = Class.create({
	
	initialize: function(menu, options) 
	{	
		var that = this;
		this.options = options;
		this.menu = $(menu);
		this.menuitems = this.menu.childElements();
		
		this.menuitems.each(function(mi) {
			Event.observe(mi, 'mouseover', this.morphTo.bindAsEventListener(this, mi));
			Event.observe(mi, 'mouseout', this.morphTo.bindAsEventListener(this));
			Event.observe(mi, 'click', this.click.bindAsEventListener(this, mi));
		}.bind(this));
		
		var div = Builder.node('div', {className:'left'});
		this.bg = Builder.node('li', {className:'background'}, div);
		$(this.bg).hide();
		
		this.menu.insert(this.bg);
		
		//this.bg.set('morph', {link: 'cancel'});
		
		this.setCurrent(this.menu.select('.current').first());
	},     

	click: function(e, item) 
	{
		this.setCurrent(item, true);
	},
	
	setCurrent: function(el, effect)
	{  
		if(el && !this.current) 
		{
			new Effect.Morph($(this.bg), {
				style: {
					left: el.offsetLeft+'px', 
					top: el.offsetTop+'px',
					width: el.offsetWidth+'px', 
					height: el.offsetHeight+'px'
				},
				duration: 0.3
			});
				
			(effect) ? this.bg.appear() : this.bg.setOpacity(1);
		}
		
		if(this.current) this.current.removeClassName('current');
		if(el) this.current = el.addClassName('current');
	},         
         
	morphTo: function(e, to) 
	{
		if(!this.current) return;
		
		if(to == null) to = this.current;
		
		var related = e.relatedTarget;
		
		if( (e.type == 'mouseout') && (related != null) && related.descendantOf(to.up()) )
			return;
		
		new Effect.Morph($(this.bg), {
			style: {
				left: to.offsetLeft+'px', 
				top: to.offsetTop+'px',
				width: to.offsetWidth+'px', 
				height: to.offsetHeight+'px'
			},
			duration: 0.3
		});
		
		//this.fire('onMorph', to);
	}
});
