var Tabgroup = {

	stack : {},

	init : function(tabgroupId, callback) {
		var lis = this.getLi(tabgroupId);
		lis.each(function(li, index) {
					if (0 == index) {
						li.addClassName('first');
					}
					if (index < lis.length - 1) {
						li.addClassName('notLast');
					}
					li.observe('click', this.clickElm.bindAsEventListener(this, tabgroupId));
				}, this)
		this.stack[tabgroupId] = callback;
	},

	cleanAll : function() {
		this.stack = {};
	},

	selectTab : function(tabgroupId, index) {
		if (Object.isString(index)) {
			var tabs = this.getLi(tabgroupId);
			index = $R(0, tabs.length, true).find(function(i) {
						return tabs[i].id == tabgroupId + '_' + index;
					});
		}
		if (Object.isUndefined(index)) {
			index = 0;
		}
		this.selectOne(tabgroupId, this.getLi(tabgroupId)[index], index);
	},

	getSelectedTab : function(tabgroupId) {
		var tabs = this.getLi(tabgroupId);
		return $R(0, tabs.length, true).find(function(i) {
					return tabs[i].hasClassName('selected');
				});
	},

	/**
	 * @private
	 * @param {}
	 *          tabgroupId
	 * @param {}
	 *          srcElm
	 */
	selectOne : function(tabgroupId, srcElm, index) {
		this.getLi(tabgroupId).each(function(o) {
					o[(o == srcElm ? 'add' : 'remove') + 'ClassName']('selected');
				});
		this.stack[tabgroupId](srcElm, index);
	},

	/**
	 * @private
	 * @param {}
	 *          tabgroupId
	 * @return {}
	 */
	getLi : function(tabgroupId) {
		return $$('#' + tabgroupId + '.tabgroup li');
	},

	/**
	 * @private
	 * @param {}
	 *          tabgroupId
	 * @return {}
	 */
	clickElm : function(ev, tabgroupId) {
		var srcElm = Event.element(ev);
		var index = -1;
		this.getLi(tabgroupId).each(function(o) {
					index++;
					if (o == srcElm) {
						throw $break;
					}
				});
		this.selectOne(tabgroupId, srcElm, index);
	}
}
