<?php
####################################################
# nav_functions contents
# 
# Toolbar functions
#   nav_toolbar
#   gen_link
#
# StatsLab
#   logged_in
#   check_nav
#   get_version
####################################################


####################################################
# nav_toolbar
#  displays a nav bar
#
# Parameters:
#  which - which nav bar to display
#  title - a title to add to the toolbar
#  lgid  - the currently active league_id
#  slid  - the currently active sub_league_id
#  tid   - the currently active team_id
#  year  - the currently displayed year
#  addlSel - allows for additional, pipe delimited selects
#            id^param
####################################################
function nav_toolbar($which,$title="",$lgid="",$slid="",$tid="",$year="",$addlSel="")
{
	if ($which=="") {return 0;}

	$toolbars=explode("|",$which);
	$titles=explode("|",$title);

	$links="";
	$tooltips="";

	foreach ($toolbars as $key => $which)
	{
		$title=$titles[$key];

		switch ($which)
		{
		case 'admin':
			$links.="|Admin^admin.php|SQL Files^sql_file_load.php|Pages^pgAdmin.php|Draft^draftAdmin.php|Season^lsAdmin.php|All-Star^asAdmin.php|Awards^awAdmin.php|Contracts^contractsAdmin.php|Users^userAdmin.php";
			$tooltips.="|StatsLab Admin|Individual SQL File Load|Page Admin|Draft Admin|Season/Last Sim Admin|All-Star Voting Admin|End of Season Awards Admin|Report of signed contract extensions|Administer Users";
			break;
		case 'allstar':
			# Check admin access
			if ($_SESSION['user_is_commish']==1) 
			{
				$links.="|Admin^asAdmin.php";
				$tooltips.="|All-Star Voting Admin";
			}

			# Compose links
			$links.="|Voting^allstar.php|Results^allstar.php?page=results|History^asVotingHist.php";
			$tooltips.="|Vote for All-Stars|This Year's All-Star Voting Results|Historical All-Star Voting Results";
			break;
		case 'awards':
			# Check admin access
			if ($_SESSION['user_is_commish']==1) 
			{
				$links.="|Admin^awAdmin.php";
				$tooltips.="|Awards Voting Admin";
			}

			# Compose links
			$links.="|Voting^eos_ballot.php|Results^eos_ballot.php?page=results|History^awVotingHist.php";
			$tooltips.="|Vote for End of Season Awards|This Year's End of Season Award Voting Results|Historical End of Season Award Voting Results";
			break;
		case 'draft':
			$lgid=$_SESSION['lgid'];

			# Check admin access
			if ($_SESSION['user_is_commish']==1) 
			{
				$links.="|Admin^draftAdmin.php|Draft Order^draftOrder.php";
				$tooltips.="|Draft Admin|View/Modify the Draft Order";
			}

			if (($_SESSION['user_is_commish']==1)||($_SESSION['user_league_id']==$lgid))
			{
				$links.="|Team Warroom^draftWarroom.php";
				$tooltips.="|Team Draft Warroom";
			}

			# Compose links
			$links.="|Draft Board^draftBoard.php|History^draft_history.php";
			$tooltips.="|Draft Board|Draft History";
			break;
		case 'front_office':
			$lgid=$_SESSION['lgid'];

			if (!isset($_SESSION['adminpath'])) {set_adminpath();}
			include($_SESSION['adminpath']."/dbopen.php");

			# Get enabled pages
			$query="SELECT setting,value FROM ootp_sql_admin WHERE scope IN ('ALL',$lgid) AND setting IN ('tbEnable','finEnable','ratEnable','devEnable')";
			$result=mysqli_query($db,$query);
			if (mysqli_num_rows($result)>0)
			{
				while ($row=mysqli_fetch_array($result))
				{
					$setting=$row['setting'];
					$settings[$setting]=$row['value'];
				}
			}

			mysqli_close($db);

			if ($settings['tbEnable']==1)
			{
				if ((isset($_SESSION['user_id']))&&($_SESSION['user_team_id']>0))
				{
					$links.="|Trade Block Admin^tradeBlockAdmin.php";
					$tooltips.="|Adjust your team's trade block";
				}

				$links.="|Trade Block^tradeBlock.php";
				$tooltips.="|Trade Block";
			}
			$links.="|Injuries^injury_report.php";
			$tooltips.="|Injury Report";
			if ($settings['finEnable']==1)
			{
				$links.="|Payroll^payroll.php|FA's^projFreeAgents.php";
				$tooltips.="|Projected Payroll|Projected Free Agents";
			}
			if ($settings['ratEnable']==1)
			{
				$links.="|Ratings^ratings.php";
				$tooltips.="|Player Ratings Report";
			}
			if ($settings['devEnable']==1)
			{
				$links.="|Development^development.php";
				$tooltips.="|Development Tracker";
			}
			if ($settings['ratEnable']==1)
			{
				$links.="|Search^playerSearch.php";
				$tooltips.="|Search For Players By Ratings";
			}

			break;
		case 'history':
			$links.="|Leagues^league_index.php|Teams^team_index.php|Players^player_index.php|Parks^parks.php|Graphs^carGraphs.php|Leaderboards^leaderboards.php|Draft^draft_history.php|Hall of Fame^hall_of_fame.php";
			$tooltips.="|League History|Team History|Player Pages|Park Factors|Historical Graphs|Player, Team, and Progressive Leaderboards|Draft History|Hall of Fame";
			break;
		case 'hof':
			# Check admin access
			if ($_SESSION['user_is_commish']==1) 
			{
				$links.="|Admin^hofAdmin.php";
				$tooltips.="|Hall of Fame Voting Admin";
			}

			# Compose links
			$links.="|Hall of Fame^hall_of_fame.php|Voting^hall_of_fame_vote.php|Results^hall_of_fame_vote.php?page=results|History^hofVotingHist.php";
			$tooltips.="|Current members of the Hall of Fame|Vote for the Hall of Fame|This Year's Hall of Fame Voting Results|Historical Hall of Fame Voting Results";
			break;
		case 'leagues':
			echo "<script type='text/javascript'>\n";
			echo " <!--\n";
			include("nav_functions.js");
			echo " -->\n";
			echo "</script>\n";

			$lgid=$_SESSION['lgid'];

			if (!isset($_SESSION['adminpath'])) {set_adminpath();}
			include($_SESSION['adminpath']."/dbopen.php");

			echo "  <div id='subnav' style='width:100%;padding:0;'>   <!-- START $which subnav DIV -->\n";
			echo "   <form action='".basename($_SERVER['PHP_SELF'])."' method='get'>\n";
			echo "    <table border=0 cellpadding=2 cellspacing=0 style='margin-left:auto;margin-right:auto;'>\n";
			echo "     <tr>\n";
			# Sub-League List
			$query="SELECT sl.league_id,sub_league_id,sl.name,lg.name as lgname,lg.abbr as lgabbr FROM sub_leagues as sl,leagues as lg WHERE sl.league_id=lg.league_id AND sl.league_id=$lgid ORDER BY league_id,sub_league_id";
			$result=mysqli_query($db,$query);
			if (mysqli_num_rows($result)>0)
			{
				echo "      <td class='pgTitle'>Sub-League:</td>\n";
				echo "      <td>\n";
				echo "       <select name='sub_league_id' id='sub_league_id'>\n";
				$lastLgID=-1;
				while ($row=mysqli_fetch_array($result))
				{
					$league_id=$row['league_id'];
					$sub_league_id=$row['sub_league_id'];

					if (($lastLgID!=$league_id)&&(isset($leagues[$league_id]['name']))) {echo "        <optgroup name='".$leagues[$league_id]['name']."'>\n";}

					echo "        <option value='$sub_league_id'";
					if ($sub_league_id==$slid) {echo " selected='selected'";}
					if ($row['name']=="")
					{
						if (mysqli_num_rows($result)==1) {echo ">".$row['lgname']."</option>\n";}
						else {echo ">".$row['lgabbr']." Division ".$sub_league_id."</option>\n";}
					}
					else {echo ">".$row['name']."</option>\n";}

					$lastLgID=$league_id;
				}
				echo "       </select>\n";
				echo "      </td>\n";
			}
			# Page List
			$pageArray=Array('league_index.php'=>'League Index','league_summary.php'=>'Season Summary','league_positional_leaders.php'=>'Positional Leaderboards','parks.php'=>'Ballparks','league_strength.php'=>'League Strength','league_trends.php'=>'League Trends','league_postseason_table.php'=>'Postseason Grid','league_award_winners.php'=>'Award Winners','draft_history.php'=>'Draft History');
			echo "      <td class='pgTitle'>View:</td>\n";
			echo "      <td>\n";
			echo "       <select id='view' onchange=\"this.form.action=this.options[this.selectedIndex].value;
			                                toggleSelect(this,document.getElementById('yearnav'),'league_summary.php|league_positional_leaders.php|draft_history.php','league_index.php|league_strength.php|league_trends.php|league_postseason_table.php|league_award_winners.php');
			                                \">\n";
			foreach ($pageArray as $key => $lbl)
			{
				echo "        <option value='$key'";
				if ($key==basename($_SERVER['PHP_SELF'])) {echo " selected='selected'";}
				echo ">$lbl</option>\n";
			}
			echo "       </select>\n";
			echo "      </td>\n";
			# Year List
			$lgyear=$_SESSION['lgyear'];
			$query="SELECT MIN(year) AS minYr, MAX(year) AS maxYr FROM (SELECT DISTINCT year FROM team_history UNION SELECT $lgyear as year) as x";
			$result=mysqli_query($db,$query);
			if (mysqli_num_rows($result)>0)
			{
				echo "      <td class='pgTitle'>Year:</td>\n";
				echo "      <td>\n";
				echo "       <select name='year' id='yearnav'";
				switch (basename($_SERVER['PHP_SELF']))
				{
				case 'league_summary.php':
				case 'league_positional_leaders.php':
				case 'parks.php':
				case 'draft_history.php':
					break;
				default:
					echo " disabled=1";
					break;
				}
				echo ">\n";
				$row=mysqli_fetch_array($result);
				if ((is_numeric($row['maxYr']))&&(is_numeric($row['minYr'])))
				{
					for ($i=$row['maxYr'];$i>=$row['minYr'];$i--)
					{
						echo "        <option value='$i'";
						if ($i==$year) {echo " selected='selected'";}
						echo ">$i</option>\n";
					}
				}
				if (basename($_SERVER['PHP_SELF'])=='draft_history.php')
				{
					$query="SELECT COUNT(*) as dcnt FROM players WHERE draft_year=0 AND draft_round>0 AND draft_league_id=$lgid";
					$result=mysqli_query($db,$query);
					$row=mysqli_fetch_array($result);
					if ($row['dcnt']>0)
					{
						echo "        <option value='inaug'";
						if ($year=='inaug') {echo " selected='selected'";}
							echo ">Inaugural</option>\n";
					}
				}
				echo "       </select>\n";
				echo "      </td>\n";
			}
			# Additional Selects
			if ($addlSel!="")
			{
				$e=explode("|",$addlSel);
				foreach ($e as $key => $addOn)
				{
					$t=explode("^",$addOn);
					$addID=$t[0];
					$param=$t[1];

					echo "      <td class='pgTitle'>".ucwords(str_replace("_"," ",$addID)).":</td>\n";
					echo "      <td>\n";
					echo "       <select name='$addID' id='$addID'>\n";
					switch ($addID)
					{
					case 'awards':
						if ($param=='idx') {$addArray[-1]='Overview';}

						$query="SELECT mvp_award_name,pitcher_award_name,rookie_award_name,defense_award_name FROM leagues WHERE league_id=$lgid;";
					      	if ($_GET['showq']==1) {echo "$query<br/>\n";}
						$result=mysqli_query($db,$query);
						$row=mysqli_fetch_array($result);
						$addArray[4]=$row['pitcher_award_name'];
						$addArray[5]=$row['mvp_award_name'];
						$addArray[6]=$row['rookie_award_name'];
						$addArray[7]=$row['defense_award_name'];

						$query="SELECT value FROM ootp_sql_admin WHERE scope=$lgid AND module='Awards' AND setting='cmAwardName'";
					      	if ($_GET['showq']==1) {echo "$query<br/>\n";}
						$result=mysqli_query($db,$query);
						if (mysqli_num_rows($result))
						{
							$row=mysqli_fetch_array($result);
							$addArray[10]=$row['value'];
						}
						$addlAwards=Array(9,1,2,3,0);
						foreach ($addlAwards as $key => $awID) {$addArray[$awID]=get_award($awID);}

						if (!is_numeric($_GET[$addID])) {$_GET[$addID]=-1;}
						break;
					case 'position':
						switch ($param)
						{
						case 'b':
							$addArray=Array('all'=>'Summary','2'=>'C','3'=>'1B','4'=>'2B','5'=>'3B','6'=>'SS','7'=>'LF','8'=>'CF','9'=>'RF','10'=>'DH');
							break;
						case 'bp':
							$addArray=Array('all'=>'Summary','2'=>'C','3'=>'1B','4'=>'2B','5'=>'3B','6'=>'SS','7'=>'LF','8'=>'CF','9'=>'RF','10'=>'DH','11'=>'SP','21'=>'RP');
							break;
						}
						break;
					case 'view':
						switch ($param)
						{
						case 'bpf':
							$addArray=Array('batting'=>'Batting','pitching'=>'Pitching','fielding_stats'=>'Fielding');
							break;
						}
						break;
					}
					foreach ($addArray as $key => $lbl)
					{
						echo "        <option value='$key'";
						if ($key==$_GET[$addID]) {echo " selected='selected'";}
						echo ">$lbl</option>\n";
					}
					break;
					echo "       </select>\n";
					echo "      </td>\n";
				}
			}
			# Form Submission
			echo "      <td><input type='submit' value='Go' /></td>\n";
			echo "     </tr>\n";
			echo "    </table>\n";
			echo "   </form>\n";
			echo "  </div>   <!-- END $which subnav DIV -->\n";
			
			mysqli_close($db);

			return;

			break;
		case 'main':
			$lgid=$_SESSION['lgid'];

			if ($_SESSION['user_is_commish']==1)
			{
				$links.="|Admin^admin.php";
				$tooltips.="|StatsLab Admin";
			}

			if (!isset($_SESSION['adminpath'])) {set_adminpath();}
			include($_SESSION['adminpath']."/dbopen.php");

			# Get enabled pages
			$query="SELECT setting,value FROM ootp_sql_admin WHERE scope IN ('ALL',$lgid) AND setting IN ('expEnable','asEnable','awEnable','hofEnable','devEnable','dftEnable','finEnable','ratEnable','tbEnable')";
			if ($_GET['showq']==1) {echo "$query<br/>\n";}
			$result=mysqli_query($db,$query);
			if (mysqli_num_rows($result)>0)
			{
				while ($row=mysqli_fetch_array($result))
				{
					$setting=$row['setting'];
					$settings[$setting]=$row['value'];
				}
			}

			mysqli_close($db);

			#Export Tracker
			if ($settings['expEnable']==1)
			{
				$links.="|Exports^exports.php";
				$tooltips.="|Export Tracker";
			}

			#All-Star Voting Utility
			if ($settings['asEnable']==1)
			{
				$links.="|All-Star^allstar.php";
				$tooltips.="|All-Star Voting";
			}

			#End of Season Awards Utility
			if ($settings['awEnable']==1)
			{
				$links.="|Awards^eos_ballot.php";
				$tooltips.="|End of Season Awards Voting";
			}

			#Hall of Fame Voting Utility
			if ($settings['hofEnable']==1)
			{
				$links.="|HOF^hall_of_fame_vote.php";
				$tooltips.="|Hall of Fame Voting";
			}
			#Draft Utility
			if ($settings['dftEnable']==1)
			{
				$links.="|Draft^draftBoard.php";
				$tooltips.="|Draft Utility";
			}

			#Standard Season
			$links.="|Season^boxscores.php";
			$tooltips.="|Current Season Information";

			#Front Office
			if (($settings['tbEnable']==1)||($settings['finEnable']==1)||($settings['ratEnable']==1)||($settings['devEnable']==1))
			{
				$tooltips.="|Team Administration Reports";

				if ($settings['tbEnable']==1) {$links.="|Front Office^tradeBlock.php";}
				elseif ($settings['finEnable']==1) {$links.="|Front Office^payroll.php";}
				elseif ($settings['ratEnable']==1) {$links.="|Front Office^ratings.php";}
				elseif ($settings['devEnable']==1) {$links.="|Front Office^development.php";}
			}

			#Standard History, Help, Managers
			$links.="|History^league_index.php|Managers^managers.php|?^help.php";
			$tooltips.="|League History Pages|Manager Listing & Contact Info|Help";

			if (isset($_SESSION['user_id']))
			{
				$username=$_SESSION['username'];
				if ($username=="")
				{
					if (!isset($_SESSION['adminpath'])) {set_adminpath();}
					include($_SESSION['adminpath']."/dbopen.php");
					$query="SELECT first_name,last_name FROM human_managers WHERE human_manager_id=".$_SESSION['user_id'];
					$result=mysqli_query($db,$query);
					$row=mysqli_fetch_array($result);
					$username=$row['first_name']." ".$row['last_name'];
					$_SESSION['username']=$username;
					mysqli_close($db);
				}
				$links.="|Logout^login.php?logout=1^$username";
				$tooltips.="|Logout";
			}
			else 
			{
				$links.="|Login^login.php";
				$tooltips.="|Login";
			}
			break;
		case 'managers':
			$links.="|Current Managers^managers.php|Records^manager_records.php";
			$tooltips.="|List of currently active managers|Historical human manager records";
			break;
		case 'players':
			echo "  <div id='subnav' style='width:100%;padding:0;'>   <!-- START $which subnav DIV -->\n";
			echo "   <table border=0 cellpadding=0 cellspacing=0 style='margin-left:2px;width:100%;'>\n";
			echo "    <tr>\n";
			echo "     <td>";
			echo "      <ul>\n";
			echo "       <li class='pgTitle'>Players</li>\n";
			for ($i=65;$i<=90;$i++) 
	      		{
				$x=chr($i);
				echo "       <li>";
				echo "<a href='./player_index.php?letter=$x";
				if (isset($_GET['view'])) {echo "&view=".$_GET['view'];}
				echo "' class='menu'";
				if ($i==65) {echo " id='first'";}
				echo ">";
				echo "$x</a></li>\n";
			}
			echo "      </ul>\n";
			echo "     </td>\n";
			echo "     <td>\n";
			echo "      <form action='./player_index.php' method='get'>\n";
			echo "       <table cellpadding=2 cellspacing=0 border=0 style='float:right;'>\n";
			echo "        <tr>\n";
			echo "         <td class='pgTitle'>Search</td>\n";
                        echo "         <td><input type='textbox' maxlength=20 size=6 name='player_id' ";
			if ($pid!="") {echo "value='$pid' ";}
				echo "/></td>\n";
			echo "         <td><input type='submit' value='Go' /></td>\n";
			echo "        </tr>\n";
			echo "       </table>\n";
			echo "      </form>\n";
			echo "     </td>\n";
			echo "    </tr>\n";
			echo "   </table>\n";
			echo "  </div>   <!-- END $which subnav DIV -->\n";

			return;
			break;
		case 'season':
			# Get Enabled Pages
			include($_SESSION['adminpath']."/dbopen.php");
			$query="SELECT setting,value FROM ootp_sql_admin WHERE module='Last Sim' AND setting LIKE '%Enable' AND scope=".$_SESSION['lgid'];
			$result=mysqli_query($db,$query);
	      		if (mysqli_num_rows($result))
			{
	      			while ($row=mysqli_fetch_array($result))
				{
	      				$setting=$row['setting'];
	      				$value=$row['value'];
	      
					$settings[$setting]=$value;
				}
	      		}
			mysqli_close($db);

			# Check admin access
			if ($_SESSION['user_is_commish']==1) 
			{
				$links.="|Admin^lsAdmin.php";
				$tooltips.="|Season Admin";
			}

			# Compose links
			$links.="|Standings^standings.php|Box Scores^boxscores.php|Graphs^graphs.php|Stats^simstats.php|Team Stats^teamStats.php|Top Perfs^topperf.php";
			$tooltips.="|Date Adjustable Standings|Last Sim Box Scores|Graphs|Player Stats|Team Stats|Top Performances";
			if ($settings['spEnable']==1)
			{
				$links.="|Sim Preview^simPreview.php";
				$tooltips.="|Sim Preview";
			}
			if ($settings['mrEnable']==1)
			{
				$links.="|Milestones^milestones.php";
				$tooltips.="|Milestones and Records Watch Reports";
			}
			if ($settings['poEnable']==1)
			{
				$links.="|Playoff Odds^playoffOdds.php";
				$tooltips.="|Playoff Odds Report";
			}
			if ($settings['pstEnable']==1)
			{
				$links.="|Playoffs^playoffs.php";
				$tooltips.="|Postseason Reports";
			}
			if ($settings['sotdEnable']==1)
			{
				$links.="|SOTD^statOfTheDay.php";
				$tooltips.="|Stat of the Day";
			}
			break;
		case 'teams':
			echo "<script type='text/javascript'>\n";
			echo " <!--\n";
			include("nav_functions.js");
			echo " -->\n";
			echo "</script>\n";

			if (!isset($_SESSION['adminpath'])) {set_adminpath();}
			include($_SESSION['adminpath']."/dbopen.php");

			echo "  <div id='subnav' style='width:100%;padding:0;'>   <!-- START $which subnav DIV -->\n";
			echo "   <form action='".basename($_SERVER['PHP_SELF'])."' method='get'>\n";
			echo "    <table border=0 cellpadding=2 cellspacing=0 style='margin-left:auto;margin-right:auto;'>\n";
			echo "     <tr>\n";
			# Team List
			$query="SELECT *,MIN(active) as minAct FROM (SELECT team_id,name,nickname,1 as active FROM teams WHERE league_id=".$_SESSION['lgid']." AND allstar_team=0";
			$query.=" UNION ";
			$query.="SELECT team_id,name,nickname,0 as active FROM (SELECT year,team_id,name,nickname FROM team_history WHERE team_id NOT IN (SELECT team_id FROM teams WHERE league_id=".$_SESSION['lgid']." AND allstar_team=0) AND league_id=".$_SESSION['lgid']." ORDER BY year DESC,name,nickname) as t GROUP BY team_id";
			$query.=") as t GROUP BY team_id ORDER BY active DESC,name,nickname";
			$result=mysqli_query($db,$query);
			if (mysqli_num_rows($result)>0)
			{
				echo "      <td class='pgTitle'>Team:</td>\n";
				echo "      <td>\n";
				echo "       <input type='hidden' name='league_id' value='".$_SESSION['lgid']."'>\n";
				echo "       <select name='team_id' id='team_id'>\n";
				$prevAct=-1;
				while ($row=mysqli_fetch_array($result))
				{
					$team_id=$row['team_id'];
					$name=$row['name']." ".$row['nickname'];
					$actStat=$row['active'];



					if (($actStat!=$prevAct)&&($actStat==1)&&($row['minAct']==0)) {echo "        <optgroup name='Active Teams' label='Active Teams'>\n";}
					if (($actStat!=$prevAct)&&($actStat==0)) {echo "        <optgroup name='Former Teams' label='Former Teams'>\n";}

					echo "        <option value='$team_id'";
					if ($team_id==$tid) {echo " selected='selected'";}
					echo ">$name</option>\n";

					$prevAct=$actStat;
				}
				echo "       </select>\n";
				echo "      </td>\n";
			}
			# Page List
			$pageArray=Array('team_overview.php'=>'Team Overview','team_hist.php'=>'Team Index','team_batting_registry.php'=>'Batting Registry','team_pitching_registry.php'=>'Pitching Registry','team_fielding_registry.php'=>'Fielding Registry','team_positional_starters.php'=>'Positional Starters','team_pitcher_starters.php'=>'Pitching Starters','team_batting_leaders.php'=>'Batting Leaders','team_pitching_leaders.php'=>'Pitching Leaders','team_park_history.php'=>'Park History','team_postseason_table.php'=>'Postseason Grid','team_summary.php'=>'Season Summary','team_player_tenure.php'=>'Player Tenure','team_draft_history.php'=>'Draft History');
			echo "      <td class='pgTitle'>View:</td>\n";
			echo "      <td>\n";
			echo "       <select id='view' onchange=\"this.form.action=this.options[this.selectedIndex].value;
			                                toggleSelect(this,document.getElementById('yearnav'),'team_summary.php|team_player_tenure.php|team_draft_history.php','team_overview.php|team_hist.php|team_batting_registry.php|team_pitching_registry.php|team_fielding_registry.php|team_positional_starters.php|team_pitcher_starters.php|team_batting_leaders.php|team_pitching_leaders.php|team_park_history.php|team_postseason_table.php');
			                                \">\n";
			foreach ($pageArray as $key => $lbl)
			{
				echo "        <option value='$key'";
				if ($key==basename($_SERVER['PHP_SELF'])) {echo " selected='selected'";}
				echo ">$lbl</option>\n";
			}
			echo "       </select>\n";
			echo "      </td>\n";
			# Year List
			$query="SELECT MIN(year) as minYr,MAX(year) as maxYr FROM (SELECT year FROM team_history WHERE team_id=$tid UNION SELECT '".$_SESSION['lgyear']."' as year FROM team_record WHERE team_id=$tid AND g>0) as t;";
			if ($_GET['showq']==1) {echo "$query<br/>\n";}
			$result=mysqli_query($db,$query);
			if (mysqli_num_rows($result)>0)
			{
				echo "      <td class='pgTitle'>Year:</td>\n";
				echo "      <td>\n";
				echo "       <select name='year' id='yearnav'";
				switch (basename($_SERVER['PHP_SELF']))
				{
				case 'team_summary.php':
				case 'team_player_tenure.php':
				case 'team_draft_history.php':
					break;
				default:
					echo " disabled=1";
					break;
				}
				echo ">\n";
				echo "        <option value=''>Index Page</option>\n";
				$row=mysqli_fetch_array($result);
				for ($i=$row['maxYr'];$i>=$row['minYr'];$i--)
				{
					echo "        <option value='$i'";
					if ($i==$year) {echo " selected='selected'";}
					echo ">$i</option>\n";
				}
				if (basename($_SERVER['PHP_SELF'])=='team_draft_history.php')
				{
					$query="SELECT COUNT(*) as dcnt FROM players WHERE draft_year=0 AND draft_round>0 AND draft_team_id=$tid AND draft_league_id=".$_SESSION['lgid'];
					$result=mysqli_query($db,$query);
					$row=mysqli_fetch_array($result);
					if ($row['dcnt']>0)
					{
						echo "        <option value='inaug'";
						if ($year=='inaug') {echo " selected='selected'";}
						echo ">Inaugural</option>\n";
					}
				}				echo "       </select>\n";
				echo "      </td>\n";
			}
			# Form Submission
			echo "      <td><input type='submit' value='Go' /></td>\n";
			echo "     </tr>\n";
			echo "    </table>\n";
			echo "   </form>\n";
			echo "  </div>   <!-- END $which subnav DIV -->\n";
			
			mysqli_close($db);

			return;

			break;
		}

		if ($which=='main')
		{
			if (!isset($_SESSION['adminpath'])) {set_adminpath();}
			include($_SESSION['adminpath']."/dbopen.php");
			# League List
			$query="SELECT league_id,name,abbr,league_level FROM leagues ORDER BY league_id";
			$result=mysqli_query($db,$query);
			if (mysqli_num_rows($result)>1)
			{
				echo "  <div id='subnav' style='padding-top:0;padding-bottom:0;margin-top:0;margin-bottom:0;'>   <!-- START $which subnav DIV -->\n";
				if ($lgid=="") {$lgid=$_SESSION['lgid'];}
				echo "   <form action='".basename($_SERVER['PHP_SELF'])."' method='get'>\n";
				foreach ($_GET as $key => $val)
				{
					if (($key=='league_id')||($key=='team_id')) {continue;}
					echo "    <input type='hidden' name='$key' value=\"$val\" />\n";
				}
				echo "    <table border=0 cellpadding=2 cellspacing=0 style='width:100%;text-align:right;'>\n";
				echo "     <tr>\n";
				echo "      <td>\n";
				echo "       <select name='league_id' id='league_id' onchange='this.form.submit();' style='float:left;' title='Use this selector to switch between leagues'>\n";
				while ($row=mysqli_fetch_array($result))
				{
					$league_id=$row['league_id'];
					$leagues[$league_id]['name']=$row['name'];
					echo "        <option value='$league_id'";
					if ($league_id==$lgid) {echo " selected='selected'";}
						echo " title='".$row['name']."'>".$row['abbr'];
					$level=$row['league_level'];
					if (($level!=1)&&($level!=8)) {echo " (".get_level($level).")";}
					echo "</option>\n";
				}
				echo "       </select>\n";
				echo "      </td>\n";
				echo "      <td style='text-align:right;'>\n";
			}
			else
			{
				echo "  <div id='subnav'>   <!-- START $which subnav DIV -->\n";
			}
			mysqli_close($db);
		}
		else
		{
			echo "  <div id='subnav'>   <!-- START $which subnav DIV -->\n";
		}

		echo "   <ul>\n";
		if ($title!="") {echo "    <li class='pgTitle'>$title</li>\n";}
	
		$links=trim($links," |");
		$tooltips=trim($tooltips," |");
		$e=explode("|",$links);
		$tt=explode("|",$tooltips);

		foreach ($e as $key => $val)
	    	{
			$s=explode("^",$val);
		  	$text=$s[0];
			$addr=$s[1];
			$specialHandling=$s[2];
			echo "    <li>";		
			if ($specialHandling!="")
			{
				switch ($text)
				{
				case 'Logout':
					echo "<a href='$addr' class='menu' style='padding-right:0;'";
					if ($tt[$cnt]!="") {echo " title=\"".htmlspecialchars($tt[$cnt])."\"";}
					if (($title=="") && ($cnt==0)) {echo " id='first'";}
					echo ">Logout</a>";
					echo " <a href='./login.php' class='menu' title='Show user settings' style='border:none;padding:0;'>($specialHandling)</a>";
					break;
				}
			}
			else
			{
				if ($addr!="")
				{
					echo "<a href='$addr' class='menu'";
					if ($tt[$cnt]!="") {echo " title=\"".htmlspecialchars($tt[$cnt])."\"";}
					if (($title=="") && ($cnt==0)) {echo " id='first'";}
					echo ">";
				}
				echo $text;
				if ($addr!="") {echo "</a>";}
			}
			echo "</li>\n";
			$cnt++;
	    	}
	
		echo "   </ul>\n";

		if (($which=='main')&&(mysqli_num_rows($result)>1))
		{
			echo "      </td>\n";
			echo "     </tr>\n";
			echo "    </table>\n";
			echo "   </form>\n";
		}

		echo "  </div>   <!-- END $which subnav DIV -->\n";
	}
}

####################################################
# gen_link
#  generates a link with appropriate $_GET params
#
# Parameters:
#  page    - if blank, the current page
#  incList - params to include, ignore the rest
#  excList - params to exclude, include the rest
####################################################
function gen_link($page="",$incList="",$excList="")
{
	if ($page=="") {$page=basename($_SERVER['PHP_SELF']);}

	if ($incList!="")
	{
		$inc=explode("|",$incList);
		foreach ($inc as $key => $val) {$include[$val]=1;}
	}
	if ($excList!="") 
	{
		$exc=explode("|",$excList);
		foreach ($exc as $key => $val) {$exclude[$val]=1;}
	}

	$cnt=0;
	foreach ($_GET as $name => $value)
	{
		$inc=0;
		if ($include[$name]==1) {$inc=1;}
		elseif ($exclude[$name]!=1) {$inc=1;}

		if (($inc==1)&&($cnt==0)) {$page.="?";}
		if ($inc==1)
		{
			if ($cnt>0) {$page.="&";}
			$page.="$name=$value";
			$cnt++;
		}
	}
	return $page;
}

####################################################
# logged_in
#  checks to see if a user has logged in
#
# Parameters:
#  page - if blank, the current page
#  lgid - if blank, the current session league
####################################################
function logged_in($page="",$lgid="")
{
	$boolRes=1;

	if (isset($_SESSION['user_id'])) {return $boolRes;}

	if (!isset($_SESSION['adminpath'])) {set_adminpath();}

	include($_SESSION['adminpath']."/dbopen.php");

	$query="SHOW TABLES LIKE 'ootp_sql_users';";
      	$result=mysqli_query($db,$query);
	if (!mysqli_num_rows($result)) 
      	{
	}
	else
	{
		$query="SELECT value FROM ootp_sql_admin WHERE setting='requireLogin'";
		if ($_GET['showq']==1) {echo "$query<br/>\n";}
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
		{
			$row=mysqli_fetch_array($result);
			$requireLogin=$row['value'];
	
			if ($_GET['showq']==1) {echo "requireLogin:$requireLogin :: user_id:".$_SESSION['user_id']."<br/>\n";}
			if (($requireLogin==1)&&(!isset($_SESSION['user_id']))) {$boolRes=0;}
		}
	}

	mysqli_close($db);

	return $boolRes;
}


####################################################
# check_nav
#  checks to see that a page is enabled when switching between leagues
#
# Parameters:
#  page - if blank, the current page
#  lgid - if blank, the current session league
####################################################
function check_nav($page="",$lgid="")
{
	if ($page=="") {$page=basename($_SERVER['PHP_SELF']);}
	if ($lgid=="") {$lgid=$_SESSION['lgid'];}
	if (isset($_GET['league_id'])) {$lgid=$_GET['league_id'];}

	$boolRes=1;

	if ($_GET['showq']==1) {echo "Checking if '$page' is enabled...<br/>\n";}

	switch ($page)
	{
	case 'allstar.php':
	case 'asVotingHist.php':
		$module="All-Star";
		$setting='asEnable';
		break;
	case 'eos_ballot.php':
	case 'awVotingHist.php':
		$module="Awards";
		$setting='awEnable';
		break;
	case 'draftWarroom.php':
	case 'draftBoard.php':
	case 'draftHist.php':
		$module="Draft";
		$setting='dftEnable';
		break;
	case 'milestones.php':
		$module="Last Sim";
		$setting='mrEnable';
		break;
	case 'playoffOdds.php':
		$module="Last Sim";
		$setting='poEnable';
		break;
	case 'playoffs.php':
		$module="Last Sim";
		$setting='pstEnable';
		break;
	case 'statOfTheDay.php':
		$module="Last Sim";
		$setting='sotdEnable';
		break;
	default:
		$module="";
		break;
	}

	if ($module!="")
	{
		if (!isset($_SESSION['adminpath'])) {set_adminpath();}

		include($_SESSION['adminpath']."/dbopen.php");

		$query="SELECT value FROM ootp_sql_admin WHERE scope IN ('ALL',$lgid) AND module='$module' AND setting='$setting'";
		if ($_GET['showq']==1) {echo "$query<br/>\n";}
		$result=mysqli_query($db,$query);
		$row=mysqli_fetch_array($result);
		$boolRes=$row['value'];
		if ($_GET['showq']==1) {echo "$page enabled: $boolRes<br/>\n";}

		mysqli_close($db);
	}
	elseif ($_GET['showq']==1) {echo "$page enabled by default<br/>\n";}


	return $boolRes;
}

####################################################
# get_version
#  returns the version of StatsLab
####################################################
function get_version() {return "3.20.09 (PHP7.2)";}

?>