SL.mobile = {};

(function() {

	SL.mobile.Nav = Class.create(SL.Component, {
		init : function() {
			this.attachE = $(this.config.get('attach_id'));

			if (!this.attachE) {
				this.attachE = this.e.up(this.config.get('attach_class'));
				if (!this.attachE) {
					this.attachE = this.e.up().up();
				}
			}

			this.activeE = $(this.config.get('active_id'));

			this.e.select('li.with_children>div.item').each(function(e) {
				e.observe('click', this.showChildren.bind(this, e));
			}.bind(this));

			this.e.select('li.with_children>div.children div.item>div').each(function(e) {
				e.observe('click', this.showParent.bind(this, e));
			}.bind(this));

			(function() {
				var top = this.attachE.cumulativeOffset().top + this.attachE.getHeight();

				this.e.setStyle({
					top : top + 'px'
				});
			}.bind(this)).defer();
		},

		showChildren : function(e) {
			e.up().down('div.children>ul').setStyle({
				marginLeft : '0'
			});
		},

		showParent : function(e) {
			e.up('ul').setStyle({
				marginLeft : ''
			});
		},

		toggle : function() {
			if (this.shown) {
				this.hide();
			} else {
				this.show();
			}
		},

		show : function() {
			if (this.shown) {
				return;
			}

			// this.attachE.scrollTo();

			var top = this.attachE.cumulativeOffset().top + this.attachE.getHeight();
			var minHeight = document.viewport.getHeight() - this.attachE.getHeight();

			var height = 0;

			this.e.select('ul').each(function(e) {
				var h = e.getHeight();
				if (h > height) {
					height = h;
				}
			});

			this.e.select('ul').each(function(e) {
				e.setStyle({
					height : height + 'px'
				});
			});

			this.e.setStyle({
				top : top + 'px',
				minHeight : minHeight + 'px',
				height : height + 'px'
			});

			this.activeE.addClassName('active');
			this.shown = true;
		},

		hide : function() {
			if (!this.shown) {
				return;
			}

			this.e.setStyle({
				height : '0',
				minHeight : '0'
			});

			this.activeE.removeClassName('active');
			this.shown = false;
		}
	});

})();

