window.addEvent('domready', function() {
	window.$ifel = function(el) { return $chk($(el)); };
	
	// Базовый класс. Можно расширить при помощи implement()
	window.TextMuncher = new Class({
		target: false,
		//source: false,
		victim: false,
		
		// Селекторы для заголовков и блоков
		headEl: 'h2',
		blockEl: 'div.tab',
		
		// Куда переносить заголовки и блоки соответственно
		// По умолчанию блоки реинжектируются в victim
		targetH: 'button',
		targetB: false,
		
		// Выполнять ли дефолтные setStyle('display', 'none/block')
		directStyle: true,
		
		headers: [],
		blocks: [],
		
		current: false,
		
		transformH: false,
		transformB: false,
		
		leaveH: false,
		
		initialize: function(v) {
			$chk(v) && (this.victim = $(v));			
			//this.source && (this.victim = this.source);			
			if (this.victim.getChildren(this.headEl).length < 1) return;			
			this.targetH || (this.targetH = this.victim);
			this.targetB || (this.targetB = this.victim);			
			this.onInitialized();
			this.process();
		},
		
		process: function() {
		
			(this.target ? this.target.addClass('tmEnabled') : this.victim.addClass('tmEnabled'));
			
			this.headers = this.victim.getChildren(this.headEl);
			this.blocks = this.victim.getChildren(this.blockEl);
			
			this.headers.each(function(v, k) { v.addEvent('click', function() {
				var h = this.headers[k].addClass('active');
				if (k==0)  this.headers[k].addClass('first ');
				if (this.current) {
					if (this.current ==  this.blocks[k]) return false;
					this.directStyle && this.current.setStyle('display', '');
					this.headers[this.blocks.indexOf(this.current)].removeClass('active');
					this.onHidingCurrent();
				}
				
				this.current = this.blocks[k];
				
				this.directStyle && this.current.setStyle('display', 'block');
				
				this.onHClick(h, k);
				return false;
			}.bind(this))}.bind(this));
			
			this.onBeforeInjection();
			
			if (this.transformH) {
				this.headers.each(function(v, k){
					var nh = this.transformH(v).inject(this.targetH).cloneEvents(v);
					this.leaveH ? v.inject(this.blocks[k], 'top') : v.dispose();
					this.headers[k] = nh;
				}.bind(this));
			}
			this.headers.inject(this.targetH);
			
			if (this.transformB) {
				this.blocks.each(function(v, k){
					var nb = this.transformB(i).inject(this.targetB).cloneEvents(i);
					v.dispose();
					this.blocks[k] = nb;
				}.bind(this));
			}
			else this.blocks.inject(this.targetB);
			
			this.headers[0].fireEvent('click');
		},
		
		//events
		onInitialized: function() {},
		onHClick: function(h, i) {},
		onBeforeInjection: function() {},
		onHidingCurrent: function() {}
	});
	
	$ifel('tabs') && new TextMuncher('tabs');
	
	
});
