/**
 * @author andreas
 */


	$(document).ready(function() {
		TabController.init();
	});

	
	var TabController = {
		tabcontainers: [],
		init: function() {
			$('.tabpanel').hide();
			this.tabcontainers = this.getTabContainers();
			$('.tabcontainer .tablink').click(function() {
				TabController.handlers.tabclick(this);
			});			
		},
		getTabContainers: function() {
			var arr = [];
			var tc = null;
			$('.tabcontainer').each(function (idx) {
				if (! this.id) { this.id = 'tabcontainer' + idx; }
				tc = new TabContainer(this);
				if (tc) {arr[tc.id] = tc; }
				tc = null;
			});
			return arr;
		},
		handlers: {
			tabclick: function(clicked) {
				var elm = $(clicked).closest('.tabcontainer')[0];
				if (elm) {
					var tc = TabController.tabcontainers[elm.id];
					tc.openTab(clicked);	
				} else {
					return false;
				}				
			}
		}
	};

	function TabContainer(element) {
		this.element = element;
		this.id = element.id;
		this.activetab = null;
			
		this.openTab = function(clicked) {
			if (this.activetab == clicked) { return false; }
			var currtp = $('#tp_' + clicked.id);
			if (this.activetab) { 
				var prevtp = $('#tp_' + this.activetab.id); 
				if (prevtp) {
					$(this.activetab).parent('li').toggleClass('active');
					$(prevtp).fadeOut('fast', function() {
						$(currtp).fadeIn();
					});
				}
			} else {
				$(currtp).fadeIn('fast');
			}
			$(clicked).parent('li').toggleClass('active');
			this.activetab = clicked;
		}
		
		this.openTab($('#' + this.id + ' .tablink:first')[0]);		
	}

