var Menu = new Class({
	Implements: [Options, Events],
	
	options: {
		background: false,
		elements: new Array(),
		offset: 0,
		event: 'mouseover',
		returnevent: 'mouseout',
		active: null
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		if(!this.options.container) this.options.container = this.options.element[0].getParent();
		if(!this.options.background) this.options.background = this.creatBackground();
		if(!this.options.toMove) this.options.toMove = this.options.background;
		
		this.options.elements.each(function(e){
			e.addEvent(this.options.event, function(){
				this.move(e);
			}.bind(this));
			e.addEvent(this.options.returnevent, function(){
				this.back();
			}.bind(this));
		}.bind(this));
		
		this.options.toMove.set('tween', {
			//transition: Fx.Transitions.Elastic.easeOut,
			//duration: 1000
		});
		this.options.background.set('tween', {
			//transition: Fx.Transitions.Elastic.easeOut,
			//duration: 500
		});
		
		this.back();
	},
	
	move: function(e){
		clearTimeout(this.t);
		this.options.toMove.fade('show');
		//var pos = e.getParent().getPosition(this.options.container).x - this.options.offset;
		var pos = e.getPosition(this.options.container).x - this.options.offset;
		var w = e.getSize().x;
		this.options.toMove.tween('left', pos);
		this.options.background.tween('width', w);
	},
	
	back: function(){
		var e = this.options.active, pos, w;
		
		//pos = !e ? 0 : e.getParent().getPosition(this.options.container).x - this.options.offset;
		pos = !e ? 0 : e.getPosition(this.options.container).x - this.options.offset;
		w = !e ? 0 : e.getSize().x;
		if(!e){
			this.options.toMove.fade('out');
		} else {
			this.t = setTimeout(function(){
				this.options.toMove.tween('left', pos);
				this.options.background.tween('width', w);
			}.bind(this), 300);
		}
	},
	
	creatBackground: function(){
		var d = new Element('div', {
			'class': 'background'
		});
		d.inject(this.options.container);
		
		return d;
	}
});

window.addEvent('domready', function(){
	var myMenu = new Menu({
		elements: $$('#top_menu ul li'),
		background: $$('#begunok span span span')[0],
		container: $('top_menu'),
		toMove: $$('#begunok')[0],
		offset: 20,
		active: $$('#top_menu ul li.curr')[0]
	});
	
	var curr = $$('#top_menu ul li.curr a.current')[0];
	if(curr){
		var t;
		$$('#top_menu ul li a').each(function(e){
			if(e == curr) return;
			e.addEvent('mouseover', function(){
				clearTimeout(t);
				curr.removeClass('current');
			});
			e.addEvent('mouseout', function(){
				t = setTimeout(function(){
					curr.addClass('current'); 
				}, 700);
				
			});
		});
	}
});