var Menu = new Class({

	Implements: Options,

	options: {
		moverLeft: null,
		moverRight: null,
		moreText: 'Подробнее...',

		elements: {
			'google': 'http://www.google.com/',
			'yandex': 'http://www.yandex.ru/',
			'giga': 'http://forum.giga.ua'
		},

		minWidth: 150,
		maxWidth: 200
	},

	count: 0,
	index: 0,

	container: null,

	initialize: function(container, options) {
		this.container = $(container);
		if (this.container) {
			this.setOptions(options);
			this.index = Cookie.read('MenuIndex')?Cookie.read('MenuIndex').toInt():0;

			if (this.options.moverLeft) {
				$(this.options.moverLeft).addEvent('click', function(event) {
					if (this.index > 0) {
						this.index--;
						this.render();
					}
					Cookie.write('MenuIndex', this.index, {path: '/'});
					event.stop();
				}.bind(this));
			}

			if (this.options.moverRight) {
				$(this.options.moverRight).addEvent('click', function(event) {
					var elementsLength = $H(this.options.elements).getLength();
					if ((this.count + this.index) < (elementsLength)) {
						this.index++;						
						this.render();
					}
					Cookie.write('MenuIndex', this.index, {path: '/'});
					event.stop();
				}.bind(this));
			}
			
			window.addEvent('resize', function() {
				this.index = 0;
				Cookie.write('MenuIndex', this.index, {path: '/'});
				this.render();
			}.bind(this));
			this.render();
		}
	},

	render: function() {
		var table = new Element('table');
		var tr = new Element('tr');

		var elements = $H(this.options.elements);
		this.count = this.calculate();

		var index = 0;
		var count = this.count;
		elements.each(function(value, key) {
			if ((index >= this.index) && (count-- > 0)) {
				var td = new Element('td');
				var content = $(value).clone(true, true);
				if ($(value).hasClass('selected')) {
					var wrapper = new Element('div', {'class': 'selected', 'style': 'height: 100%'});
					value = wrapper.grab(value.clone(true, true));
					td.addClass('selected');
				}
				tr.grab(td.grab(content));
			}
			index++;
		}.bind(this));
		$(this.container).empty().grab(table.grab(tr));
		if (Browser.Engine.trident) {
			$(this.container).set('html', table.getParent().get('html'));
		}
	},

	calculate: function() {
		var result = 1;

		var elements = $H(this.options.elements);

		var width = this.container.getSize().x;
		var maxNum = (width/this.options.minWidth).toInt();
		var minNum = (width/this.options.maxWidth).toInt();

		if (maxNum > elements.getLength()) {
			result = elements.getLength();
		} else {
			if (maxNum > 1) {
				result = maxNum;
				if (maxNum - minNum > 1) {
					result = result--;
				}
			}
		}
		return result;
	}

});
