var Nav = Class.create();
Nav.prototype = {
	initialize: function(container) {
		this.container = $('nav');
		this.togglers  = this.container.childElements('li');
		this.tabs      = this.container.childElements('div.callout');
		this.setup();
	},
	setup: function() {
		this.togglers.each(function(el, i) {
			if (el.down('a.tab')) {
				Event.observe(el, 'mouseenter', this.open.bindAsEventListener(this, i));
				Event.observe(el, 'mouseleave', this.hide.bindAsEventListener(this, i));
			}
		}.bind(this));
	},
	open: function(event, i) {
		this.timeout = setTimeout(this.show.bind(this,i), 100);
		Event.stop(event);
	},
	show: function(i) {
		for(var j=0, l=this.togglers.length; j<l; j++){
			this.togglers[j].style.zIndex = 1;
		}
		this.load(this.togglers[i]);
		this.togglers[i].style.zIndex = 5;
		this.togglers[i].className = 'active';
		clearTimeout(this.timeout);
		
	},
	hide: function(event, i) {
		if (this.timeout) {
			clearTimeout(this.timeout);
		}
		this.togglers[i].className = '';
		Event.stop(event);
	},
	load: function(tab) {
		var target = tab.down('div.progress');
		if (!target) return;
		
		switch(tab.id) {
			case 'account' :
				new Ajax.Updater(target, '/ae/control/myAccountTab',
					{ method: 'get', onComplete:Element.removeClassName(target, 'progress') });
				break;
			case 'reorder' :
				new Ajax.Updater(target, '/ae/control/reorderCenterTab',
					{ method: 'get', onComplete:Element.removeClassName(target, 'progress') });
				break;
		}
	}
}

/*--------------------------------------------------------------------------*/

var Tabs = Class.create();
Tabs.prototype = {
	initialize: function(container, active) {
		this.container = $(container);
		this.togglers  = this.container.getElementsBySelector('ul.togglers li');
		this.tabs      = this.container.getElementsBySelector('div.tab');
		this.active    = active || 0;
		this.setup();
	},
	setup: function() {
		this.tabs[this.active].addClassName('active');
		this.togglers[this.active].addClassName('active');
		this.togglers.each(function(el, i) {
			el.onclick = function() {
				if (i != this.active) {
					el.addClassName('active');
					this.togglers[this.active].removeClassName('active');
					
					if(this.tabs.length == this.togglers.length){
						this.tabs[this.active].removeClassName('active');
						this.tabs[i].addClassName('active');
					}
				}
				this.active = i;
				return false;
			}.bind(this);
		}.bind(this));
	}
}
/*--------------------------------------------------------------------------*/

Event.onDOMReady(function(){
	new Nav('nav');
	
});
