// $Id: zptabs-accordion.js 6714 2007-03-22 13:35:52Z vkulov $
/**
 * @fileoverview Accordion style tabs extension. Extends Tabs class (zptabs.js)
 * adding accordion style tabs.
 *
 * <pre>
 * Copyright (c) 2004-2006 by Zapatec, Inc.
 * http://www.zapatec.com
 * 1700 MLK Way, Berkeley, California,
 * 94709, U.S.A.
 * All rights reserved.
 * </pre>
 */

/**
 * Zapatec.AccordionTab constructor. Creates a new accordion tab object with
 * given parameters. Configuration options are the same as in Zapatec.Tab
 *
 * @constructor
 * @extends Zapatec.Widget
 * @param {object} objArgs Tab configuration
 */
Zapatec.AccordionTab = function(objArgs) {
  if(arguments.length == 0){
    objArgs = {};
  }

  // Call constructor of superclass
  Zapatec.AccordionTab.SUPERconstructor.call(this, objArgs);
};

/**
 * Unique static id of the widget class. Gives ability for Zapatec#inherit to
 * determine and store path to this file correctly when it is included using
 * Zapatec#include. When this file is included using Zapatec#include or path
 * to this file is gotten using Zapatec#getPath, this value must be specified
 * as script id.
 * @private
 */
Zapatec.AccordionTab.id = 'Zapatec.AccordionTab';

// Inherit Tab
Zapatec.inherit(Zapatec.AccordionTab, Zapatec.Tab);

/**
 * Creates elements needed for the new tab
 */
Zapatec.AccordionTab.prototype.createTab = function()
{
  var tabParent = this.config.tabParent;

  // Create a container for this tab
  this.tabContainer = document.createElement('div');

  // Add tab container to tabs
  tabParent.appendChild(this.tabContainer);
  this.config.tabParent = this.tabContainer;

  // Call parent init
  Zapatec.AccordionTab.SUPERclass.createTab.call(this);

  // Show content pane
  this.container.getContainer().style.display = 'block';
  this.container.getContainer().style.width = '';

  this.tabContainer.tabId = this.id;

  // Keyboard navigation support
	this.linkNode.tabIndex = Zapatec.AccordionTab.tabIndex;

	if(!this.tab2tab)
	{
		// Next tabIndex is reserved for tab content
		Zapatec.AccordionTab.tabIndex += 2;
		// } else {
	    // No need to increase tabIndex
	}

	// Add title bar to tab
	this.chooser = Zapatec.Utils.createElement('div');
	this.chooser.className = 'tabChooser';
	this.tabContainer.insertBefore(this.chooser,
          this.tabContainer.childNodes[0]);

  this.chooser.appendChild(this.linkNode);

  // Create WCH
  this.wch = Zapatec.Utils.createWCH(this.container.getContainer());
  // Put WCH under container
  if (this.wch) {
    this.wch.style.zIndex = -1;
  }
};

/**
 * Determines child node of the container which gets focus first.
 * Needed for keyboard navigation.
 * @private
 */
Zapatec.AccordionTab.prototype.getFocusOn = function ()
{
	// Remove old value
	this.focusOn = null;

	// Check keyboard navigation type
	if(this.tab2tab)
	{
		return;
	}

	// Put it in separate process to speed up initialization
	var self = this;

	setTimeout(function()
		{
			// Flag to determine lower tabIndex
			var iTabIndex = 0;

			// Gets element with lower tabIndex
			function parse(objNode)
			{
				var objChild = objNode.firstChild;

				while(objChild)
				{
					if(objChild.nodeType == 1)
					{
						// ELEMENT_NODE
						var strTag = objChild.tagName.toLowerCase();

						if(strTag == 'a' || strTag == 'input' || strTag == 'select' ||
							strTag == 'textarea' || strTag == 'button')	// Element may obtain focus
						{
							if(!self.focusOn)
							{
								self.focusOn = objChild;
							}
							else if(objChild.tabIndex && objChild.tabIndex > 0 &&
								(!iTabIndex || iTabIndex > objChild.tabIndex))
							{
								self.focusOn = objChild;
								iTabIndex = objChild.tabIndex;
							}

							if(!objChild.tabIndex)
							{
								objChild.tabIndex = self.linkNode.tabIndex + 1;
							}
						}

						parse(objChild);
					}

				objChild = objChild.nextSibling;
			}
		};

		// Parse tab content
		parse(self.container.getContainer());
	},
	0);
};



/**
 * Zapatec.AccordionTabs constructor. Creates a new accordion tabs object
 * with given parameters.
 *
 * @constructor
 * @extends Zapatec.Widget
 * @param {object} objArgs Tab configuration
 *
 * See Zapatec.Tabs for a list of recognized properties of the config object
 */
Zapatec.AccordionTabs = function(objArgs) {
  Zapatec.AccordionTabs.SUPERconstructor.call(this, objArgs);
};

/**
 * Unique static id of the widget class. Gives ability for Zapatec#inherit to
 * determine and store path to this file correctly when it is included using
 * Zapatec#include. When this file is included using Zapatec#include or path
 * to this file is gotten using Zapatec#getPath, this value must be specified
 * as script id.
 * @private
 */
Zapatec.AccordionTabs.id = 'Zapatec.AccordionTabs';

// Inherit Tabs
Zapatec.inherit(Zapatec.AccordionTabs, Zapatec.Tabs);

/**
 * Initializes object.
 *
 * @param {object} objArgs User configuration
 */
Zapatec.AccordionTabs.prototype.init = function(objArgs,i)
{
	// Reference to this
	var self = this;

	// Patch onInit handler
	var funcOnInit = objArgs.onInit;

	objArgs.onInit = function()
	{
		// Setup tabs
		//var _tabContainer = Zapatec.Widget.getElementById(self.config.tabs);
		var _tabContainer = self.config.tabs;
		var items = _tabContainer.childNodes;
		for(var i=items.length-1; i>=0; i--)
		{
			if(items[i].tagName=='div' || items[i].tagName=='DIV')
			{
				self.config._tabArray.push(items[i]);
			}
		}
		topPos = self.config._tabArray[self.config._tabArray.length-1].offsetTop;

		// Enable mouse navigation by clicking the title bars
		var items = _tabContainer.getElementsByTagName('div');
		for(var i=0; i<items.length; i++)
		{
			if(items[i].className=='tabChooser')
			{
        var localItem = items[i];
        items[i].onclick = function()
				{
          self.changeTab(this.parentNode.tabId);
					if(this.blur)
					{
						this.blur();
					}

					return true; // To change document.URL
				};
			}
		}

		// Position tabs
		// You need the number of tabs and their order
		// then, you can calculate where they should start and stop.
		////
		// Each tab has a visible area of:
		//	tabContainerHeight - (numOfTabs-1 * heightOfTabTitle)
		//
		// Each tab has a unique viewing position, derived from its place among the tabs as follows:
		//	tabTop = tabContainerTop + (tabIndex-1 * heightOfTabTitle)
		//
		// Each tab has a unique hidden position, derived from its place among the tabs as follows:
		//	tabTop = tabContainerTop + tabContainerHeight - (tabIndex * heightOfTabTitle)
		//
		// The tabs are layerd on top of each other in the order in which they appear in the HTML.
		// The first tab appears as the default.
		// In opening a tab, the chosen tab will carry all tabs below it along with it.
		// In closing a tab, the chosen tab will carry all tabs above it along with it.

		var _tabZIndex = 100;

		for(var i=0; i<self.config._tabArray.length; i++)
		{
      var tab = self.getTabByIndex(i);
      var tabContainer = tab.tabContainer;
      var contentContainer = tab.container.getContainer();

      // Set tab content container height to 1 pixel
      contentContainer.style.height = '1px';
      contentContainer.style.overflow = "hidden";
      // Subract two to account for border
			tabContainer.style.width = _tabContainer.style.width;

			// Layer the tabs
			tabContainer.style.zIndex = _tabZIndex--;

			// This tab's array position
			tabContainer.arrayPosition = i;

			// This tab's viewing position
			tabContainer.viewingPosition = topPos + ((self.config._tabArray.length-1-i)*self.config.tabBarHeight);

			// This tab's hidden position
			tabContainer.hiddenPosition = topPos + parseInt(_tabContainer.style.height) - ((i+1)*self.config.tabBarHeight);

			// This tab's final viewing height
			tabContainer.viewingHeight = parseInt(_tabContainer.style.height) - ((self.config._tabArray.length/*-1*/)*self.config.tabBarHeight);

			// This tab's hidden height
			tabContainer.hiddenHeight = self.config.tabBarHeight;
		}

    // Get tab id to make active
    var activeTabId = self.getInitialActiveTabId();
    // Get tab to make active
    var activeTab = self.getTab(activeTabId);
    var tabContainer = activeTab.tabContainer;
    var contentContainer = activeTab.container.getContainer();
    // Activate tab
    contentContainer.style.height = tabContainer.viewingHeight + 'px';
    var setOverflowFunc = function() {
      contentContainer.style.overflow = activeTab.config.overflow;
    };
    if (Zapatec.is_ie) {
      setTimeout(setOverflowFunc, 0);
    }
    else {
      setOverflowFunc();
    }
    self.currentIndex = activeTab.index;
    // Reload tab if needed and call onTabChange
    self.refreshTab(activeTab, null, activeTabId);

    // Patch onBeforeTabChange handler
		var funcOnBeforeTabChange = self.config.onBeforeTabChange;

		self.config.onBeforeTabChange = function(objArgs)
		{
			// Call original function
			if(typeof funcOnBeforeTabChange == 'function')
			{
				return funcOnBeforeTabChange(objArgs);
			}
			return true;
		};

		// Patch onTabChange handler
		var funcOnTabChange = self.config.onTabChange;

		self.config.onTabChange = function(objArgs)
		{
			// Get new tab id
			var strNewTabId = objArgs.newTabId;

			// Get new tab
			var objNewTab = self.tabs[strNewTabId];

			if(!objNewTab)
			{
				return;
			}

			// Call original function
			if(typeof funcOnTabChange == 'function')
			{
				funcOnTabChange(objArgs);
			}
		};

		// Call original function
		if(typeof funcOnInit == 'function')
		{
			funcOnInit(objArgs);
		}
	};


  // Disable tab bar
  this.noTabBar = true;

  // Define config options
  this.config.windowOnLoad = null;

  // Tab controllers
  this.config._tabArray = new Array();
  this.config.IN_MOTION = false;
  this.config.tabBarHeight = 24;
  this.config.topPos = null;
  this.config.indexOfWidget = i;

  this.tabsThemeSuffix = 'AccordionContent';

  // Call parent init
  Zapatec.AccordionTabs.SUPERclass.init.call(this, objArgs);

};

/**
 * Adds a new tab.
 *
 * @private
 * Following format is recognized:
 * \code
 *  {
 *    id: [string, optional] id of the tab,
 *    innerHTML: [string] label,
 *    accessKey: [string, optional] access key,
 *    title: [string] title,
 *    url: [string] URL of the content,
 *	  tabType: [string] "div" or "iframe" for the content pane
 *    index: [number, optional] index to make insert the new tab at
 * }
 * \endcode
 *
 * @param {object} objTabDef JSON object.
 */
Zapatec.AccordionTabs.prototype.addTab = function(objTabDef) {

  // Call parent addTab
  var objTab = Zapatec.AccordionTabs.SUPERclass.addTab.call(this, objTabDef);

  // Store index of tab container within tabs
  objTab.tabContainer.index = objTab.index;

  return objTab;
}

/**
 * Create a new tab instance
 *
 * @param {object} objArgs tab configuration
 */
Zapatec.AccordionTabs.prototype.newTab = function(objArgs) {
  var objTab = new Zapatec.AccordionTab(objArgs);
  return objTab;
}

/**
 * Display a new accordion tab. If onBeforeTabChange() returns false, the
 * operation is cancelled.
 *
 * @param {string} strNewTabId id of the new tab.
 */
Zapatec.AccordionTabs.prototype.changeTab = function(strNewTabId) {
  var strCurrTabId = null;
	var objTab = null;

	if (this.tabsArray[this.currentIndex])
	{
		strCurrTabId = this.tabsArray[this.currentIndex].id;
		objTab = this.tabsArray[this.currentIndex];
	}

	if (strCurrTabId != strNewTabId && !this.config.IN_MOTION)
	{
		// Change tab
		if(objTab)
		{
			Zapatec.Utils.removeClass(objTab.linkNode, 'zpTabsActive');
		}

    objTab = this.getTab(strNewTabId);

    var oOffset = Zapatec.Utils.getElementOffset(this.config.tabs);
    // Setup WCH
    Zapatec.Utils.setupWCH(objTab.wch, 0, 0, oOffset.width, oOffset.height);

		Zapatec.Utils.addClass(objTab.linkNode, 'zpTabsActive');
    this.currentIndex = objTab.index;

    // Initiate sliding:
    this.slide(objTab.tabContainer.arrayPosition, 5, 10);

    // Reload tab if needed and call onTabChange
    this.refreshTab(objTab, strCurrTabId, strNewTabId);
  }
};

/**
 * Scrolls tabs to the left. Moves tab(s) by pxInc every timeInc
 *
 * @private
 * @param {boolean} setTab Whether the function should set the selected tab
 * on its own.
 */
Zapatec.AccordionTabs.prototype.slide = function(index,pxInc,timeInc) {
  if (false == this.config.IN_MOTION) {
    var date = new Date();
    this.moveStartTime = date.getTime();
    this.lastTime = this.moveStartTime - timeInc;
    this.isDecreaseHeight = true;
  }

	// Test for index validity
	if(isNaN(index) || index<0 || index>=this.config._tabArray.length)
	{
		// Allow switching again
		this.config.IN_MOTION = false;

		return;
	}

  var date = new Date();
  var time = date.getTime();
  var diffTime = time - this.lastTime;
  var inc = Math.round((diffTime/timeInc)*pxInc);
  if (0 == inc) {
    var self = this;
    // Go again
    setTimeout(function() {
      self.slide(index, pxInc, timeInc);
      }, timeInc);
    return;
  }
  this.lastTime = time;

  var resizeTabs = {};

  // Flags if any tab has been resized
  var isAdjust = false;
  // Find 1 tab to increase and 1 tab to decrease
  for(var tries=0; tries<2; tries++) {
  for(var i=0; i<this.config._tabArray.length; i++)
  {
    var tab = this.getTabByIndex(i);
    var tabContainer = tab.tabContainer;
    var contentContainer = tab.container.getContainer();
    var newHeight = -1;

    var oldHeight = parseInt(contentContainer.style.height);
    var isCurrent = tab.index == this.currentIndex;
    if (!isCurrent && this.isDecreaseHeight) {
      newHeight = oldHeight - inc;

      // Check for lower limit
      if (newHeight < 1) {
        newHeight = 1;
      }
    }
    else if (isCurrent && !this.isDecreaseHeight) {
      newHeight = oldHeight + inc;

      // Watch out for upper limit
      if (tabContainer.viewingHeight <= newHeight) {
        newHeight = tabContainer.viewingHeight;
      }
    }
    // If a new height is determined
    if (-1 != newHeight && oldHeight != newHeight) {

      if (this.isDecreaseHeight) {
        resizeTabs.decreaseTab = contentContainer;
        resizeTabs.decreaseDif = oldHeight - newHeight;
      }
      else {
        resizeTabs.increaseTab = contentContainer;
        resizeTabs.increaseDif = newHeight - oldHeight;
      }

      isAdjust = true;

      break;
    }
  }
    this.isDecreaseHeight = !this.isDecreaseHeight;

  }

  var dif = Math.min(resizeTabs.decreaseDif, resizeTabs.increaseDif);
  var incTab = resizeTabs.increaseTab;
  var decTab = resizeTabs.decreaseTab;
  if (incTab) {
    var incOldHeight = parseInt(incTab.style.height);
    incTab.style.height = (incOldHeight + dif) + 'px';
  }
  if (decTab) {
    var decOldHeight = parseInt(decTab.style.height);
    decTab.style.height = (decOldHeight - dif) + 'px';

    if (decTab.style.overflow != "hidden") {
      // Hide tab overflow during slide animation
      decTab.style.overflow = "hidden";
    }
  }

  if (!isAdjust) {
    // Allow switching again
    this.config.IN_MOTION = false;

    var currentTab = this.getTabByIndex(this.currentIndex);
    if (currentTab.config.overflow) {
      // Restore original tab overflow style
      currentTab.container.getContainer().style.overflow = currentTab.config.overflow;
    }
    
    return;
  }

  // Stop switching while this process is running
	this.config.IN_MOTION = true;

  var self = this;
  // Go again
  setTimeout(function() {
    self.slide(index, pxInc, timeInc);
    }, timeInc);
}
