/**
 * @author Sjors
 */
var SubMenu = new Class({
	initialize: function (element) {
		this.element = element;
		this.element.addEvent('mouseover', this.mouseover.bind(this));
		this.element.addEvent('mouseout', this.mouseout.bind(this));
		this.element.addEvent('click', this.click.bind(this));

		this.element.getParent().setStyle('height', this.element.getHeight());

		this.selected = this.element.getChildren('li:not([class~=hide])')[0];
	},

	mouseover: function () {
		this.showAll();
	},

	mouseout: function () {
		this.hideUnselected();
	},

	click: function (e) {
		this.selected = document.id(e.target).getParent();
		this.hideUnselected();

		var sectionId = this.selected.getParent().getParent().get('id').match(/[0-9]+/)[0];
		var sectionSlug = Denham.sections.get(sectionId);

		var filters1 = document.id('section-' + sectionId + '-filter1');
		var filters2 = document.id('section-' + sectionId + '-filter2');

		if (filters1) {
			var filter1Node = filters1.getElement('li:not([class~=hide])');
			var filter1Slug = filter1Node.get('id').split('-')[0];
		} else {
			filter1Slug = 'all';
		}

		if (filters2) {
			var filter2Node = filters2.getElement('li:not([class~=hide])');
			var filter2Slug = filter2Node.get('id').split('-')[0];
		} else {
			filter2Slug = 'all';
		}

		if (filters1) {
			filters1.getElements('a').each(function (link) {
				var ownFilterSlug = link.getParent().get('id').split('-')[0];
				link.set('href', '/#/' + sectionSlug + '/' + ownFilterSlug + '/' + filter2Slug + '/1/');
			});
		}

		if (filters2) {
			filters2.getElements('a').each(function (link) {
				var ownFilterSlug = link.getParent().get('id').split('-')[0];
				link.set('href', '/#/' + sectionSlug + '/' + filter1Slug + '/' + ownFilterSlug + '/1/');
			});
		}

		if (this.selected.get('id').match(/^takecare/i)) {
			this.selected.getParent('div').getLast().addClass('hide');
		} else {
			this.selected.getParent('div').getLast().removeClass('hide');
		}
	},

	showAll: function () {
		this.element.getChildren('li').removeClass('hide');
	},

	hideUnselected: function () {
		this.element.getChildren('li').addClass('hide');
		this.selected.removeClass('hide');
	}
});

window.addEvent('domready', function () {
	$$('#submenu ul').each(function (ul) {
		new SubMenu(ul);
	});
});