<?php

  include("html_functions.php");



  ################## PAGE INITIALIZATION #########################

  $lgid=$_SESSION['lgid'];

  $lgyear=$_SESSION['lgyear'];

  $yr=$_GET['year'];

  $slid=$_GET['sub_league_id'];



  if (($slid!="")&&($yr!=""))

  {

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

	  $query="SELECT name,designated_hitter FROM sub_leagues WHERE league_id=$lgid AND sub_league_id=$slid;";

	  $result=mysqli_query($db,$query);

	  $row=mysqli_fetch_array($result);

	  $slName=$row['name'];

	  $useDH=$row['designated_hitter'];

	  $query="SELECT value FROM ootp_sql_admin WHERE setting='dh$slid';";

	  $result=mysqli_query($db,$query);

	  $row=mysqli_fetch_array($result);

	  $dhYr=$row['value'];

	  mysqli_close($db);

	  if ($dhYr!="")

	  {

		  if (($useDH==1)&&($dhYr>$yr)) {$useDH=0;}

		  elseif (($useDH==0)&&($dhYr>$yr)) {$useDH=1;}

	  }



	  $title="$yr $slName Overview";

  }

  else {$title="League Overview";}



  page_head($title,$_SESSION['lgpath'],"","","./jquery/excanvas.js|./jquery/jquery.min.js|./jquery/jquery.jqplot.min.js|./jquery/plugins/jqplot.highlighter.min.js|./jquery/plugins/jqplot.cursor.min.js|./jquery/plugins/jqplot.pieRenderer.min.js");

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

  main_titlebar($lgid,$_SESSION['lgpath'],$title);

  nav_toolbar("history","History");

  nav_toolbar("leagues","",$lgid,$slid,"",$yr);

  echo " </div>   <!-- END topbar DIV -->\n";

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



  ## Close if unselected

  if (($slid=="")||($yr==""))

  {

	  echo "<p>Please choose a sub-league and year.</p>\n";

	  ################## END OF PAGE #########################

	  echo " </div>   <!-- END contentpane DIV -->\n";

	  page_foot($_SESSION['lgpath']);

	  exit;

  }

	

  ################## START OF PAGE CONTENT #########################

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



  #Get Division Names

  $query="SELECT division_id,name FROM divisions WHERE league_id=$lgid AND sub_league_id=$slid;";

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);

  $divCnt=0;

  while ($row=mysqli_fetch_array($result))

  {

	  $divID=$row['division_id'];

	  $divisions[$divID]['name']=$row['name'];

	  $divCnt++;

  }

  #Get Team Names

  $query="SELECT team_id,name,nickname,abbr";

  if ($lgyear==$yr) {$query.=" FROM teams WHERE league_id=$lgid AND allstar_team=0";}

  else {$query.=",made_playoffs,won_playoffs FROM team_history WHERE league_id=$lgid AND year=$yr";}

  $query.=" AND sub_league_id=$slid;";

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);

  $tlist="";

  $tmCnt=0;

  while ($row=mysqli_fetch_array($result))

  {

	  $tid=$row['team_id'];

	  $teams[$tid]['name']=$row['name']." ".$row['nickname'];

	  $teams[$tid]['city']=$row['name'];

	  $teams[$tid]['abbr']=$row['abbr'];

	  $teams[$tid]['made_playoffs']=$row['made_playoffs'];

	  $teams[$tid]['won_playoffs']=$row['won_playoffs'];

	  $tlist.="$tid,";

	  $tmCnt++;

  }

  $tlist=trim($tlist,",");

  $teams[0]['abbr']="Ukwn";



  #Get Team Colors

  $query="SELECT team_id,text_color_id,background_color_id FROM teams WHERE team_id IN ($tlist);";

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);

  while ($row=mysqli_fetch_array($result))

  {

	  $tid=$row['team_id'];

	  $teams[$tid]['text_color_id']=$row['text_color_id'];

	  $teams[$tid]['background_color_id']=$row['background_color_id'];

  }



  ## Get Award Names

  $query="SELECT mvp_award_name,pitcher_award_name,rookie_award_name,defense_award_name FROM leagues WHERE league_id=$lgid;";

  $result=mysqli_query($db,$query);

  $row=mysqli_fetch_array($result);

  $awardName[5]=$row['mvp_award_name'];

  $awardName[4]=$row['pitcher_award_name'];

  $awardName[6]=$row['rookie_award_name'];

  $awardName[7]=$row['defense_award_name'];

  $awardName[9]='All-Star';





  #Get Standings

  $query="SELECT t.team_id,name,nickname,abbr,w,l,w/(w+l) as pct,gb ";

  if ($yr==$lgyear) {$query.=",tr.division_id FROM teams as t,team_record as thr,team_relations as tr WHERE t.team_id=thr.team_id AND t.team_id=tr.team_id AND thr.team_id=tr.team_id";}

  else {$query.=",t.division_id FROM team_history as t,team_history_record as thr WHERE t.team_id=thr.team_id AND t.year=thr.year AND t.year=$yr";}

  $query.=" AND t.league_id=$lgid AND t.sub_league_id=$slid ORDER BY division_id,pct DESC";

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);



  $prevDIV=-1;

  $rowCnt=0;

  echo "<div class='textbox' style='width:100%;'>   <!-- open standings -->\n";

  echo " <table border=0 cellpadding=4 cellspacing=0 width='100%' style='margin-left:auto;margin-right:auto;'>   <!-- open standings -->\n";

  echo "  <tr class='title2'><td colspan=$divCnt>Divisional Standings</td></tr>\n";

  echo "  <tr><td style='vertical-align:top;'>";

  while ($row=mysqli_fetch_array($result))

  {

	  $tid=$row['team_id'];

	  $teams[$tid]['city']=$row['name'];

	  $teams[$tid]['mascot']=$row['nickname'];

	  $teams[$tid]['name']=$row['name']." ".$row['nickname'];

	  $teams[$tid]['abbr']=$row['abbr'];



	  $divID=$row['division_id'];      //OOTP12

	  //$divID=$row['division_id']+1;    OOTP13



	  if ($divID!=$prevDIV)

	  {

		  if ($prevDIV!=-1)

		  {

			  echo "   </table>\n";

			  echo "  </td>\n";

			  echo "  <td style='vertical-align:top;'>\n";

		  }



		  echo "   <table border=0 cellpadding=2 cellspacing=0 width='100%' style='margin-left:auto;margin-right:auto;'>   <!-- open division table -->\n";

		  echo "    <tr class='title'><td colspan=5>".$divisions[$divID]['name']."</td></tr>\n";

		  echo "    <tr class='headline'><td class='hsc2_l'>Team</td><td class='hsc2'>W</td><td class='hsc2'>L</td><td class='hsc2'>Pct</td><td class='hsc2'>GB</td></tr>\n";

		  $rowCnt=0;

	  }



	  if ($teams[$tid]['won_playoffs']==1) {$cls='b';} else {$cls='s';}

	  $cls.=($rowCnt%2+1);



	  echo "    <tr class='$cls'>";

	  echo "<td class='".$cls."_l'><a href='./team_summary.php?team_id=$tid&year=$yr'";

	  if ($teams[$tid]['won_playoffs']==1) {echo " style='font-weight:bold;'";}

	  echo ">".$teams[$tid]['name']."</a>";

	  if ($teams[$tid]['won_playoffs']==1) {echo "*";$showLegend=1;}

	  elseif ($teams[$tid]['made_playoffs']==1) {echo "~";$showLegend=1;}

	  echo "</td>";

	  echo "<td>".$row['w']."</td>";

	  echo "<td>".$row['l']."</td>";

	  $pct=sprintf("%.3f",$row['pct']);

	  if ($pct<1) {$pct=strstr($pct,".");}

	  echo "<td>$pct</td>";

	  $gb=$row['gb'];

	  if ($gb==0) {$gb="-";}

	  echo "<td>$gb</td>";

	  echo "</tr>\n";



	  $rowCnt++;

	  $prevDIV=$divID;

  }

  echo "   </table>   <!-- close division table -->\n";

  echo "  </td></tr>\n";

  echo " </table>   <!-- close standings -->\n";

  echo "</div>   <!-- close standings -->\n";

  if ($showLegend==1) {echo " <p>* = Won Championship<br/>~ = Reached Postseason</p>\n";}



  ## Get Postseason Results



  ## Get Award Winners

  #Major Awards

  $query="SELECT p.player_id,first_name,last_name,pa.team_id,award_id,pa.position FROM players as p,(";

  $query.="(SELECT best_pitcher_id as player_id,team_id,award_id,position FROM league_history as lh,players_awards as pa WHERE lh.league_id=$lgid AND lh.sub_league_id=$slid AND lh.year=pa.season AND award_id=4 AND best_pitcher_id=player_id AND season=$yr)";

  $query.=" UNION (SELECT best_hitter_id as player_id,team_id,award_id,position FROM league_history as lh,players_awards as pa WHERE lh.league_id=$lgid AND lh.sub_league_id=$slid AND lh.year=pa.season AND award_id=5 AND best_hitter_id=player_id AND season=$yr)";

  $query.=" UNION (SELECT best_rookie_id as player_id,team_id,award_id,position FROM league_history as lh,players_awards as pa WHERE lh.league_id=$lgid AND lh.sub_league_id=$slid AND lh.year=pa.season AND award_id=6 AND best_rookie_id=player_id AND season=$yr)";

  $query.=" UNION (SELECT player_id,team_id,award_id,position FROM players_awards WHERE league_id=$lgid AND sub_league_id=$slid AND season=$yr AND award_id IN (7,8,9))";

  $query.=") as pa WHERE p.player_id=pa.player_id ORDER BY award_id,position,last_name,first_name;";

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);

  if (mysqli_num_rows($result))

  {

	  echo "<div class='textbox' style='width:100%;'>   <!-- open award winners -->\n";

	  echo " <table border=0 cellpadding=4 cellspacing=0 width='100%' style='margin-left:auto;margin-right:auto;'>   <!-- open award winners -->\n";

	  echo "  <tr class='title2'><td colspan=2>Award Winners</td></tr>\n";



	  #Get Winners

	  $plist="";

	  $gglist="";

	  $aslist="";
      
      $fasList="";

	  while ($row=mysqli_fetch_array($result))

	  {

		  $pid=$row['player_id'];

		  $tid=$row['team_id'];

		  $awid=$row['award_id'];

		  $pos=$row['position'];



		  $players[$pid]['name']=$row['first_name']." ".$row['last_name'];

		  if ($tid!=0) {$players[$pid]['tid']=$tid;}

		  if ($awid==7) {$players[$pid]['pos']=$pos;}



		  switch ($awid)

		  {

		  case 7:  $gglist.="$pid,"; break;

		  case 9:
                  if ($tid==0) {$fasList.="$pid,";}
                  else {$aslist.="$pid,";}
                  break;

		  default: $plist.="$pid,"; $awards[$awid]['pid']=$pid; break;

		  }

	  }

	  $plist=trim($plist,",");

	  $gglist=trim($gglist,",");

      $aslist=trim($aslist,",");
      $fasList=trim($fasList,",");



	  #Display Major Award Winners

	  echo "  <tr><td style='vertical-align:top;width:350px;'>\n";

	  echo "   <table border=0 cellpadding=2 cellspacing=0 width='100%'>\n";

	  echo "    <tr class='headline'><td class='hsc2_l' colspan=2>Awards</td></tr>\n";

	  #Get EOS Award Winner Stats

	  if ($plist!="")

	  {

		  $query="SELECT player_id,team_id,SUM(pa) as pa,SUM(ip) as ip FROM (";

		  $query.="(SELECT player_id,team_id,SUM(pa) as pa,0 as ip FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND year=$yr AND team_id IN ($tlist) AND player_id IN ($plist) GROUP BY player_id)";

		  $query.=" UNION ";

		  $query.="(SELECT player_id,team_id,0 as pa,SUM(ip)+SUM(ipf)/3 as ip FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND year=$yr AND team_id IN ($tlist) AND player_id IN ($plist) GROUP BY player_id)";

		  $query.=") as x GROUP BY player_id";

		  if ($_GET['showq']==1) {echo "$query<br/>\n";}

		  $result=mysqli_query($db,$query);

		  $pplist="";

		  $pblist="";

		  while ($row=mysqli_fetch_array($result))

		  {

			  $pid=$row['player_id'];

			  if (!isset($players[$pid]['tid'])) {$players[$pid]['tid']=$row['team_id'];}

			  $pa=$row['pa'];

			  $ip=$row['ip'];

			  if ($pa>2*$ip) {$pblist.=",$pid";} else {$pplist.=",$pid";}

		  }

		  $pplist=trim($pplist,",");

		  $pblist=trim($pblist,",");

		  if ($pblist!="")

		  {

			  $query="SELECT player_id,CONCAT(ROUND(SUM(h)/SUM(ab),3),' AVG, ',SUM(hr),' HR, ',SUM(rbi),' RBI') as statline FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND year=$yr AND team_id IN ($tlist) AND player_id IN ($pblist) GROUP BY player_id";

			  if ($_GET['showq']==1) {echo "$query<br/>\n";}

			  $result=mysqli_query($db,$query);

			  while ($row=mysqli_fetch_array($result))

			  {

				  $pid=$row['player_id'];

				  $statline=$row['statline'];

				  if ($statline[0]=='0') {$statline=substr($statline,1);}

				  $players[$pid]['statline']=$statline;

			  }

		  }

		  if ($pplist!="")

		  {

			  $query="SELECT player_id,CONCAT(SUM(w),'-',SUM(l),', ',ROUND(9*SUM(er)/(SUM(ip)+SUM(ipf)/3),2),' ERA, ',ROUND(SUM(ip)+SUM(ipf)/3,1),' IP, ',SUM(k),' K',if(SUM(s)>0,CONCAT(', ',SUM(s),' SV'),'')) as statline FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND year=$yr AND team_id IN ($tlist) AND player_id IN ($pplist) GROUP BY player_id";

			  if ($_GET['showq']==1) {echo "$query<br/>\n";}

			  $result=mysqli_query($db,$query);

			  while ($row=mysqli_fetch_array($result))

			  {

				  $pid=$row['player_id'];

				  $players[$pid]['statline']=$row['statline'];

			  }

		  }

		  #Dispaly EOS Award Winners

		  $rowCnt=0;

		  foreach ($awards as $awid => $val)

		  {

			  $pid=$awards[$awid]['pid'];

			  $tid=$players[$pid]['tid'];



			  $cls='s'.($rowCnt%2+1);

			  echo "    <tr class='".$cls."_l'><td>".$awardName[$awid]."</td>";

			  echo "<td><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>";

			  if (($tid!=0)&&($tid!="")) {echo " (<a href='./team_summary.php?year=$yr&team_id=$tid'>".$teams[$tid]['abbr']."</a>)";}

			  echo "</td>";

			  echo "</tr>\n";

			  echo "    <tr class='".$cls."_l'><td>&nbsp;</td>";

			  echo "<td>".$players[$pid]['statline']."</td>";

			  echo "</tr>\n";



			  $rowCnt++;

		  }

	  }

	  else {echo "    <tr><td colspan=2 style='text-align:center;'> - None - </td></tr>\n";}

	  echo "   </table>\n";

	  echo "  </td>\n";



	  #Display Gold Glovers

	  $awid=7;

	  echo "  <td style='vertical-align:top;width:450px;'>\n";

	  echo "   <table border=0 cellpadding=2 cellspacing=0 width='100%'>\n";

	  echo "    <tr class='headline'><td class='hsc2_l' colspan=3>".$awardName[$awid]."</td></tr>\n";

	  #Get GG Stats

	  if ($gglist!="")

	  {

		  $query="SELECT player_id,position,team_id,CONCAT(ROUND((SUM(po)+SUM(a))/SUM(tc),3),', ',ROUND(SUM(ip)+SUM(ipf)/3,1),' Inn, ',SUM(po),' PO, ',SUM(a),' A, ',SUM(e),' E',if(SUM(sba)>0,CONCAT(', ',ROUND(100*SUM(rto)/SUM(sba),1),'% RTO'),'')) as statline FROM players_career_fielding_stats WHERE league_id=$lgid AND year=$yr AND position<10 AND team_id IN ($tlist) AND player_id IN ($gglist) GROUP BY player_id,position;";

		  if ($_GET['showq']==1) {echo "$query<br/>\n";}

		  $result=mysqli_query($db,$query);

		  while ($row=mysqli_fetch_array($result))

		  {

			  $pid=$row['player_id'];

			  $ppos=$players[$pid]['pos'];

			  if ($ppos!=$row['position']) {continue;}

			  $statline=$row['statline'];

			  if ($statline[0]=='0') {$statline=substr($statline,1);}

			  $players[$pid]['statline']=$statline;

			  if (!isset($players[$pid]['tid'])) {$players[$pid]['tid']=$row['team_id'];}

		  }

		  #Display GG Winners

		  $e=explode(",",$gglist);

		  $rowCnt=0;

		  foreach ($e as $key => $pid)

		  {

			  $pos=$players[$pid]['pos'];

			  $tid=$players[$pid]['tid'];



			  $cls='s'.($rowCnt%2+1);

			  echo "    <tr class='".$cls."_l'><td>".get_pos($pos)."</td>";

			  echo "<td><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>";

			  if (($tid!=0)&&($tid!="")) {echo " (<a href='./team_summary.php?year=$yr&team_id=$tid'>".$teams[$tid]['abbr']."</a>)";}

			  echo "</td>";

			  echo "<td>".$players[$pid]['statline']."</td>";

			  echo "</tr>\n";



			  $rowCnt++;

		  }

	  }

	  else {echo "    <tr><td colspan=3 style='text-align:center;'> - None - </td></tr>\n";}

	  echo "   </table>\n";

	  echo "  </td></tr>\n";



	  #Display All-Stars

	  if ($aslist!="")

	  {

		  echo "  <tr><td style='vertical-align:top;padding:0px 4px 4px 4px;' colspan=2>\n";

		  echo "   <table border=0 cellpadding=2 cellspacing=0 width='100%'>\n";

		  echo "    <tr class='headline'><td class='hsc2' style='text-align:center;' colspan=5>All-Stars</td></tr>\n";

		  $e=explode(",",$aslist);

		  $asCnt=0;

		  $rowCnt=0;

		  foreach ($e as $key => $pid)

		  {

			  $tid=$players[$pid]['tid'];

			  if (!isset($allstars[$tid])) {$allstars[$tid]=1;}

			  else {$allstars[$tid]+=1;}



			  if (($asCnt%5)==0)

			  {

				  $cls='s'.($rowCnt%2+1);

				  if ($asCnt>0) {echo "</tr>\n";}

				  echo "    <tr class='".$cls."_l'>";

				  $rowCnt++;

			  }

			  echo "<td><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>";

			  if (($tid!=0)&&($tid!="")) {echo " (<a href='./team_summary.php?year=$yr&team_id=$tid'>".$teams[$tid]['abbr']."</a>)";}

			  echo "</td>";

			  $asCnt++;

		  }

		  if (($asCnt%5)!=0) {echo "<td colspan=".(5-$asCnt%5).">&nbsp;</td>";}

		  echo "</tr>\n";

		  echo "   </table>\n";

		  echo "  </td></tr>\n";



		  # Display by team pie chart

		  echo "  <tr><td colspan=2><div id='chartdiv' style='height:300px;width:400px;margin-left:auto;margin-right:auto;'></div></td></tr>\n";

		  echo "  <script class='code' type='text/javascript'>\n";

		  echo "   <!--\n";

		  echo "    $(document).ready(function(){\n";

		  echo "      var data = [";

		  arsort($allstars);

		  $rowCnt=0;

		  foreach ($allstars as $tid => $asCnt) 

		  {

			  if ($rowCnt>0) {echo ",";}

			  echo "['".$teams[$tid]['abbr']."', ".$allstars[$tid]."]";

			  $rowCnt++;

		  }

		  echo "];\n";

		  echo "      var plot1 = jQuery.jqplot ('chartdiv', [data], {\n";

		  echo "       title:'All-Stars By Team',\n";

		  echo "	  seriesDefaults: {\n";

		  echo "                 renderer: jQuery.jqplot.PieRenderer,\n";

		  echo "                 rendererOptions: {showDataLabels: true, dataLabels: 'value', startAngle: -180},\n";

		  echo "                 },\n";

		  echo "          seriesColors:[";

		  $rowCnt=0;

		  foreach ($allstars as $tid => $asCnt) 

		  {

			  if ($rowCnt>0) {echo ",";}

			  echo "'".$teams[$tid]['background_color_id']."'";

			  $rowCnt++;

		  }

		  echo "],\n";

		  echo "	  legend: {show: true, location: 'e', placement: 'outsideGrid' }\n";

		  echo "       });\n";



		  echo "      $(\"#chartdiv\").bind('jqplotDataHighlight', function(ev, seriesIndex, pointIndex, data) {\n";

		  echo "	  var $"."this = $(this);\n";

		  echo "	  $"."this.attr('title', data[0] + \": \" + data[1]);\n";

		  echo "      });\n";

		  echo "      $(\"#chartdiv\").bind('jqplotDataUnhighlight', function(ev, seriesIndex, pointIndex, data) {\n";

		  echo "	  var $"."this = $(this);\n";

		  echo "	  $"."this.attr('title',\"\");\n";

	   	  echo "      });\n";



		  echo "      var pieLabelElements = jQuery('.jqplot-pie-series.jqplot-data-label').get();\n";

		  $rowCnt=0;

		  foreach ($allstars as $tid => $asCnt) 

		  {

			  echo "      pieLabelElements[$rowCnt].style.color='".$teams[$tid]['text_color_id']."';\n";

			  $rowCnt++;

		  }



		  echo "    });\n";

		  echo "   -->\n";

		  echo "  </script>\n";

	  }

      #Display All-Star Futures Game Players

      if ($fasList!="")

      {

          echo "  <tr><td style='vertical-align:top;padding:0px 4px 4px 4px;' colspan=2>\n";

          echo "   <table border=0 cellpadding=2 cellspacing=0 width='100%'>\n";

          echo "    <tr class='headline'><td class='hsc2' style='text-align:center;' colspan=5>All-Star Futures Game Participants</td></tr>\n";

          $e=explode(",",$fasList);

          $asCnt=0;

          $rowCnt=0;

          foreach ($e as $key => $pid)

          {
              
              $tid=$players[$pid]['tid'];

              if (($asCnt%5)==0)

              {

                  $cls='s'.($rowCnt%2+1);

                  if ($asCnt>0) {echo "</tr>\n";}

                  echo "    <tr class='".$cls."_l'>";

                  $rowCnt++;

              }

              echo "<td><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>";

              if (($tid!=0)&&($tid!="")) {echo " (<a href='./team_summary.php?year=$yr&team_id=$tid'>".$teams[$tid]['abbr']."</a>)";}

              echo "</td>";

              $asCnt++;

          }

          if (($asCnt%5)!=0) {echo "<td colspan=".(5-$asCnt%5).">&nbsp;</td>";}

          echo "</tr>\n";

          echo "   </table>\n";

          echo "  </td></tr>\n";

      }

	  echo " </table>   <!-- close award winners -->\n";

	  echo "</div>   <!-- close award winners -->\n";

  }



  ## Get League Team Stats

  $whoArray=Array("batting","pitching","fielding_stats");

  foreach ($whoArray as $key => $who)

  {

	  switch ($who)

	  {

	  case "batting":

		  $statArray=Array('rperg','r','g','pa','ab','h','d','t','hr','rbi','bb','k','sb','cs','avg','obp','slg','ops');

		  break;

	  case "pitching":

		  $statArray=Array("rperg","w","l","winpct","r","g","cg","sho","s","era","ip","ha","hra","bb","k","whip","oavg","babip");

		  break;

	  case "fielding_stats":

		  $statArray=Array("g","po","a","dp","tp","tc","e","fpct","inn","rng","pb","sba","rto","rtoPct");

		  break;

	  }



	  echo "<div class='textbox' style='width:100%;'>   <!-- open $who stats -->\n";

	  echo " <table border=0 cellpadding=4 cellspacing=0 width='100%' style='margin-left:auto;margin-right:auto;'>   <!-- open $who stats -->\n";

	  if ($who=='fielding_stats') {echo "  <tr class='title2'><td>Fielding Stats</td></tr>\n";}

	  else {echo "  <tr class='title2'><td>".ucwords($who)." Stats</td></tr>\n";}

	  echo "  <tr><td style='padding:0px;'>\n";

	  echo "   <table border=0 cellpadding=2 cellspacing=0 width='100%' class='sortable'>\n";

	  echo "    <thead><tr class='headline'>";

	  echo "<td class='hsc2_l'>Team</td>";

	  foreach ($statArray as $key => $statLbl) {echo "<td class='hsc2'>".stat_text($statLbl,2)."</td>";}

	  echo "</tr></thead>\n";

	  $query="SELECT ts.team_id";

	  foreach ($statArray as $key => $statLbl)

	  {

		  switch ($statLbl)

		  {

		  case 'rperg':

			  $query.=",if(SUM(tr.g)=0,0,SUM(ts.r)/SUM(tr.g)) as $statLbl";

			  break;

		  case 'g':

		  case 'w':

		  case 'l':

		  case 'winpct':

			  $query.=",".stat_query($statLbl,'tr')." as $statLbl";

			  break;

		  default:

			  $query.=",".stat_query($statLbl,'ts')." as $statLbl";

			  break;

		  }

	  }

	  if ($lgyear==$yr) {$query.=" FROM team_".$who."_stats as ts,team_record as tr WHERE ";}

	  else {$query.=" FROM team_history_".$who."_stats as ts,team_history_record as tr WHERE ts.year=tr.year AND ts.year=$yr AND ";}

	  $query.=" ts.team_id=tr.team_id AND ts.team_id IN ($tlist) GROUP BY team_id";

	  switch ($who)

	  {

	  case "batting"       : $query.=" ORDER BY rperg DESC,r DESC"; break;

	  case "pitching"      : $query.=" ORDER BY rperg,r";           break;

	  case "fielding_stats": $query.=" ORDER BY inn DESC";          break;

	  }

	  if ($_GET['showq']==1) {echo "$query<br/>\n";}

	  $result=mysqli_query($db,$query);

	  $rowCnt=0;

	  while ($row=mysqli_fetch_array($result))

	  {

		  $tid=$row['team_id'];



		  $cls='s'.($rowCnt%2+1);



		  echo "    <tr class='$cls'>";

		  echo "<td class='".$cls."_l'><a href='./team_summary.php?year=$yr&team_id=$tid'>".$teams[$tid]['name']."</a></td>";

		  foreach ($statArray as $key => $statLbl) {echo "<td>".stat_format($statLbl,$row[$statLbl])."</td>";}

		  echo "</tr>\n";

		  $rowCnt++;

	  }



	  $e=explode(" GROUP BY",$query);

	  $query=$e[0];

	  if ($_GET['showq']==1) {echo "$query<br/>\n";}

	  $result=mysqli_query($db,$query);

	  $row=mysqli_fetch_array($result);

	  echo "    <tfoot><tr class='headline'>";

	  echo "<td class='hsc2_l'>Totals</td>";

	  foreach ($statArray as $key => $statLbl) {echo "<td class='hsc2'>".stat_format($statLbl,$row[$statLbl])."</td>";}

	  echo "</tr></tfoot>\n";



	  echo "   </table>\n";

	  echo "  </td></tr>\n";

	  echo " </table>   <!-- close $who stats -->\n";

	  echo "</div>   <!-- close $who stats -->\n";

  }

  

  ## Get Team Financial Stats

  $statArray=Array('attendance','avgtix','player_expenses','staff_expenses','budget','tot_revenue','tot_expenses','profit');

  echo "<div class='textbox' style='width:100%;'>   <!-- open financial stats -->\n";

  echo " <table border=0 cellpadding=4 cellspacing=0 width='100%' style='margin-left:auto;margin-right:auto;'>   <!-- open financial stats -->\n";

  echo "  <tr class='title2'><td>Financial Stats</td></tr>\n";

  echo "  <tr><td style='padding:0px;'>\n";

  echo "   <table border=0 cellpadding=2 cellspacing=0 width='100%' class='sortable'>\n";

  echo "    <thead><tr class='headline'>";

  echo "<td class='hsc2_l'>Team</td>";

  foreach ($statArray as $key => $statLbl) {echo "<td class='hsc2'>".stat_text($statLbl,2)."</td>";}

  echo "</tr></thead>\n";

  $query="SELECT ts.team_id";

  foreach ($statArray as $key => $statLbl) {$query.=",".stat_query($statLbl)." as $statLbl";}

  if ($lgyear==$yr) {$query.=" FROM team_financials as ts WHERE ";}

  else {$query.=" FROM team_history_financials as ts WHERE ts.year=$yr AND ";}

  $query.="ts.team_id IN ($tlist) GROUP BY team_id ORDER BY attendance DESC";

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);

  $rowCnt=0;

  while ($row=mysqli_fetch_array($result))

  {

	  $tid=$row['team_id'];



	  $cls='s'.($rowCnt%2+1);



	  echo "    <tr class='$cls'>";

	  echo "<td class='".$cls."_l'><a href='./team_summary.php?year=$yr&team_id=$tid'>".$teams[$tid]['name']."</a></td>";

	  foreach ($statArray as $key => $statLbl) {echo "<td sorttable_customkey='".$row[$statLbl]."'>".stat_format($statLbl,$row[$statLbl])."</td>";}

	  echo "</tr>\n";

	  $rowCnt++;

  }



  $e=explode(" GROUP BY",$query);

  $query=$e[0];

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);

  $row=mysqli_fetch_array($result);

  echo "    <tfoot><tr class='headline'>";

  echo "<td class='hsc2_l'>Totals</td>";

  foreach ($statArray as $key => $statLbl) {echo "<td class='hsc2'>".stat_format($statLbl,$row[$statLbl])."</td>";}

  echo "</tr></tfoot>\n";



  echo "   </table>\n";

  echo "  </td></tr>\n";

  echo " </table>   <!-- close financial stats -->\n";

  echo "</div>   <!-- close financial stats -->\n";



  ## Get League Leaders

  $whoArray=Array("batting","pitching");

  foreach ($whoArray as $key => $who)

  {

	  switch ($who)

	  {

	  case "batting":

		  $statArray=Array("avg","obp","slg","ops","g","gs","ab","pa","h","d","t","hr","r","rbi","tb","ebh","sb","cs","bb","k","war");

		  break;

	  case "pitching":

		  $statArray=Array("w","l","era","whip","winpct","g","ip","bf","k","bb","er","r","gs","gf","cg","sho","hper9","kper9","rper9","hrper9","kperbb","s","war");

		  break;

	  }

	  $statCnt=0;

	  echo "<div class='textbox' style='width:100%;'>   <!-- open leaders -->\n";

	  echo " <table border=0 cellpadding=4 cellspacing=0 width='100%' style='border=1px solid black;margin-left:auto;margin-right:auto;'>   <!-- open leaders -->\n";

	  echo "  <tr class='title2'><td colspan=4>".ucwords($who)." Leaders</td></tr>\n";

	  echo "  <tr>";

	  foreach ($statArray as $key => $statLbl)

	  {

		  if ((($statCnt%4)==0)&&($statCnt!=0))   ## Start New Row Every 4 Stats

		  {

			  echo "  </tr>\n";

			  echo "  <tr>\n";

		  }



		  if ($statLbl=='winpct') {$squery=stat_query($statLbl,"pcs");}

		  else {$squery=stat_query($statLbl);}

		  $ssort=stat_sort($statLbl);

		  $stext=stat_text($statLbl);



		  #Get 5th place

		  $query="SELECT player_id,";

		  switch ($statLbl)

		  {

		  case "avg":

		  case "obp":

		  case "slg":

		  case "ops":

			  $query.="ts.g,ROUND($squery,5) as $statLbl FROM players_career_".$who."_stats as pcs,";

			  if ($lgyear==$yr) {$query.="team_record";} else {$query.="team_history_record";}

	 		  $query.=" as ts WHERE pcs.split_id=1 AND pcs.team_id=ts.team_id AND pcs.year=$yr";

			  if ($lgyear!=$yr) {$query.=" AND pcs.year=ts.year";}

	 		  $query.=" AND pcs.team_id IN ($tlist) GROUP BY player_id HAVING SUM(pa)>=(3.1*ts.g) ORDER BY $statLbl $ssort LIMIT 4,1";

			  break;

		  case "era":

		  case "whip":

		  case "winpct":

		  case "kper9":

		  case "bbper9":

		  case "hper9":

		  case "rper9":

		  case "hrper9":

		  case "kperbb":

			  $query.="ts.g,ROUND($squery,5) as $statLbl FROM players_career_".$who."_stats as pcs,";

			  if ($lgyear==$yr) {$query.="team_record";} else {$query.="team_history_record";}

	 		  $query.=" as ts WHERE pcs.split_id=1 AND pcs.team_id=ts.team_id AND pcs.year=$yr";

			  if ($lgyear!=$yr) {$query.=" AND pcs.year=ts.year";}

	 		  $query.=" AND pcs.team_id IN ($tlist) GROUP BY player_id HAVING (SUM(ip)+SUM(ipf)/3)>=ts.g ORDER BY $statLbl $ssort LIMIT 4,1";

			  break;

		  default:

			  $query.="$squery as $statLbl FROM players_career_".$who."_stats WHERE split_id=1 AND year=$yr AND team_id IN ($tlist) GROUP BY player_id ORDER BY $statLbl $ssort LIMIT 4,1";

			  break;

		  }

		  if ($_GET['showq']==1) {echo "$query<br/>\n";}

		  $result=mysqli_query($db,$query);

		  $row=mysqli_fetch_array($result);

		  $fifth=$row[$statLbl];		  

		  #Get Top 5

		  $query="SELECT p.player_id,p.first_name,p.last_name,pcs.team_id,COUNT(DISTINCT pcs.team_id) as nTeams,";

		  switch ($statLbl)

		  {

		  case "avg":

		  case "obp":

		  case "slg":

		  case "ops":

			  $query.="ts.g,ROUND($squery,5) as $statLbl FROM players as p,players_career_".$who."_stats as pcs,";

			  if ($lgyear==$yr) {$query.="team_record";} else {$query.="team_history_record";}

			  $query.=" as ts WHERE pcs.split_id=1 AND pcs.team_id=ts.team_id AND pcs.year=$yr";

			  if ($lgyear!=$yr) {$query.=" AND pcs.year=ts.year";}

	 		  $query.=" AND p.player_id=pcs.player_id AND pcs.team_id IN ($tlist) GROUP BY player_id HAVING SUM(pa)>=(3.1*ts.g) AND ROUND($squery,5) ".stat_sort($statLbl,1,1)." $fifth ORDER BY $statLbl $ssort";

			  break;

		  case "era":

		  case "whip":

		  case "winpct":

		  case "kper9":

		  case "bbper9":

		  case "hper9":

		  case "rper9":

		  case "hrper9":

		  case "kperbb":

			  $query.="ts.g,ROUND($squery,5) as $statLbl FROM players as p,players_career_".$who."_stats as pcs,";

			  if ($lgyear==$yr) {$query.="team_record";} else {$query.="team_history_record";}

			  $query.=" as ts WHERE pcs.split_id=1 AND pcs.team_id=ts.team_id AND pcs.year=$yr";

			  if ($lgyear!=$yr) {$query.=" AND pcs.year=ts.year";}

	 		  $query.=" AND p.player_id=pcs.player_id AND pcs.team_id IN ($tlist) GROUP BY player_id HAVING (SUM(ip)+SUM(ipf)/3)>=ts.g AND ROUND($squery,5) ".stat_sort($statLbl,1,1)." $fifth ORDER BY $statLbl $ssort";

			  break;

		  default:

			  $query.="$squery as $statLbl FROM players as p,players_career_".$who."_stats as pcs WHERE pcs.split_id=1 AND pcs.year=$yr AND p.player_id=pcs.player_id AND pcs.team_id IN ($tlist) GROUP BY player_id HAVING $squery ".stat_sort($statLbl,1,1)." $fifth ORDER BY $statLbl $ssort";

			  break;

		  }

		  if ($_GET['showq']==1) {echo "$query<br/>\n";}

		  $result=mysqli_query($db,$query);

		  $totRowCnt=mysqli_num_rows($result);

	

		  echo "   <td style='width:200px;vertical-align:top;'>\n";

		  echo "    <table border=0 cellpadding=2 cellspacing=0 width='100%' style='margin-left:auto;margin-right:auto;'>   <!-- open stat table -->\n";

		  echo "     <tr class='title'><td colspan=2 style='vertical-align:top;'>$stext</td><td style='vertical-align:middle;text-align:right;padding:2px 2px 0px 0px;'><a href='./leaderboards.php?view=players&scope=season&sub_league_id=$slid&listing=top100&team_id=ALL&split=regular&stat=$statLbl&who=ALL&pos=ALL&from=$yr&to=$yr'><img src='./images/leaderLink.png' style='border:none;' title='Display $yr $stext Leaders'></a></td></tr>\n";

		  $rowCnt=0;

		  while ($row=mysqli_fetch_array($result))

		  {

			  if ($rowCnt>=5) {continue;}

			  $pid=$row['player_id'];

			  $tid=$row['team_id'];

			  $statVal=$row[$statLbl];

			  if ($rowCnt==0) {$leaderVal=$statVal;}



			  if (($statVal==$leaderVal)&&(($rowCnt!=4)||($totRowCnt<6))) {$cls='b';}

			  else {$cls='s';}

			  $cls.=($rowCnt%2+1);



			  echo "     <tr class='$cls'>";

			  if (($totRowCnt>5)&&($rowCnt==4))

			  {

				  echo "<td colspan=2>".($totRowCnt-4);

				  if ($prevStat==$statVal) {echo " more";}

				  echo " players tied with</td>";

			  }

			  else

			  {

				  echo "<td class='".$cls."_l'><a href='./player.php?player_id=$pid'";

				  if (($statVal==$leaderVal)&&(($rowCnt!=4)||($totRowCnt<6))) {echo " style='font-weight:bold;'";}

				  echo ">".$row['first_name'][0].". ".$row['last_name']."</a></td>";

				  echo "<td class='".$cls."_l'><a href='./team_hist.php?team_id=$tid&year=$yr'";

				  if (($statVal==$leaderVal)&&(($rowCnt!=4)||($totRowCnt<6))) {echo " style='font-weight:bold;'";}

				  echo ">".$teams[$tid]['abbr']."</a>";

				  if ($row['nTeams']>1) {echo "<sup>(".$row['nTeams'].")</sup>";}

				  echo "</td>";

			  }

			  echo "<td>".stat_format($statLbl,$statVal)."</td>";

			  echo "</tr>\n";

			  $rowCnt++;

			  $prevStat=$statVal;

		  }

		  echo "    </table>\n";

		  echo "   </td>\n";

		  $statCnt++;

	  }



	  if (($statCnt%4)>0) {echo "   <td colspan=".(4-$statCnt%4).">&nbsp;</td>\n";}

	  echo "  </tr>\n";

	  echo " </table>   <!-- close leaders -->\n";

	  echo "</div>   <!-- close leaders -->\n";

  }



  ## Get Top Players By Position

  echo "<div class='textbox' style='width:100%;'>   <!-- open top players -->\n";

  echo " <table border=0 cellpadding=4 cellspacing=0 width='100%' style='border=1px solid black;margin-left:auto;margin-right:auto;'>   <!-- open top players -->\n";

  echo "  <tr class='title2'><td colspan=2>Top Players By Position</td></tr>\n";

  echo "  <tr>\n";

  $tCnt=0;

  # Get Positions

  if ($useDH==1)

  {

      $query="SELECT t1.player_id,pa,ip FROM (SELECT player_id,SUM(pa) as pa FROM players_career_batting_stats WHERE league_id=$lgid AND team_id IN ($tlist) AND split_id=1 AND year=$yr GROUP BY player_id) as t1 LEFT JOIN (SELECT player_id,SUM(ip)+SUM(ipf)/3 as ip FROM players_career_fielding_stats WHERE league_id=$lgid AND year=$yr AND team_id IN ($tlist) AND position!=10 GROUP BY player_id) as t2 ON t1.player_id=t2.player_id WHERE pa>ip OR ip IS NULL";

      if ($_GET['showq']==1) {echo "$query<br/>\n";}

      $result=mysqli_query($db,$query);

      $posPids[10]="";

      if (mysqli_num_rows($result))

      {

	      while ($row=mysqli_fetch_array($result))

	      {

		      $pid=$row['player_id'];

		      $posPids[10].=",$pid";

	      }

	      $posPids[10]=trim($posPids[10],",");

      }

  }

  $query="SET @pid:=0;";

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);

  $query="SELECT player_id,position FROM (SELECT if(@pid!=player_id,1,0) as priPos,@pid:=player_id as player_id,position,g,ip FROM (SELECT player_id,position,SUM(g) as g,SUM(ip)+SUM(ipf)/3 as ip FROM players_career_fielding_stats WHERE league_id=$lgid AND year=$yr AND position>1 AND position<10 AND team_id IN ($tlist)";

  if ($posPids[10]!="") {$query.=" AND player_id NOT IN (".$posPids[10].")";}

  $query.=" GROUP BY player_id,position ORDER BY player_id,ip DESC,g DESC) as x) as t WHERE priPos=1";

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);

  if (mysqli_num_rows($result))

  {

	  for ($pos=2;$pos<10;$pos++) {$posPids[$pos]="";}



	  while ($row=mysqli_fetch_array($result))

	  {

		  $pid=$row['player_id'];

		  $pos=$row['position'];

		  $posPids[$pos].=",$pid";

	  }



	  $statArray=Array("h","hr","rbi","sb","avg","ops","war");

	  $statCnt=count($statArray)+1;



	  for ($pos=2;$pos<=10;$pos++)

	  {

		  $plist=trim($posPids[$pos],",");

		  if ($plist=="") {continue;}

		  $query="SELECT p.player_id,first_name,last_name,x.team_id,nTeams";

		  foreach ($statArray as $key => $statLbl) {$query.=",$statLbl";}

		  $query.=" FROM players as p,(";

		  $query.="SELECT player_id,team_id,COUNT(DISTINCT team_id) as nTeams";

		  foreach ($statArray as $key => $statLbl)

		  {

			  $query.=",".stat_query($statLbl)." as $statLbl";

		  }

		  $query.=",(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) + SUM(pa)/25 ) as lw";

		  $query.=" FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND year=$yr AND team_id IN ($tlist) AND player_id IN ($plist) GROUP BY player_id ORDER BY war DESC,lw DESC LIMIT 5";

		  $query.=") as x WHERE p.player_id=x.player_id ORDER BY war DESC,lw DESC";

		  if ($_GET['showq']==1) {echo "$query<br/>\n";}

		  $result=mysqli_query($db,$query);



		  if ((($tCnt%2)==0)&&($tCnt!=0)) {echo "  <tr>\n";}

		  echo "   <td style='width:400px;vertical-align:top;'>\n";

		  echo "    <table border=0 cellpadding=2 cellspacing=0 width='100%' style='margin-left:auto;margin-right:auto;'>   <!-- open stat table -->\n";

		  echo "     <tr class='title'><td colspan=$statCnt style='vertical-align:top;'>".get_pos($pos,"",1)."</td></tr>\n";

		  echo "     <tr class='headline'><td class='hsc2_l'>Player</td><td class='hsc2_l'>Tm</td>";

		  foreach ($statArray as $key => $statLbl) 

		  {

			  switch ($statLbl)

			  {

			  case 'war':

			  case 'lw':

				  break;

			  default:

				  echo "<td class='hsc2'>".stat_text($statLbl,2)."</td>";

				  break;

			  }

		  }

		  echo "</tr>\n";

		  $rowCnt=0;

		  while ($row=mysqli_fetch_array($result))

		  {

			  $pid=$row['player_id'];

			  $tid=$row['team_id'];



			  $cls='s'.($rowCnt%2+1);

			  echo "     <tr class='$cls'>";

			  echo "<td class='".$cls."_l'><a href='./player.php?player_id=$pid'>".$row['first_name'][0].". ".$row['last_name']."</a></td>";

			  echo "<td class='".$cls."_l'><a href='./team_summary.php?year=$yr&team_id=$tid'>".$teams[$tid]['abbr']."</a>";

			  if ($row['nTeams']>1) {echo "<sup>(".$row['nTeams'].")</sup>";}

			  echo "</td>";

			  foreach ($statArray as $key => $statLbl) 

			  {

				  switch ($statLbl)

				  {

				  case 'war':

				  case 'lw':

					  break;

				  default:

					  echo "<td>".stat_format($statLbl,$row[$statLbl])."</td>";

					  break;

				  }

			  }

			  echo "</tr>\n";

			  $rowCnt++;

		  }

		  echo "    </table>\n";

		  echo "   </td>\n";



		  $tCnt++;

		  if (($tCnt%2)==0) {echo "  </tr>\n";}

	  }

  }

  if (($tCnt%2)==1)

  {

	  echo "   <td>&nbsp;</td>";

	  $tCnt++;

	  if (($tCnt%2)==0) {echo "  </tr>\n";}

  }

  # Starters (more than half of appearances as starts)

  $statArray=Array("w","l","era","ip","k","bb","war");

  $statCnt=count($statArray)+1;

  $pos=11;

  $query="SELECT p.player_id,first_name,last_name,x.team_id,nTeams";

  foreach ($statArray as $key => $statLbl) {$query.=",$statLbl";}

  $query.=" FROM players as p,(";

  $query.="SELECT player_id,team_id,COUNT(DISTINCT team_id) as nTeams";

  foreach ($statArray as $key => $statLbl) {$query.=",".stat_query($statLbl)." as $statLbl";}

  $query.=",3*((SUM(ip)*3+SUM(ipf))/3)+4*SUM(w)-4*SUM(l)+5*SUM(s)+4*SUM(hld)+SUM(k)-2*SUM(ha)-2*SUM(bb) as score";

  $query.=" FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND year=$yr AND team_id IN ($tlist) GROUP BY player_id HAVING (SUM(gs)/SUM(g))>.5 ORDER BY war DESC,score DESC LIMIT 10";

  $query.=") as x WHERE p.player_id=x.player_id ORDER BY war DESC,score DESC";

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);

  if ((($tCnt%2)==0)&&($tCnt!=0)) {echo "  <tr>\n";}

  echo "   <td style='width:400px;vertical-align:top;'>\n";

  echo "    <table border=0 cellpadding=2 cellspacing=0 width='100%' style='margin-left:auto;margin-right:auto;'>   <!-- open stat table -->\n";

  echo "     <tr class='title'><td colspan=$statCnt style='vertical-align:top;'>".get_pos($pos,"",1)."</td></tr>\n";

  echo "     <tr class='headline'><td class='hsc2_l'>Player</td><td class='hsc2_l'>Tm</td>";

  foreach ($statArray as $key => $statLbl) 

  {

	  switch ($statLbl)

	  {

	  case 'war':

	  case 'lw':

		  break;

	  default:

		  echo "<td class='hsc2'>".stat_text($statLbl,2)."</td>";

		  break;

	  }

  }

  echo "</tr>\n";

  $rowCnt=0;

  while ($row=mysqli_fetch_array($result))

  {

	  $pid=$row['player_id'];

	  $tid=$row['team_id'];



	  $cls='s'.($rowCnt%2+1);

	  echo "     <tr class='$cls'>";

	  echo "<td class='".$cls."_l'><a href='./player.php?player_id=$pid'>".$row['first_name'][0].". ".$row['last_name']."</a></td>";

	  echo "<td class='".$cls."_l'><a href='./team_summary.php?year=$yr&team_id=$tid'>".$teams[$tid]['abbr']."</a>";

	  if ($row['nTeams']>1) {echo "<sup>(".$row['nTeams'].")</sup>";}

	  echo "</td>";

	  foreach ($statArray as $key => $statLbl) 

	  {

		  switch ($statLbl)

		  {

		  case 'war':

		  case 'lw':

			  break;

		  default:

			  echo "<td>".stat_format($statLbl,$row[$statLbl])."</td>";

			  break;

		  }

	  }

	  echo "</tr>\n";

	  $rowCnt++;

  }

  echo "    </table>\n";

  echo "   </td>\n";

  $tCnt++;

  if (($tCnt%2)==0) {echo "  </tr>\n";}



  # Relievers (less than half of appearances as starts)

  $statArray=Array("w","l","era","ip","s","hld","war");

  $statCnt=count($statArray)+1;

  $pos=21;

  $query="SELECT p.player_id,first_name,last_name,x.team_id,nTeams";

  foreach ($statArray as $key => $statLbl) {$query.=",$statLbl";}

  $query.=" FROM players as p,(";

  $query.="SELECT player_id,team_id,COUNT(DISTINCT team_id) as nTeams";

  foreach ($statArray as $key => $statLbl) {$query.=",".stat_query($statLbl)." as $statLbl";}

  $query.=",3*((SUM(ip)*3+SUM(ipf))/3)+4*SUM(w)-4*SUM(l)+5*SUM(s)+4*SUM(hld)+SUM(k)-2*SUM(ha)-2*SUM(bb) as score";

  $query.=" FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND year=$yr AND team_id IN ($tlist) GROUP BY player_id HAVING (SUM(gs)/SUM(g))<.5 ORDER BY war DESC,score DESC LIMIT 10";

  $query.=") as x WHERE p.player_id=x.player_id ORDER BY war DESC,score DESC";

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);

  if ((($tCnt%2)==0)&&($tCnt!=0)) {echo "  <tr>\n";}

  echo "   <td style='width:400px;vertical-align:top;'>\n";

  echo "    <table border=0 cellpadding=2 cellspacing=0 width='100%' style='margin-left:auto;margin-right:auto;'>   <!-- open stat table -->\n";

  echo "     <tr class='title'><td colspan=$statCnt style='vertical-align:top;'>".get_pos($pos,"",1)."</td></tr>\n";

  echo "     <tr class='headline'><td class='hsc2_l'>Player</td><td class='hsc2_l'>Tm</td>";

  foreach ($statArray as $key => $statLbl) 

  {

	  switch ($statLbl)

	  {

	  case 'war':

	  case 'lw':

		  break;

	  default:

		  echo "<td class='hsc2'>".stat_text($statLbl,2)."</td>";

		  break;

	  }

  }

  echo "</tr>\n";

  $rowCnt=0;

  while ($row=mysqli_fetch_array($result))

  {

	  $pid=$row['player_id'];

	  $tid=$row['team_id'];



	  $cls='s'.($rowCnt%2+1);

	  echo "     <tr class='$cls'>";

	  echo "<td class='".$cls."_l'><a href='./player.php?player_id=$pid'>".$row['first_name'][0].". ".$row['last_name']."</a></td>";

	  echo "<td class='".$cls."_l'><a href='./team_summary.php?year=$yr&team_id=$tid'>".$teams[$tid]['abbr']."</a>";

	  if ($row['nTeams']>1) {echo "<sup>(".$row['nTeams'].")</sup>";}

	  echo "</td>";

	  foreach ($statArray as $key => $statLbl) 

	  {

		  switch ($statLbl)

		  {

		  case 'war':

		  case 'lw':

			  break;

		  default:

			  echo "<td>".stat_format($statLbl,$row[$statLbl])."</td>";

			  break;

		  }

	  }

	  echo "</tr>\n";

	  $rowCnt++;

  }

  echo "    </table>\n";

  echo "   </td>\n";

  $tCnt++;

  if (($tCnt%2)==0) {echo "  </tr>\n";}



  echo "  </tr>\n";

  echo " </table>   <!-- close top players -->\n";

  echo "</div>   <!-- close top players -->\n";



  ## Get Debuts and Breakout Performances

  echo "<div class='textbox' style='width:100%;'>   <!-- open breakout players -->\n";

  echo " <table border=0 cellpadding=4 cellspacing=0 width='100%' style='border=1px solid black;margin-left:auto;margin-right:auto;'>   <!-- open breakout players -->\n";

  echo "  <tr class='title2'><td colspan=2>Notable Debuts and Breakout Performances</td></tr>\n";

  echo "  <tr>\n";



  # Batters

  $statArray=Array("h","hr","rbi","sb","avg","ops");

  $statCnt=count($statArray)+2;





  $query="SELECT first_name,last_name,x.* FROM players as p,(SELECT t1.player_id,team_id,t1.war as newWAR,t2.war as oldWAR,(t1.war-IF(t2.war IS NULL,0,t2.war))*IF(t2.war<-1,.5,1) as warDIFF";

  foreach ($statArray as $key => $statLbl)

  {

	  $query.=",$statLbl";

  }

  $query.=" FROM (SELECT y1.player_id,team_id,y2.war";

  foreach ($statArray as $key => $statLbl)

  {

	  $query.=",$statLbl";

  }

  $query.=" FROM (SELECT player_id,team_id,SUM(war) as war FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND year=$yr GROUP BY player_id,team_id ORDER BY player_id,war DESC) as y1,(SELECT player_id,SUM(war) as war";

  foreach ($statArray as $key => $statLbl)

  {

	  $query.=",".stat_query($statLbl)." as $statLbl";

  }

  $query.=" FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND year=$yr GROUP BY player_id) as y2 WHERE y1.player_id=y2.player_id GROUP BY player_id) as t1 LEFT JOIN (SELECT player_id,MAX(war) as war FROM(SELECT player_id,year,SUM(war) as war FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND year<$yr GROUP BY player_id,year) as t0 GROUP BY player_id) as t2 ON t1.player_id=t2.player_id WHERE team_id IN ($tlist) ORDER BY warDIFF desc LIMIT 10) as x WHERE p.player_id=x.player_id ORDER BY warDIFF desc";

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);



  echo "   <td style='width:400px;vertical-align:top;'>\n";

  echo "    <table border=0 cellpadding=2 cellspacing=0 width='100%' style='margin-left:auto;margin-right:auto;'>   <!-- open stat table -->\n";

  echo "     <tr class='title'><td colspan=$statCnt style='vertical-align:top;'>Batters</td></tr>\n";

  echo "     <tr class='headline'><td class='hsc2_l'>Player</td><td class='hsc2_l'>Tm</td>";

  foreach ($statArray as $key => $statLbl) 

  {

	  echo "<td class='hsc2'>".stat_text($statLbl,2)."</td>";

  }

  echo "</tr>\n";

  $rowCnt=0;

  while ($row=mysqli_fetch_array($result))

  {

	  $pid=$row['player_id'];

	  $tid=$row['team_id'];



	  $cls='s'.($rowCnt%2+1);

	  echo "     <tr class='$cls'>";

	  echo "<td class='".$cls."_l'><a href='./player.php?player_id=$pid'>".$row['first_name'][0].". ".$row['last_name']."</a></td>";

	  echo "<td class='".$cls."_l'><a href='./team_summary.php?year=$yr&team_id=$tid'>".$teams[$tid]['abbr']."</a>";

	  if ($row['nTeams']>1) {echo "<sup>(".$row['nTeams'].")</sup>";}

	  echo "</td>";

	  foreach ($statArray as $key => $statLbl) 

	  {

		  echo "<td>".stat_format($statLbl,$row[$statLbl])."</td>";

	  }

	  echo "</tr>\n";

	  $rowCnt++;

  }

  echo "    </table>\n";

  echo "   </td>\n";



  # Pitchers

  $statArray=Array("w","l","era","ip","k","bb","s","hld");

  $statCnt=count($statArray)+2;





  $query="SELECT first_name,last_name,x.* FROM players as p,(SELECT t1.player_id,team_id,t1.war as newWAR,t2.war as oldWAR,(t1.war-IF(t2.war IS NULL,0,t2.war))*IF(t2.war<-10,.5,1) as warDIFF";

  foreach ($statArray as $key => $statLbl)

  {

	  $query.=",$statLbl";

  }

  $query.=" FROM (SELECT y1.player_id,team_id,y2.war";

  foreach ($statArray as $key => $statLbl)

  {

	  $query.=",$statLbl";

  }

  $query.=" FROM (SELECT player_id,team_id,SUM(war) as war FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND year=$yr GROUP BY player_id,team_id ORDER BY player_id,war DESC) as y1,(SELECT player_id,SUM(war) as war";

  foreach ($statArray as $key => $statLbl)

  {

	  $query.=",".stat_query($statLbl)." as $statLbl";

  }

  $query.=" FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND year=$yr GROUP BY player_id) as y2 WHERE y1.player_id=y2.player_id GROUP BY player_id) as t1 LEFT JOIN (SELECT player_id,MAX(war) as war FROM(SELECT player_id,year,SUM(war) as war FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND year<$yr GROUP BY player_id,year) as t0 GROUP BY player_id) as t2 ON t1.player_id=t2.player_id WHERE team_id IN ($tlist) ORDER BY warDIFF desc LIMIT 10) as x WHERE p.player_id=x.player_id ORDER BY warDIFF desc";

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);



  echo "   <td style='width:400px;vertical-align:top;'>\n";

  echo "    <table border=0 cellpadding=2 cellspacing=0 width='100%' style='margin-left:auto;margin-right:auto;'>   <!-- open stat table -->\n";

  echo "     <tr class='title'><td colspan=$statCnt style='vertical-align:top;'>Pitchers</td></tr>\n";

  echo "     <tr class='headline'><td class='hsc2_l'>Player</td><td class='hsc2_l'>Tm</td>";

  foreach ($statArray as $key => $statLbl) 

  {

	  echo "<td class='hsc2'>".stat_text($statLbl,2)."</td>";

  }

  echo "</tr>\n";

  $rowCnt=0;

  while ($row=mysqli_fetch_array($result))

  {

	  $pid=$row['player_id'];

	  $tid=$row['team_id'];



	  $cls='s'.($rowCnt%2+1);

	  echo "     <tr class='$cls'>";

	  echo "<td class='".$cls."_l'><a href='./player.php?player_id=$pid'>".$row['first_name'][0].". ".$row['last_name']."</a></td>";

	  echo "<td class='".$cls."_l'><a href='./team_summary.php?year=$yr&team_id=$tid'>".$teams[$tid]['abbr']."</a>";

	  if ($row['nTeams']>1) {echo "<sup>(".$row['nTeams'].")</sup>";}

	  echo "</td>";

	  foreach ($statArray as $key => $statLbl) 

	  {

		  echo "<td>".stat_format($statLbl,$row[$statLbl])."</td>";

	  }

	  echo "</tr>\n";

	  $rowCnt++;

  }

  echo "    </table>\n";

  echo "   </td>\n";



  echo "  </tr>\n";

  echo "  <tr><td colspan=2>Players sorted by WAR minus previous career high in WAR<br/>Displayed stats are combined between leagues</td></tr>\n";

  echo " </table>   <!-- close breakout players -->\n";

  echo "</div>   <!-- close breakout players -->\n";







  mysqli_close($db);



  ################## END OF PAGE #########################

  echo " </div>   <!-- END contentpane DIV -->\n";

  page_foot($_SESSION['lgpath']);





?>

