﻿	/**************************
	 Restructure code
	**************************/
	function unpack(element)
	{
		var divs = new Array();
		var cur = element.firstChild;
		var i=0;
		while(cur != null)
		{
			if(cur.nodeType == 1 && cur.nodeName == 'DIV')
			{
				divs[i] = cur;
				i++;
			}
			cur = cur.nextSibling;
		}	
		createTabItemList(element, divs);
		createTabDataList(element, divs);
	}
	/* tab data */
	function createTabDataList(cont, divs)
	{
		var ContainerDiv =	document.createElement('DIV');
		ContainerDiv.className = 'data';
		cont.appendChild(ContainerDiv);
		for(var i=0; i<divs.length; i++)
		{
			relocateDiv(ContainerDiv, divs[i]);
		}
	}
	function relocateDiv(adopter, div)
	{
		adopter.appendChild(div);
		div.setAttribute('id', div.id + '_data');
		div.className = 'tab';
		div.removeAttribute('title');
		/*
		 insert an extra clearing div with clear:both, so that the container
		 will always wrap around containing floats */
		var ClearingDiv;
		ClearingDiv  =	document.createElement('DIV');
		ClearingDiv.className = 'clearing';
		div.appendChild(ClearingDiv);
			
	}
	/* tab items */
	function createTabItemList(cont, divs)
	{
		var List;
		List =	document.createElement('UL');
		List.className = 'strip';
		cont.appendChild(List);
		for(var i=0; i<divs.length; i++)
		{
			createTabItem(List, divs[i]);
		}
		setNoMarginLastChild(List)
	}
	
	function setNoMarginLastChild(List)
	{
		if (List.lastChild != null) 
		{
			List.lastChild.className += " nomargin"
		}
	}
	function createTabItem(cont, div)
	{
		var Item = document.createElement('LI');
		var ItemSpan = document.createElement('SPAN');
		Item.appendChild(ItemSpan);
		cont.appendChild(Item);
		Item.setAttribute('id', div.id);
		ItemSpan.appendChild(document.createTextNode(div.getAttribute('title')));
	}
	function unpackTabDivs(tabsetClassName, node)
	{
		if(node.nodeType == 1 && node.nodeName == 'DIV' && node.className.indexOf(tabsetClassName) > -1) {

			var Count = 0;
			for (var y = 0; y < node.childNodes.length; y++) {
				if (node.childNodes[y].nodeName == "DIV") {
				Count++
				}
			}

			if (Count == 1) {
				node.className = node.className + " onetab";
			}
			unpack(node);
			// Check if the current tabset was hidden (while loading the page). If so, make it visible now.
			if (node.className.indexOf('hidden') > -1) 
			{
				node.className = node.className.replace(/\s*hidden/, '');
			}
		}
		
		for(var i=0; i<node.childNodes.length ; i++)
		{		
		 unpackTabDivs(tabsetClassName, node.childNodes[i]);
		}	
	}

	

	/**************************
	 runtime behavior code
	**************************/
	
	function tabclick(el)
	{
		var tab = document.getElementById(el.id + '_data');
		focusTab(tab);
		focusTabItem(el);
		GetOriginalStrips(tab)
	}
	/* tab strip items behavior */
	function focusTabItem(tabItem)
	{
		var tabStripList = tabItem.parentNode.parentNode.childNodes
	  var i;
	  
	  for (i=0; i< tabStripList.length; i++)
	  {
	    if((tabStripList[i].nodeType == 1) && (tabStripList[i].className.indexOf('strip') > -1))
	    {
	      blurSiblingTabItems(tabStripList[i].firstChild)
	    }
	  }
//		blurSiblingTabItems(tabItem.parentNode.firstChild);
		tabItem.className += " on";
	}
	function blurSiblingTabItems(tabItem)
	{
		if(tabItem != null)
		{
			if(tabItem.nodeType == 1)// elements only
			{
				tabItem.className = tabItem.className.replace(/\s*on/, '');
				if(document.all)
				{
				  tabItem.className = tabItem.className.replace(/\s*hover/, "");
				}
			}
			blurSiblingTabItems(tabItem.nextSibling);
		}
	}
	/* tab (data) behavior */
	function focusTab(tabElement)
	{
		blurSiblingTabs(tabElement.parentNode.firstChild);
		tabElement.className += " on";
	}
	
	function findActiveTab(tabSet)
	{
		// find the first div in a div (first tab in data div)
		var CurTab = tabSet.getElementsByTagName('DIV')[1];
		while(CurTab != null)
		{
			if(CurTab.className.indexOf('on') > -1)
			{
				return CurTab;
			}
			else
			{
				CurTab = CurTab.nextSibling;
			}
		}
		return null;
	}
	function resizeParent(tabElement)
	{
		var maincont = tabElement.parentNode.parentNode;
	}
	function blurSiblingTabs(tabElement)
	{
		if(tabElement != null)
		{
			if(tabElement.nodeType == 1)// elements only
			{
				tabElement.className = tabElement.className.replace(/\s*on/, '');
			}
			blurSiblingTabs(tabElement.nextSibling);
		}
	}
	/* behavior init methods */
	function setTabsBehavior(tabdiv)
	{	
		var TabItem = tabdiv.getElementsByTagName('LI')[0];
		while(TabItem != null)
		{
			SetTabItemBehavior(TabItem);
			TabItem = TabItem.nextSibling;
		}	
	}
	function SetTabItemBehavior(node)
	{
		node.onmouseover = function() {node.className +=	' hover'}
		node.onmouseout  = function() {node.className =	node.className.replace(/\s*hover/, '')}
		node.onclick = function(){tabclick(node);}
	}
	function openFirstTabs(tabsetClassName, node)
	{
		if(node.nodeType == 1 && node.nodeName == 'DIV' && node.className.indexOf(tabsetClassName) > -1)
		{
			if(node.getElementsByTagName('LI')[0]) {
				tabclick(node.getElementsByTagName('LI')[0]);
			}
		}
		for(var i=0; i<node.childNodes.length ; i++)
		{		
		 openFirstTabs(tabsetClassName, node.childNodes[i]);
		}	
	}
	function applyTabBehaviors(tabsetClassName, node)
	{
		if(node.nodeType == 1 && node.nodeName == 'DIV' && node.className.indexOf(tabsetClassName) > -1)
		{
			setTabsBehavior(node);						
		}
		for(var i=0; i<node.childNodes.length ; i++)
		{		
		 applyTabBehaviors(tabsetClassName, node.childNodes[i]);
		}	
	}
	/* like click on tab */
	function openTab(tabId)
	{
		var tab = document.getElementById(tabId);
		
		if(tab)
		{
			// open the tab
			tabclick(tab);
			// open parent
			var parent = tab.parentElement;
			while(parent != null &&  parent.id.indexOf('_data') <0)
			{
				parent = parent.parentElement;
			}
			if(parent != null)
			{
				openTab(parent.id.replace('_data', ''));
			}
		}
		else
		{
		  setTimeout("openTab('"+tabId+"')", 200);
		}
	}
	
	function openLocationHashTab()
	{
		var hash = location.hash;
		var tabId;
		
		if(hash != '')
		{
			tabId = tabId=hash.replace('#', '');
			var element = document.getElementById(tabId);
			/* Check if the element is not null, and the tag is either li or div. */
			if (element != null && (element.tagName == 'LI' || element.tagName == 'DIV'))
			{				
				openTab(tabId);
			}			
		}
	}
	
	

// New Scale specific script

//search strip elements
//if a strip element is found
//look is there are sibling strip elements
function GetOriginalStrips(node)
{
  var count = 0;
  var list;
  list = node.getElementsByTagName('UL');
  //loop through all ul items
  for(count; count < list.length; count ++)
  {
    //if it is a strip element
    if (list[count].className.indexOf("strip") > -1)
    {
      var placeholder;
      var placeholderSet = false;
      var parent;
      var originalStrip;
      //get sibling ul set for a complete list item set. This is done in case a tabstrip is already split across several strips. 
      var siblingSet = list[count].parentNode.childNodes
      var y;
      
      //create a dummy placeholder for the future tabstrips
      placeholder = document.createElement('DIV');
      placeholder.className = 'placeholder';
      placeholder.id = 'dummy';
      
      originalStrip = document.createElement('UL');
      originalStrip.className = 'strip';
      
      placeholder.appendChild(originalStrip);
      
      //reverse order. Original tabstrip is split across several ul's with the last ul containing the first li's
      for(y = siblingSet.length -1; y >= 0 ; y--)
      {
        if(siblingSet[y].nodeType == 1 && siblingSet[y].className.indexOf("strip") > -1)
        {
          parent = siblingSet[y].parentNode;
          if(!placeholderSet)
          {
            // place a placeholder and remove the split strip
            parent.insertBefore(placeholder,siblingSet[y]);
            y=y+1;
            AppendListItems(originalStrip , parent.removeChild(siblingSet[y]));
            placeholderSet = true;
          }
          else
          {
            //remove the split strip
            AppendListItems(originalStrip ,parent.removeChild(siblingSet[y]));
          }
        }
       
      }  
      //original strip is restored. and placed in the placeholder in a strip element. It is placed in a strip element
      // for the width calculation of the elements. If this is not done the style on the listitems are lost.
      
      //create new tabstrips next
      count += CreateNewTabStrips(originalStrip,placeholder) -1;
      
    
    }
  }

}

//create new tabstrips at the place of the placeholder
function CreateNewTabStrips(originalStrip, placeholder)
{
  var currentInsertPoint;
  var totalWidth;
  var elementWidth;
  var elementCount;
  var stripCount = 0;
  var widthLimit = GetWidthLimit(document.getElementById(originalStrip.childNodes[0].id+'_data'));
  var i = 0;
  //set current insertion point
  currentInsertPoint = placeholder;
  //get list item count
  elementCount = originalStrip.childNodes.length;
  
  //get a new tab strip with the correct css classes
  var newStrip = GetNewStrip(stripCount++)
  //strip paddings
  var totalWidth = 5 * stripCount;
  //add the strip to the dom and set is as the current insert point for listitems/strips
  currentInsertPoint.parentNode.insertBefore(newStrip,currentInsertPoint)
  currentInsertPoint = newStrip;
  //loop through all the list items
  for(i=0; i<elementCount; i++)
  {
    //get elementwidth(offsetwidth(contentwidth + paddingwidth's + borderWidth's) + marginWidth's
    elementWidth = GetElementWidth(originalStrip.childNodes[0]);
    
    //check if new width exceeds the limit
    if((totalWidth + elementWidth) > widthLimit)
    {
      //limit exceded
      //create a new tabstrip set.
      //insert it in the DOM
      //Set it as the current insertion point.
      //reset the width counter
      // TODO TIM: Check if function is needed for a non-scalable site.
      //setNoMarginLastChild(currentInsertPoint);
      newStrip = GetNewStrip(stripCount++);
      currentInsertPoint.parentNode.insertBefore(newStrip,currentInsertPoint)
      currentInsertPoint = newStrip;
      totalWidth = 5*stripCount;
    }
    //add the list item to the strip
    currentInsertPoint.appendChild(originalStrip.childNodes[0]);
    //count the width
    totalWidth += elementWidth;
  
  }
  
  //when done remove the obsolete placeholder container
  placeholder.parentNode.removeChild(placeholder);
  return stripCount;
}


//gather all the list items of the strips in a set.
function AppendListItems(targetElement, listItemContainer)
{
  var itemList = listItemContainer.getElementsByTagName('LI');
  var count = itemList.length;
  var i = 0;
  for(i=0; i < count; i++)
  {
    //IE FIX
    //fixes stuck hover effect.
    // TODO check why hover is stuck and check strange behavior when 2 tabsets are involved
    // guessing hover style gets stuck at a resize event cycle when the li's are split across different strips.
    while (itemList[0].className.indexOf('hover')>1)
    {
      itemList[0].className = itemList[0].className.replace(/\s*hover/, "");
    }
    
    targetElement.appendChild(itemList[0]);
  }

}

//calculate the element currentwidth of the provided element
function GetElementWidth(el)
{
  var totalElementWidth = 0;
  if(document.all)
  {
    //IE
    totalElementWidth = el.offsetWidth +  parseInt(el.currentStyle.marginLeft.replace('px','')) + parseInt(el.currentStyle.marginRight.replace('px',''));
    
  }
  else
  {
    //Firefox opera does not work in safari
    totalElementWidth = el.offsetWidth +  parseInt(window.getComputedStyle(el,null).marginLeft.replace('px','')) + parseInt(window.getComputedStyle(el,null).marginRight.replace('px',''));
  }
  return totalElementWidth;
}

//create a strip with the correct css classes
function GetNewStrip(count)
{
  var newStrip = document.createElement('UL');
  if(count == 0)
  {
    newStrip.className = 'strip';
  }
  else
  {
    newStrip.className = 'strip strip'+ count;
  }
  return newStrip
}

//get the width limit of the strips
//gets the tab_data segment and searches the displayed tab
//and returns it's offsetWidth
function GetWidthLimit(el)
{
  if (el == null)
  {
    return 500;
  }
  var list = el.parentNode.childNodes;
  var counter = 0;
  while(list[counter] != null)
  {
    if( list[counter].nodeType ==1 && list[counter].offsetWidth > 0)
    {
      return list[counter].offsetWidth - 5;
     
    }
    counter++
  }
  return 300;//in the event that no width is found return a standard value
}

function initTabs(tabsetClassName) {
	unpackTabDivs(tabsetClassName, document);
	applyTabBehaviors(tabsetClassName, document);
	openFirstTabs(tabsetClassName, document);
	openLocationHashTab();
	GetOriginalStrips(document);
}


