/* CBS classes */
CBS = {};
CBS.TABS = (function() {
  var TABS = [];

  return function(p) {
	var tid = p.tab_id;
	var cl = p.tab_class;
	var nfn = p.nav_fn || [];
	var acl = p.tab_active_class || 'active';
	var tev = p.trigger_event || 'click';
	var title = p.name || 'My tabs';
	var ali = -1;
	var nav = [];
	var cont = [];
	// only tabs or tabs with content divs
	var mode = false;

	this.setAli = function(n) {
		var type = $type(n);
		if (type == 'number' && n >= 0) ali = parseInt(n,10);
		else if (type == 'string') ali = ['first', 'second', 'third', 'fourth'].indexOf(n);
		else ali = -1;
	};
	this.getNav = function(i) {return nav[i];};
	this.getMode = function() {return mode;};
	this.setNavClass = function(i, cl) {nav[i].className = cl || '';};
	this.getCont = function(i) {return cont[i];};
	this.getAli = function() {return ali;};
	this.getAcl = function() {return acl;};
	
	var el = $(tid);
	if (!el) {
      return false;
    //throw new Error('Tab "'+tid+'" failed to initialize.');
  }
	var ul = el.getElementsByTagName("ul");
	for (var i = 0, l = ul.length; i < l; i++) {
		if (ul[i].className == cl) {
			nav = ul[i].getElementsByTagName("li");
			for (var j = 0, k = nav.length; j < k; j++) {
				var el2 = $(nav[j]);
				if (!el2) continue;
				el2.addEvent(tev, function(ev, n) {
					this.activate(n);
				}.bindWithEvent(this, j));
				if (nfn[j]) {
					el2.addEvent(tev, nfn[j]);
				}
			}
			break;
		}
	}

	var div = el.getElementsByTagName("div"),
	re = new RegExp("^" + tid + "[\\d]+$");
	for (var i2 = 0, l2 = div.length; i2 < l2; i2++) {
		var div_id = div[i2].id.toString();
		if (re.exec(div_id)) {
			cont.push($(div_id));
		}
	}
	mode = cont.length > 0 ? true : false;

	TABS.push(title);
	this.setAli(p.active_item);
	this.activate(ali);
  }
})();

CBS.TABS.prototype = {

  activate: function(n) {
    var i = this.getAli();
    this.setAli(n);
    var n = this.getAli(),
    m = this.getMode();
  	if (i >= 0 && i != n) {
	  	if (m) {
			var curr_div = this.getCont(i);
			curr_div.style.display = 'none';
		}
		this.setNavClass(i);
	}
	if (n >= 0) {
		if (m) {
			var new_div = this.getCont(n);
			new_div.style.display = 'block';
		}
		this.setNavClass(n, this.getAcl());
	}
  }
}