var NXC = NXC || {};
NXC.TopMenu = new Class( {

	Implements: [Options],

	options:{
		fadeDuration: 500,
		timerDelay: 200
	},

	links: [],
	contents: [],
	timer: $empty,
	opened: false,

	initialize: function( linksCSSSelector, contentsCSSSelector, options ) {
		this.setOptions( options );

		this.links    = document.getElements( linksCSSSelector );
		this.contents = document.getElements( contentsCSSSelector );

		this.installEvents();
	},

	installEvents: function() {
		this.links.each( function( link, index ) {
			link.addEvent( 'mouseover', this.showItem.bind( this, index ) );
			link.addEvent( 'mouseout', this.startTimer.bind( this ) );
		}.bind( this ) );

		this.contents.each( function( el ) {
			el.setStyle( 'opacity', 0 );
			el.addEvent( 'mouseover', this.stopTimer.bind( this ) );
			el.addEvent( 'mouseout', this.startTimer.bind( this ) );
		}.bind( this ) );
	},

	showItem: function( itemIndex ) {
		this.stopTimer();

		this.contents.each( function( el, index ) {
			if( index !== itemIndex ) {
				this.hideItem( el );
			} else {
				this.opened = true;

				el.setStyle( 'display', 'block' );
				el.get( 'tween', { property: 'opacity', duration: this.options.fadeDuration } ).start( 1 );
			}
		}.bind( this ) );
	},

	hideItem: function( el ) {
		if( el.getStyle( 'display' ) == 'block' ) {
			el.get( 'tween', { property: 'opacity', duration: this.options.fadeDuration } ).start( 0 ).chain( function() {
				el.setStyle( 'display', 'none' );
			} );
		}
	},

	startTimer: function() {
		this.timer = function() {
			if( this.opened ) {
				this.contents.each( function( el, index ) {
					this.opened = false;
					this.hideItem( el );
				}.bind( this ) );
			}
		}.delay( ((this.options.timerDelay + this.options.fadeDuration)/2), this );
	},

	stopTimer: function() {
		$clear( this.timer );
	}
} );
