Event.observe(window, 'load', function() {

	$$('form.validate').each(function(elm) {
		new Validation(elm, {
			stopOnFirst: elm.hasClassName('validate-stopOnFirst')
		});
	});

	if ($('leftNav'))
		$('leftNav').select('li').invoke('observe', 'click', handleNavClick);
		
	$$('a.popup').invoke('observe', 'click', function(e) {
		Event.stop(e);
		window.open(this.href);
	});
	
	$$('div.success').each(function(elm) {
		if (!elm.hasClassName('noleave'))
			new Effect.SlideUp(elm.wrap('div'), {
				duration: 0.5,
				delay: 5,
				afterFinish: function() {
					elm.remove();
				}
			});
	});
	
	initFormErrors();
	
	$$('form').each(function(elm) {
	
		elm.observe('submit', function() {
		
			this.getElements().each(function(formElm) {
				if (formElm.hasClassName('inactive'))
					formElm.setValue('');
			});
			
		});
		
	});

});

function handleNavClick(e) {
	
	var elm = Event.element(e);
	
	if (e.tagName != 'LI')
		elm = elm.up('li');
		
	location.href = elm.down('a').href;

}

function initFormErrors() {

	$$('div.error').each(function(div) {
	
		if (div.down('div'))
			return;
			
		Element.wrap(div.firstChild, 'div');
	
	});

}



/*--- Button Tabs ---*/

Event.observe(window, 'load', function() {
	$$('div.buttonTabs').each(function(elm) {
		new UIButtonTabbedPanel(elm);
	});
});

var UIButtonTabbedPanel = Class.create({

	initialize: function(element) {

		this.element = $(element);
		
		this._initTabs();

		this.currentTabId = this._getTabId(this.element.select('a.tab.current').first());

	},
	
	_initTabs: function() {
		this.element.select('a.tab').invoke('observe', 'click', this._handleTabClick.bindAsEventListener(this));	
	},
	
	_handleTabClick: function(e) {

		var elm = Event.element(e);

		if (/#$/.match(elm.getAttribute('href'))) {

			Event.stop(e);

			var tabId = this._getTabId(Event.element(e));
			
			if (tabId != this.currentTabId)
				this.showTab(tabId);
			
		}
		
	},
	
	showTab: function(tabId) {
		
		this._getTab(this.currentTabId).removeClassName('current');
		this._getTab(tabId).addClassName('current');
	
	
		// Hide the old tab
		this._getTabContent(this.currentTabId).fade({
			duration: 0.5
		});
		
		var newHeight = this._getTabContent(tabId).getHeight();
		
		this._getTabContent(tabId).absolutize();
		
		var newStyle = { height: newHeight + 'px' };
		
		new Effect.Morph(this._getTabBody(), {
			duration: 0.5,
			style: newStyle,
			afterFinish: function() {
				this._getTabContent(tabId).relativize();
				this._getTabBody().setStyle({
					height: 'auto'
				});
			}.bind(this)
		});

		// Display the new tab
		this._getTabContent(tabId).appear({
			duration: 0.5
		});
		
		this.currentTabId = tabId;
	
	},
	
	_getTabId: function(elm) {
		return /^([\w\d]+)Tab(Content)?$/.exec(elm.id)[1];
	},
	
	_getTabContent: function(elmId) {
		return $(elmId + 'TabContent');
	},
	
	_getTab: function(elmId) {
		return $(elmId + 'Tab');
	},
	
	_getTabBody: function() {
		return this.element.down('div.tabbody');
	}

});
