var ExinitAjaxMenu = new Class({
	Implements: [Options, Events],
	options: {
		itemsVisible:				10,
		scrollTransition:			Fx.Transitions.sine,
		scrollTransitionDuration:	1000,
		overallContainer:			'ajaxMenuBox',
		elementScrolled:			'ajaxMenuContainer',
		menuElementsContainer:		'ajaxMenuElements'
	},
	initialize: function(options) {
		if(options) {
			this.setOptions(options);
		}
		
		this.forwardButton = $(this.options.overallContainer).getElement('.forwardButton');
		this.backwardButton = $(this.options.overallContainer).getElement('.backwardButton');
		 
		this.assignForwardEvent();
		this.assignBackwardEvent();
		
		this.scrollFx = new Fx.Scroll(this.options.elementScrolled, {transition: this.options.scrollTransition, duration: this.options.scrollTransitionDuration});
		this.openFx = new Fx.Morph($(this.options.overallContainer), {transition: Fx.Transitions.sine, duration: 500});
		
		this.lastSearchInputContent = $('ajaxMenuSearch').value;
		
		this.reset();
		this.menuIsOpened = false;
	},
	slide: function(step) {
		if((this.currentElement < this.elements.length-this.options.itemsVisible && step > 0) || (step < 0 && this.currentElement !== 0)) {
			this.scrollFx.cancel();
			this.currentElement += step;
			this.scrollFx.toElement(this.elements[this.currentElement]);
		}
	},
	assignForwardEvent: function() {
		this.forwardButton.addEvent('click', function() {
			this.slide(this.options.itemsVisible);
		}.bind(this));
	},
	assignBackwardEvent: function() {			
		this.backwardButton.addEvent('click', function() {										
			this.slide(this.options.itemsVisible * (-1));			
		}.bind(this));
	},
	reset: function() {
		this.elements = $(this.options.menuElementsContainer).getElements('.menuElement');
		this.currentElement = 0;
		this.scrollFx.toElement(this.elements[this.currentElement]);
	},
	injectContentIfQueryChanged: function() {
		var currentQuery = $('ajaxMenuSearch').value;
		if(this.lastSearchInputContent != currentQuery) {
			xajax_exinit_ajaxmenu_search(currentQuery);
		}
		this.lastSearchInputContent = currentQuery;
	},
	openContainer: function() {
		this.openFx.start({
			'height': 348
		}).chain(function() {
			$('ajaxMenuSearch').focus();
		});
		this.menuIsOpened = true;
	},
	closeContainer: function() {
		this.openFx.start({
			'height': 0
		});
		this.menuIsOpened = false;
	},
	toggleSize: function() {
		if(this.menuIsOpened) {
			this.closeContainer();
			window.clearInterval(this.injectContentIfQueryChanged);
		} else {
			this.openContainer();
			window.setInterval(this.injectContentIfQueryChanged, 1000);
		}
	}
});
