<?php
session_start();
include('html_functions.php');
check_cookie();
include($_SESSION['adminpath']."/dbopen.php");

$lgpath=$_SESSION['lgpath'];
$lid=$_GET['league_id'];
if ($lid!="") {$lgid=$lid;}
if ($lgid=="") {$lgid=$_SESSION['lgid'];}
if ($lgid=="") {$lgid=100;}
$date=new Date($_SESSION['lgdate']);
$lgyear=$_SESSION['lgyear'];
$lgmonth=$date->format("m");

ini_set("memory_limit","64M");

##### Start Page #####
$title="Season Predictions";
	
page_head($title,$_SESSION['lgpath']);
echo " <div id='topbar'>\n";
main_titlebar($lgid,$_SESSION['lgpath'],$title);
nav_toolbar("season","Season");
echo " </div>   <!-- END topbar DIV -->\n";
echo " <div id='contentpane'>\n";

##### Generate Page Content and include it #####
echo sea_preview($lgid);

##### Close out page #####
echo "</div>   <!-- END contentpane DIV -->\n";

page_foot($lgpath);


	function sea_preview($lgid)
	{
		$adminpath=$_SESSION['adminpath'];
		include($adminpath."/dbopen.php");
		
		##### Get league settings #####
		$lgdate=$_SESSION['lgdate'];
		$lgpath=$_SESSION['lgpath'];
		if ($lgid=="") {$lgid=$_SESSION['lgid'];}
		if ($lgid=="") {$lgid=100;}
		$date=new Date($_SESSION['lgdate']);
		$lgyear=$_SESSION['lgyear'];
		$lgMo=$date->format("m");
		$lgDay=$date->format("d");
		$text="";
		
		##### Get Season Start Date and League Level #####
		$query="SELECT start_date,league_level FROM leagues WHERE league_id=$lgid;";
		if (isset($_GET['showq'])) {$text.="$query<br/>\n";}
		$result=mysqli_query($db,$query);
		$row=mysqli_fetch_array($result);
		$seaStartDt=$row['start_date'];
		$pLgLevel=$row['league_level'];
		if ($pLgLevel==8) {$pLgLevel=1;}
	
		##### Get Season Completion Percentage #####
		$query="SELECT played,COUNT(game_id) as g FROM games WHERE league_id=$lgid AND game_type=0 AND games.date>='$seaStartDt' GROUP BY played;";
		$result=mysqli_query($db,$query);
		if ($result)
		{
			while ($row=mysqli_fetch_array($result))
			{
				switch ($row['played'])
				{
				case 0: $unPlayGm=$row['g']; break;
				case 1: $playGm=$row['g']; break;
				}
			}
			$seaCompPct=$playGm/($unPlayGm+$playGm);
		}
		if ($_GET['showq']==1) {$text.=$seaCompPct;}
		if ($seaCompPct>=1) {$lgyear++;}
	
		##### Get Playoff Odds Configuration
		$query="SHOW TABLES LIKE 'ootp_sql_admin';";
	      	$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result)) 
	      	{
			# Get Settings
			$query="SELECT setting,value FROM ootp_sql_admin WHERE scope IN ('ALL',$lgid) AND module IN ('admin','Last Sim') AND setting IN ('nSeasons','pythMeth','pythExp','nPOTeams')";
			$result=mysqli_query($db,$query);
	      		if (mysqli_num_rows($result))
			{
	      			while ($row=mysqli_fetch_array($result))
				{
	      				$setting=$row['setting'];
					$value=$row['value'];

					switch ($setting)
	      				{
					case 'nSeasons': $seasons=$value;  break;
	      				case 'pythMeth': $pythMeth=$value; break;
					case 'pythExp' : $pythExp=$value;  break;
	      				case 'nPOTeams': $nPOTeams=$value; break;
					}
	      			}
			}
	      	}
	      
		switch ($pythMeth)
		{
	      	case 'Pythagorean Win Pct (Pythagenpat)': $pythMeth='pythPat';break;
		case 'Actual Win Pct': $pythMeth='record'; break;
	      	default: $pythMeth='pythExp';break;
		}
	      	if ($pythMeth=="") {$pythMeth='pythExp';}
		if ($seasons=="") {$seasons=10;}
	      	if ($pythExp=="") {$pythExp=1.82;}
		
		##### Get Team Record And Name #####
		$query="SELECT thr.team_id,t.league_id,w,l,pos,gb,name,nickname,abbr,background_color_id,text_color_id,logo_file_name FROM team_history_record as thr,teams as t WHERE thr.team_id=t.team_id AND thr.league_id=$lgid AND t.team_id!=0 AND thr.year=".($lgyear-1)." ORDER BY name,nickname;";
		if (isset($_GET['showq'])) {$text.="$query<br/>\n";}
		$result=mysqli_query($db,$query);
		while ($row=mysqli_fetch_array($result))
		{
			$tid=$row['team_id'];
			$w=$row['w'];
			$l=$row['l'];
			
			$teams[$tid]['lgid']=$row['league_id'];
			$teams[$tid]['w']=$w;
			$teams[$tid]['l']=$l;
			$teams[$tid]['pct']=$w/($w+$l);
			$teams[$tid]['pos']=$row['pos'];
			$teams[$tid]['gb']=$row['gb'];
			$teams[$tid]['name']=$row['name']." ".$row['nickname'];
			$teams[$tid]['abbr']=$row['abbr'];
			$teams[$tid]['background_color_id']=$row['background_color_id'];
			$teams[$tid]['text_color_id']=$row['text_color_id'];
			$teams[$tid]['logo_file']=$row['logo_file_name'];

			## Calculate Average Games
			$g=$w+$l;
			$totG=$totG+$g;
			$totTm=$totTm+1;
		}
		$avgG=floor($totG/$totTm);
		
		##### Get Team Payroll Information #####
		$query="SELECT tf.team_id,thf.player_expenses,player_payroll FROM team_financials as tf,team_history_financials as thf WHERE tf.team_id=thf.team_id AND thf.year=".($lgyear-1)." AND thf.league_id=$lgid;";
		if (isset($_GET['showq'])) {$text.="$query<br/>\n";}
		$result=mysqli_query($db,$query);
		while ($row=mysqli_fetch_array($result))
		{
			$tid=$row['team_id'];
			$teams[$tid]['lastPayroll']=$row['player_expenses'];
			$teams[$tid]['thisPayroll']=$row['player_payroll'];
		}			
		
		##### Get Team Relations #####
		$tCnt=0;
		$query="SELECT tr.team_id,tr.sub_league_id,tr.division_id,sl.name as slname,sl.abbr as slabbr,designated_hitter,di.name as divname FROM team_relations as tr,sub_leagues as sl,divisions as di WHERE tr.team_id!=0 AND tr.league_id=$lgid AND sl.league_id=$lgid AND di.league_id=$lgid AND sl.sub_league_id=tr.sub_league_id AND sl.sub_league_id=di.sub_league_id AND tr.division_id=di.division_id ORDER BY sub_league_id,division_id;";
		if (isset($_GET['showq'])) {$text.="$query<br/>\n";}
		$result=mysqli_query($db,$query);
		while ($row=mysqli_fetch_array($result))
		{
			$tid=$row['team_id'];
			$slid=$row['sub_league_id'];
			$divID=$slid."^".$row['division_id'];
			
			$subleagues[$slid]['name']=$row['slname'];
			$subleagues[$slid]['abbr']=$row['slabbr'];
			$subleagues[$slid]['teams']=$subleagues[$slid]['teams'].",".$tid;
			$subleagues[$slid]['tCnt']=$subleagues[$slid]['tCnt']+1;
			$subleagues[$slid]['divs'][$divID]=1;
			
			$divisions[$divID]['name']=$row['divname'];
			$divisions[$divID]['slid']=$slid;
			
			$teams[$tid]['slid']=$slid;
			$teams[$tid]['divID']=$divID;
			$tCnt++;
		}
		foreach ($subleagues as $slid => $val)
		{
			$subleagues[$slid]['teams']=trim($subleagues[$slid]['teams'],',');
			$subleagues[$slid]['divCnt']=count($subleagues[$slid]['divs']);
		}
		
		##### Get Pythagorean Record #####
		$query="SELECT thb.team_id,thb.r AS rf, thp.r AS ra,if(thp.gs=0,thp.g,thp.gs) as g,thb.ab as ab,thb.h as h,(thp.ip*3+thp.ipf)/3 as ip,thp.er as er FROM team_history_batting_stats AS thb, team_history_pitching_stats AS thp WHERE thb.year=thp.year AND thb.league_id=$lgid AND thb.year=".($lgyear-1)." AND thb.team_id=thp.team_id;";
		if (isset($_GET['showq'])) {$text.="$query<br/>\n";}
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
		{
			while ($row=mysqli_fetch_array($result))
			{
				$tid=$row['team_id'];
				$rf=$row['rf'];
				$ra=$row['ra'];
				$g=$row['g'];
				
				if ($g==0) {$pythPct=0.5;}
				else 
				{
					switch ($pythMeth)
					{
						case 'pythPat':
							$pythExp=pow(($rf+$ra)/$g,0.287);
							$pythPct=pow($rf,$pythExp)/(pow($rf,$pythExp)+pow($ra,$pythExp));
							break;
						default:
							$pythPct=pow($rf,$pythExp)/(pow($rf,$pythExp)+pow($ra,$pythExp));
							break;
					}
				}
				$pythW=round($g*$pythPct,0);
				$pythL=$g-$pythW;
				
				$teams[$tid]['rf']=$rf;
				$teams[$tid]['ra']=$ra;
				$teams[$tid]['g']=$g;
				$teams[$tid]['pythPct']=$pythPct;
				$teams[$tid]['pythW']=$pythW;
				$teams[$tid]['pythL']=$pythL;
				
				$teams[$tid]['expW']=($teams[$tid]['w']+$pythW)/2;
			}
		}
		
		##### Get Number of Scheduled Games #####
		$query="SELECT t1.team_id,t1.g+t2.g as g FROM (SELECT home_team as team_id,COUNT(DISTINCT game_id) as g FROM games WHERE game_type=0 AND league_id=$lgid AND games.date>='$seaStartDt' AND home_team!=0 GROUP BY home_team) as t1,(SELECT away_team as team_id,COUNT(DISTINCT game_id) as g FROM games WHERE game_type=0 AND league_id=$lgid AND games.date>='$seaStartDt' AND away_team!=0 GROUP BY away_team) as t2 WHERE t1.team_id=t2.team_id GROUP BY team_id;";
		if (isset($_GET['showq'])) {$text.="$query<br/>\n";}
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
		{
			while ($row=mysqli_fetch_array($result))
			{
				$tid=$row['team_id'];
				$teams[$tid]['schedG']=$row['g'];
				if ($teams[$tid]['schedG']==0) {$teams[$tid]['schedG']=$avgG;}
				
				if ((!isset($teams[$tid]['rf']))||($teams[$tid]['rf']=="")||($teams[$tid]['rf']==0))
				{
					$teams[$tid]['rf']=1;
					$teams[$tid]['ra']=1;
					$teams[$tid]['g']=$teams[$tid]['schedG'];
					$teams[$tid]['pythPct']=.500;
					$teams[$tid]['pythW']=$teams[$tid]['schedG']/2;
					$teams[$tid]['pythL']=$teams[$tid]['schedG']/2;
					
					$teams[$tid]['expW']=($teams[$tid]['w']+$teams[$tid]['pythW'])/2;
				}
			}
		}
		else
		{
			foreach ($teams as $tid => $val)
			{
				$teams[$tid]['schedG']=$avgG;
				if ((!isset($teams[$tid]['rf']))||($teams[$tid]['rf']=="")||($teams[$tid]['rf']==0))
				{
					$teams[$tid]['rf']=1;
					$teams[$tid]['ra']=1;
					$teams[$tid]['g']=$teams[$tid]['schedG'];
					$teams[$tid]['pythPct']=.500;
					$teams[$tid]['pythW']=$teams[$tid]['schedG']/2;
					$teams[$tid]['pythL']=$teams[$tid]['schedG']/2;
					
					$teams[$tid]['expW']=($teams[$tid]['w']+$teams[$tid]['pythW'])/2;
				}
			}
		}
		
		##### Get Notable Players From Last 3 Seasons (this is added when acquired) #####
		# Batters
		$batLim=ceil(2.5*$tCnt);
		$query="SELECT p.player_id,position,first_name,last_name,age,organization_id,league_level,lw,lw*(if(position=2,1.3,if(position=6,1.2,if(position=4,1.1,if(position=8,1.075,if(position=5,1.05,1))))))*(if(age>31,1+0.1*(31-age),if(age<27,1+0.05*(27-age),1))) lwVal FROM players as p,(SELECT player_id,SUM(lw) as lw,MIN(league_level) as league_level FROM (SELECT player_id,year,pcb.league_id,if(league_level=8,1,league_level) as league_level,(1/($lgyear-year))*if(league_level=8,.5,(1/league_level))*((0.47*(sum(h)-sum(d)-sum(t)-sum(hr))+.78*sum(d)+1.09*sum(t)+1.4*sum(hr)+.33*(sum(bb)-sum(hp))+.3*sum(sb)-.52*sum(cs)-.26*(sum(ab)-sum(h)-sum(gdp))-.72*sum(gdp))) as lw FROM players_career_batting_stats as pcb,leagues as l WHERE pcb.league_id=l.league_id AND split_id=1 AND year>=($lgyear-3) AND year!=$lgyear GROUP BY player_id,year,league_id) as t1 GROUP BY player_id) as x WHERE p.player_id=x.player_id ORDER BY lwVal DESC;";
		if (isset($_GET['showq'])) {$text.="$query<br/>\n";}
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
		{
			while ($row=mysqli_fetch_array($result))
			{
				$pid=$row['player_id'];
				$name=$row['first_name']." ".$row['last_name'];
				$pos=$row['position'];
				$lw=$row['lwVal']/17;
				
				if ($lw<1) {continue;}
				
				$players[$pid]['name']=$name;
				$players[$pid]['pos']=$pos;
				$players[$pid]['age']=$row['age'];
				$players[$pid]['level']=$row['league_level'];
				$players[$pid]['lwgain']=$lw;
				$players[$pid]['tid']=$row['organization_id'];
			}
		}
		# Starting Pitchers
		$spLim=ceil(2*$tCnt);
		$query="SELECT p.player_id,role,first_name,last_name,age,organization_id,league_level,lw,lw*(if(role=11,1.3,if(role=12,1,0.8)))*(if(age>31,1+0.1*(31-age),if(age<27,1+0.05*(27-age),1))) lwVal FROM players as p,(SELECT player_id,SUM(lw) as lw,MIN(league_level) as league_level FROM (SELECT player_id,year,pcb.league_id,if(league_level=8,1,league_level) as league_level,(1/($lgyear-year))*if(league_level=8,.5,(1/league_level))*(3*((SUM(ip)*3+SUM(ipf))/3)+4*sum(w)-4*sum(l)+5*sum(s)+sum(k)-2*sum(ha)-2*sum(bb)) as lw FROM players_career_pitching_stats as pcb,leagues as l WHERE pcb.league_id=l.league_id AND split_id=1 AND year>=($lgyear-3) AND year!=$lgyear GROUP BY player_id,year,league_id) as t1 GROUP BY player_id) as x WHERE p.player_id=x.player_id AND role=11 ORDER BY lwVal DESC;";
		if (isset($_GET['showq'])) {$text.="$query<br/>\n";}
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
		{
			while ($row=mysqli_fetch_array($result))
			{
				$pid=$row['player_id'];
				$name=$row['first_name']." ".$row['last_name'];
				$pos=$row['role'];
				$lw=$row['lwVal']/170;
				
				if ($lw<1) {continue;}
				
				$players[$pid]['name']=$name;
				$players[$pid]['pos']=$pos;
				$players[$pid]['age']=$row['age'];
				$players[$pid]['level']=$row['league_level'];
				$players[$pid]['lwgain']=$lw;
				$players[$pid]['tid']=$row['organization_id'];
			}
		}
		# Relief Pitchers
		$rpLim=ceil(1.5*$tCnt);
		$query="SELECT p.player_id,role,first_name,last_name,age,organization_id,league_level,lw,lw*(if(role=11,1.3,if(role=12,1,0.8)))*(if(age>31,1+0.1*(31-age),if(age<27,1+0.05*(27-age),1))) lwVal FROM players as p,(SELECT player_id,SUM(lw) as lw,MIN(league_level) as league_level FROM (SELECT player_id,year,pcb.league_id,if(league_level=8,1,league_level) as league_level,(1/($lgyear-year))*if(league_level=8,.5,(1/league_level))*(3*((SUM(ip)*3+SUM(ipf))/3)+4*sum(w)-4*sum(l)+5*sum(s)+sum(k)-2*sum(ha)-2*sum(bb)) as lw FROM players_career_pitching_stats as pcb,leagues as l WHERE pcb.league_id=l.league_id AND split_id=1 AND year>=($lgyear-3) AND year!=$lgyear GROUP BY player_id,year,league_id) as t1 GROUP BY player_id) as x WHERE p.player_id=x.player_id AND role!=11 ORDER BY lwVal DESC;";
		if (isset($_GET['showq'])) {$text.="$query<br/>\n";}
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
		{
			while ($row=mysqli_fetch_array($result))
			{
				$pid=$row['player_id'];
				$name=$row['first_name']." ".$row['last_name'];
				$pos=$row['role'];
				$lw=$row['lwVal']/170;
				
				if ($lw<1) {continue;}
				
				$players[$pid]['name']=$name;
				$players[$pid]['pos']=$pos;
				$players[$pid]['age']=$row['age'];
				$players[$pid]['level']=$row['league_level'];
				$players[$pid]['lwgain']=$lw;
				$players[$pid]['tid']=$row['organization_id'];
			}
		}
		
		##### Get Notable Players From Last Season (this is subtracted when lost) #####
		# Batters
		$batLim=ceil(2.5*$tCnt);
		$query="SELECT p.player_id,position,first_name,last_name,age,organization_id,lw,lw*(if(position=2,1.3,if(position=6,1.2,if(position=4,1.1,if(position=8,1.075,if(position=5,1.05,1))))))*(if(age>31,1+0.1*(31-age),if(age<27,1+0.05*(27-age),1))) lwVal FROM players as p,(SELECT player_id,SUM(lw) as lw FROM (SELECT player_id,year,pcb.league_id,league_level,(1/($lgyear-year))*if(league_level=8,.5,(1/league_level))*((0.47*(sum(h)-sum(d)-sum(t)-sum(hr))+.78*sum(d)+1.09*sum(t)+1.4*sum(hr)+.33*(sum(bb)-sum(hp))+.3*sum(sb)-.52*sum(cs)-.26*(sum(ab)-sum(h)-sum(gdp))-.72*sum(gdp))) as lw FROM players_career_batting_stats as pcb,leagues as l WHERE pcb.league_id=l.league_id AND pcb.league_id=$lgid AND split_id=1 AND year=($lgyear-1) GROUP BY player_id,year,league_id) as t1 GROUP BY player_id) as x WHERE p.player_id=x.player_id ORDER BY lwVal DESC;";
		if (isset($_GET['showq'])) {$text.="$query<br/>\n";}
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
		{
			while ($row=mysqli_fetch_array($result))
			{
				$pid=$row['player_id'];
				$name=$row['first_name']." ".$row['last_name'];
				$lw=$row['lwVal']/10;
				$pos=$row['position'];
				
				if ($lw<1) {continue;}
				
				$players[$pid]['name']=$name;
				$players[$pid]['lwloss']['total']=$lw;
				$players[$pid]['pos']=$pos;
				$players[$pid]['age']=$row['age'];
				$players[$pid]['tid']=$row['organization_id'];
			}
		}
		# Starting Pitchers
		$spLim=ceil(2*$tCnt);
		$query="SELECT p.player_id,role,first_name,last_name,age,organization_id,lw,lw*(if(role=11,1.3,if(role=12,1,0.8)))*(if(age>31,1+0.1*(31-age),if(age<27,1+0.05*(27-age),1))) lwVal FROM players as p,(SELECT player_id,SUM(lw) as lw FROM (SELECT player_id,year,pcb.league_id,league_level,(1/($lgyear-year))*if(league_level=8,.5,(1/league_level))*(3*((SUM(ip)*3+SUM(ipf))/3)+4*sum(w)-4*sum(l)+5*sum(s)+sum(k)-2*sum(ha)-2*sum(bb)) as lw FROM players_career_pitching_stats as pcb,leagues as l WHERE pcb.league_id=l.league_id AND pcb.league_id=$lgid AND split_id=1 AND year=($lgyear-1) GROUP BY player_id,year,league_id) as t1 GROUP BY player_id) as x WHERE p.player_id=x.player_id AND role=11 ORDER BY lwVal DESC;";
		if (isset($_GET['showq'])) {$text.="$query<br/>\n";}
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
		{
			while ($row=mysqli_fetch_array($result))
			{
				$pid=$row['player_id'];
				$name=$row['first_name']." ".$row['last_name'];
				$lw=$row['lwVal']/90;
				$pos=$row['role'];
				
				if ($lw<1) {continue;}
				
				$players[$pid]['name']=$name;
				$players[$pid]['lwloss']['total']=$lw;
				$players[$pid]['pos']=$pos;
				$players[$pid]['age']=$row['age'];
				$players[$pid]['tid']=$row['organization_id'];
			}
		}
		# Relief Pitchers
		$rpLim=ceil(1.5*$tCnt);
		$query="SELECT p.player_id,role,first_name,last_name,age,organization_id,lw,lw*(if(role=11,1.3,if(role=12,1,0.8)))*(if(age>31,1+0.1*(31-age),if(age<27,1+0.05*(27-age),1))) lwVal FROM players as p,(SELECT player_id,SUM(lw) as lw FROM (SELECT player_id,year,pcb.league_id,league_level,(1/($lgyear-year))*if(league_level=8,.5,(1/league_level))*(3*((SUM(ip)*3+SUM(ipf))/3)+4*sum(w)-4*sum(l)+5*sum(s)+sum(k)-2*sum(ha)-2*sum(bb)) as lw FROM players_career_pitching_stats as pcb,leagues as l WHERE pcb.league_id=l.league_id AND pcb.league_id=$lgid AND split_id=1 AND year=($lgyear-1) GROUP BY player_id,year,league_id) as t1 GROUP BY player_id) as x WHERE p.player_id=x.player_id AND role!=11 ORDER BY lwVal DESC;";
		if (isset($_GET['showq'])) {$text.="$query<br/>\n";}
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
		{
			while ($row=mysqli_fetch_array($result))
			{
				$pid=$row['player_id'];
				$name=$row['first_name']." ".$row['last_name'];
				$lw=$row['lwVal']/90;
				$pos=$row['role'];
				
				if ($lw<1) {continue;}
				
				$players[$pid]['name']=$name;
				$players[$pid]['lwloss']['total']=$lw;
				$players[$pid]['pos']=$pos;
				$players[$pid]['age']=$row['age'];
				$players[$pid]['tid']=$row['organization_id'];
			}
		}
		
		##### Generate Player Lists #####
		$bList="";
		$pList="";
		foreach ($players as $pid => $val)
		{
			$pos=$players[$pid]['pos'];
			if ($pos<=10) {$bList.=",$pid";}
			else {$pList.=",$pid";}
		}
		$bList=trim($bList,",");
		$pList=trim($pList,",");
		
		##### Get Percentage of Loss To Each Team #####
		# Batters
		$query="SELECT t1.player_id,team_id,g,pa,nTeams,paTot FROM (SELECT player_id,team_id,g,pa FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND player_id IN ($bList) AND year=".($lgyear-1).") as t1,
		(SELECT player_id,COUNT(DISTINCT team_id) as nTeams,SUM(pa) as paTot FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND player_id IN ($bList) AND year=".($lgyear-1)." GROUP BY player_id HAVING SUM(pa)>0) as t2 WHERE t1.player_id=t2.player_id ORDER BY nTeams DESC,player_id";
		if (isset($_GET['showq'])) {$text.="$query<br/>\n";}
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
		{
			while ($row=mysqli_fetch_array($result))
			{
				$pid=$row['player_id'];
				$tid=$row['team_id'];
				$ptRatio=$row['pa']/$row['paTot'];
				
				$lwloss=$ptRatio*$players[$pid]['lwloss']['total'];
				$players[$pid]['lwloss'][$tid]=$lwloss;
				
				$players[$pid]['teams'][$tid]=1;
				$players[$pid]['ptRatio'][$tid]=$ptRatio;
				$players[$pid]['nTeams']=$row['nTeams'];
				
				if ($lgid==$teams[$tid]['lgid']) {$players[$pid]['inLeague']=1;}

				if (($players[$pid]['level']>$pLgLevel)&&($players[$pid]['age']>25)) {unset($players[$pid]);}
			}
		}
		# Pitchers
		$query="SELECT t1.player_id,team_id,g,ip,nTeams,ipTot FROM (SELECT player_id,team_id,g,(ip+ipf/3) as ip FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND player_id IN ($pList) AND year=".($lgyear-1).") as t1,
		(SELECT player_id,COUNT(DISTINCT team_id) as nTeams,(SUM(ip)+SUM(ipf)/3) as ipTot FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND player_id IN ($pList) AND year=".($lgyear-1)." GROUP BY player_id HAVING (SUM(ip)+SUM(ipf)/3)>0) as t2 WHERE t1.player_id=t2.player_id ORDER BY nTeams DESC,player_id";
		if (isset($_GET['showq'])) {$text.="$query<br/>\n";}
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
		{
			while ($row=mysqli_fetch_array($result))
			{
				$pid=$row['player_id'];
				$tid=$row['team_id'];
				$ptRatio=$row['ip']/$row['ipTot'];
				
				$lwloss=$ptRatio*$players[$pid]['lwloss']['total'];
				$players[$pid]['lwloss'][$tid]=$lwloss;
				
				$players[$pid]['teams'][$tid]=1;
				$players[$pid]['ptRatio'][$tid]=$ptRatio;
				$players[$pid]['nTeams']=$row['nTeams'];
				
				if ($lgid==$teams[$tid]['lgid']) {$players[$pid]['inLeague']=1;}
				
				if (($players[$pid]['level']>$pLgLevel)&&($players[$pid]['age']>25)) {unset($players[$pid]);}
			}
		}
		
		##### Loop Through Notable Players #####
		foreach ($players as $pid => $val)
		{
			$tid=$players[$pid]['tid'];
			$lwgain=$players[$pid]['lwgain'];
			
			if (!isset($players[$pid]['teams'][$tid]))   ## Totally new addition
			{
				if ($players[$pid]['level']>$pLgLevel) 
				{
					$teams[$tid]['callups']=$teams[$tid]['callups'].",$pid";
					if ($lwgain<1.5) {continue;}
				}
				else
				{
					$teams[$tid]['adds']=$teams[$tid]['adds'].",$pid";
				}
				$teams[$tid]['expW']=$teams[$tid]['expW']+$lwgain;
				
				if (isset($players[$pid]['teams']))
				{
					foreach ($players[$pid]['teams'] as $oldTID => $val2)
					{					
						$teams[$oldTID]['expW']=$teams[$oldTID]['expW']-$players[$pid]['lwloss'][$oldTID];
						$teams[$oldTID]['losses']=$teams[$oldTID]['losses'].",$pid";
					}
				}
			}
			elseif ($players[$pid]['nTeams']>1)   ## Partial season last year
			{
				if (isset($players[$pid]['teams']))
				{
					$players[$pid]['partTime']=1;
					foreach ($players[$pid]['teams'] as $oldTID => $val2)
					{
						$ptRatio=$players[$pid]['ptRatio'][$oldTID];
						if ($oldTID==$tid) {$teams[$oldTID]['expW']=$teams[$oldTID]['expW']+($lwgain*(1-$players[$pid]['ptRatio'][$oldTID]));}
						else {$teams[$oldTID]['expW']=$teams[$oldTID]['expW']-$players[$pid]['lwloss'][$oldTID];}
						
						if (($ptRatio<.3)&&($oldTID==$tid))
						{
							$teams[$oldTID]['adds']=$teams[$oldTID]['adds'].",$pid";
						}
						elseif (($ptRatio>.7)&&($oldTID!=$tid))
						{
							$teams[$oldTID]['losses']=$teams[$oldTID]['losses'].",$pid";
						}
					}
				}
			}
			else   ## Returning player
			{
				$teams[$tid]['returns']=$teams[$tid]['returns'].",$pid";
			}
		}
		
		
		## Get projected record
		foreach ($teams as $tid => $val)
		{
			if (($tid=="")||($tid==0)) {continue;}
			if ($lgid!=$teams[$tid]['lgid'])
			{
				unset($teams[$tid]);
				continue;
			}
			$teams[$tid]['expW']=min($teams[$tid]['schedG'],$teams[$tid]['expW']);
			
			$slid=$teams[$tid]['slid'];
			$subleagues[$slid]['rawWtot']=$subleagues[$slid]['rawWtot']+$teams[$tid]['expW'];
			$subleagues[$slid]['maxWtot']=$subleagues[$slid]['maxWtot']+$teams[$tid]['schedG'];
		}	   
		## Normalize to number of games scheduled
		foreach ($teams as $tid => $val)
		{
			if (($tid=="")||($tid==0)) {continue;}
			$expW=$teams[$tid]['expW'];
			$slid=$teams[$tid]['slid'];
			$slTotW=$subleagues[$slid]['rawWtot'];
			$slMaxW=$subleagues[$slid]['maxWtot']/2;
			$slRatio=$slMaxW/$slTotW;
			
			$expW=$expW*$slRatio;
			$teams[$tid]['expW']=round($expW);
			
			$teams[$tid]['expL']=$teams[$tid]['schedG']-$teams[$tid]['expW'];
			$teams[$tid]['expPct']=$teams[$tid]['expW']/$teams[$tid]['schedG'];
			$tsort[$tid]=$teams[$tid]['expPct'];
		}
		arsort($tsort);
		
		##### Generate Projected Standings #####
		$prevSL=-1;
		$prevDiv=-1;
		$slCnt=0;
		$divCnt=0;
		foreach ($subleagues as $sl => $val)
		{
			foreach ($divisions as $div => $val2)
			{
				if ($sl!=$divisions[$div]['slid']) {continue;}
				
				$cls='s'.($rownum%2+1);
				if ($sl!=$prevSL)
				{
					if ($slCnt>0)
					{
						$text.="    </table>\n";
						$text.="   </td>\n";
						$text.="  </tr>\n";
						$text.=" </table>\n";
					}
					$text.=" <table class='textbox' cellspacing=0 cellpadding=2 class='lpo' width='100%' style='margin-top:12px;'>\n";
					$text.="  <tr class='title'>\n";
					$text.="   <td colspan=1>".$subleagues[$sl]['name']."</td>\n";
					$text.="  </tr>\n";
					$slCnt+=1;
				}
				
				if (($divCnt>0) && ($sl==$prevSL))
				{
					$text.="    </table>\n";
					$text.="   </td>\n";
					$text.="  </tr>\n";
				}
				$text.="  <tr>\n";
				$text.="   <td style='padding-top:12px;padding-left:12px;padding-right:12px;'>\n";
				$text.="    <table cellspacing=0 cellpadding=0 class='lpo' style='margin-bottom:12px;'>\n";
				$text.="     <tr class='title'>\n";
				$text.="      <td style='padding:2px;'>".$divisions[$div]['name']."</td>\n";
				$text.="     </tr>\n";
				$text.="     <tr><td>\n";
				$text.="      <table border=0 cellpadding=2 cellspacing=0 class='sortable' style='width:911px;'>\n";
				$text.="       <tr class='headline'>";
				$text.="<td class='hsc2_l'>Team</td>";
				$text.="<td class='hsc2'>Changes</td>";
				$text.="<td class='hsc2'>Proj W</td>";
				$text.="<td class='hsc2'>Proj L</td>";
				$text.="<td class='hsc2'>Proj Pct</td>";
				$text.="<td class='hsc2' title='Projected improvement from last year'>Proj Imp.</td>";
				$text.="<td class='hsc2'>".($lgyear-1).": W</td>";
				$text.="<td class='hsc2'>L</td>";
				$text.="<td class='hsc2'>Pct</td>";
				$text.="<td class='hsc2'>Pyth W</td>";
				$text.="<td class='hsc2'>Pyth L</td>";
				$text.="<td class='hsc2'>Pyth Pct</td>";
				$text.="</tr>\n";
				$divCnt+=1;
				
				$rownum=0;
				foreach ($tsort as $tid => $val3)
				{
					if ($sl!=$teams[$tid]['slid']) {continue;}
					if ($div!=$teams[$tid]['divID']) {continue;}
					
					if ($rownum==0) {$teams[$tid]['divWin']=1;}
										
					$cls='s'.($rownum%2+1);
					$text.="        <tr class='$cls'>";
					$text.="<td class='".$cls."_l'><a href='$lgpath/teams/team_$tid.html'>".$teams[$tid]['name']."</a></td>";
					$text.="<td><a href='#tid$tid'>+/- Report</a></td>";
					$text.= "<td>".$teams[$tid]['expW']."</td>";
					$text.= "<td>".$teams[$tid]['expL']."</td>";
					if ($teams[$tid]['expPct']>=1) {$winPctx=sprintf("%.3f",$teams[$tid]['expPct']);}
					else {$winPctx=strstr(sprintf("%.3f",$teams[$tid]['expPct']),".");}
					$text.="<td>".$winPctx."</td>";
					$text.= "<td sortable_customkey='".($teams[$tid]['expW']-$teams[$tid]['w'])."'>";
					if ($teams[$tid]['expW']>$teams[$tid]['w']) {$text.="+";}
					$text.=($teams[$tid]['expW']-$teams[$tid]['w'])."</td>";
					$text.= "<td>".$teams[$tid]['w']."</td>";
					$text.= "<td>".$teams[$tid]['l']."</td>";
					if ($teams[$tid]['pct']>=1) {$winPctx=sprintf("%.3f",$teams[$tid]['pct']);}
					else {$winPctx=strstr(sprintf("%.3f",$teams[$tid]['pct']),".");}
					$text.="<td>".$winPctx."</td>";
					$text.= "<td>".$teams[$tid]['pythW']."</td>";
					$text.= "<td>".$teams[$tid]['pythL']."</td>";
					if ($teams[$tid]['pythPct']>=1) {$winPctx=sprintf("%.3f",$teams[$tid]['pythPct']);}
					else {$winPctx=strstr(sprintf("%.3f",$teams[$tid]['pythPct']),".");}
					$text.="<td>".$winPctx."</td>";
					$text.="</tr>\n";
					$prevSL=$sl;
					$prevDiv=$div;
					$rownum++;
				}
				$text.="      </table>\n";
				$text.="     </td></tr>\n";
				
			}  ## End Division
			$text.="    </table>\n";
		}  ## End Sub League
		$text.="   </td>\n";
		$text.="  </tr>\n";
		$text.=" </table>\n";
		
		##### Get Playoff Structure #####
		$query="SELECT * FROM league_playoffs WHERE league_id=$lgid;";
		if (isset($_GET['showq'])) {echo "$query<br/>\n";}
		$result=mysqli_query($db,$query);
		$row=mysqli_fetch_array($result);
		$nRounds=$row['max_round'];
		for ($i=0;$i<$nRounds;$i++)
		{
			$fldName="best_of".$i;
			$poRounds[$i]['serLength']=$row[$fldName];
			$fldName="round_names".$i;
			$poRounds[$i]['serName']=$row[$fldName];
		}
		if ($nPOTeams=="")
		{
			$nPOTeams=pow(2,$nRounds);
		}
		
		## Seed Teams
		foreach ($subleagues as $slid => $val)
		{
			$subleagues[$slid]['wcCnt']=$nPOTeams-$subleagues[$slid]['divCnt'];
			$subleagues[$slid]['seed']=1;
		}
		foreach ($tsort as $tid => $val)
		{
			$slid=$teams[$tid]['slid'];
			$seed=$subleagues[$slid]['seed'];
			
			$divWin=$teams[$tid]['divWin'];
			
			if (($divWin==1)||($subleagues[$slid]['wcCnt']>0))
			{
				if ($seed==1) 
				{
					$subleagues[$slid]['champ']['tid']=$tid;
					$subleagues[$slid]['champ']['w']=$teams[$tid]['expW'];
				}
				$subleagues[$slid]['poSeed'][$seed]=$tid;
				$subleagues[$slid]['seed']=$subleagues[$slid]['seed']+1;
				if ($divWin!=1) {$subleagues[$slid]['wcCnt']=$subleagues[$slid]['wcCnt']-1;}
			}
		}
		
		## Start Display
		$text.="  <table class='textbox' border=0 cellpadding=2 cellspacing=0>\n";
		$text.="   <tr class='title'><td>Postseason</td></tr>\n";
		
		## Subleague Playoff Series Predictions
		for ($j=0;$j<($nRounds-1);$j++)
		{
			$nTeams=$nPOTeams/(pow(2,$j));
			$serLength=$poRounds[$j]['serLength'];
			$serName=$poRounds[$j]['serName'];
			
			## Start Series Sub-table
			$text.="   <tr><td style='padding:10px;'>\n";
			$text.="    <table class='lpo' border=0 cellpadding=2 cellspacing=0 style='width:917px;'>\n";
			$text.="     <tr class='title'><td colspan=2>".$serName."</td></tr>\n";
			$text.="     <tr class='headline'>\n";
			foreach ($subleagues as $slid => $val)
			{
				$text.="      <td class='hsc2' style='text-align:center;'>".$subleagues[$slid]['name']."</td>\n";
			}
			$text.="     </tr>\n";
			
			## Determine Results
			$cnt=1;
			for ($i=1;$i<=($nTeams/2);$i++)
			{
				$text.="     <tr>\n";
				$cls='s'.($cnt%2+1);
				foreach ($subleagues as $slid => $val)
				{
					## Get Teams
					$hid=$subleagues[$slid]['poSeed'][$i];
					$aseed=$nTeams-$i+1;
					$aid=$subleagues[$slid]['poSeed'][$aseed];

					$higherSeedWinPct=$teams[$hid]['expW']/$teams[$hid]['schedG'];
					$lowerSeedWinPct=$teams[$aid]['expW']/$teams[$aid]['schedG'];
					
					$higherSeedWinPct=$higherSeedWinPct+(($teams[$hid]['expW']-$teams[$aid]['expW'])*.015);
					$lowerSeedWinPct=$lowerSeedWinPct-(($teams[$hid]['expW']-$teams[$aid]['expW'])*.015);

					$winPct=log5WinPct($higherSeedWinPct,$lowerSeedWinPct);
					$winsNeeded=ceil($serLength/2);
					
					$serID=$hid."^".$aid;
					
					## Determine Games for Higher Seed to Win
					for ($k=$winsNeeded;$k<=$serLength;$k++)
					{
						$hWins=round($k*$winPct);
						if ($hWins==$winsNeeded)
						{
							$series[$serID]['totG']=$k;
							break;
						}
					}
					if (!isset($series[$serID]['totG'])) {$series[$serID]['totG']=$serLength;}
					
					$text.="      <td class='$cls' style='text-align:center;'>".$teams[$hid]['name']." over ".$teams[$aid]['name']." in ".$series[$serID]['totG']." games</td>\n";
				}
				$text.="     </tr>\n";
				$cnt++;
			}
			## Close Series Sub-table
			$text.="     </tr>\n";
			$text.="    </table>\n";
			$text.="   </td></tr>\n";
			
		}
		## Championship Playoff Series Prediction
		$j=$nRounds-1;
		$serLength=$poRounds[$j]['serLength'];
		$serName=$poRounds[$j]['serName'];
		## Start Series Sub-table
		$text.="   <tr><td style='padding:10px;'>\n";
		$text.="    <table class='lpo' border=0 cellpadding=2 cellspacing=0 style='width:917px;'>\n";
		$text.="     <tr class='title'><td colspan=2>".$serName."</td></tr>\n";
		$text.="     <tr class='hsc2'>\n";
		## Get Teams
		if (count($subleagues)==1)
		{
			$hid=$subleagues[0]['champ']['tid'];
			$aid=$subleagues[0]['poSeed'][2];
		}
		elseif ($subleagues[0]['champ']['w']>$subleagues[1]['champ']['w'])
		{
			$hid=$subleagues[0]['champ']['tid'];
			$aid=$subleagues[1]['champ']['tid'];
		}
		else
		{
			$hid=$subleagues[1]['champ']['tid'];
			$aid=$subleagues[0]['champ']['tid'];
		}
		$higherSeedWinPct=$teams[$hid]['expW']/$teams[$hid]['schedG'];
		$lowerSeedWinPct=$teams[$aid]['expW']/$teams[$aid]['schedG'];
		
		$higherSeedWinPct=$higherSeedWinPct+(($teams[$hid]['expW']-$teams[$aid]['expW'])*.015);
		$lowerSeedWinPct=$lowerSeedWinPct-(($teams[$hid]['expW']-$teams[$aid]['expW'])*.015);

		$winPct=log5WinPct($higherSeedWinPct,$lowerSeedWinPct);
		$winsNeeded=ceil($serLength/2);
		$serID=$hid."^".$aid;
		## Determine Games for Higher Seed to Win
		for ($i=$winsNeeded;$i<=$serLength;$i++)
		{
			$hWins=round($i*$winPct);
			if ($hWins==$winsNeeded)
			{
				$series[$serID]['totG']=$i;
				break;
			}
		}
		if (!isset($series[$serID]['totG'])) {$series[$serID]['totG']=$serLength;}
		$text.="      <td style='text-align:center;'>".$teams[$hid]['name']." over ".$teams[$aid]['name']." in ".$series[$serID]['totG']." games</td>\n";
		## Close Series Sub-table
		$text.="     </tr>\n";
		$text.="    </table>\n";
		$text.="   </td></tr>\n";
		## Close Postseason Predictions Table
		$text.="  </table>\n";
		
		
		##### Generate Team-by-Team Summaries #####
		foreach ($teams as $tid => $val)
		{
			if ($tid=="") {continue;}
			$text.=" <div class='textbox'>\n";
			$text.="  <table border=0 cellpadding=2 cellspacing=0 style='width:935px;'>\n";
			$text.="   <tr><td colspan=4 style='background-color:".$teams[$tid]['background_color_id'].";color:".$teams[$tid]['text_color_id'].";font-weight:bold;font-size:2em;'> <a href='$lgpath/teams/team_$tid.html' style='border:0;'><img src='$lgpath/images/team_logos/".str_replace(".png","_40.png",htmlentities($teams[$tid]['logo_file']))."' style='vertical-align:bottom;height:30px;width:30px;border-style:none;' /></a> <a name='tid$tid'></a> ".$teams[$tid]['name']."</td></tr>\n";
			$text.="   <tr>\n";
			$text.="    <td colspan=2>\n";
			$text.="     <table border=0 cellpadding=0 cellspacing=0 style='width:233px;'>\n";
			$text.="      <tr><td><b>Actual ".($lgyear-1)." Record:</b></td><td style='text-align:right;'>".$teams[$tid]['w']."-".$teams[$tid]['l']."</td></tr>\n";
			$text.="      <tr><td><b>Predicted $lgyear Record:</b></td><td style='text-align:right;'>".$teams[$tid]['expW']."-".$teams[$tid]['expL']."</td></tr>\n";
			$text.="      <tr><td><b>+/-:</b></td><td style='text-align:right;'>";
			if ($teams[$tid]['expW']>$teams[$tid]['w']) {$text.="+";}
			$text.=($teams[$tid]['expW']-$teams[$tid]['w'])." wins</td></tr>\n";
			$text.="     </table>\n";
			$text.="    </td>\n";
			$text.="    <td colspan=2>\n";
			$text.="     <table border=0 cellpadding=0 cellspacing=0 style='width:233px;'>\n";
			$text.="      <tr><td><b>".($lgyear-1)." Payroll:</b></td><td style='text-align:right;'>$".number_format($teams[$tid]['lastPayroll'],0,".",",")."</td></tr>\n";
			$text.="      <tr><td><b>$lgyear Payroll:</b></td><td style='text-align:right;'>$".number_format($teams[$tid]['thisPayroll'],0,".",",")."</td></tr>\n";
			$text.="      <tr><td><b>Payroll +/-:</b></td><td style='text-align:right;'>$".number_format($teams[$tid]['thisPayroll']-$teams[$tid]['lastPayroll'],0,".",",")."</td></tr>\n";
			$text.="     </table>\n";
			$text.="    </td>\n";
			$text.="   </tr>\n";
			$text.="   <tr class='headline'><td class='hsc2_l' style='width:233px;'>Key Holdovers</td><td class='hsc2_l' style='width:233px;'>Key Departures</td><td class='hsc2_l' style='width:233px;'>Key Additions</td><td class='hsc2_l'>Potential Key Call-Ups</td></tr>\n";
			$text.="   <tr>\n";
			$cnt=0;
			# Show Returnees
			$cls='s'.($cnt%2+1);
			$text.="<td class='".$cls."_l' style='vertical-align:top;'>";
			$pcnt=0;
			$teams[$tid]['returns']=trim($teams[$tid]['returns'],",");
			$e=explode(",",$teams[$tid]['returns']);
			unset($tPlayers);
			foreach ($e as $key => $pid)
			{
				$tPlayers[$pid]=1000*(20-$players[$pid]['pos'])+$players[$pid]['lwgain'];
			}
			arsort($tPlayers);
			$spCnt=0;
			$rpCnt=0;
			foreach ($tPlayers as $pid => $valp)
			{
				if ($pid=="") {$text.="None";continue;}
				$pos=$players[$pid]['pos'];
				if ($pos<11)
				{
					if (($players[$pid]['lwgain']<1.25)&&($players[$pid]['lwloss']['total']<1.25)) {continue;}
				}
				if ($pos==11) 
				{
					if (($players[$pid]['lwgain']<2)&&($players[$pid]['lwloss']['total']<2)) {continue;}
					if (($spCnt>4)&&($players[$pid]['lwgain']<2.5)) {continue;}
					$spCnt++;
				}
				if ($pos>11) 
				{
					if (($players[$pid]['lwgain']<2)&&($players[$pid]['lwloss']['total']<2)) {continue;}
					if (($rpCnt>4)&&($players[$pid]['lwgain']<2.5)) {continue;}
					$rpCnt++;
				}
				if ($pcnt>0) {$text.="<br/>";}
				$text.=get_pos($players[$pid]['pos'],1);
				$text.=" ";
				$text.="<a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>";
				if (isset($_GET['showPIDval'])) {$text.=" ".round($players[$pid]['lwgain'],2).":".round($players[$pid]['lwloss']['total'],2);}
				$pcnt++;
			}
			$text.="</td>\n";
			$cnt++;
			# Show Departures
			$cls='s'.($cnt%2+1);
			$text.="<td class='".$cls."_l' style='vertical-align:top;'>";
			$pcnt=0;
			$teams[$tid]['losses']=trim($teams[$tid]['losses'],",");
			$e=explode(",",$teams[$tid]['losses']);
			unset($tPlayers);
			foreach ($e as $key => $pid)
			{
				$tPlayers[$pid]=1000*(20-$players[$pid]['pos'])+$players[$pid]['lwgain'];
			}
			arsort($tPlayers);
			$spCnt=0;
			$rpCnt=0;
			foreach ($tPlayers as $pid => $valp)
			{
				if ($pid=="") {$text.="None";continue;}
				$pos=$players[$pid]['pos'];
				if ($pos==11) 
				{
					if (($spCnt>4)&&($players[$pid]['lwgain']<2.5)) {continue;}
					$spCnt++;
				}
				if ($pos>11) 
				{
					if (($rpCnt>4)&&($players[$pid]['lwgain']<2.5)) {continue;}
					$rpCnt++;
				}
				if ($pcnt>0) {$text.="<br/>";}
				$text.=get_pos($players[$pid]['pos'],1);
				$text.=" ";
				$text.="<a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>";
				if ($players[$pid]['partTime']==1) {$text.="<sup>~</sup>";}
				if (isset($_GET['showPIDval'])) {$text.=" ".round($players[$pid]['lwgain'],2).":".round($players[$pid]['lwloss']['total'],2);}
				$pcnt++;
			}
			$text.="</td>\n";
			$cnt++;
			# Show Additions
			$cls='s'.($cnt%2+1);
			$text.="<td class='".$cls."_l' style='vertical-align:top;'>";
			$pcnt=0;
			$teams[$tid]['adds']=trim($teams[$tid]['adds'],",");
			$e=explode(",",$teams[$tid]['adds']);
			unset($tPlayers);
			foreach ($e as $key => $pid)
			{
				$tPlayers[$pid]=1000*(20-$players[$pid]['pos'])+$players[$pid]['lwgain'];
			}
			arsort($tPlayers);
			$spCnt=0;
			$rpCnt=0;
			foreach ($tPlayers as $pid => $valp)
			{
				if ($pid=="") {$text.="None";continue;}
				$pos=$players[$pid]['pos'];
				if ($pos==11) 
				{
					if (($spCnt>4)&&($players[$pid]['lwgain']<2.5)) {continue;}
					$spCnt++;
				}
				if ($pos>11) 
				{
					if (($rpCnt>4)&&($players[$pid]['lwgain']<2.5)) {continue;}
					$rpCnt++;
				}
				if (($spCnt>4)&&($players[$pid]['lwgain']<2.5)) {continue;}
				if ($pcnt>0) {$text.="<br/>";}
				$text.=get_pos($players[$pid]['pos'],1);
				$text.=" ";
				if (isset($players[$pid]['inLeague'])) {$text.="<a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>";}
				else {$text.="<a href='$lgpath/players/player_$pid.html'>".$players[$pid]['name']."</a>";}
				if ($players[$pid]['partTime']==1) {$text.="<sup>~</sup>";}
				if (isset($_GET['showPIDval'])) {$text.=" ".round($players[$pid]['lwgain'],2).":".round($players[$pid]['lwloss']['total'],2);}
				$pcnt++;
			}
			$text.="</td>\n";
			$cnt++;
			# Show Callups
			$cls='s'.($cnt%2+1);
			$text.="<td class='".$cls."_l' style='vertical-align:top;'>";
			$pcnt=0;
			$teams[$tid]['callups']=trim($teams[$tid]['callups'],",");
			$e=explode(",",$teams[$tid]['callups']);
			unset($tPlayers);
			foreach ($e as $key => $pid)
			{
				$tPlayers[$pid]=1000*(20-$players[$pid]['pos'])+$players[$pid]['lwgain'];
			}
			arsort($tPlayers);
			$spCnt=0;
			$rpCnt=0;
			foreach ($tPlayers as $pid => $valp)
			{
				if ($pid=="") {$text.="None";continue;}
				$pos=$players[$pid]['pos'];
				if ($pos==11) 
				{
					if (($spCnt>4)&&($players[$pid]['lwgain']<2.5)) {continue;}
					$spCnt++;
				}
				if ($pos>11) 
				{
					if (($rpCnt>4)&&($players[$pid]['lwgain']<2.5)) {continue;}
					$rpCnt++;
				}
				if (($spCnt>4)&&($players[$pid]['lwgain']<2.5)) {continue;}
				if ($pcnt>0) {$text.="<br/>";}
				$text.=get_pos($players[$pid]['pos'],1);
				$text.=" ";
				if (isset($players[$pid]['inLeague'])) {$text.="<a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>";}
				else {$text.="<a href='$lgpath/players/player_$pid.html'>".$players[$pid]['name']."</a>";}
				if ($players[$pid]['partTime']==1) {$text.="<sup>~</sup>";}
				if (isset($_GET['showPIDval'])) {$text.=" ".round($players[$pid]['lwgain'],2).":".round($players[$pid]['lwloss']['total'],2);}
				$pcnt++;
			}
			$text.="</td>\n";
			
			$text.="   </tr>\n";
			$text.="  </table>\n";
			$text.=" </div>\n";
		}
		
		## Legend
		$text.=" <div class='textbox' style='border:none;'>\n";
		$text.="  <b>Legend</b><br/>\n";
		$text.="  ~ - Played partial season with team in ".($lgyear-1)."<br/>\n";
		$text.=" </div>\n";
		
		return $text;
	}

	?>
