 /**
 * @author:  Ivan Andonov
 * @email:   ivan.andonov[at]design[dot]bg
 * 
 * @require: dbg.Utils, jquery
 * @use:     dbg.Debug
 **/

/**
 * Show tab content and hides teh content al all other tabs
 * 
 * tab:          html element - the tab that should be activated
 * container:    jquery selector - tabs and containers holder
 * contentPath:  jquery selector - path to the tab containers
 * contentClass: string - the class that will set to all hidden tab containers
 * tabPath:      jquery selector - path to the tabs
 * tabClass:     string - the class that will set to current tab
 * cookie:       string - name of the cookie that correspond to this group of tabs (not required)
 * 
 **/
function onTabClick(tab, container, contentPath, contentClass, tabPath, tabClass, cookie) {
	//$log('onTabClick tab='+tab+' container='+container+' contentPath='+contentPath+' contentClass='+contentClass+' tabPath='+tabPath+' tabClass='+tabClass);
	if (!dbg.Utils.haveClass(tab, tabClass)) {
		// get tabs container
		var cont = jQuery(container);
		if (cont.length) {
			// get all tabs
			var tabs = cont.find(tabPath);
			// find current tab
			var len = tabs.length;
			for (var i = 0; i < len; i++) {
				if (tab == tabs[i]) {
					// show coresponding content
					if (cookie != null) $cookie(cookie, i);
					updateTabs(i, container, contentPath, contentClass, tabPath, tabClass);
					break;
				}
			}
		}
	}
	return false;
};

/**
 * Show last selected tab. This function should be caled after 
 * the html code of the tabs and its container are already loaded
 * 
 * parameters: see onTabClick
 * 
 **/
function checkTabs(container, contentPath, contentClass, tabPath, tabClass, cookie) {
	//$log('onTabClick container='+container+' contentPath='+contentPath+' contentClass='+contentClass+' tabPath='+tabPath+' tabClass='+tabClass);
	var currentTab = $cookie(cookie);
	if (currentTab != null && !isNaN(currentTab)) {
		updateTabs(Number(currentTab), container, contentPath, contentClass, tabPath, tabClass);
	}
};

/**
 * Show tab content and hides teh content al all other tabs
 *
 * index:      number - position of tab that will become current
 * parameters: see onTabClick
 *
 **/
function updateTabs(index, container, contentPath, contentClass, tabPath, tabClass) {
	//$log('updateTabs index='+index+' container='+container+' contentPath='+contentPath+' contentClass='+contentClass+' tabPath='+tabPath+' tabClass='+tabClass);
	var cont = jQuery(container);
	if (cont.length) {
		// hide tab containers
		var containers = cont.find(contentPath).hide().addClass(contentClass);
		// show current tab container
		jQuery(containers[index]).show().removeClass(contentClass);
		// get all tabs
		var tabs = cont.find(tabPath);
		// remove current class from all tabs
		tabs.removeClass(tabClass);
		// set current class to clicked tab
		jQuery(tabs[index]).addClass(tabClass);
	}
};