// setup the namespace
if (typeof onepica == "undefined" || !onepica) {
    var onepica = {};
}

onepica.TopNav = Class.create({
	initialize: function() {
		
		/*
		 * 2nd Tier
		 */
		this.set = [];
		var set = $$('ul#nav li.level0');
		for (var i = 0; i < set.length; i++) {
			if (!set[i].hasClassName('nav-mycart')) {
				set[i].identify();
				set[i].hover(this.eventSetOver.bindAsEventListener(this), this.unsetOver.bindAsEventListener(this));
				this.set.push(set[i]);
			}
		}
		var elem = this.getActive();
		this.setOver(elem, true);
		
		/*
		 * 2nd tier & 3rd tier popouts
		 */
		var elements = [$$('.level1 div.mouseover').toArray(), $$('.league div.mouseover').toArray()].flatten();
		elements.each(function(n) {
			var divs = n.select('div');
			n.hover(
				function() { divs.invoke('show'); },
				function() { divs.invoke('hide'); }
			);
		});		
		if(Prototype.Browser.IE) {		
			$$('#TopLayeredNav dl.team dd ol li.league').each(function(i) {
				i.observe('mouseenter', function() {
					this.nextSiblings().each(function(i) { i.style.zIndex = -1; });
				});
				i.observe('mouseleave', function() { 
					this.nextSiblings().each(function(i) { i.style.zIndex = 1; });
				});
			});
		}
	},
	
	getActive: function() {
		return this.set.find(function(n){ return n.hasClassName('active'); });
	},
	
	getOver: function(elem) {
		return this.set.find(function(n){ return n.hasClassName('over'); });
	},

	eventSetOver: function (event) {
		var el = event.element();
		if (el.tagName.toLowerCase() == 'li' && el.hasClassName('level0')) {
			this.setOver(el);
		}
		else {
			this.setOver(el.up('li.level0'));
		}
	},
	
	setOver: function(elem, withoutPromo) {
		if(this.unsetTimeHandle) {
			clearTimeout(this.unsetTimeHandle);
		}
		
		var id = (elem ? elem.id : '');
		this.set.each(function(n){
			if (n.id != id) {  // prevents flickering
				n.removeClassName('over');
				var ul = n.down('ul');
				if(ul) ul.hide();
			}
			var div = n.down('div.promo_block');
			if(div) div.hide();
		});

		if (elem) {
			elem.addClassName('over');
			var ul = elem.down('ul');
			if(ul) ul.show();
			var div = elem.down('div.promo_block');
			if(div && !withoutPromo) div.show();
		}
	},
	
	unsetOver: function() {
		var getActive = this.getActive.bindAsEventListener(this);
		var setOver = this.setOver.bindAsEventListener(this);
		this.unsetTimeHandle = setTimeout(function(){setOver(getActive(), true);}, 200);
	}	
});
