var menu

window.addEvent('domready',function(){
	menu = new Menu()
})

var Menu = new Class({
		
	initialize: function(){
		
		if(!$('product-menu')){
			return
		}
		
		this.topElement = $('product-menu')
		
		this.opened = -1
		this.topNodes = this.topElement.getChildren('li')
		
		this.topElement.addEvent('mouseleave', this.closeOpenedDropdown.bind(this))
		
		this.topNodes.each(function(el,i){

			var aEl = el.getElement('a')
			var subEl = el.getElement('div.dropdown')
			
			
			
			if(subEl){
				
				if(subEl.getElements('li').length > 0){
					aEl.addEvent('mouseenter', this.openDropdown.bind(this,i))
					subEl.addEvent('mouseleave', this.closeDropdown.bind(this,i))
				}else{
					aEl.addEvent('mouseenter', this.closeOpenedDropdown.bind(this))
					subEl.destroy()
				}
				
			}else{
				aEl.addEvent('mouseenter', this.closeOpenedDropdown.bind(this))
			}

		},this)
		
	},
	
	openDropdown: function(id){
		//close open dropdown
		this.closeOpenedDropdown()
		
		var liEl = this.topNodes[id]
		var aEl = this.topNodes[id].getElement('a')
		var subEl = this.topNodes[id].getElement('div.dropdown')
		if(!subEl){
			return
		}
		
		this.opened = id

		liEl.addClass('current')
		liEl.addClass('selected')
		subEl.setStyle('display', 'block')		
	},
	
	closeDropdown: function(id){
		var liEl = this.topNodes[id]
		var aEl = this.topNodes[id].getElement('a')
		var subEl = this.topNodes[id].getElement('div.dropdown')
		if(!subEl){
			return
		}
		
		liEl.removeClass('current')
		liEl.removeClass('selected')
		subEl.setStyle('display', 'none')
		
		this.opened = -1
	},
	
	closeOpenedDropdown: function(){
		if(this.opened == -1){
			return
		}
		
		this.closeDropdown(this.opened)
	},
	
	selectItem: function(className){
		this.topElement.getElement('li.' +  className).addClass('current')
	}

})

