/*
 * Supports the TopTabGroup to dynamically change class.
 */

// Variables used to implement menu show delay.
// The ID of timer used for the delay.
var currentMenuTimerID = -1;
var displayDeptTabs = false;

// The saved variables that were passed into the "changeClass" function call.
var classChange_obj;
var classChange_newClass;
var classChange_menuID;
var classChange_iFrameID;
var classChange_SH;

function Private_changeClass(ev)
{
	var classArg = this.menu_overClass;
	
	if(this.className == this.menu_overClass)
	{
		classArg = this.menu_outClass;
	}
	
	changeClass(this, classArg, this.menu_menuID, this.menu_iFrameID, this.menu_change_visibility);
}


function changeClass(obj, newClass, menuID, iFrameID, SH)
{
	if(obj != null && obj != undefined)
	{
		obj.className = newClass;
	}
	
	if(menuID != null && iFrameID != null && SH != null)
	{
		var menu = document.getElementById(menuID);
		var iFrame = document.getElementById(iFrameID);
		if(menu && iFrame)
		{
			menu.style.visibility = (SH == "show") ? "visible" : "hidden";
			iFrame.style.visibility = (SH == "show") ? "visible" : "hidden";
		}
	}
}


function Private_changeClassWithCheck(ev)
{
	var theEvent = ev;
	
	if(ev == null || ev == undefined)
	{
		theEvent = window.event;	
	}
	
	changeClassWithCheck(theEvent, this, this.menu_outClass, this.menu_menuID, this.menu_iFrameID, this.menu_changeWithCheck_visibility);
}


//------------------------------------------------------------------------------------------------
// Function: changeClassWithCheck
/**
 * Called to hide and show the drop down menus for the page.
 */
//------------------------------------------------------------------------------------------------
function changeClassWithCheck(e, obj, newClass, menuID, iFrameID, SH)
{
    
	var element = e.relatedTarget || e.toElement; 
	
	var doProcessing = true;
	
	// This event will fire even if you are transitioning from any control within the table call to anywhere else 
	// inside the table cell.  If not handled, this causes a ficker. Therefore, the anchor and the cell are ID'ed
	// and we can tell if we are still in the same cell, but transitioning from the anchor to the cell body and
	// ignore the change event for that case.
	if ( ( element != null ) && ( element != undefined ) && ( element.id != null ) && ( element.id != undefined ) && ( classChange_obj != null ) && ( classChange_obj != undefined ) )
	{
	
	  // Determine if this is a menu ID.
	  if ( element.id.substring ( 0, 10 ) == "LEAGUE_TAB" )
	  {
	    
	    // Drop the anchor identifier if the ID is for the anchor.
	    var targetMenu = element.id;
	    if ( element.id.substring ( element.id.length - 2, element.id.length ) == "_a" )
	    {
	      targetMenu = element.id.substring ( 0, element.id.length - 2 );
	    }
	    
	    // Drop the anchor identifier if the ID is for the anchor.
	    var existingMenu = classChange_obj.id;
	    if ( classChange_obj.id.substring ( classChange_obj.id.length - 2, classChange_obj.id.length ) == "_a" )
	    {
	      existingMenu = classChange_obj.id.substring ( 0, classChange_obj.id.length - 2 );
	    }
	
	    if ( targetMenu == existingMenu )
	    {
	    
	      // This is simply a transition from the anchor to the cell body or vice versa, so ignore it. We
	      // don't want ficker.
	      doProcessing = false;
	      
	    }
	    
	  }
	}
	
	if ( doProcessing )
	{
	
	  // See if the timer is running, and stop it if it is. 
	  if ( currentMenuTimerID >= 0 )
      {
        // The timer is running, so stop it. The user moved the mouse before the timer
        // timed out.
        clearTimeout ( currentMenuTimerID );
        currentMenuTimerID = -1;
      }
	
	  var menu = document.getElementById(menuID);
	  if(menu && element && isInSpiderMenu(element, menu))
	  {
		/* mouse moved into TopTabGroup - do not hide */
	  }
	  else
	  {
	    classChange_menuID = "";
	  	changeClass(obj, newClass, menuID, iFrameID, SH);
	  }
	
	}
	
} // End changeClassWithCheck


//---------------------------------------------------------------------------
// Function: showMenuWithDelay
/**
 * Called to have the specified menu show after a specified delay. The
 * method parameters are saved and a timer is set to simulate the hover
 * delay.
 */
//---------------------------------------------------------------------------
function showMenuWithDelay ( obj, newClass, menuID, iFrameID, SH, delay )
{
	
    if ( ( classChange_menuID == null ) || ( classChange_menuID == undefined ) )
    {
 
        // This is the first visit, so allow the timer to be set.
        classChange_obj = obj;
        classChange_newClass = newClass;
        classChange_menuID = menuID;
        classChange_iFrameID = iFrameID;
        classChange_SH = SH;
        
        // Set the timer, and capture the timer ID so that we can cancel it
        // later if we need to.
        currentMenuTimerID = setTimeout ( "showMenuWithAfterDelay()", delay );
        
    }
    else if ( menuID != classChange_menuID )
    {
    
        // We are switching menus, so allow the menu timer to be activated.
        classChange_obj = obj;
        classChange_newClass = newClass;
        classChange_menuID = menuID;
        classChange_iFrameID = iFrameID;
        classChange_SH = SH;
        
        // Set the timer, and capture the timer ID so that we can cancel it
        // later if we need to.
        currentMenuTimerID = setTimeout ( "showMenuWithAfterDelay()", delay );
  
    }
    
} // End showMenuWithDelay


//---------------------------------------------------------------------------
// Function: Private_showMenuWithDelay
/**
 * Called by the JS build menu tabs.  The arguments are pulled from local
 * variables.
 */
//---------------------------------------------------------------------------
function Private_showMenuWithDelay ( ev )
{
    var classArg = this.menu_overClass;
	
	showMenuWithDelay(this, classArg, this.menu_menuID, this.menu_iFrameID, this.menu_change_visibility, 150);
} // End Private_showMenuWithDelay


//---------------------------------------------------------------------------
// Function: showMenuWithAfterDelay
/**
 * Called after the timer has expired and it's time to show the menu content.
 */
//---------------------------------------------------------------------------
function showMenuWithAfterDelay ()
{
    // Clear the timer ID.
    currentMenuTimerID = -1;
    
    // Use the saved paramter values to change the menu class.
    changeClass ( classChange_obj, classChange_newClass, classChange_menuID, classChange_iFrameID, classChange_SH );
} // End showMenuWithAfterDelay


function Private_hideSpiderMenuWithCheck(ev)
{
	var theEvent = ev;
	if(ev == null || ev == undefined)
	{
		theEvent = window.event;
	}
	
	hideSpiderMenuWithCheck(theEvent, this, this.menu_tabID, this.menu_iFrameID, this.menu_tabClass);
}

function hideSpiderMenuWithCheck(e, obj, tabID, iFrameID, tabClass)
{
	var element = e.relatedTarget || e.toElement;
	if( element && obj && ( element.id == tabID || isInSpiderMenu(element, obj) ))
	{
		/* mouse moved into parent tab or is still in TopTabGroup - do not hide */
	}
	else
	{
		var t = document.getElementById(tabID);
		changeClass(t, tabClass, obj.id, iFrameID, 'hide');
	}
}

function isInSpiderMenu(element, spiderMenu)
{
	if(element.id == spiderMenu.id)
	{
		return true;
	}
	else
	{
		while(element = element.offsetParent)
		{
			if(element.id == spiderMenu.id)
			{
				return true;
			}
		}
	}
	return false;
}

function HandleLeagueTab(e, url)
{	
	var element = e.target || e.srcElement;
	if(element.tagName == "TD")
	{
		window.location = url;
	}
}

function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	var retval = new Array();
	retval[0] = curleft;
	retval[1] = curtop;
	return retval;
}

/*
* called on window.onload to position all top tab sub menus.
*/
function positionAllMenus()
{
	var i = 0;
	var cell = null;
	var escapedText = '';
	var tabGroupRow = document.getElementById(feTopTabTR);
	var justifyThreshold = 4;
	var justification = '';
	
	positionMenu(feTopTabTR, feTopTabDiv);

	for(i=0; i < tabGroupRow.cells.length; i++)
	{
		escapedText = tabGroupRow.cells[i].childNodes[0].innerHTML.replace(/ /g, '_');
		cell = tabGroupRow.cells[i];
		
		try
		{
			if(!feTopTabGroup.metadata.justifyAllLeft)
			{
				justification = (i < justifyThreshold ? 'left' : 'right');
			}
		}catch(err)
		{
			justification = (i < justifyThreshold ? 'left' : 'right');
		}
		
		positionSpiderMenu('LEAGUE_MENU_' + escapedText, 'IFRAME_' + escapedText, cell.id, justification);
	}
}

function positionMenu(divMenu, tblTabGroup)
{
	var m = document.getElementById(divMenu);
	var t = document.getElementById(tblTabGroup);
	var a = new Array();
	if (m && t && a)
	{
		a = findPos(t);
		m.style.left = a[0] + 'px';
		m.style.top = (a[1] + t.offsetHeight) + 'px';
	}
}

function positionSpiderMenu(menuID, iFrameID, tabID, LR)
{
	var activePageWidth;
	if (feTopTabGroup)
	{
		activePageWidth = feTopTabGroup.metadata.activePageWidth; //Usable page width in pixels
	}
	else if (serverSideActivePageWidth)
	{
		activePageWidth = serverSideActivePageWidth;
	}
	
	var m = document.getElementById(menuID);
	var i = document.getElementById(iFrameID);
	var c = document.getElementById(tabID);

	if(m && i && c)
	{
		//Must position iframe first, then place div on top of it
		if(LR && LR == 'left')
		{
			if((c.offsetLeft + m.offsetWidth) > activePageWidth)
			{
				//Exceeds right boundary; right justify
				i.style.left = (activePageWidth - m.offsetWidth) + "px";
			}
			else
			{
				i.style.left = c.offsetLeft + "px";
			}
		}
		else if(LR && LR == 'right')
		{
			if((c.offsetLeft - (m.offsetWidth - c.offsetWidth)) < 0)
			{
				//Exceeds left boundary; left justify
				i.style.left = "0px";
			}
			else
			{
				i.style.left = (c.offsetLeft - (m.offsetWidth - c.offsetWidth)) + "px";
			}
		}
		// else, skip any repositioning
		
		i.style.top = "0px";
		i.style.width = m.offsetWidth + "px";
		i.style.height = m.offsetHeight + "px";
		//Iframe is in desired position; place div in exactly the same place
		m.style.left = i.style.left;
		m.style.top = i.style.top;
	}
}
/*
 */

/*
Builds the top tab group from TopTabGroupData.js 
*/
function BuildNormalizedTopTabGroup ()
{
    //check for existence of the tab data and the menu div before processing.
	if ( //typeof(ttgTopTabGroupTableDiv) == 'undefined' ||
	     typeof(ttgDivMenuHtml) == 'undefined' ||
	     typeof(feTopTabTableDiv) == 'undefined' ||
		 typeof(feTopTabTbl) == 'undefined' ||
		 typeof(feTopTabTR) == 'undefined' ||
	 	 typeof(feTopTabDiv) == 'undefined' )
	{
		window.setTimeout(BuildNormalizedTopTabGroup, 200);
		return;
	}

	// Get each of the required elements.
	//var ttgDivTbl = document.getElementById(feTopTabTableDiv);
	var ttgDivMenu = document.getElementById(feTopTabDiv);
	
	if ( //typeof(ttgDivTbl) == 'undefined' ||
	     typeof(ttgDivMenu) == 'undefined' )
	{
		window.setTimeout(BuildNormalizedTopTabGroup, 200);
		return;
	}
	
	/*
	FB Case 7905 - Don't replace the innerHTML of the table, the table is rendered by the top tab group control regardless of if it is ServerSide or not.
	// Replace the placeholder ID's in the TTG inner HTML with those specified in
	// the variables.
	var idIndex = ttgTopTabGroupTableDiv.indexOf ( "TTGTBLID" );
	var beforeIDStr = ttgTopTabGroupTableDiv.substr ( 0, idIndex );
	var afterIDStr = ttgTopTabGroupTableDiv.substr ( idIndex + 8, ( ttgTopTabGroupTableDiv.length - ( idIndex + 8 ) ) );
	ttgTopTabGroupTableDiv = beforeIDStr + feTopTabTbl + afterIDStr;
	
	
	idIndex = ttgTopTabGroupTableDiv.indexOf ( "TTGTRID" );
	beforeIDStr = ttgTopTabGroupTableDiv.substr ( 0, idIndex );
	afterIDStr = ttgTopTabGroupTableDiv.substr ( idIndex + 7, ( ttgTopTabGroupTableDiv.length - ( idIndex + 7 ) ) );
	ttgTopTabGroupTableDiv = beforeIDStr + feTopTabTbl + afterIDStr;
	ttgDivTbl.innerHTML = ttgTopTabGroupTableDiv;
	*/
	
	ttgDivMenu.innerHTML = ttgDivMenuHtml;
	
	//setup the window onload to position menus
	var oldonload = window.onload;
	
	if (typeof(window.onload) != 'function') 
	{
		window.onload = ttgPositionAllMenus;
	} 
	else 
	{	
		window.onload = function() {
			ttgPositionAllMenus();
			if (oldonload) 
			{
				oldonload();
			}
		}
	}
	
	if(document.readyState == 'complete')
	{
		ttgPositionAllMenus();
	}
}


/*
Sets the display dept tabs variable to true, then calls the 
BuildTopTabGroup function.
*/
function BuildDeptTopTabGroup()
{
  displayDeptTabs = true;
  BuildTopTabGroup();
}

 
 /*
Builds the top tab group in conjunction with 
raw data provided by /[store]/TopTabGroupData.js.
*/
function BuildTopTabGroup()
{
	//check for existence of the tab data and the menu div before processing.
	if(typeof(feTopTabGroup) == 'undefined' ||
		typeof(feTopTabTR) == 'undefined' ||
	 	typeof(feTopTabDiv) == 'undefined')
	{
		window.setTimeout(BuildTopTabGroup, 200);
		return;
	}
	
	var divMenu = document.getElementById(feTopTabDiv);
	
	if(typeof(divMenu) == 'undefined' )
	{
		window.setTimeout(BuildTopTabGroup, 200);
		return;
	}
	
	//setup the window onload to position menus
	var oldonload = window.onload;
	
	if (typeof(window.onload) != 'function') 
	{
		window.onload = positionAllMenus;
	} 
	else 
	{	
		window.onload = function() {
			positionAllMenus();
			if (oldonload) 
			{
				oldonload();
			}
		}
	}

	var hoverTabLinkCssClassLeftMost = 'TopTabGroupLeftMostHover';
	var hoverTabLinkCssClassRightMost = 'TopTabGroupRightMostHover';
	var hoverTabLinkCssClassMiddle = 'TopTabGroupMiddleHover';
	var cell = null;
	var escapedText = '';
	var i = 0;
	var allMenuIDs = new Array();
	var tabGroupRow = document.getElementById(feTopTabTR);
	var allSportDetected = false;
		
	for(i=0; i < tabGroupRow.cells.length; i++)
	{
		var hoverTabClass = (i == 0) ? hoverTabLinkCssClassLeftMost :
				(i == tabGroupRow.cells.length - 1) ? hoverTabLinkCssClassRightMost :
				hoverTabLinkCssClassMiddle;
				
		escapedText = tabGroupRow.cells[i].childNodes[0].innerHTML.replace(/ /g, '_');
		cell = tabGroupRow.cells[i];

		var buildSpiderMenu = true;
		if ( displayDeptTabs )
		{
			// Make sure that the menu has content.
			if ( feTopTabGroup.teams [ i ].departments.length <= 0 )
			{
				buildSpiderMenu = false;
			}
		}

		if ( buildSpiderMenu )
		{
			var menuIDs = BuildTabSpiderMenu(cell.id, cell.className, escapedText, feTopTabGroup.mainTabs[i].sId, (allSportDetected ? i-1 : i));

			if(feTopTabGroup.sportLookup[feTopTabGroup.mainTabs[i].sId].sport == -1)
			{
				allSportDetected = true;
			}

			cell.menu_menuID = menuIDs[0];
			cell.menu_iFrameID = menuIDs[1];
			cell.menu_change_visibility = 'show';
			cell.menu_changeWithCheck_visibility = 'hide';
			cell.menu_overClass = hoverTabClass;
			cell.menu_outClass = cell.className;

			// Show the menu with a delay unless the name of the tab indicates that there
			// show be no delay. This way the server determines whether the delay is enforced.
			if ( cell.id.substring ( 0, 13 ) == "LEAGUE_TABDEL" )
			{
			  // DEL = Delay
			  // Call the function that delays the showing of the menu.
			  cell.onmouseover = Private_showMenuWithDelay;
			}
			else
			{
			  // No delay... business as usual.
			  cell.onmouseover = Private_changeClass;
			}

			cell.onmouseout = Private_changeClassWithCheck;
		}
	}

	if(document.readyState == 'complete')
	{
		positionAllMenus();
	}
}

/*returns string[]*/
function BuildTabSpiderMenu(tabID, tabClass, escapedLinkText, sportLookupID, personGroupIndex)
{
	var divMenu = document.getElementById(feTopTabDiv);
	var div = document.createElement('div');
	div.id = 'LEAGUE_MENU_' + escapedLinkText;
	div.className = 'leagueMenuItem';
	
	var iFrame = document.createElement('iframe');
	iFrame.id = 'IFRAME_' + escapedLinkText;
	iFrame.frameBorder = '0';
	iFrame.scrolling = 'no';
	iFrame.src = 'javascript:\'<html></html>\';';
	iFrame.className = 'leagueMenuIFrame';
	divMenu.appendChild(iFrame);

	div.menu_tabID = tabID;
	div.menu_iFrameID = iFrame.id;
	div.menu_tabClass = tabClass;
	div.onmouseout = Private_hideSpiderMenuWithCheck;
	BuildMenuContent(div, feTopTabGroup.metadata.storeId, escapedLinkText, sportLookupID, personGroupIndex);

	divMenu.appendChild(div);
	
	var returnArray = new Array(3);
	returnArray[0] = div.id;
	returnArray[1] = iFrame.id;
	returnArray[2] = tabID;
	
	return returnArray;
}

function BuildMenuContent(menuDiv, storeID, escapedLinkText, sportLookupID, personGroupIndex)
{
	var isAllSports = (feTopTabGroup.sportLookup[sportLookupID].sport == -1);
	var mainTable = document.createElement('table');
	mainTable.id = 'MAIN_TABLE_' + escapedLinkText;

	if ( !displayDeptTabs )
	{
		var rowToAdd = mainTable.insertRow(-1);
		var cellToAdd = rowToAdd.insertCell(-1);
		cellToAdd.id = 'TITLE_CELL_' + escapedLinkText;
		cellToAdd.className = 'leagueMenuItemTitle';
		cellToAdd.colSpan = feTopTabGroup.metadata.PERSON_GROUP_COLUMNS;
		cellToAdd.innerHTML = isAllSports ? 'SELECT&nbsp;LEAGUE&nbsp;OR&nbsp;CATEGORY' :
			'SELECT&nbsp;' + escapedLinkText.replace(/_/g, ' ') + '&nbsp;TEAM&nbsp;OR&nbsp;CATEGORY';
	
		AddSpacerRow(mainTable);
		BuildPersonGroupContent(sportLookupID, mainTable, isAllSports, escapedLinkText, personGroupIndex);
		AddSpacerRow(mainTable);
	}

	BuildDepartmentContent(sportLookupID, mainTable, isAllSports, escapedLinkText, personGroupIndex);
	AddSpacerRow(mainTable);
	menuDiv.appendChild(mainTable);
}

function AddSpacerRow(mainTable)
{
	var rowToAdd = mainTable.insertRow(-1);
	var cellToAdd = rowToAdd.insertCell(-1);
	cellToAdd.className = 'leagueMenuItemSpacer';
	if ( !displayDeptTabs )
	{
		cellToAdd.colSpan = feTopTabGroup.metadata.PERSON_GROUP_COLUMNS;
	}
	else
	{
		cellToAdd.colSpan = feTopTabGroup.metadata.DEPARTMENT_COLUMNS;
	}
	cellToAdd.innerHTML = '&nbsp;';
}

function AddHeaderRow(mainTable, headerText, escapedLinkText)
{
	var rowToAdd = mainTable.insertRow(-1);
	var cellToAdd = rowToAdd.insertCell(-1);
	cellToAdd.id = 'TITLE_CELL_' + escapedLinkText;
	cellToAdd.className = 'leagueMenuItemTitle';
	cellToAdd.colSpan = feTopTabGroup.metadata.PERSON_GROUP_COLUMNS;
	cellToAdd.InnerHtml = headerText;

	rowToAdd.Cells.Add(cellToAdd);
	mainTable.Rows.Add(rowToAdd);

	AddSpacerRow(mainTable);
}

function BuildPersonGroupContent(sportLookupID, mainTable, isAllSports, escapedLinkText, personGroupIndex)
{
	escapedLinkText = escapedLinkText.toUpperCase().substring(0, 1) + escapedLinkText.toLowerCase().substring(1, escapedLinkText.length);

	var rowToAdd = mainTable.insertRow(-1);
	var cellToAdd = rowToAdd.insertCell(-1);

	var index = 0;
	var dvPersonGroups = null;
	var parentNodeDataLineage = null;
	var navLinkCustom = '';
	var isNCAA = false;
	var isNASCAR = false;
	var isMiLB = false;

	if (isAllSports)
	{
		//Get Leagues
		dvPersonGroups = feTopTabGroup.leagues;
	}
	else
	{
		var dvLeague = GetLeagueBySportLookupId(sportLookupID);

		if (dvLeague != null)
		{
			//Only used for NCAA,NASCAR, and MiLB All team links
			isNCAA = feTopTabGroup.sportLookup[sportLookupID].sName.toLowerCase().indexOf('ncaa') != -1;
			isNASCAR = feTopTabGroup.sportLookup[sportLookupID].sName.toLowerCase().indexOf('nascar') != -1;
			isMiLB = feTopTabGroup.sportLookup[sportLookupID].sName.toLowerCase().indexOf('milb') != -1;
		}
		
		dvPersonGroups = feTopTabGroup.teams[personGroupIndex].team;
	}

	for (var i = 1; i <= feTopTabGroup.metadata.PERSON_GROUP_COLUMNS; i++)
	{
		var longName = '';
		var totalEntryCount = dvPersonGroups.length;
		
		var columnEntries = Math.floor((totalEntryCount + ((isNCAA || isNASCAR || isMiLB) ? 3 : 0))/feTopTabGroup.metadata.PERSON_GROUP_COLUMNS) +
			((i > (feTopTabGroup.metadata.PERSON_GROUP_COLUMNS - ((totalEntryCount + ((isNCAA || isNASCAR || isMiLB) ? 3 : 0)) % feTopTabGroup.metadata.PERSON_GROUP_COLUMNS))) ? 1 : 0);

		var columnTable = document.createElement('table');
		columnTable.style.width = '100%';

		for (var j = 0; j < columnEntries; j++)
		{
			if ((isNCAA || isNASCAR || isMiLB) && i == 1 && j == 0)
			{
				AddControlToCellToRowToTable(columnTable, '<font class="SpiderMenuTop30"><b>TOP ' + totalEntryCount + '</b></font>', false);
				var topTab = GetTopTabBySportLookupId(sportLookupID);
				
				if(topTab != null)
				{
					//navLinkCustom = AddFireclickParam(topTab.href, isNCAA ? 'NcaaMenuAllTms' : 'NascarMenuAllTms');
					
					/* 6751: This page only exists for Star Struck currently.
					 * Also by changing the link to MiLBLanding.aspx this means
					 * that the "see all" links will be different than the link for 
					 * the MiLB tab button and the MiLB category in the all sports menu.
					 */
					navLinkCustom = isMiLB ? '/MiLBLanding.aspx' : topTab.href;
				}
				
				AddControlToCellToRowToTable(columnTable, '<a href="{0}"'.replace(/\{0\}/, navLinkCustom) + ' id="menuAll' + (isNCAA ? 'NCAA' : (isNASCAR ? 'NASCAR' : 'MiLB')) + '1">See all ' + (isNCAA ? 'NCAA ' : (isNASCAR ? 'NASCAR ' : 'MiLB ')) + ( (isNCAA || isMiLB) ? 'Teams' : 'Drivers') + '</a><br />', false);
				j += 2;
			}

			//only used for AllMenu FC Params 
			var leagueName = null;

			if (isAllSports)
			{
				leagueName = feTopTabGroup.sportLookup[dvPersonGroups[index].sId].sName;
				leagueName = leagueName.toUpperCase().substring(0,1) + leagueName.toLowerCase().substring(1, leagueName.length);
				longName = feTopTabGroup.sportLookup[dvPersonGroups[index].sId].lName;
				if(longName == '')
				{
					longName = feTopTabGroup.sportLookup[dvPersonGroups[index].sId].sName;
				}
			}
			else
			{
				longName = dvPersonGroups[index].text;
			}

			//var navUrl = AddFireclickParam(
			//		dvPersonGroups[index].href,
			//		isAllSports ? 'AllMenu' + leagueName : escapedLinkText + 'MenuTm');

			var navUrl = dvPersonGroups[index].href;

			AddControlToCellToRowToTable(columnTable, '<a href="' + navUrl + '">' + longName + '</a><br />', true);
			index++;
			if (index == totalEntryCount)
				break;
		}

		if ((isNCAA || isNASCAR || isMiLB) && i == feTopTabGroup.metadata.PERSON_GROUP_COLUMNS)
		{
			AddControlToCellToRowToTable(columnTable, '<a href="' + navLinkCustom + '" id="menuAll' + (isNCAA ? 'NCAA' : (isNASCAR ? 'NASCAR' : 'MiLB')) + '2">See all ' + (isNCAA ? 'NCAA ' : (isNASCAR ? 'NASCAR ' : 'MiLB ')) + ((isNCAA || isMiLB) ? 'Teams' : 'Drivers') + '</a>', false);
		}

		if (i > 1)
		{
			cellToAdd.style.borderLeft = 'solid 1px #e8e8e8';
		}

		cellToAdd.style.width = (i == feTopTabGroup.metadata.PERSON_GROUP_COLUMNS ?
			String(Math.ceil(100.0 / feTopTabGroup.metadata.PERSON_GROUP_COLUMNS)) :
			String(Math.floor(100.0 / feTopTabGroup.metadata.PERSON_GROUP_COLUMNS))) + '%';

		cellToAdd.className = 'leagueMenuItemColumn';

		cellToAdd.appendChild(columnTable);
		cellToAdd = rowToAdd.insertCell(-1);
	}
	
	//delete last cell
	rowToAdd.deleteCell(rowToAdd.cells.length-1);
}

function GetLeagueBySportLookupId(sportLookupID)
{
	for(var i=0; i < feTopTabGroup.leagues.length; i++)
	{
		if(feTopTabGroup.leagues[i].sId == sportLookupID)
		{
			return feTopTabGroup.leagues[i];
		}
	}
	
	return null;
}

function GetTopTabBySportLookupId(sportLookupID)
{
	for(var i=0; i < feTopTabGroup.mainTabs.length; i++)
	{
		if(feTopTabGroup.mainTabs[i].sId == sportLookupID)
		{
			return feTopTabGroup.mainTabs[i];
		}
	}
	
	return null;
}

function AddControlToCellToRowToTable(table, literalText, addMouseOverEffects)
{
	var row = table.insertRow(-1);
	var cell = row.insertCell(-1);
	if (addMouseOverEffects)
	{
		cell.menu_menuID = null;
		cell.menu_iFrameID = null;
		cell.menu_change_visibility = null;
		cell.menu_overClass = 'leagueMenuItemRowOver';
		cell.menu_outClass = 'leagueMenuItemRowOut';
		cell.onmouseover = Private_changeClass;
		cell.onmouseout = Private_changeClass;
	}
	cell.innerHTML = literalText;
}

/* returns string */
function AddFireclickParam(baseUrl, val)
{
    //TODO: only add the fireclick parameter if the user agent is not a crawler

    if (baseUrl != null && baseUrl != '' && baseUrl != undefined && val != null && val != '' && val != undefined)
    {
        var url = baseUrl.split('?');

        if (url.length == 1)
        {
            baseUrl = baseUrl + '?fc=' +  val;
        }
        else
        {
			var qs = url[1].split('&');
            qs.push('fc=' + val);
            baseUrl = url[0] + '?' + qs.join('&');
        }
    }

    return baseUrl;
}

function BuildDepartmentContent(sportLookupID, mainTable, isAllSports, escapedLinkText, personGroupIndex)
{
	var row = mainTable.insertRow(-1);
	var cell = row.insertCell(-1);
	if ( !displayDeptTabs )
	{
	  cell.colSpan = feTopTabGroup.metadata.PERSON_GROUP_COLUMNS;
	}
	cell.appendChild(BuildDepartmentTable(sportLookupID, isAllSports, escapedLinkText, personGroupIndex));
}

/* returns table */
function BuildDepartmentTable(sportLookupID, isAllSports, escapedLinkText, personGroupIndex)
{
	var longName = '';
	var shortName = '';
	var deptDV = null;
	var deptTable = document.createElement('table');
	deptTable.className = 'leagueMenuDeptTable';
	var deptRow = deptTable.insertRow(-1);

	if (isAllSports)
	{
		deptDV = feTopTabGroup.departments;
	}
	else
	{
		deptDV = feTopTabGroup.teams[personGroupIndex].departments;
	}

	var index = 0;

	for (var i = 1; i <= feTopTabGroup.metadata.DEPARTMENT_COLUMNS; i++)
	{
		var deptCell = deptRow.insertCell(-1);
		var deptColumnTable = document.createElement('table');
		deptColumnTable.style.width = '100%';
		
		var columnEntries = Math.floor(deptDV.length / feTopTabGroup.metadata.DEPARTMENT_COLUMNS) +
			((i > (feTopTabGroup.metadata.DEPARTMENT_COLUMNS - (deptDV.length % feTopTabGroup.metadata.DEPARTMENT_COLUMNS))) ? 1 : 0);

		for (var j = 0; j < columnEntries; j++)
		{
			if(isAllSports)
			{
				shortName = deptDV[index].text;
				longName = shortName;
			}
			else
			{
				shortName = feTopTabGroup.departments[deptDV[index].dId].text;
				if ( !displayDeptTabs )
				{
					longName = feTopTabGroup.sportLookup[sportLookupID].lName == '' ? feTopTabGroup.sportLookup[sportLookupID].sName : feTopTabGroup.sportLookup[sportLookupID].lName;
					longName = longName + '&nbsp;' + shortName;
				}
				else 
				{
				  longName = shortName;
				}
				
			}
			
			//var linkURL = AddFireclickParam(deptDV[index].href, GenerateDeptFCParam(isAllSports, escapedLinkText, shortName));
			var linkURL = deptDV[index].href;

			AddControlToCellToRowToTable(deptColumnTable, '<a href="' + linkURL + '">' + longName + '</a>', true);

			index++;
		}

		deptCell.appendChild(deptColumnTable);
		if (i > 1)
		{
			deptCell.style.borderLeft = 'solid 1px #e8e8e8';
		}

		if ( !displayDeptTabs )
		{
			deptCell.style.width = i == feTopTabGroup.metadata.PERSON_GROUP_COLUMNS ?
				String(Math.ceil(100.0 / feTopTabGroup.metadata.PERSON_GROUP_COLUMNS)) :
				String(Math.floor(100.0 / feTopTabGroup.metadata.PERSON_GROUP_COLUMNS)) + '%';
		}
		else
		{
			deptCell.style.width = i == feTopTabGroup.metadata.DEPARTMENT_COLUMNS ?
				String(Math.ceil(100.0 / feTopTabGroup.metadata.DEPARTMENT_COLUMNS)) :
				String(Math.floor(100.0 / feTopTabGroup.metadata.DEPARTMENT_COLUMNS)) + '%';
		}

		deptCell.className = 'leagueMenuItemColumn';
	}
	
	return deptTable;
}

/* returns string */
function GenerateDeptFCParam(isAllSports, escapedLinkText, deptName)
{
	return (isAllSports ? 'AllMenu' + GetDeptNameEscaped(deptName) : (escapedLinkText.toUpperCase().substring(0, 1) + escapedLinkText.toLowerCase().substring(1, escapedLinkText.length) + 'Menu' + GetDeptNameEscaped(deptName)));
}

/* returns string */
function GetDeptNameEscaped(deptName)
{
	var firstWord = deptName.split('&nbsp')[0];
	firstWord = firstWord.replace(/[^a-zA-Z]/g, '');

	return firstWord.length > 8 ? firstWord.substring(0, 8) : firstWord;
}

/* 
*
*END TopTabGroup functions 
*
*/
