(function() {
	
	var expandMenu = Class.create({
	  initialize: function(element) {
		this.element = $(element);
		if (!element) return;
		
		this.options = Object.extend({
		  parent: 'menu',
		  delays: {
			show: 0,
			hide: 0.1
		  },
		  durations: {
		    show: 0,
		    hide: 0
		  }
		}, arguments[1] || {});
		
		this.parent = $(this.options.parent);
		if (!this.parent) return;
		
		this.startObserving();
	  },
	
	  startObserving: function() {
		var elements = (this.options.elements ? this.options.elements : [this.element]);
		
		if (!Prototype.Browser.MobileSafari) {
		  elements
		    .invoke('observe', 'mouseenter', this.show.bindAsEventListener(this))
		    .invoke('observe', 'mouseleave', this.hide.bindAsEventListener(this));
		} else {
		  this.options.activate.observe('click', this.show.bindAsEventListener(this));
		  
		  // give each element an id
		  var inSelector = [];
		  elements.each(function(element) {
			inSelector.push('#' + element.identify());
		  });
		  var match = inSelector.join(', ');
		  $(document.body).observe('touchstart', function(event) {
			var element = event.findElement(match);
			if (!element && this.element.visible()) {
			  this.hide();
			}
		  }.bindAsEventListener(this));
		}
	  },
	  
	  showDelayed: function() {
		if (this._showTimer) 
			
	    this.showTimer = this.show.delay(this.options.delays.show);
	  },
	  
	  cancelEffects: function() {
		if (this._showing) this._showing.cancel();
		if (this._hiding) this._hiding.cancel();
	  },
	  
	  show: function(event) {
		if (Prototype.Browser.MobileSafari) { event.stop(); }
		this.cancelEffects();
		this._showing = new Effect.Appear(this.element, { delay: this.options.delays.show, duration: this.options.durations.show,
		  beforeStart: function() {
			if (this.options.activate) this.options.activate.addClassName("hasmenu");
		  }.bind(this)
		});
	  },
	  
	  hide: function() {
		this.cancelEffects();
		this._hiding = new Effect.Fade(this.element, { delay: this.options.delays.hide, duration: this.options.durations.hide,
		  afterFinish: function() {
			if (this.options.activate) this.options.activate.removeClassName("hasmenu");
		  }.bind(this)
		});
	  }
	});
	
	document.observe('dom:loaded', function() {
		  new expandMenu('assortmentCategoryMenu', { elements: $$('#menuitems .assortment a.state, #assortmentCategoryMenu'), activate: $$('#menuitems .assortment a.state')[0] });
		  new expandMenu('customCategoryMenu', { elements: $$('#menuitems .custom a.state, #customCategoryMenu'), activate: $$('#menuitems .custom a.state')[0] });
	});
	
})();
	
