/* * 
 * TAB
 * Author: Deo 2010.01.06
 * Param: 
 *	1. [title box id] > [children tagName] eg: demoTitle > a
 *	2. [tagName].[content className] eg: div.demoContent
 *	3. [clicked title class]
 *	4. [index - number or 'prev' , 'next' - string]
 *	5. callback, back current index and length - options
 */
function tab(title, content, titleClass, showIndex, func) {
	var matchTitle = /(\w+)\s*>\s*(\w+)/.exec( title ), matchCont = /(\w+).(\w+)/.exec( content );
	
	var titleBoxId 	= matchTitle[1],	titleTag = matchTitle[2];
	var contentTag 	= matchCont[1],		contentClass= matchCont[2];
	
	var	conList 	= [], 
		titleList 	= $( titleBoxId ).getElementsByTagName( titleTag ),
		contElemList = document.getElementsByTagName( contentTag );
	
	// Put into a array
	for(var i = 0; i < contElemList.length; i ++) {
		var regClass = RegExp(contentClass, 'g');
		var elemClass = contElemList[ i ].className;
		if ( regClass.test( elemClass ) ) {
			conList.push( contElemList[ i ] );
			hide( contElemList[ i ] );
		}
	}
	
	var totalLen = titleList.length == conList.length? titleList.length: null;
	
	if (totalLen == null) { alert('Title and content do not correspond to the number.'); return; } 
	
	// If showIndex is string
	if (typeof showIndex == 'string') {
		for(var i = 0; i < titleList.length; i ++) {
			if(titleList[ i ].className == titleClass) break;
		}
		
		if (showIndex == 'prev') showIndex = -- i < 0? 0: i;
		if (showIndex == 'next') showIndex = ++ i > totalLen? totalLen: i;
	}
	
	// Display the instance element
	resetAll();
	show( conList[ showIndex ] );
	classEvent(titleList[ showIndex ], titleClass, 'add');
	
	// Click Event of Elements
	each(titleList, function(t, c, i){
		t.onclick = function(){
			resetAll();
			classEvent(t, titleClass, 'add');
			show( c );
			if (func && typeof func === 'function') func(i, totalLen);
		}
	});
	
	function each(arr, func) { 
		for (var i = 0; i < arr.length; i ++)
			func(titleList[i], conList[i], i);
	}
		
	function show( elem ) { elem.style.display = 'block'; };
	function hide( elem ) { elem.style.display = 'none'; };
	function $( id ) { return document.getElementById( id ); }
		
	// Reset all elements className and style
	function resetAll() {
		for(var i = 0; i < conList.length; i ++) { 
			classEvent(titleList[i], titleClass, 'remove');
			hide( conList[ i ] );
		}
	}
	
	// Element className event
	function classEvent(elem, className, type) {
		var arr = [], map = {}, isClass = false, hasClass = elem.className.split(" ");
		for (var i = 0; i < hasClass.length; i ++) {
			if (hasClass[i] != className) { map[ hasClass[i] ] = hasClass[i]; }
			else { isClass = true; }
			arr.push( hasClass[i] );
		}
		if (type == 'add' && !isClass) 	{ arr.push( className ); }
		if (type == 'remove') 			{ arr = []; for (var key in map) { arr.push( key ); } }
		elem.className = arr.join(" ").replace(/^\s*|\s*$/g,'');
	}
	
	if (func && typeof func === 'function') func(showIndex, totalLen);
}
