function Tab(tabsBar, element) {
	
	this.element = null;
	this.tabsBar = null;
	this.active = false;
	var obj = this;
	
	
	this.init = function(tabsBar, element) {
		
		if (element.hasClass('selected')) {
			
			this.active = true;
		}
		
		element.addEvent('click', tabClick);
		this.element = element;
		this.tabsBar = tabsBar;
		
		if (true == this.active) {
			initAnchors(this.tabsBar.container);
		}
	};
	
	
	this.activate = function() {
		
		this.active = true;
		
		var requestUrl = this.element.getElement('a').get('href');
		var container = obj.tabsBar.container;
		var htmlRequest = new Request.HTML({
			method: 'get',
			url: requestUrl,
			data: 'request=tab',
			update: container,
			
			onSuccess: function() {
				
				initAnchors(container);
				
				if (true == obj.active) {
					obj.element.addClass('selected');
				}
			}
		}).send();
	}
	
	
	this.deactivate = function() {
		
		if (false == this.element.hasClass('selected')) {
			return false;
		}
		this.element.removeClass('selected');
		this.active = false;
		return true;
	}
	
	
	this.onClick = function() {};
	
	
	function tabClick(event) {
		
		var event = new Event(event).stop();
		obj.onClick();
	};
	
	
	function initAnchors(container) {
		var anchors = container.getElements('a');
		anchors.each(function (anchor) {
			
			if (anchor.hasClass('openInTab')) {
				
				anchor.addEvent('click', function(event) {
					var event = new Event(event).stop();
					
					if (true !== anchor.retrieve('waiting_for_request')) {
						
						anchor.store('waiting_for_request', true);
						var htmlRequest = new Request.HTML({
							method: 'get',
							url: anchor.get('href'),
							data: 'request=tab',
							update: container,
							
							onSuccess: function() {
								anchor.store('waiting_for_request', false);
								initAnchors(container);
							}
						}).send();
					}
				});
			}
		});
	}
	
	
	this.init(tabsBar, element);
}


function TabsBar(element) {
	
	this.element = null;
	this.activeTab = null;
	this.container = null;
	
	var obj = this;
	
	
	this.init = function(element) {
		
		this.element = element;
		this.container = element.getElement('.tabContent');
		
		var tabsElements = $$('.button');
		tabsElements.each(function(element) {
			
			var tab = new Tab(obj, element);
			tab.onClick = function() {
				
				if (false == this.active) {
					if (true == obj.activeTab.deactivate()) {
						obj.activeTab = this;
						obj.activeTab.activate();
					}
				}
			};
			
			if (true === tab.active) {
				obj.activeTab = tab;
			}
		});
	};
	
	
	this.init(element);
}


window.addEvent('domready', function() {
	
	var tabsBarsElements = $$('.tabs');
	
	tabsBarsElements.each(function(element) {
		
		var bar = new TabsBar(element);
	});
});
