<?php
  include("html_functions.php");

  ################## PAGE INITIALIZATION #########################
  $lgid=$_SESSION['lgid'];
  $lgpath=$_SESSION['lgpath'];
  $date=new Date($_SESSION['lgdate']);
  $lgyear=$_SESSION['lgyear'];

  if (($_SESSION['user_team_id']>0)&&(!isset($_GET['team_id'])))
  {
	  if ($_SESSION['user_league_id']==$lgid) {$team_id=$_SESSION['user_team_id'];}
	  else
	  {
		  include($_SESSION['adminpath']."/dbopen.php");
		  $query="SELECT team_id FROM teams WHERE parent_team_id=".$_SESSION['user_team_id']." AND league_id=$lgid";
		  $result=mysqli_query($db,$query);
		  if (mysqli_num_rows($result))
		  {
			  $row=mysqli_fetch_array($result);
			  $team_id=$row['team_id'];
		  }
		  mysqli_close($db);
	  }
  }
  elseif (isset($_GET['team_id'])) {$team_id=$_GET['team_id'];}
  if ($team_id=="") {$team_id=-1;}
  $tyear=$_GET['year'];

  if (($tyear==0)||($tyear=="")) {header("Location: ./team_hist.php?team_id=$team_id");}

	  
  ##### Get Team Names #####
  include($_SESSION['adminpath']."/dbopen.php");
  $query="SELECT team_id,name,nickname FROM teams WHERE league_id=$lgid";
  if ($team_id>0) {$query.=" AND team_id=$team_id";}
  $query.=" AND allstar_team=0 ORDER BY name,nickname LIMIT 1;";
  $result=mysqli_query($db,$query);
  while ($row=mysqli_fetch_array($result))
  {
	  $team_id=$row['team_id'];
	  $tname=$row['name']." ".$row['nickname'];
  }
  mysqli_close($db);
  
  ##### Get Title #####
  $title=$tname." History - $tyear Summary";
  page_head($title,$_SESSION['lgpath'],"","","./jquery/excanvas.js|./jquery/jquery.min.js|./jquery/jquery.jqplot.min.js|./jquery/plugins/jqplot.categoryAxisRenderer.min.js|./jquery/plugins/jqplot.pointLabels.min.js|./jquery/plugins/jqplot.barRenderer.min.js|./jquery/plugins/jqplot.highlighter.min.js|./jquery/plugins/jqplot.cursor.min.js");
  echo " <div id='topbar'>\n";
  main_titlebar($lgid,$_SESSION['lgpath'],$title,$team_id);
  nav_toolbar("history","History");
  nav_toolbar("teams","Teams","","",$team_id,$tyear);

  ##### Show Page Content #####
  echo " </div>   <!-- END topbar DIV -->\n";

  echo " <div id='contentpane'>\n";

  ##### Check for file #####
  echo gen_year($team_id,$tyear);

  ################## END OF PAGE #########################
  echo " </div>   <!-- END contentpane DIV -->\n";
  page_foot($_SESSION['lgpath']);

  exit;

##############################################################################################
# gen_year - Year Summary
##############################################################################################
function gen_year($tid="",$year="")
 {
   ##### Exit if no team_id #####
   if (($tid=="")||($year=="")) {exit;}
   include($_SESSION['adminpath']."/dbopen.php");

   ##### Check for tables #####
   $query="SHOW TABLES LIKE 'team_history%';";
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result)<5) {return "Please load the team_history SQL tables first";}

   ##### Get basic parameters #####
   $date=new Date($_SESSION['lgdate']);
   $thisYear=$_SESSION['lgyear'];
   $lgpath=$_SESSION['lgpath'];
   $lgid=$_GET['lgid'];
   if ($lgid=="") {$lgid=$_SESSION['lgid'];}
   if ($lgid=="") {$lgid=100;}
   $text="";
	 
	 ##### Get League Abbr #####
	 $query="SELECT abbr FROM leagues WHERE league_id=$lgid;";
	 $result=mysqli_query($db,$query);
	 $row=mysqli_fetch_array($result);
	 $lgAbbr=$row['abbr'];
	 
	 ##### Get Subleague #####
     $query="SELECT team_id,t.sub_league_id,sl.abbr FROM ";
	 if ($year==$thisYear) {$query.="teams";} else {$query.="team_history";}
	 $query.=" as t,sub_leagues as sl WHERE t.sub_league_id=sl.sub_league_id AND t.league_id=sl.league_id AND t.league_id=$lgid";
	 if ($year==$thisYear) {$query.=" AND allstar_team=0;";} else {$query.=" AND year=$year";}
	 $result=mysqli_query($db,$query);
	 while ($row=mysqli_fetch_array($result))
	 {
		 $team_id=$row['team_id'];
		 $slID=$row['sub_league_id'];
		 if ($team_id==$tid) {$slAbbr=$row['abbr'];$tmSLid=$slID;}
		 $subleagues[$slID]['teamList']=$subleagues[$slID]['teamList'].",".$team_id;
	 }
	 $teamList=trim($subleagues[$tmSLid]['teamList'],",");
	 
   ##### Get OPS+/ERA+ #####
   $query="SHOW TABLES LIKE 'park_factors';";
   $result=mysqli_query($db,$query);
   if (!mysqli_num_rows($result)) {$noPSM=1;}
   else
   {
	   ##ERA+
	   $query="SELECT y1.player_id,y1.team_id,y1.year,y1.ip,y1.era,y2.sub_league_id,y2.rpf,y2.lgERA,if(((y1.ip=0) OR (y1.era=0)),0,100*rpf*y2.lgERA/y1.era) as eraPlus,rpfAdj FROM (SELECT player_id,team_id,year,SUM(ip)+SUM(ipf)/3 as ip,if(SUM(ip)+SUM(ipf)/3=0,0,9*SUM(er)/(SUM(ip)+SUM(ipf)/3)) as era FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND team_id=$tid AND year=$year GROUP BY player_id,team_id,year ORDER BY player_id,year,team_id) as y1,(SELECT t1.team_id,lg1.sub_league_id,t1.year,if(rpf IS NULL,1,rpf) as rpf,if(rpf IS NULL,0,1) as rpfAdj,era as lgERA FROM (SELECT t.team_id,t.year,sub_league_id,rpf FROM team_history as t LEFT JOIN park_factors as pf ON t.team_id=pf.team_id AND t.league_id=pf.league_id AND t.year=pf.year WHERE t.league_id=$lgid UNION SELECT t.team_id,'$thisYear' as year,sub_league_id,rpf FROM teams as t LEFT JOIN park_factors as pf ON t.team_id=pf.team_id AND t.league_id=pf.league_id WHERE t.league_id=$lgid AND pf.year=$thisYear) as t1,(SELECT sub_league_id,year,if(SUM(ip)+SUM(ipf)/3=0,0,9*SUM(er)/(SUM(ip)+SUM(ipf)/3)) as era FROM team_history_pitching_stats WHERE league_id=$lgid GROUP BY sub_league_id,year UNION SELECT tr.sub_league_id,'$thisYear' as year,if(SUM(ip)+SUM(ipf)/3=0,0,9*SUM(er)/(SUM(ip)+SUM(ipf)/3)) as era FROM team_pitching_stats as tps,team_relations as tr WHERE tps.team_id=tr.team_id AND tps.league_id=$lgid GROUP BY sub_league_id) as lg1 WHERE t1.sub_league_id=lg1.sub_league_id AND t1.year=lg1.year) as y2 WHERE y1.team_id=y2.team_id AND y1.year=y2.year";
     	   $result=mysqli_query($db,$query);
	   if (mysqli_num_rows($result))
    	   {
		   while ($row=mysqli_fetch_array($result))
	 	   {
			   $pid=$row['player_id'];
	       		   $players[$pid]['eraPlus']=$row['eraPlus'];
		   }
	   }
	   ##OPS+
	   $query="SELECT y1.player_id,y1.team_id,y1.year,y1.pa,y1.obp,y1.slg,y2.sub_league_id,y2.rpf,y2.lgOBP,y2.lgSLG,if(y1.pa=0,0,100 * (y1.obp/(y2.lgOBP*rpf) + y1.slg/(y2.lgSLG*rpf) - 1)) as opsPlus,rpfAdj FROM (SELECT player_id,team_id,year,SUM(pa) as pa,if((SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))=0,0,(SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))) as obp,if (SUM(ab)=0,0,(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab)) as slg FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND team_id=$tid AND year=$year GROUP BY player_id,team_id,year) as y1,(SELECT t1.team_id,lg1.sub_league_id,t1.year,if(rpf IS NULL,1,rpf) as rpf,obp as lgOBP,slg as lgSLG,if(rpf IS NULL,0,1) as rpfAdj FROM (SELECT t.team_id,t.year,sub_league_id,rpf FROM team_history as t LEFT JOIN park_factors as pf ON t.team_id=pf.team_id AND t.league_id=pf.league_id AND t.year=pf.year WHERE t.league_id=$lgid UNION SELECT t.team_id,'$thisYear' as year,sub_league_id,rpf FROM teams as t LEFT JOIN park_factors as pf ON t.team_id=pf.team_id AND t.league_id=pf.league_id WHERE t.league_id=$lgid AND pf.year=$thisYear) as t1,(SELECT sub_league_id,year,if((SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))=0,0,(SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))) as obp,if (SUM(ab)=0,0,(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab)) as slg FROM team_history_batting_stats WHERE league_id=$lgid GROUP BY sub_league_id,year UNION SELECT tr.sub_league_id,'$thisYear' as year,if((SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))=0,0,(SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))) as obp,if (SUM(ab)=0,0,(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab)) as slg FROM team_batting_stats as tps,team_relations as tr WHERE tps.team_id=tr.team_id AND tps.league_id=$lgid GROUP BY sub_league_id) as lg1 WHERE t1.sub_league_id=lg1.sub_league_id AND t1.year=lg1.year) as y2 WHERE y1.team_id=y2.team_id AND y1.year=y2.year";
     	   $result=mysqli_query($db,$query);
	   if (mysqli_num_rows($result))
    	   {
		   while ($row=mysqli_fetch_array($result))
	 	   {
			   $pid=$row['player_id'];
	       		   $players[$pid]['opsPlus']=$row['opsPlus'];
		   }
    	   }
   }

   ##### Check for Win Shares #####
   $query="SHOW TABLES LIKE 'players_win_shares';";
   $result=mysqli_query($db,$query);
   if (!mysqli_num_rows($result)) {$noWS=1;}
    else
    {
      $query="SELECT player_id,ows,fws2,fws3,fws4,fws5,fws6,fws7,fws8,fws9,fwsTot,pws FROM players_win_shares WHERE team_id=$tid AND year=$year;";
      $result=mysqli_query($db,$query);
      if (mysqli_num_rows($result))
       {
         while ($row=mysqli_fetch_array($result))
 	  {
	    $pid=$row['player_id'];
	    $players[$pid]['ows']=$row['ows'];
	    for ($i=2;$i<=9;$i++) {$ind="fws".$i;$players[$pid][$ind]=$row[$ind];}
	    $players[$pid]['fwsTot']=$row['fwsTot'];
	    $players[$pid]['pws']=$row['pws'];
	  }
       }
       else {$noWS=1;}
    }

   ##### 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 ('pythMeth','pythExp')";
	   $result=mysqli_query($db,$query);
 	   if (mysqli_num_rows($result))
	   {
 		   while ($row=mysqli_fetch_array($result))
		   {
 			   $setting=$row['setting'];
			   $val=$row['value'];

			   switch ($setting)
 			   {
			   case 'pythMeth'     : $pythMeth=$val;     break;
			   case 'pythExp'      : $pythExp=$val;      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 ($pythExp=="") {$pythExp=1.82;}

   ##### Get Run Differential #####
   if ($thisYear!=$year) {$query="SELECT thb.year, 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.team_id=thp.team_id AND thb.team_id=$tid AND thb.year=$year;";}
   else {$query="SELECT '$thisYear' as year, tbs.r AS rf, tps.r AS ra,tps.gs as g,tbs.ab as ab,tbs.h as h,(tps.ip*3+tps.ipf)/3 as ip,tps.er as er FROM team_batting_stats AS tbs, team_pitching_stats AS tps WHERE tbs.team_id=tps.team_id AND tbs.team_id=$tid;";}
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result))
    {
      while ($row=mysqli_fetch_array($result))
       {
         $yr=$row['year'];
	 $rf=$row['rf'];
	 $ra=$row['ra'];
	 $g=$row['g'];
    
	 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;
	  }
	 $years[$yr]['pythPct']=$pythPct;
	 $pythW=round($g*$pythPct,0);
	 $pythL=$g-$pythW;
	 $years[$yr]['pythW']=$pythW;
	 $years[$yr]['pythL']=$pythL;

	 $TpythW+=$pythW;
	 $TpythL+=$pythL;

	 $ab=$row['ab'];
	 $h=$row['h'];
	 $ip=$row['ip'];
	 $er=$row['er'];

	 if ($ab==0) {$avg=0;} else {$avg=$h/$ab;}
         if ($ip==0) {$era=0;} else {$era=(9*$er)/$ip;}
	 $avg=sprintf("%.3f",$avg);
         if ($avg<1) {$avg=strstr($avg,".");}
	 $era=sprintf("%.2f",$era);

	 $years[$yr]['avg']=$avg;
	 $years[$yr]['era']=$era;
       }
    }

   ##### Get Team Record #####
   if ($thisYear!=$year) {$query="SELECT thr.year,g,w,l,pos,gb,made_playoffs,won_playoffs,name,nickname FROM team_history_record as thr,team_history as th WHERE thr.team_id=th.team_id AND thr.year=th.year AND thr.team_id=$tid AND thr.year=$year;";}
   else {$query="SELECT '$thisYear' as year,g,w,l,pos,gb,NULL,NULL,name,nickname FROM team_record as tr,teams as t WHERE tr.team_id=t.team_id AND tr.team_id=$tid;";}
   $result=mysqli_query($db,$query);
   while ($row=mysqli_fetch_array($result))
    {
      $yr=$row['year'];
      $g=$row['g'];
      $l=$row['l'];
      $w=$row['w'];
      $pos=$row['pos'];
      $gb=$row['gb'];
      $poff=$row['made_playoffs'];
      $wsWin=$row['won_playoffs'];
      $name=$row['name']." ".$row['nickname'];

      if ($g==0) {$wpct=0;} else {$wpct=$w/$g;}
      $wpct=sprintf("%.3f",$wpct);
      if ($wpct<1) {$wpct=strstr($wpct,".");}

      if ($poff==0) {$poff="";} else {$poff="X";}
      if ($wsWin==0) {$wsWin="";} else {$wsWin="X";}
	      
      $years[$yr]['w']=$w;
      $years[$yr]['l']=$l;
      $years[$yr]['wpct']=$wpct;
      $years[$yr]['gb']=$gb;
      $years[$yr]['pos']=$pos;
      $years[$yr]['poff']=$poff;
      $years[$yr]['wsWin']=$wsWin;
      $years[$yr]['name']=$name;

      $TeamGames=$g;
    }

   ##### Get Team Financials #####
   if ($thisYear!=$year) {$query="SELECT year,attendance,player_expenses,player_expenses+staff_expenses+stadium_expenses as expenses,gate_revenue+media_revenue+merchandising_revenue+season_ticket_revenue+playoff_revenue as revenue FROM team_history_financials WHERE team_id=$tid AND year=$year;";}
   else {$query="SELECT '$year' as year,attendance,player_expenses,player_expenses+staff_expenses+stadium_expenses as expenses,gate_revenue+media_revenue+merchandising_revenue+season_ticket_revenue+playoff_revenue as revenue FROM team_financials WHERE team_id=$tid;";}
   $result=mysqli_query($db,$query);
   if ($_GET['showq']==1) {echo $query;}
   if (mysqli_num_rows($result))
    {
      while ($row=mysqli_fetch_array($result))
       {
         $yr=$row['year'];
	 $att=$row['attendance'];
	 $payroll=$row['player_expenses'];
	 $expenses=$row['expenses'];
	 $revenue=$row['revenue'];
	 $net=$revenue-$expenses;

	 $years[$yr]['attendance']=$att;
	 $years[$yr]['payroll']=$expenses;
	 $years[$yr]['revenue']=$revenue;
       }
    }

   ##### Display Results #####
   $text.="<div class='textbox'>\n";
   $text.=" <table cellpadding=0 cellspacing=0 border=0 width='935px'>\n";
   $text.="  <tr class='title'><td style='padding:2px;'>Team Results</td></tr>\n";
   $text.="  <tr><td>\n";
   $text.="   <table cellpadding=2 cellspacing=0 border=0 class='sortable' width='100%'>\n";
   $text.="    <thead><tr class='headline'><td class='hsc2_l'>Year</td><td class='hsc2'>W</td><td class='hsc2'>L</td><td class='hsc2'>WPct</td><td class='hsc2'>Finish</td><td class='hsc2'>GB</td><td class='hsc2'>Exp Rec</td><td class='hsc2'>Diff</td><td class='hsc2'>Avg</td><td class='hsc2'>ERA</td><td class='hsc2'>Playoffs</td><td class='hsc2'>Champion</td><td class='hsc2'>Attendance</td><td class='hsc2'>Expenses</td><td class='hsc2'>Revenue</td>";
   $text.="</tr></thead>\n";

   $nYrs=count($years);
   $cnt=0;
   foreach ($years as $yr => $val)
    {
      $cls='s'.($cnt%2+1);
      $gb=$years[$yr]['gb'];
      if ($gb==0) {$gb="-";}
      $pos=$years[$yr]['pos'];
      $pythDiff=$years[$yr]['w']-$years[$yr]['pythW'];
      $TpythDiff+=$pythDiff;

      $text.="    <tr class='$cls'>";
      $text.="<td class='".$cls."_l'><a href='./team_summary.php?team_id=$tid&year=$yr'>$yr $name</a></td>";
      $text.="<td>".$years[$yr]['w']."</td>";
      $text.="<td>".$years[$yr]['l']."</td>";
      $text.="<td>".$years[$yr]['wpct']."</td>";
      $text.="<td>".ordinal_suffix($pos,1)."</td>";
      $text.="<td>".$gb."</td>";
      $text.="<td>".$years[$yr]['pythW']."-".$years[$yr]['pythL']."</td>";
      $text.="<td>".$pythDiff."</td>";
      $text.="<td>".$years[$yr]['avg']."</td>";
      $text.="<td>".$years[$yr]['era']."</td>";
      $text.="<td>".$years[$yr]['poff']."</td>";
      $text.="<td>".$years[$yr]['wsWin']."</td>";
      $text.="<td>".number_format($years[$yr]['attendance'])."</td>";
      $text.="<td>$".number_format($years[$yr]['payroll'])."</td>";
      $text.="<td>$".number_format($years[$yr]['revenue'])."</td>";
      $text.="</tr>\n";
      $cnt++;
    }
   $text.="   </table>\n";
   $text.="  </td></tr>\n";
   $text.=" </table>\n";
   $text.="</div>\n";

   ##### Get Award Info #####
   $query="SELECT mvp_award_name,pitcher_award_name,rookie_award_name,defense_award_name FROM leagues as l,teams as t WHERE t.league_id=l.league_id AND t.team_id=$tid;";
   $result=mysqli_query($db,$query);
   $row=mysqli_fetch_array($result);
   $awardName['boy']=$row['mvp_award_name'];
   $awardName['poy']=$row['pitcher_award_name'];
   $awardName['roy']=$row['rookie_award_name'];
   $awardName['gg']=$row['defense_award_name'];

   ##### Get Awards #####
   $query="SELECT pa.player_id,first_name,last_name,award_id,pa.position,month FROM (";
   $query.="(SELECT best_pitcher_id as player_id,award_id,position,month FROM league_history as lh,players_awards as pa WHERE lh.year=pa.season AND pa.team_id=$tid AND season=$year AND lh.best_pitcher_id=pa.player_id AND award_id=4)";
   $query.=" UNION (SELECT best_hitter_id as player_id,award_id,position,month FROM league_history as lh,players_awards as pa WHERE lh.year=pa.season AND pa.team_id=$tid AND season=$year AND lh.best_hitter_id=pa.player_id AND award_id=5)";
   $query.=" UNION (SELECT best_rookie_id as player_id,award_id,position,month FROM league_history as lh,players_awards as pa WHERE lh.year=pa.season AND pa.team_id=$tid AND season=$year AND lh.best_rookie_id=pa.player_id AND award_id=6)";
   $query.=" UNION (SELECT player_id,award_id,position,month FROM players_awards WHERE team_id=$tid AND season=$year AND award_id IN (7,9))";
   $query.=") as pa,players as p WHERE pa.player_id=p.player_id ORDER BY award_id,position,last_name,first_name;";
   $query2="SELECT pa.player_id,first_name,last_name,if(award_id=0,100,award_id) as award_id,pa.position,month,day FROM players_awards as pa,players as p,teams as t WHERE pa.player_id=p.player_id AND pa.team_id=t.team_id AND t.league_id=pa.league_id AND pa.team_id=$tid AND season=$year AND award_id IN (0,1,2,3) ORDER BY award_id,year,month,day,position,last_name,first_name;";
   $result=mysqli_query($db,$query);
   if ($_GET['showq']==1) {echo $query;}
   $result2=mysqli_query($db,$query2);
   if (mysqli_num_rows($result)||mysqli_num_rows($result2))
    {
      $text.="<div class='textbox'>\n";
      $text.=" <table cellpadding=0 cellspacing=0 border=0 width='935px'>\n";
      $text.="  <tr class='title'><td style='padding:2px;'>Award Winners</td></tr>\n";
      $text.="  <tr><td>\n";
      $text.="   <table cellpadding=2 cellspacing=0 border=0 width='100%'>\n";
      $text.="    <tr class='headline'><td class='hsc2_l'>Award</td><td class='hsc2_l'>Players</td><td class='hsc2_l'>Qty</td></tr>\n";
    }
   if (mysqli_num_rows($result))
    {
      $prevAW=-1;
      $rcnt=-1;
      while ($row=mysqli_fetch_array($result))
       {
         $awid=$row['award_id'];
         if ($awid==100) {$awid=0;}
         $pid=$row['player_id'];
	 $name=$row['first_name']." ".$row['last_name'];
	 $pos=$row['position'];
	 $month=$row['month'];
         if ($prevAW!=$awid)
 	  {
            if ($rcnt>-1) {$text.="<td>$acnt</td></td></tr>";}
	    $acnt=0;
            $rcnt++;
	    $cls='s'.($rcnt%2+1);
	    switch ($awid)
	     {
	       case 4: $awName=$awardName['poy']; break;
	       case 5: $awName=$awardName['boy']; break;
	       case 6: $awName=$awardName['roy']; break;
	       case 7: $awName=$awardName['gg']; break;
	       default: $awName=get_award($awid); break;
	     }
	    $text.="    <tr class='".$cls."_l'><td>$awName</td><td>";
	  }
         if ($acnt>0) {$text.=", ";}
         $text.="<a href='./player.php?player_id=$pid'>$name</a>";
         if (($pos!="")&&($pos!=0)) {$text.=" (".get_pos($pos,1).")";}
	 $acnt++;
	 $prevAW=$awid;
       }
      $text.="<td>$acnt</td></td></tr>\n";
    }
   if (mysqli_num_rows($result2))
    {
      $prevAW=-1;
      $prevPID=-1;
      while ($row=mysqli_fetch_array($result2))
       {
         $awid=$row['award_id'];
         if ($awid==100) {$awid=0;}
         $pid=$row['player_id'];
	 $name=$row['first_name']." ".$row['last_name'];
	 $pos=$row['position'];
	 $month=$row['month'];
	 $day=$row['day'];
         if ($prevAW!=$awid)
 	  {
            if (($rcnt>-1)&&($prevAW!=-1)) 
	     {
               if (($awid==0)||($awid==1)||($awid==2)||($awid==3)) {$text.=")";}
	       $text.="<td>$acnt</td></td></tr>";
	     }
	    $acnt=0;
            $prevPID=-1;
            $rcnt++;
	    $cls='s'.($rcnt%2+1);
	    switch ($awid)
	     {
	       case 4: $awName=$awardName['poy']; break;
	       case 5: $awName=$awardName['boy']; break;
	       case 6: $awName=$awardName['roy']; break;
	       case 7: $awName=$awardName['gg']; break;
	       default: $awName=get_award($awid); break;
	     }
	    $text.="    <tr class='".$cls."_l'><td>$awName</td><td>";
          }
	 if ($prevPID!=$pid)
 	  {
	    if ($acnt>0) 
	     {
               if (($awid==0)||($awid==1)||($awid==2)||($awid==3)) {$text.=")";}
	       $text.=", ";
	     }
	    $text.="<a href='./player.php?player_id=$pid'>$name</a>";
            if (($pos!="")&&($pos!=0)) {$text.=" (".get_pos($pos,1).")";}
	  }
	 switch ($awid)
	  {
	    case 0: 
              if ($prevPID!=$pid) {$text.=" (";} else {$text.=", ";}
	      $text.=date("M j",mktime(0,0,0,$month,$day));
	      break;
            case 1:
            case 2:
	    case 3: 
              if ($prevPID!=$pid) {$text.=" (";} else {$text.=", ";}
	      $text.=date("M",mktime(0,0,0,$month-1));
	      break;
	  }
	 $acnt++;
	 $prevAW=$awid;
	 $prevPID=$pid;
       }
      if (($awid==0)||($awid==1)||($awid==2)||($awid==3)) {$text.=")";}
      $text.="<td>$acnt</td></td></tr>\n";
    }
   if (mysqli_num_rows($result)||mysqli_num_rows($result2))
   {
      $text.="   </table>\n";
      $text.="  </td></tr>\n";
      $text.=" </table>\n";
      $text.="</div>\n";      
    }

   ##### Get Fielding Stats #####
   $query="SELECT pcf.player_id,first_name,last_name,pcf.position,(ip*3+ipf)/3 as ip,g,gs,po,a,e,dp,tc,zr,pb,sba,rto FROM players_career_fielding_stats as pcf,players as p WHERE pcf.player_id=p.player_id AND pcf.team_id=$tid AND pcf.year=$year ORDER BY position,ip DESC;";
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result))
    {
      while ($row=mysqli_fetch_array($result))
       {
         $pid=$row['player_id'];
         $pos=$row['position'];
	 $name=$row['first_name']." ".$row['last_name'];
   	 $players[$pid]['name']=$name;
   	 $players[$pid]['shortname']=$row['first_name'][0].". ".$row['last_name'];
	 $g=$row['g'];
	 $gs=$row['gs'];
	 $po=$row['po'];
	 $a=$row['a'];
	 $dp=$row['dp'];
	 $tc=$row['tc'];
	 $e=$row['e'];
	 $ip=$row['ip'];
	 $zr=$row['zr'];
	 $pb=$row['pb'];
	 $sba=$row['sba'];
	 $rto=$row['rto'];
	
	 if ($tc==0) {$fpct=0;}
	 else {$fpct=($po+$a)/$tc;}
	 if ($ip==0) {$rng=0;}
	 else {$rng=($po+$a)/($ip/9);}
	 if ($sba==0) {$csPct=0;}
  	 else {$csPct=$rto/$sba;}
	   
	 $fpct=sprintf("%0.3f",$fpct);
	 if ($fpct<1) {$fpct=substr($fpct,1);}
	 $rng=sprintf("%0.2f",$rng);
	 $csPct=sprintf("%0.1f",100*$csPct);

	 $maxFIP=$players[$pid]['maxFIP'];
	 $maxFG=$players[$pid]['maxFG'];
	 if (($maxFIP<$ip)&&($pos!=10))
	  {
            $players[$pid]['maxFIP']=$ip;
	    $players[$pid]['maxFG']=$g;
	    $players[$pid]['pos']=$pos;
	  }
	  elseif (($maxFG<$g)&&($pos==10))
	  {
            $players[$pid]['maxFIP']=$ip;
	    $players[$pid]['maxFG']=$g;
	    $players[$pid]['pos']=$pos;
	  }
         $position[$pos][$pid]=$ip;

	 $players[$pid][$pos]['ip']=$ip;
	 $players[$pid][$pos]['g']=$g;
	 $players[$pid][$pos]['gs']=$gs;
	 $players[$pid][$pos]['po']=$po;
	 $players[$pid][$pos]['a']=$a;
	 $players[$pid][$pos]['e']=$e;
	 $players[$pid][$pos]['dp']=$dp;
	 $players[$pid][$pos]['tc']=$tc;
	 $players[$pid][$pos]['zr']=$zr;
	 $players[$pid][$pos]['fpct']=$fpct;
	 $players[$pid][$pos]['rng']=$rng;
	 $players[$pid][$pos]['pb']=$pb;
	 $players[$pid][$pos]['rsta']=$sba;
	 $players[$pid][$pos]['rto']=$rto;
	 $players[$pid][$pos]['csPct']=$csPct;
       }
    }

   ##### Get Batters #####
   $text.="<div class='textbox'>\n";
   $text.=" <table cellpadding=0 cellspacing=0 border=0 width='935px'>\n";
   $text.="  <tr class='title'><td style='padding:2px;'>Batting Stats</td></tr>\n";
   $text.="  <tr><td>\n";
   $text.="   <table cellpadding=2 cellspacing=0 border=0 class='sortable' width='100%'>\n";
   $text.="    <thead><tr class='headline'><td class='hsc2'>Pos</td><td class='hsc2_l'>Player</td><td class='hsc2'>Age</td><td class='hsc2'>G</td><td class='hsc2'>AB</td><td class='hsc2'>H</td><td class='hsc2'>2B</td><td class='hsc2'>3B</td><td class='hsc2'>HR</td><td class='hsc2'>RBI</td><td class='hsc2'>R</td><td class='hsc2'>BB</td><td class='hsc2'>HP</td><td class='hsc2'>SH</td><td class='hsc2'>SF</td><td class='hsc2'>K</td><td class='hsc2'>SB</td><td class='hsc2'>CS</td><td class='hsc2'>AVG</td><td class='hsc2'>OBP</td><td class='hsc2'>SLG</td><td class='hsc2'>OPS</td><td class='hsc2'>WAR</td>";
   if ($noPSM!=1) {$text.="<td class='hsc2'>OPS+</td>";}
   if ($noWS!=1) {$text.="<td class='hsc2'>OWS</td><td class='hsc2'>DWS</td>";}
   $text.="</tr></thead>\n";

   $query="SELECT pcb.player_id,first_name,last_name,(pcb.year-YEAR(date_of_birth)-(RIGHT(date_of_birth,5)>'07-01')) as age,g,ab,h,d,t,hr,rbi,r,bb,hp,sh,sf,k,sb,cs,war,pa FROM players_career_batting_stats as pcb,players as p WHERE pcb.player_id=p.player_id AND pcb.team_id=$tid AND pcb.year=$year AND split_id=1 AND (pa>0 OR r>0 OR sb>0 OR cs>0) ORDER BY pa DESC,h DESC";
   $result=mysqli_query($db,$query);
   $cnt=0;
   $bleaderCat=array('avg','obp','slg','ops','g','ab','r','h','d','t','hr','rbi','sb','cs','bb','k');
   while ($row=mysqli_fetch_array($result))
    {
      $pid=$row['player_id'];
      $name=$row['first_name']." ".$row['last_name'];
      $players[$pid]['name']=$name;
      $players[$pid]['sortname']=$row['last_name'].", ".$row['first_name'];
      $age=$row['age'];
      $g=$row['g'];
      $ab=$row['ab'];
      $h=$row['h'];
      $d=$row['d'];
      $t=$row['t'];
      $hr=$row['hr'];
      $rbi=$row['rbi'];
      $r=$row['r'];
      $bb=$row['bb'];
      $hp=$row['hp'];
      $sh=$row['sh'];
      $sf=$row['sf'];
      $k=$row['k'];
      $sb=$row['sb'];
      $cs=$row['cs'];
      $war=$row['war'];
      $pa=$row['pa'];

      if ((($players[$pid]['pos']==0)||($players[$pid]['pos']=="")||(!isset($players[$pid]['pos'])))&&(($ab/$g)>=2)) {$players[$pid]['pos']=10;}

      $Tg+=$g;
      $Tab+=$ab;
      $Th+=$h;
      $Td+=$d;
      $Tt+=$t;
      $Thr+=$hr;
      $Trbi+=$rbi;
      $Tr+=$r;
      $Tbb+=$bb;
      $Thp+=$hp;
      $Tsh+=$sh;
      $Tsf+=$sf;
      $Tk+=$k;
      $Tsb+=$sb;
      $Tcs+=$cs;
      $Twar+=$war;
      $Tpa+=$pa;

      $Tage+=($age*$pa);

      if ($ab==0) {$avg=0;$slg=0;}
       else
       {
         $avg=$h/$ab;
         $slg=($h+$d+2*$t+3*$hr)/$ab;
       }
      if (($ab+$bb+$hp+$sf)==0) {$obp=0;}
       else {$obp=($h+$bb+$hp)/($ab+$bb+$hp+$sf);}
      
      $ops=$obp+$slg;

      $players[$pid]['g']=$g;
      $players[$pid]['ab']=$ab;
      $players[$pid]['r']=$r;
      $players[$pid]['h']=$h;
      $players[$pid]['d']=$d;
      $players[$pid]['t']=$t;
      $players[$pid]['hr']=$hr;
      $players[$pid]['rbi']=$rbi;
      $players[$pid]['sb']=$sb;
      $players[$pid]['cs']=$cs;
      $players[$pid]['bb']=$bb;
      $players[$pid]['k']=$k;
      $players[$pid]['avg']=$avg;
      $players[$pid]['obp']=$obp;
      $players[$pid]['slg']=$slg;
      $players[$pid]['ops']=$ops;

      foreach ($bleaderCat as $ind => $key)
      {
        $pval=$players[$pid][$key];
        $lval=$bleaderVal[$key];
        switch ($key)
	 {
 	   case 'avg':
	   case 'obp':
	   case 'slg':
	   case 'ops':
	     if (($pval==$lval)&&($pa>=(3.1*$TeamGames))) {$bleaders[$key]=$bleaders[$key].",".$pid;$bleaderVal[$key]=$pval;}
	     if (($pval>$lval)&&($pa>=(3.1*$TeamGames))) {$bleaders[$key]=$pid;$bleaderVal[$key]=$pval;}
	     break;
           default:
	     if ($pval==$lval) {$bleaders[$key]=$bleaders[$key].",".$pid;$bleaderVal[$key]=$pval;}
	     if ($pval>$lval) {$bleaders[$key]=$pid;$bleaderVal[$key]=$pval;}
             break;
	 }
      }

      $avg=sprintf("%.3f",$avg);
      $obp=sprintf("%.3f",$obp);
      $slg=sprintf("%.3f",$slg);
      $ops=sprintf("%.3f",$ops);
      if ($avg<1) {$avg=strstr($avg,".");}
      if ($obp<1) {$obp=strstr($obp,".");}
      if ($slg<1) {$slg=strstr($slg,".");}
      if ($ops<1) {$ops=strstr($ops,".");}
      $war=sprintf("%.1f",$war);

      $cls='s'.($cnt%2+1);
      $text.="    <tr class='$cls'>";
      $text.="<td sorttable_customkey=\"".$players[$pid]['pos']."\">".get_pos($players[$pid]['pos'],1)."</td>";
      $text.="<td class='".$cls."_l' sorttable_customkey=\"".$players[$pid]['sortname']."\"><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a></td>";
      $text.="<td>$age</td>";
      $text.="<td>$g</td>";
      $text.="<td>$ab</td>";
      $text.="<td>$h</td>";
      $text.="<td>$d</td>";
      $text.="<td>$t</td>";
      $text.="<td>$hr</td>";
      $text.="<td>$rbi</td>";
      $text.="<td>$r</td>";
      $text.="<td>$bb</td>";
      $text.="<td>$hp</td>";
      $text.="<td>$sh</td>";
      $text.="<td>$sf</td>";
      $text.="<td>$k</td>";
      $text.="<td>$sb</td>";
      $text.="<td>$cs</td>";
      $text.="<td>$avg</td>";
      $text.="<td>$obp</td>";
      $text.="<td>$slg</td>";
      $text.="<td>$ops</td>";
      $text.="<td>$war</td>";
      if ($noPSM!=1)
       {
         $opsPlus=$players[$pid]['opsPlus'];
         $TopsPlus+=($opsPlus*$pa);
         $text.="<td>".round($opsPlus)."</td>";
       }
      if ($noWS!=1)
      {
         $ows=$players[$pid]['ows'];
	 $fwsTot=$players[$pid]['fwsTot'];
	 $Tows+=$ows;
	 $TfwsTot+=$fwsTot;
   	 $text.="<td>".sprintf("%.1f",$ows)."</td><td>".sprintf("%.1f",$fwsTot)."</td>";
      }
      $text.="</tr>\n";
      $cnt++;
    }
   ##Show Team Totals
   if ($Tab==0) {$avg=0;$slg=0;}
    else
    {
      $avg=$Th/$Tab;
      $slg=($Th+$Td+2*$Tt+3*$Thr)/$Tab;
    }
   if (($Tab+$Tbb+$Thp+$Tsf)==0) {$Tobp=0;}
    else {$obp=($Th+$Tbb+$Thp)/($Tab+$Tbb+$Thp+$Tsf);}
   
   $ops=$obp+$slg;
   $avg=sprintf("%.3f",$avg);
   $obp=sprintf("%.3f",$obp);
   $slg=sprintf("%.3f",$slg);
   $ops=sprintf("%.3f",$ops);
   if ($avg<1) {$avg=strstr($avg,".");}
   if ($obp<1) {$obp=strstr($obp,".");}
   if ($slg<1) {$slg=strstr($slg,".");}
   if ($ops<1) {$ops=strstr($ops,".");}
   $Twar=sprintf("%.1f",$Twar);
   
   $text.="    <tfoot>\n";
   $text.="     <tr class='headline'>";
   $text.="<td class='hsc2_l' colspan=2>$cnt Players</td>";
   $text.="<td class='hsc2'>".sprintf("%.1f",$Tage/$Tpa)."</td>";
   $text.="<td class='hsc2'>$Tg</td>";
   $text.="<td class='hsc2'>$Tab</td>";
   $text.="<td class='hsc2'>$Th</td>";
   $text.="<td class='hsc2'>$Td</td>";
   $text.="<td class='hsc2'>$Tt</td>";
   $text.="<td class='hsc2'>$Thr</td>";
   $text.="<td class='hsc2'>$Trbi</td>";
   $text.="<td class='hsc2'>$Tr</td>";
   $text.="<td class='hsc2'>$Tbb</td>";
   $text.="<td class='hsc2'>$Thp</td>";
   $text.="<td class='hsc2'>$Tsh</td>";
   $text.="<td class='hsc2'>$Tsf</td>";
   $text.="<td class='hsc2'>$Tk</td>";
   $text.="<td class='hsc2'>$Tsb</td>";
   $text.="<td class='hsc2'>$Tcs</td>";
   $text.="<td class='hsc2'>$avg</td>";
   $text.="<td class='hsc2'>$obp</td>";
   $text.="<td class='hsc2'>$slg</td>";
   $text.="<td class='hsc2'>$ops</td>";
   $text.="<td class='hsc2'>$Twar</td>";
   if ($noPSM!=1) {$text.="<td class='hsc2'>".round($TopsPlus/$Tpa,0)."</td>";}
   if ($noWS!=1) {$text.="<td class='hsc2'>".sprintf("%.1f",$Tows)."</td><td class='hsc2'>".sprintf("%.1f",$TfwsTot)."</td>";}
   $text.="</tr>\n";
	 if (count($subleagues)>1)
	 {
	 ## Team SubLeague Ranks
	 $text.="     <tr class='headline'>";
	 $text.="<td class='hsc2_l' colspan=4>$slAbbr Rank</td>";
	 $statList=Array('ab','h','d','t','hr','rbi','r','bb','hp','sh','sf','k','sb','cs','avg','obp','slg','ops','war');
	 foreach ($statList as $key => $statLbl)
	 {
		 $sQuery="SELECT COUNT(DISTINCT team_id)+1 as cnt FROM (SELECT team_id,";
		 switch ($statLbl)
		 {
			 case 'avg':$sQuery.="SUM(h)/SUM(ab)"; break;
			 case 'obp':$sQuery.="(SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))"; break;
			 case 'slg':$sQuery.="(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab)"; break;
			 case 'ops':$sQuery.="(SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))+(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab)"; break;
			 default: $sQuery.="SUM($statLbl)"; break;
		 }
		 $sQuery.=" as stat FROM players_career_batting_stats WHERE league_id=$lgid AND year=$year AND split_id=1 AND team_id IN ($teamList) GROUP BY team_id) as t1,(SELECT ";
		 switch ($statLbl)
		 {
			 case 'avg':$sQuery.="SUM(h)/SUM(ab)"; break;
			 case 'obp':$sQuery.="(SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))"; break;
			 case 'slg':$sQuery.="(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab)"; break;
			 case 'ops':$sQuery.="(SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))+(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab)"; break;
			 default: $sQuery.="SUM($statLbl)"; break;
		 }
		 $sQuery.=" as stat FROM players_career_batting_stats WHERE league_id=$lgid AND year=$year AND split_id=1 AND team_id=$tid GROUP BY team_id) as t2 WHERE t1.stat>t2.stat;";
		 $sResult=mysqli_query($db,$sQuery);
		 $sRow=mysqli_fetch_array($sResult);
		 $statVal=$sRow['cnt'];
		 $text.="<td class='hsc2'>".($statVal)."</td>";
	 }
	 if ($noPSM!=1) {$text.="<td class='hsc2'>&nbsp;</td>";}
	 if ($noWS!=1) {$text.="<td class='hsc2' colspan=2>&nbsp;</td>";}
	 $text.="</tr>\n";
	 }
	 ## Team League Ranks
	 $text.="     <tr class='headline'>";
	 $text.="<td class='hsc2_l' colspan=4>$lgAbbr Rank</td>";
	 $statList=Array('ab','h','d','t','hr','rbi','r','bb','hp','sh','sf','k','sb','cs','avg','obp','slg','ops','war');
	 foreach ($statList as $key => $statLbl)
	 {
		 $sQuery="SELECT COUNT(DISTINCT team_id)+1 as cnt FROM (SELECT team_id,";
		 switch ($statLbl)
		 {
			 case 'avg':$sQuery.="SUM(h)/SUM(ab)"; break;
			 case 'obp':$sQuery.="(SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))"; break;
			 case 'slg':$sQuery.="(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab)"; break;
			 case 'ops':$sQuery.="(SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))+(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab)"; break;
			 default: $sQuery.="SUM($statLbl)"; break;
		 }
		 $sQuery.=" as stat FROM players_career_batting_stats WHERE league_id=$lgid AND year=$year AND split_id=1 GROUP BY team_id) as t1,(SELECT ";
		 switch ($statLbl)
		 {
			 case 'avg':$sQuery.="SUM(h)/SUM(ab)"; break;
			 case 'obp':$sQuery.="(SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))"; break;
			 case 'slg':$sQuery.="(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab)"; break;
			 case 'ops':$sQuery.="(SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))+(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab)"; break;
			 default: $sQuery.="SUM($statLbl)"; break;
		 }
		 $sQuery.=" as stat FROM players_career_batting_stats WHERE league_id=$lgid AND year=$year AND split_id=1 AND team_id=$tid GROUP BY team_id) as t2 WHERE t1.stat>t2.stat;";
		 $sResult=mysqli_query($db,$sQuery);
		 $sRow=mysqli_fetch_array($sResult);
		 $statVal=$sRow['cnt'];
		 $text.="<td class='hsc2'>".($statVal)."</td>";
	 }
	 if ($noPSM!=1) {$text.="<td class='hsc2'>&nbsp;</td>";}
	 if ($noWS!=1) {$text.="<td class='hsc2' colspan=2>&nbsp;</td>";}
	 $text.="</tr>\n";
	 $text.="    </tfoot>\n";

   $text.="   </table>\n";
   $text.="  </td></tr>\n";
   $text.=" </table>\n";
   $text.="</div>   <!-- END of Batter Stats -->\n";

   ##### Get Pitchers #####
   $Tg=0;
   $Tab=0;
   $Tr=0;
   $Tbb=0;
   $Tsf=0;
   $Tk=0;
   $Twar=0;
   $Tage=0;
   $text.="<div class='textbox'>\n";
   $text.=" <table cellpadding=0 cellspacing=0 border=0 width='935px'>\n";
   $text.="  <tr class='title'><td style='padding:2px;'>Pitching Stats</td></tr>\n";
   $text.="  <tr><td>\n";
   $text.="   <table cellpadding=2 cellspacing=0 border=0 class='sortable' width='100%'>\n";
   $text.="    <thead><tr class='headline'><td class='hsc2_l'>Player</td><td class='hsc2'>Age</td><td class='hsc2'>G</td><td class='hsc2'>GS</td><td class='hsc2'>W</td><td class='hsc2'>L</td><td class='hsc2'>SV</td><td class='hsc2'>ERA</td><td class='hsc2'>IP</td><td class='hsc2'>HA</td><td class='hsc2'>R</td><td class='hsc2'>ER</td><td class='hsc2'>HR</td><td class='hsc2'>BB</td><td class='hsc2'>K</td><td class='hsc2'>HLD</td><td class='hsc2'>CG</td><td class='hsc2'>SHO</td><td class='hsc2'>WHIP</td><td class='hsc2'>BABIP</td><td class='hsc2'>WAR</td>";
   if ($noPSM!=1) {$text.="<td class='hsc2'>ERA+</td>";}
   if ($noWS!=1) {$text.="<td class='hsc2'>PWS</td>";}
   $text.="</tr></thead>\n";

   $query="SELECT pcp.player_id,first_name,last_name,(pcp.year-YEAR(date_of_birth)-(RIGHT(date_of_birth,5)>'07-01')) as age,g,gs,w,l,s,er,(ip*3+ipf)/3 as ip,ha,r,hra,bb,k,hld,cg,sho,ab,sf,war FROM players_career_pitching_stats as pcp,players as p WHERE pcp.player_id=p.player_id AND pcp.team_id=$tid AND pcp.year=$year AND split_id=1 AND (ipf>0 OR ip>0 OR w>0 OR l>0 OR hld>0 OR s>0 OR bf>0) ORDER BY ip DESC,k DESC";
   $result=mysqli_query($db,$query);
   $cnt=0;
   $pleaderCat=array('w','l','s','pg','gs','cg','sho','ip','ha','hra','pk','pbb','era','whip','babip');
   $pleaderVal['era']=999;
   $pleaderVal['whip']=999;
   $pleaderVal['babip']=999;
   while ($row=mysqli_fetch_array($result))
    {
      $pid=$row['player_id'];
      $name=$row['first_name']." ".$row['last_name'];
      $players[$pid]['name']=$name;
      $players[$pid]['sortname']=$row['last_name'].", ".$row['first_name'];
      $age=$row['age'];
      $g=$row['g'];
      $gs=$row['gs'];
      $w=$row['w'];
      $l=$row['l'];
      $s=$row['s'];
      $ip=$row['ip'];
      $ha=$row['ha'];
      $r=$row['r'];
      $er=$row['er'];
      $hra=$row['hra'];
      $bb=$row['bb'];
      $k=$row['k'];
      $hld=$row['hld'];
      $cg=$row['cg'];
      $sho=$row['sho'];
      $ab=$row['ab'];
      $sf=$row['sf'];
      $war=$row['war'];

      $Tg+=$g;
      $Tgs+=$gs;
      $Tw+=$w;
      $Tl+=$l;
      $Ts+=$s;
      $Tip+=$ip;
      $Tha+=$ha;
      $Tr+=$r;
      $Ter+=$er;
      $Thra+=$hra;
      $Tbb+=$bb;
      $Tk+=$k;
      $Thld+=$hld;
      $Tcg+=$cg;
      $Tsho+=$sho;
      $Tab+=$ab;
      $Tsf+=$sf;
      $Twar+=$war;

      $Tage+=($age*$ip);

      if ($ip==0) {$era=0;$whip=0;}
       else
       {
         $era=9*$er/$ip;
         $whip=($ha+$bb)/$ip;
       }
      $bip=$ab-$k-$hra+$sf;
      if ($bip==0) {$babip=0;}
       else {$babip=($ha-$hra)/$bip;}

      $players[$pid]['w']=$w;
      $players[$pid]['l']=$l;
      $players[$pid]['s']=$s;
      $players[$pid]['pg']=$g;
      $players[$pid]['gs']=$gs;
      $players[$pid]['cg']=$cg;
      $players[$pid]['sho']=$sho;
      $players[$pid]['ip']=$ip;
      $players[$pid]['ha']=$ha;
      $players[$pid]['hra']=$hra;
      $players[$pid]['pk']=$k;
      $players[$pid]['pbb']=$bb;
      $players[$pid]['era']=$era;
      $players[$pid]['whip']=$whip;
      $players[$pid]['babip']=$babip;

      foreach ($pleaderCat as $ind => $key)
      {
        $pval=$players[$pid][$key];
        $lval=$pleaderVal[$key];
        switch ($key)
	 {
 	   case 'era':
	   case 'whip':
	   case 'babip':
	     if (($pval==$lval)&&($ip>=$TeamGames)) {$pleaders[$key]=$pleaders[$key].",".$pid;$pleaderVal[$key]=$pval;}
	     if (($pval<$lval)&&($ip>=$TeamGames)) {$pleaders[$key]=$pid;$pleaderVal[$key]=$pval;}
	     break;
           default:
	     if ($pval==$lval) {$pleaders[$key]=$pleaders[$key].",".$pid;$pleaderVal[$key]=$pval;}
	     elseif ($pval>$lval) {$pleaders[$key]=$pid;$pleaderVal[$key]=$pval;}
             break;
	 }
      }

      $era=sprintf("%.2f",$era);
      $whip=sprintf("%.2f",$whip);
      $babip=sprintf("%.3f",$babip);
      if ($whip<1) {$whip=strstr($whip,".");}
      if ($babip<1) {$babip=strstr($babip,".");}
      $war=sprintf("%.1f",$war);
      $dispip=sprintf("%.1f",$ip);

      $cls='s'.($cnt%2+1);
      $text.="    <tr class='$cls'>";
      $text.="<td class='".$cls."_l' sorttable_customkey=\"".$players[$pid]['sortname']."\"><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a></td>";
      $text.="<td>$age</td>";
      $text.="<td>$g</td>";
      $text.="<td>$gs</td>";
      $text.="<td>$w</td>";
      $text.="<td>$l</td>";
      $text.="<td>$s</td>";
      $text.="<td>$era</td>";
      $text.="<td>$dispip</td>";
      $text.="<td>$ha</td>";
      $text.="<td>$r</td>";
      $text.="<td>$er</td>";
      $text.="<td>$hra</td>";
      $text.="<td>$bb</td>";
      $text.="<td>$k</td>";
      $text.="<td>$hld</td>";
      $text.="<td>$cg</td>";
      $text.="<td>$sho</td>";
      $text.="<td>$whip</td>";
      $text.="<td>$babip</td>";
      $text.="<td>$war</td>";
      if ($noPSM!=1)
       {
         $eraPlus=$players[$pid]['eraPlus'];
         $TeraPlus+=($eraPlus*$ip);
         $text.="<td>".round($eraPlus)."</td>";
       }
      if ($noWS!=1)
      {
         $pws=$players[$pid]['pws'];
	 $Tpws+=$pws;
   	 $text.="<td>".sprintf("%.1f",$pws)."</td>";
      }
      $text.="</tr>\n";
      $cnt++;
    }
   ##Show Team Totals
   if ($Tip==0) {$era=0;$whip=0;}
    else
    {
      $era=9*$Ter/$Tip;
      $whip=($Tha+$Tbb)/$Tip;
    }
   $bip=$Tab-$Tk-$Thra+$Tsf;
   if ($bip==0) {$babip=0;}
    else {$babip=($Tha-$Thra)/$bip;}
     
   $era=sprintf("%.2f",$era);
   $whip=sprintf("%.2f",$whip);
   $babip=sprintf("%.3f",$babip);
   if ($whip<1) {$whip=strstr($whip,".");}
   if ($babip<1) {$babip=strstr($babip,".");}
   $Twar=sprintf("%.1f",$Twar);
   $Tip=sprintf("%.1f",$Tip);
   
   $text.="    <tfoot><tr class='headline'>";
   $text.="<td class='hsc2_l'>$cnt Pitchers</td>";
   $text.="<td class='hsc2'>".sprintf("%.1f",$Tage/$Tip)."</td>";
   $text.="<td class='hsc2'>$Tg</td>";
   $text.="<td class='hsc2'>$Tgs</td>";
   $text.="<td class='hsc2'>$Tw</td>";
   $text.="<td class='hsc2'>$Tl</td>";
   $text.="<td class='hsc2'>$Ts</td>";
   $text.="<td class='hsc2'>$era</td>";
   $text.="<td class='hsc2'>$Tip</td>";
   $text.="<td class='hsc2'>$Tha</td>";
   $text.="<td class='hsc2'>$Tr</td>";
   $text.="<td class='hsc2'>$Ter</td>";
   $text.="<td class='hsc2'>$Thra</td>";
   $text.="<td class='hsc2'>$Tbb</td>";
   $text.="<td class='hsc2'>$Tk</td>";
   $text.="<td class='hsc2'>$Thld</td>";
   $text.="<td class='hsc2'>$Tcg</td>";
   $text.="<td class='hsc2'>$Tsho</td>";
   $text.="<td class='hsc2'>$whip</td>";
   $text.="<td class='hsc2'>$babip</td>";
   $text.="<td class='hsc2'>$Twar</td>";
   if ($noPSM!=1) {$text.="<td class='hsc2'>".round($TeraPlus/$Tip,0)."</td>";}
   if ($noWS!=1) {$text.="<td class='hsc2'>".sprintf("%.1f",$Tpws)."</td>";}
   $text.="</tr>\n";
	 if (count($subleagues)>1)
	 {
	 ## Team SubLeague Ranks
	 $text.="     <tr class='headline'>";
	 $text.="<td class='hsc2_l' colspan=2>$slAbbr Rank</td>";
	 $statList=Array('g','gs','w','l','s','era','ip','ha','r','er','hra','bb','k','hld','cg','sho','whip','babip','war');
	 foreach ($statList as $key => $statLbl)
	 {
		 $sQuery="SELECT COUNT(DISTINCT team_id)+1 as cnt FROM (SELECT team_id,";
		 switch ($statLbl)
		 {
			 case 'era':$sQuery.="9*SUM(er)/(SUM(ip)+SUM(ipf)/3)"; break;
			 case 'ip':$sQuery.="SUM(ip)+SUM(ipf)/3"; break;
			 case 'whip':$sQuery.="(SUM(ha)+SUM(bb))/(SUM(ip)+SUM(ipf)/3)"; break;
			 case 'babip':$sQuery.="(SUM(ha)-SUM(hra))/(SUM(ab)-SUM(k)-SUM(hra)+SUM(sf))"; break;
			 default: $sQuery.="SUM($statLbl)"; break;
		 }
		 $sQuery.=" as stat FROM players_career_pitching_stats WHERE league_id=$lgid AND year=$year AND split_id=1 AND team_id IN ($teamList) GROUP BY team_id) as t1,(SELECT ";
		 switch ($statLbl)
		 {
			 case 'era':$sQuery.="9*SUM(er)/(SUM(ip)+SUM(ipf)/3)"; break;
			 case 'ip':$sQuery.="SUM(ip)+SUM(ipf)/3"; break;
			 case 'whip':$sQuery.="(SUM(ha)+SUM(bb))/(SUM(ip)+SUM(ipf)/3)"; break;
			 case 'babip':$sQuery.="(SUM(ha)-SUM(hra))/(SUM(ab)-SUM(k)-SUM(hra)+SUM(sf))"; break;
			 default: $sQuery.="SUM($statLbl)"; break;
		 }
		 $sQuery.=" as stat FROM players_career_pitching_stats WHERE league_id=$lgid AND year=$year AND split_id=1 AND team_id=$tid GROUP BY team_id) as t2 WHERE ";
		 switch ($statLbl)
		 {
			 case 'ha':
			 case 'r':
			 case 'er':
			 case 'hra':
			 case 'bb':
			 case 'era':
			 case 'whip':
			 case 'babip':
				 $sQuery.="t1.stat<t2.stat;"; break;
			 default: $sQuery.="t1.stat>t2.stat;"; break;
		 }
		 $sResult=mysqli_query($db,$sQuery);
		 $sRow=mysqli_fetch_array($sResult);
		 $statVal=$sRow['cnt'];
		 $text.="<td class='hsc2'>".($statVal)."</td>";
	 }
	 if ($noPSM!=1) {$text.="<td class='hsc2'>&nbsp;</td>";}
	 if ($noWS!=1) {$text.="<td class='hsc2'>&nbsp;</td>";}
	 $text.="</tr>\n";
	 }
	 ## Team League Ranks
	 $text.="     <tr class='headline'>";
	 $text.="<td class='hsc2_l' colspan=2>$lgAbbr Rank</td>";
	 $statList=Array('g','gs','w','l','s','era','ip','ha','r','er','hra','bb','k','hld','cg','sho','whip','babip','war');
	 foreach ($statList as $key => $statLbl)
	 {
		 $sQuery="SELECT COUNT(DISTINCT team_id)+1 as cnt FROM (SELECT team_id,";
		 switch ($statLbl)
		 {
			 case 'era':$sQuery.="9*SUM(er)/(SUM(ip)+SUM(ipf)/3)"; break;
			 case 'ip':$sQuery.="SUM(ip)+SUM(ipf)/3"; break;
			 case 'whip':$sQuery.="(SUM(ha)+SUM(bb))/(SUM(ip)+SUM(ipf)/3)"; break;
			 case 'babip':$sQuery.="(SUM(ha)-SUM(hra))/(SUM(ab)-SUM(k)-SUM(hra)+SUM(sf))"; break;
			 default: $sQuery.="SUM($statLbl)"; break;
		 }
		 $sQuery.=" as stat FROM players_career_pitching_stats WHERE league_id=$lgid AND year=$year AND split_id=1 GROUP BY team_id) as t1,(SELECT ";
		 switch ($statLbl)
		 {
			 case 'era':$sQuery.="9*SUM(er)/(SUM(ip)+SUM(ipf)/3)"; break;
			 case 'ip':$sQuery.="SUM(ip)+SUM(ipf)/3"; break;
			 case 'whip':$sQuery.="(SUM(ha)+SUM(bb))/(SUM(ip)+SUM(ipf)/3)"; break;
			 case 'babip':$sQuery.="(SUM(ha)-SUM(hra))/(SUM(ab)-SUM(k)-SUM(hra)+SUM(sf))"; break;
			 default: $sQuery.="SUM($statLbl)"; break;
		 }
		 $sQuery.=" as stat FROM players_career_pitching_stats WHERE league_id=$lgid AND year=$year AND split_id=1 AND team_id=$tid GROUP BY team_id) as t2 WHERE ";
		 switch ($statLbl)
		 {
			 case 'ha':
			 case 'r':
			 case 'er':
			 case 'hra':
			 case 'bb':
			 case 'era':
			 case 'whip':
			 case 'babip':
				 $sQuery.="t1.stat<t2.stat;"; break;
			 default: $sQuery.="t1.stat>t2.stat;"; break;
		 }
		 $sResult=mysqli_query($db,$sQuery);
		 $sRow=mysqli_fetch_array($sResult);
		 $statVal=$sRow['cnt'];
		 $text.="<td class='hsc2'>".($statVal)."</td>";
	 }
	 if ($noPSM!=1) {$text.="<td class='hsc2'>&nbsp;</td>";}
	 if ($noWS!=1) {$text.="<td class='hsc2'>&nbsp;</td>";}
	 $text.="</tr>\n";
	 $text.="    </tfoot>\n";
	 
   $text.="   </table>\n";
   $text.="  </td></tr>\n";
   $text.=" </table>\n";
   $text.="</div>   <!-- END of Pitcher Stats -->\n";

   ##### Show Fielding Stats #####
   $text.="<div class='textbox'>\n";
   $text.=" <table cellpadding=0 cellspacing=0 border=0 width='935px'>\n";
   $text.="  <tr class='title'><td colspan=2 style='padding:2px;'>Fielding Stats</td></tr>\n";
   $text.="  <tr><td valign=top>\n";
   for ($pos=1;$pos<=9;$pos++)
    {
      if (count($position[$pos])==0) {continue;}
      if ($pos==6) {$text.="  </td><td valign=top>\n";}
      $text.="   <div class='tablebox'>\n";
      $text.="    <table cellpadding=2 cellspacing=0 border=0 class='sortable' width='445px'>\n";
      $cols=12;
      if ($pos==2) {$cols+=4;}
      if (($noWS!=1)&&($pos!=1)) {$cols+=1;}
      switch ($pos)
       {
         case 1: $posLabel="Pitchers";break;
         case 2: $posLabel="Catchers";break;
         case 3: $posLabel="First Basemen";break;
         case 4: $posLabel="Second Basemen";break;
         case 5: $posLabel="Third Basemen";break;
         case 6: $posLabel="Shortstops";break;
         case 7: $posLabel="Left Fielders";break;
         case 8: $posLabel="Center Fielders";break;
         case 9: $posLabel="Right Fielders";break;
       }
      $text.="     <thead><tr class='title'><td colspan=$cols>$posLabel</td></tr><tr class='headline'><td class='hsc2_l'>Player</td><td class='hsc2'>G</td><td class='hsc2'>GS</td><td class='hsc2'>PO</td><td class='hsc2'>A</td><td class='hsc2'>DP</td><td class='hsc2'>TC</td><td class='hsc2'>E</td><td class='hsc2'>Pct</td><td class='hsc2'>Inn</td><td class='hsc2'>Rng</td><td class='hsc2'>ZR</td>";
      if ($pos==2) {$text.="<td class='hsc2'>PB</td><td class='hsc2'>RTO%</td>";}
      if (($noWS!=1)&&($pos!=1)) {$text.="<td class='hsc2'>FWS</td>";}
      $text.="</tr></thead>\n";
      $rcnt=0;
      $Tg=0;
      $Tgs=0;
      $Tpo=0;
      $Ta=0;
      $Tdp=0;
      $Ttc=0;
      $Tzr=0;
      $Te=0;
      $Tip=0;
      $Tpb=0;
      $Trsta=0;
      $Trto=0;
      $Tfws=0;
      foreach ($position[$pos] as $pid => $inn)
       {

	 $g=$players[$pid][$pos]['g'];
	 $gs=$players[$pid][$pos]['gs'];
	 $po=$players[$pid][$pos]['po'];
	 $a=$players[$pid][$pos]['a'];
	 $dp=$players[$pid][$pos]['dp'];
	 $tc=$players[$pid][$pos]['tc'];
	 $zr=$players[$pid][$pos]['zr'];
	 $e=$players[$pid][$pos]['e'];
	 $ip=$players[$pid][$pos]['ip'];
	 $pb=$players[$pid][$pos]['pb'];
	 $rsta=$players[$pid][$pos]['rsta'];
	 $rto=$players[$pid][$pos]['rto'];

	 $Tg+=$g;
	 $Tgs+=$gs;
	 $Tpo+=$po;
	 $Ta+=$a;
	 $Tdp+=$dp;
	 $Ttc+=$tc;
	 $Tzr+=$zr;
	 $Te+=$e;
	 $Tip+=$ip;
	 $Tpb+=$pb;
	 $Trsta+=$rsta;
	 $Trto+=$rto;

	 $cls='s'.($rcnt%2+1);
	 $text.="     <tr class='$cls'>";
         $text.="<td class='".$cls."_l'><a href='./player.php?player_id=$pid'>".$players[$pid]['shortname']."</a></td>";
         $text.="<td>".$g."</td>";
         $text.="<td>".$gs."</td>";
         $text.="<td>".$po."</td>";
         $text.="<td>".$a."</td>";
         $text.="<td>".$dp."</td>";
         $text.="<td>".$tc."</td>";
         $text.="<td>".$e."</td>";
         $text.="<td>".$players[$pid][$pos]['fpct']."</td>";
         $text.="<td>".sprintf("%.1f",$ip)."</td>";
	 $text.="<td>".$players[$pid][$pos]['rng']."</td>";
         $text.="<td>".stat_format('zr',$zr)."</td>";
	 if ($pos==2)
	  {
            $text.="<td>".$pb."</td>";
	    $text.="<td>".$players[$pid][$pos]['csPct']."</td>";
	  }
         if (($noWS!=1)&&($pos!=1))
	  {
            $ind="fws".$pos;
	    $fws=$players[$pid][$ind];
	    $Tfws+=$fws;
	    $text.="<td>".sprintf("%.1f",$fws)."</td>";
	  }
	 $text.="</tr>\n";
         $rcnt++;
       }
      $text.="     <tfoot><tr class='headline'>";
      $text.="<td class='hsc2_l'>Totals</td>";
      $text.="<td class='hsc2'>".$Tg."</td>";
      $text.="<td class='hsc2'>".$Tgs."</td>";
      $text.="<td class='hsc2'>".$Tpo."</td>";
      $text.="<td class='hsc2'>".$Ta."</td>";
      $text.="<td class='hsc2'>".$Tdp."</td>";
      $text.="<td class='hsc2'>".$Ttc."</td>";
      $text.="<td class='hsc2'>".$Te."</td>";
      if ($Ttc==0) {$Tfpct=0;} else {$Tfpct=($Tpo+$Ta)/$Ttc;}
      $Tfpct=sprintf("%.3f",$Tfpct);
      if ($Tfpct<1) {$Tfpct=substr($Tfpct,1);}
      $text.="<td class='hsc2'>".$Tfpct."</td>";
      $text.="<td class='hsc2'>".sprintf("%.1f",$Tip)."</td>";
      if ($Tip==0) {$Trng=0;} else {$Trng=($Tpo+$Ta)/($Tip/9);}
      $text.="<td class='hsc2'>".sprintf("%.2f",$Trng)."</td>";
      $text.="<td class='hsc2'>".stat_format('zr',$Tzr)."</td>";
      if ($pos==2)
       {
         $text.="<td class='hsc2'>".$Tpb."</td>";
	 if ($Trsta==0) {$TcsPct=0;} else {$TcsPct=$Trto/$Trsta;}
	 $text.="<td class='hsc2'>".sprintf("%.1f",100*$TcsPct)."</td>";
       }
      if (($noWS!=1)&&($pos!=1)) {$text.="<td class='hsc2'>".sprintf("%.1f",$Tfws)."</td>";}
      $text.="</tr>";
      $text.="</tfoot>\n";
      $text.="    </table>\n";
      $text.="   </div>\n";
    }
   $text.="  </td></tr>\n";
   $text.=" </table>\n";
   $text.="</div>   <!-- END of Fielder Stats -->\n";

   ##### Team Leaders #####
   $text.="<div class='textbox'>\n";
   $text.=" <table cellpadding=0 cellspacing=0 border=0 width='935px'>\n";
   $text.="  <tr class='title'><td colspan=2 style='padding:2px;'>Team Leaders</td></tr>\n";
   ##Batting Leaders
   $text.="  <tr><td valign=top>\n";
   $text.="   <div class='tablebox'>\n";
   $text.="    <table cellpadding=0 cellspacing=0 border=0 width='445px'>\n";
   $text.="     <tr class='title'><td style='padding:2px;'>Batting Leaders</td><tr>\n";
   $text.="     <tr><td>\n";
   $text.="      <table cellpadding=2 cellspacing=0 border=0 class='sortable' width='100%'>\n";
   $text.="       <thead><tr class='headline'><td class='hsc2_l'>Category</td><td class='hsc2_l'>Player(s)</td><td class='hsc2'>Value</td></tr></thead>\n";
   $cnt=0;
   foreach ($bleaders as $cat => $pids)
    {
      $cls='s'.($cnt%2+1);
      switch ($cat)
       {
         case 'avg': $catName="Batting Average";break;
	 case 'obp': $catName="On-Base Percentage";break;
         case 'slg': $catName="Slugging Percentage";break;
         case 'ops': $catName="OPS";break;
         case 'g'  : $catName="Games";break;
         case 'ab'  : $catName="At-Bats";break;
         case 'r'  : $catName="Runs";break;
         case 'h'  : $catName="Hits";break;
         case 'd'  : $catName="Doubles";break;
         case 't'  : $catName="Triples";break;
         case 'hr'  : $catName="Home Runs";break;
         case 'rbi'  : $catName="Runs Batted In";break;
         case 'sb'  : $catName="Stolen Bases";break;
         case 'cs'  : $catName="Caught Stealing";break;
         case 'bb'  : $catName="Walks";break;
         case 'k'  : $catName="Strikeouts";break;
       }
      $text.="       <tr class='".$cls."_l'><td>$catName</td><td>";
      $pids=trim($pids,",");
      $e=explode(",",$pids);
      if (count($e)>3)
       {
	 $text.="<a title=\"";
         for ($i=0;$i<count($e);$i++)
          {
	    $pid=$e[$i];
	    if ($i>0) {$text.=", ";}
	    $text.=$players[$pid]['name'];
	  }
	 $text.="\">".count($e)." Players Tied</a>";
       }
       else
       {
         for ($i=0;$i<count($e);$i++)
          {
	    $pid=$e[$i];
	    if ($i>0) {$text.=", ";}
	    $text.="<a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>";
	  }
       }
      $val=$players[$pid][$cat];
      switch ($cat)
       {
	 case 'avg':
	 case 'obp':
	 case 'slg':
         case 'ops': $val=sprintf("%.3f",$val);if ($val<1) {$val=strstr($val,".");} break;
       }
      $text.="</td><td class='$cls'>$val</td></tr>\n";
      $cnt++;
    }
   $text.="      </table>\n";
   $text.="     </td></tr>\n";
   $text.="    </table>\n";
   $text.="   </div>\n";
   ##Pitching Leaders
   $text.="  </td><td valign=top>\n";
   $text.="   <div class='tablebox'>\n";
   $text.="    <table cellpadding=0 cellspacing=0 border=0 width='445px'>\n";
   $text.="     <tr class='title'><td style='padding:2px;'>Pitching Leaders</td><tr>\n";
   $text.="     <tr><td>\n";
   $text.="      <table cellpadding=2 cellspacing=0 border=0 class='sortable' width='100%'>\n";
   $text.="       <thead><tr class='headline'><td class='hsc2_l'>Category</td><td class='hsc2_l'>Player(s)</td><td class='hsc2'>Value</td></tr></thead>\n";
   $cnt=0;
   foreach ($pleaders as $cat => $pids)
    {
      $cls='s'.($cnt%2+1);
      switch ($cat)
       {
         case 'w': $catName="Wins";break;
         case 'l': $catName="Losses";break;
         case 's': $catName="Saves";break;
         case 'pg': $catName="Games";break;
         case 'gs': $catName="Games Started";break;
         case 'cg': $catName="Complete Games";break;
         case 'sho': $catName="Shutouts";break;
         case 'ip': $catName="Innings Pitched";break;
         case 'ha': $catName="Hits Allowed";break;
         case 'hra': $catName="Home Runs Allowed";break;
         case 'pk': $catName="Strikeouts";break;
         case 'pbb': $catName="Walks Allowed";break;
         case 'era': $catName="Earned Run Average";break;
         case 'whip': $catName="Walks + Hits per IP";break;
         case 'babip': $catName="BABIP";break;
       }
      $text.="       <tr class='".$cls."_l'><td>$catName</td><td>";
      $pids=trim($pids,",");
      $e=explode(",",$pids);
      if (count($e)>3)
       {
	 $text.="<a title=\"";
         for ($i=0;$i<count($e);$i++)
          {
	    $pid=$e[$i];
	    if ($i>0) {$text.=", ";}
	    $text.=$players[$pid]['name'];
	  }
	 $text.="\">".count($e)." Players Tied</a>";
       }
       else
       {
         for ($i=0;$i<count($e);$i++)
          {
     	    $pid=$e[$i];
	    if ($i>0) {$text.=", ";}
	    $text.="<a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>";
	  }
       }
      $val=$players[$pid][$cat];
      switch ($cat)
       {
         case 'ip': $val=sprintf("%.1f",$val);break;
	 case 'era':
	 case 'whip': $val=sprintf("%.2f",$val);break;
         case 'babip': $val=sprintf("%.3f",$val);if ($val<1) {$val=strstr($val,".");} break;
       }
      $text.="</td><td class='$cls'>$val</td></tr>\n";
      $cnt++;
    }
   $text.="      </table>\n";
   $text.="     </td></tr>\n";
   $text.="    </table>\n";
   $text.="   </div>\n";
   $text.="  </td></tr>\n";
   $text.=" </table>\n";
   $text.="</div>   <!-- END of Team Leaders -->\n";

   ##### Trades #####
   $query="SELECT * FROM trade_history as th WHERE th.date LIKE '$year%' AND (team_id_0=$tid OR team_id_1=$tid) ORDER BY th.date";
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result))
   {
	 
	   $text.="<div class='textbox'>\n";
	   $text.=" <table cellpadding=4 cellspacing=0 border=0 width='935px'>\n";
	   $text.="  <tr class='title'><td colspan=4 style='padding:2px;'>Trades</td></tr>\n";
	   $text.="  <tr class='headline'><td class='hsc2_l'>Date</td><td class='hsc2_l' colspan=2>Sent</td><td class='hsc2_l'>Recieved</td></tr>\n";

	   $rowCnt=0;
	   while ($row=mysqli_fetch_array($result))
	   {
		   $cls='s'.($rowCnt%2+1);

		   $text.="  <tr class='$cls' style='vertical-align:top;'>";
		   if (isset($trdDate)) {unset($trdDate);}
		   $trdDate=new Date($row['date']);
		   $text.="<td class='".$cls."_l'>".$trdDate->format("F jS")."</td>\n";
		   if ($row['team_id_0']==$tid)
		   {
			   $idx=0;
			   $toTid=$row['team_id_1'];
		   }
		   else
		   {
			   $idx=1;
			   $toTid=$row['team_id_0'];
		   }

		   $fnd=0;
		   $text.="<td class='".$cls."_l'>";
		   for ($i=0;$i<5;$i++)
		   {
			   if ($row['player_id_'.$idx.'_'.$i]!=0)
			   {
				   if ($fnd==1) {$text.="<br/>";}
				   $fnd=1;
				   $pid=$row['player_id_'.$idx.'_'.$i];
				   if (!isset($players[$pid]['name']))
				   {
					   $nQuery="SELECT first_name,last_name,position FROM players WHERE player_id=$pid";
					   $nResult=mysqli_query($db,$nQuery);
					   if (mysqli_num_rows($nResult))
					   {
						   $nRow=mysqli_fetch_array($nResult);
						   $players[$pid]['name']=$nRow['first_name']." ".$nRow['last_name'];
						   $players[$pid]['pos']=$nRow['position'];
					   }
					   else
					   {
						   $players[$pid]['name']='Out of baseball';
						   $players[$pid]['pos']=$row['position'];
					   }
				   }
				   $text.=get_pos($players[$pid]['pos'],1)." <a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>";
			   }
		   }
		   for ($i=0;$i<5;$i++)
		   {
			   if ($row['draft_round_'.$idx.'_'.$i]!=0)
			   {
				   if ($fnd==1) {$text.="<br/>";}
				   $fnd=1;
				   $rnd=$row['draft_round_'.$idx.'_'.$i];
				   $text.=ordinal_suffix($rnd)." Round Draft Pick";
			   }
		   }
		   if ($row['cash_'.$idx]!=0)
		   {
			   if ($fnd==1) {$text.="<br/>";}
			   $text.=stat_format('cash',$row['cash_'.$idx]);
		   }
		   $text.="</td>\n";

		   if (!isset($teams[$toTid]['name']))
		   {
			   $tQuery="SELECT name,nickname,abbr FROM team";
			   if ($year==$thisYear) {$tQuery.="s WHERE team_id=$toTid";}
			   else {$tQuery.="_history WHERE team_id=$toTid AND year=$year";}
				   $tResult=mysqli_query($db,$tQuery);
			   if (mysqli_num_rows($tResult))
			   {
				   $tRow=mysqli_fetch_array($tResult);
				   $teams[$toTid]['city']=$tRow['name'];
				   $teams[$toTid]['name']=$tRow['name']." ".$tRow['nickname'];
				   $teams[$toTid]['abbr']=$tRow['abbr'];
			   }
		   }
		   $text.="<td class='".$cls."_l'>to the <a href='./team_summary.php?team_id=$toTid&year=$year'>".$teams[$toTid]['name']."</a> for</td>";

		   $idx=abs($idx-1);
		   $fnd=0;
		   $text.="<td class='".$cls."_l'>";
		   for ($i=0;$i<5;$i++)
		   {
			   if ($row['player_id_'.$idx.'_'.$i]!=0)
			   {
				   if ($fnd==1) {$text.="<br/>";}
				   $fnd=1;
				   $pid=$row['player_id_'.$idx.'_'.$i];
				   if (!isset($players[$pid]['name']))
				   {
					   $nQuery="SELECT first_name,last_name,position FROM players WHERE player_id=$pid";
					   $nResult=mysqli_query($db,$nQuery);
					   if (mysqli_num_rows($nResult))
					   {
						   $nRow=mysqli_fetch_array($nResult);
						   $players[$pid]['name']=$nRow['first_name']." ".$nRow['last_name'];
						   $players[$pid]['pos']=$nRow['position'];
					   }
					   else
					   {
						   $players[$pid]['name']='Out of baseball';
						   $players[$pid]['pos']=$row['position'];
					   }
				   }
				   $text.=get_pos($players[$pid]['pos'],1)." <a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>";
			   }
		   }
		   for ($i=0;$i<5;$i++)
		   {
			   if ($row['draft_round_'.$idx.'_'.$i]!=0)
			   {
				   if ($fnd==1) {$text.="<br/>";}
				   $fnd=1;
				   $rnd=$row['draft_round_'.$idx.'_'.$i];
				   $text.=ordinal_suffix($rnd)." Round Draft Pick";
			   }
		   }
		   if ($row['cash_'.$idx]!=0)
		   {
			   if ($fnd==1) {$text.="<br/>";}
			   $text.=stat_format('cash',$row['cash_'.$idx]);
		   }
		   $text.="</td>\n";

		   $text.="</tr>\n";

		   $rowCnt++;
	   }

	   $text.=" </table>\n";
	   $text.="</div>   <!-- END of Trades -->\n";
   }

   mysqli_close($db);

   return $text;
 }

?>
