<?php

  include("html_functions.php");



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

  $lgid=$_SESSION['lgid'];

  $lgpath=$_SESSION['lgpath'];

  $lgdate=$_SESSION['lgdate'];

  $date=new Date($_SESSION['lgdate']);

  $lgyear=$_SESSION['lgyear'];

  $player_id=$_GET['player_id'];

  $oppTmID=$_GET['opp_id'];

  if ($oppTmID=="") {$oppTmID="All";}



  $scope=$_GET['scope'];

  if ((($lgyear%400)==0) || ((($lgyear%100)!=0) && (($lgyear%4)==0)))

  {

	  $monthDays=Array("1"=>31,"2"=>29,"3"=>31,"4"=>30,"5"=>31,"6"=>30,"7"=>31,"8"=>31,"9"=>30,"10"=>31,"11"=>30,"12"=>31);

  }

  else

  {

	  $monthDays=Array("1"=>31,"2"=>28,"3"=>31,"4"=>30,"5"=>31,"6"=>30,"7"=>31,"8"=>31,"9"=>30,"10"=>31,"11"=>30,"12"=>31);

  }

  $frDay=$_GET['frDay'];

  if ($frDay=="") {$frDay="1/1";$minDay=1;}

  else

  {

	  $e=explode("/",$frDay);

       	  $mo=$e[0];

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

       	  if ($mo<1) {$mo=1;}

	  if ($mo>12) {$mo=12;}

       	  $dy=$e[1];

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

       	  if ($dy<1) {$dy=1;}

	  if ($dy>$monthDays[$mo]) {$dy=$monthDays[$mo];}

       	  $frDay=$mo."/".$dy;

	  unset($tmpdate);

       	  $tmpdate=new Date($frDay."/".$lgyear);

	  $minDay=$tmpdate->format("z");

  }

  $toDay=$_GET['toDay'];

  if ($toDay=="") {$toDay=$date->format("m/d");$maxDay=1;}

  else

  {

	  $e=explode("/",$toDay);

       	  $mo=$e[0];

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

       	  if ($mo<1) {$mo=1;}

	  if ($mo>12) {$mo=12;}

       	  $dy=$e[1];

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

       	  if ($dy<1) {$dy=1;}

	  if ($dy>$monthDays[$mo]) {$dy=$monthDays[$mo];}

       	  $toDay=$mo."/".$dy;

	  unset($tmpdate);

       	  $tmpdate=new Date($toDay."/".$lgyear);

	  $maxDay=$tmpdate->format("z")+1;

  }

  if ($minDay==$maxDay) {$minDay-=2;}

  if ($minDay>$maxDay)

  {

       	  $tmp=$frDay;

	  $frDay=$toDay;

       	  $toDay=$tmp;

	  $tmp=$minDay;

       	  $minDay=$maxDay;

	  $maxDay=$minDay;

  }

  

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



  ##### Get Teams #####

  $query="SELECT team_id,name,nickname,sub_league_id,abbr FROM teams WHERE league_id=$lgid AND allstar_team!=1 ORDER BY name,nickname;";

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

  while ($row=mysqli_fetch_array($result))

  {

	  $tid=$row['team_id'];

    	  $slid=$row['sub_league_id'];

	  $teams[$tid]['slid']=$slid;

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

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



	  $subleagues[$slid]['teams']=$subleagues[$slid]['teams'].",".$row['team_id'];

    	  $subleagues[$slid]['cnt']=$subleagues[$slid]['cnt']+1;

  }



  ##### Get Players #####

  $query="SELECT p.player_id,first_name,last_name,if(position=1,role,position) as position,organization_id FROM players as p,(SELECT player_id FROM (SELECT player_id FROM players_career_pitching_stats WHERE league_id=$lgid AND year=$lgyear GROUP BY player_id UNION SELECT player_id FROM players_career_batting_stats WHERE league_id=$lgid AND year=$lgyear GROUP BY player_id) as t GROUP BY player_id) as x WHERE p.player_id=x.player_id ORDER BY last_name,first_name";

  if ($_GET['showq']==1) {echo $query;}

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

  if (mysqli_num_rows($result)!=0)

  {

       	  while ($row=mysqli_fetch_array($result))

	  {

	    	  $pid=$row['player_id'];

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

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

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

	    	  $players[$pid]['org_id']=$row['organization_id'];

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

      	  }

  }



  mysqli_close($db);

  

  ##### Get Sim Length #####	  

  $simLen=get_sim_length($_SESSION['adminpath'],$lgid);



  # Title Bar

  $title="Last Sim Player Statistics";

  if ($player_id!="")

  {

       	  $title.=" - ".get_pos($players[$player_id]['position'],1)." ".$players[$player_id]['name'];

	  $tid=$players[$player_id]['org_id'];

       	  $title.=" (".$teams[$tid]['abbr'].")";

  }



  page_head($title,$_SESSION['lgpath']);

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

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

  nav_toolbar("season","Season");

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

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





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

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

  

  ##### Check that regular season has begun

  $gp[0]=0;

  $gp[1]=0;

  $query="SELECT game_type,COUNT(game_id) as g FROM games WHERE league_id=".$lgid." AND played=1 GROUP BY game_type;";

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

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

  while ($row=mysqli_fetch_array($result))

  {

	  $gtype=$row['game_type'];

       	  $gp[$gtype]=$row['g'];

  }

  if (($gp[0]==0)&&($gp[2]!=0)&&($scope=='Season')) {$scope="ST";}

  if ($scope=="") {$scope="Season";}



  if (($gp[0]==0)&&($gp[2]==0))

  {

	  echo "<div class='textbox' style='border:0;'>No games played yet.  Come back after the season starts!</div>\n";

	  mysqli_close($db);

	

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

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

	  page_foot($_SESSION['lgpath']);

	  exit;

  }

	  

  ##### Filters

  echo "<div class='textbox'>\n";

  echo " <table cellspacing=0 cellpadding=2 border=0>\n";

  echo "  <tr class='title'><td colspan=10>Filters</td></tr>\n";

  echo "  <form method='get' action='playerStats.php' class='inline'>\n";

  echo "   <tr>\n";

  echo "    <td><label for='view'>View:</label></td>\n";

  echo "     <td colspan=4>\n";

  echo "      <select name='player_id' id='player_id' onchange=\"document.getElementById('opp_id').selectedIndex=0;\">\n";

  if (isset($players))

  {

       	  foreach ($players as $player => $val)

	  {

	    	  $tid=$players[$player]['org_id'];

		  if ($tid==0) {$tabbr='FA';}

	   	  else {$tabbr=$teams[$tid]['abbr'];}

		  $name=$players[$player]['name'];

	    	  $position=get_pos($players[$player]['position'],1);

		  echo "       <option value='$player'";

	    	  if ($player_id==$player) {echo " selected";}

		  echo ">$position $name ($tabbr)</option>\n";

      	  }

  }

  echo "      </select>\n";

  echo "     </td>\n";

  echo "    <td><label for='opp_id'>Vs.</label></td>\n";

  echo "     <td colspan=3>\n";

  echo "      <select name='opp_id' id='opp_id'>\n";

  echo "       <option value='All'>All Teams</option>\n";

  if (isset($teams))

  {

	  foreach ($teams as $tid => $val)

	  {

		  echo "       <option value='$tid'";

		  if ($oppTmID==$tid) {echo " selected";}

		  echo ">".$teams[$tid]['name']."</option>\n";

	  }

  }

  echo "      </select>\n";

  echo "     </td>\n";

  if ($player_id!="")

  {

	  echo "    <td align='right'><a href='./player.php?player_id=".$player_id."'>StatsLab Player Page</a>, <a href='$lgpath/players/player_".$player_id.".html'>OOTP Player Page</a></td>\n";

  }

  else {echo "    <td>&nbsp;</td>\n";}

  echo "   </tr>\n";

  echo "   <tr>\n";

  ## Show Scope Filter

  echo "    <td><b>Scope:</b></td>\n";

  echo "    <td><input type='radio' name='scope' value='LastSim' id='LastSim'";

  if ($scope=='LastSim') {echo " checked='checked'";}

  echo "></td><td valign=top><label for='LastSim'>Last Sim</label></td>\n";

  echo "    <td><input type='radio' name='scope' value='Season' id='Season'";

  if ($scope=='Season') {echo " checked='checked'";}

  echo "></td><td valign=top><label for='Season'>Season</label></td>\n";

  echo "        <td><input type='radio' name='scope' value='dRange' id='dRange'";

  if ($scope=='dRange') {echo " checked='checked'";}

  echo "></td>";

  echo "        <td valign=top><label for='dRange'>Date Range (MM/DD)</label></td>\n";

  echo "        <td><table><tr><td>From</td><td><INPUT type='text' size=5 maxlength=5 name='frDay' value='$frDay' onchange=\"document.getElementById('dRange').checked=true;\"></td><td>To</td><td><INPUT type='text' size=5 maxlength=5 name='toDay' value='$toDay' onchange=\"document.getElementById('dRange').checked=true;\"></td></tr></table></td>";

  ## Close Form

  echo "    <td align='right'>\n";

  echo "     <input type='submit' class='submitButton' value='Go' />\n";

  echo "    </td>\n";

  echo "   </tr>\n";

  echo "  </form>\n";

  echo " </table>\n";

  echo "</div>\n";



  if ($player_id=="")

  {

	  mysqli_close($db);

	

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

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

	  page_foot($_SESSION['lgpath']);

	  exit;

  }



  $frDay=str_replace("/","-",$frDay);

  $toDay=str_replace("/","-",$toDay);



  $query="SELECT first_name,last_name,position,role,team_id,organization_id FROM players WHERE player_id=$player_id;";

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

  $row=mysqli_fetch_array($result);

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

  $players[$player_id]['name']=$name;

  $players[$player_id]['team_id']==$row['team_id'];

  $players[$player_id]['org_id']==$row['organization_id'];

  $players[$player_id]['position']=$row['position'];

  $players[$player_id]['role']=$row['role'];



  ##### Generate Content #####

  ##### Get Last Sim Team by Team Stats #####	  



  ## Get All-Star Game Date	     

  $query="SELECT date FROM games WHERE league_id=$lgid AND game_type=4;";

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

  if (mysqli_num_rows($result))

  {

	  $row=mysqli_fetch_array($result);

    	  $as_date=$row['date'];

  }



  ## Get Batting Stats

  if ($players[$player_id]['position']!=1)

  {

	  $statArray=Array('g','ab','r','h','d','t','hr','rbi','bb','k','sb','cs','hp','sf');

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

	  $query="SELECT g.game_id,team_id,g.date as game_date,g.time as game_time,home_team,away_team,runs0,runs1,game_type,position";

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

	  $query.=" FROM players_game_batting as pg,games as g WHERE g.league_id=$lgid AND pg.game_id=g.game_id AND player_id=$player_id";

	  if ($scope=="LastSim") {$query.=" AND played=1 AND DATEDIFF('".$lgdate."',g.date)<".$simLen;}

	  elseif ($scope=="dRange") {$query.=" AND played=1 AND g.date>='$lgyear-$frDay' AND g.date<='$lgyear-$toDay'";}

	  else {$query.=" AND game_type=0";}

	  if ($oppTmID!="All") {$query.=" AND ((home_team=$oppTmID AND team_id!=home_team) OR (away_team=$oppTmID AND team_id!=away_team))";}

	  $query.=" GROUP BY g.game_id ORDER BY game_date";

	  

    	  if ($_GET['showq']==1) {echo $query;}

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

    	  ## Display Stats

	  if (mysqli_num_rows($result))

   	  {

		  ## Display Game Logs

		  echo " <div class='textbox'>\n";

		  echo "  <table cellpadding=0 cellspacing=0 border=0><tr class='title2'><td style='padding:2px;'>Game Logs</td></tr>\n";

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

		  echo "     <table cellpadding=2 cellspacing=0 border=0 class='sortable' style='width:935px;'>\n";

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

		  echo "       <td class='hsc2_l'>Date</td><td class='hsc2_l'>Opp</td><td class='hsc2_l'>Result</td><td class='hsc2_l'>Type</td><td class='hsc2'>AB</td><td class='hsc2'>R</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'>BB</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>\n";

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

		  $cnt=0;

	 	  $prevGtype="";

	 

		  while ($row=mysqli_fetch_array($result))

		  {

	      		  $tid=$row['team_id'];

			  $gid=$row['game_id'];

			  $hid=$row['home_team'];

			  $aid=$row['away_team'];

			  $aruns=$row['runs0'];

			  $hruns=$row['runs1'];

			  

	      		  unset($gdate);

			  $gdate=new Date($row['game_date']);

			  $gtype=$row['game_type'];

			  switch ($gtype)

			  {

			  case 0: $gtAbbr="REG"; break;

	   		  case 2: $gtAbbr="ST"; break;

			  case 3: $gtAbbr="PS"; break;

	     		  }

			  if ($tid==$hid)

			  { 

				  $oppID=$aid;

		   		  $oppAbbr=$teams[$aid]['abbr'];

				  if ($hruns>$aruns) {$score="Win, $hruns-$aruns";} else {$score="Loss, $hruns-$aruns";}

	     		  }

			  else

	     		  {

		   		  $oppID=$hid;

				  $oppAbbr="@ ".$teams[$hid]['abbr'];

		   		  if ($aruns>$hruns) {$score="Win, $aruns-$hruns";} else {$score="Loss, $aruns-$hruns";}

			  }

      

			  ## Display Game Logs

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

			  if (($prevGtype!="")&&($prevGtype!=$gtype)) {$style=" style='border-top:3px double black;'";unset($statTotal);}

			  else {$style="";}



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

			  echo "<td class='".$cls."_l'$style sorttable_customkey='".$gdate->format("Ymd")."'><a href='$lgpath/box_scores/game_box_$gid.html'>".$gdate->format("m-d-Y")."</a></td>";

			  echo "<td class='".$cls."_l'$style><a href='$lgpath/teams/team_$oppID.html'>$oppAbbr</a></td>";

			  echo "<td class='".$cls."_l'$style>$score</td>";

			  echo "<td class='".$cls."_l'$style>$gtAbbr</td>";



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

			  {

				  if (!in_array($statLbl,$dispArray)) {$statTotal[$statLbl]=$statTotal[$statLbl]+$row[$statLbl];}

			  }

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

			  {

				  switch ($statLbl)

				  {

				  case 'avg':

					  if ($statTotal['ab']==0) {$statTotal['avg']=0;}

					  else {$statTotal['avg']=$statTotal['h']/$statTotal['ab'];}

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

					  break;

				  case 'obp':

					  if (($statTotal['ab']+$statTotal['bb']+$statTotal['hp']+$statTotal['sf'])==0) {$statTotal['obp']=0;}

					  else {$statTotal['obp']=($statTotal['h']+$statTotal['bb']+$statTotal['hp'])/($statTotal['ab']+$statTotal['bb']+$statTotal['hp']+$statTotal['sf']);}

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

					  break;

				  case 'slg':

					  if ($statTotal['ab']==0) {$statTotal['slg']=0;}

					  else {$statTotal['slg']=($statTotal['h']+$statTotal['d']+2*$statTotal['t']+3*$statTotal['hr'])/$statTotal['ab'];}

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

					  break;

				  case 'ops':

					  $statTotal['ops']=$statTotal['obp']+$statTotal['slg'];

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

					  break;

				  default:

					  $statTotal[$statLbl]=$statTotal[$statLbl]+$row[$statLbl];

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

					  break;

				  }

			  }

			  echo "</tr>\n";

		      

			  $prevGtype=$gtype;

			  $cnt++;

		  }

		  echo "     </table>\n";

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

		  echo "  </table>\n";

		  echo " </div>\n";



		  ## Display Splits

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

		  $coreQuery=$query;



		  echo " <div class='textbox'>\n";

		  echo "  <table cellpadding=0 cellspacing=0 border=0><tr class='title2'><td style='padding:2px;'>Batting Splits</td></tr>\n";

	 	  if (isset($as_date)) {$headings=Array('Season','Home/Away','By Month','By Half','Day/Night','vs. Opponent','By Position');}

		  else {$headings=Array('Season','Home/Away','By Month','Day/Night','vs. Opponent','By Position');}

		   

		  foreach ($headings as $key => $header)

		  {

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

			  echo " <div class='tablebox' style='width:915px;'>\n";

	      		  echo "  <table cellpadding=0 cellspacing=0 border=0><tr class='title'><td style='padding:2px;'>$header</td></tr><tr><td>\n";

			  echo "   <table cellpadding=2 cellspacing=0 border=0 class='sortable' style='width:915px;'>\n";

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

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

	      		  echo "<td class='hsc2'>G</td><td class='hsc2'>AB</td><td class='hsc2'>R</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'>BB</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>\n";

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



			  $query="";

			  $totQuery="";

			  unset($splits);

			  switch ($header)

	     		  {

			  case 'Season'      :

				  $query="SELECT game_type as split";

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

				  $query.=" FROM ($coreQuery) as t";

				  $totQuery=$query;

				  $query.=" GROUP BY game_type";



				  $splits[0]='Regular Season';

				  $splits[2]='Spring Training';

				  $splits[3]='Postseason';

				  break;

			  case 'Home/Away'   :

				  $query="SELECT if(team_id=home_team,'Home','Away') as split";

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

				  $query.=" FROM ($coreQuery) as t";

				  $query.=" GROUP BY split ORDER BY split DESC";

				  break;

			  case 'By Month'    :

				  $query="SELECT MONTH(game_date) as split,YEAR(game_date) as sYear";

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

				  $query.=" FROM ($coreQuery) as t";

				  $query.=" GROUP BY split ORDER BY sYear,split";



				  $splits=Array("??","January","February","March","April","May","June","July","August","September","October","November","December");

				  break;

			  case 'By Half'     :

				  $query="SELECT if(game_date<'$as_date',0,1) as split";

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

				  $query.=" FROM ($coreQuery) as t";

				  $query.=" GROUP BY split ORDER BY split";



				  $splits=Array("Pre All-Star Break","Post All-Star Break");

				  break;

			  case 'Day/Night'   :

				  $query="SELECT if(game_time<1700,0,1) as split";

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

				  $query.=" FROM ($coreQuery) as t";

				  $query.=" GROUP BY split ORDER BY split";

				 

				  $splits=Array("Day","Night");

				  break;

			  case 'vs. Opponent':

				  $query="SELECT name,nickname,y.* FROM teams as t,(";

				  $query.="SELECT if(team_id=home_team,away_team,home_team) as split,game_type";

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

				  $query.=" FROM ($coreQuery) as x";

				  $query.=" GROUP BY split,game_type";

				  $query.=") as y WHERE t.team_id=y.split ORDER BY name,nickname,game_type";

			 	  break;

			  case 'By Position' :

				  $query="SELECT position as split";

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

				  $query.=" FROM ($coreQuery) as t";

				  $query.=" GROUP BY split ORDER BY split";



				  $splits[0]='PH/PR/Subs';

				  for ($i=1;$i<=10;$i++) {$splits[$i]=get_pos($i,1);}

				  break;

	     		  }



			  ## Display Data by Split

			  if ($_GET['showq']==1) {echo $query;}

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

			  $rowCnt=0;

			  while ($row=mysqli_fetch_array($result))

			  {

				  $split=$row['split'];

				  if (isset($splits[$split])) {$split=$splits[$split];}



				  $rcls=$rowCnt%2+1;

				  echo "    <tr class='s".$rcls."'>";

				  switch ($header)

				  {

				  case 'vs. Opponent':

					  $oppID=$split;

					  $split="<a href='$lgpath/teams/team_$oppID.html'>".$row['name']." ".$row['nickname']."</a>";

					  switch ($row['game_type'])

					  {

					  case 0: break;

					  case 2: $split.=" (ST)"; break;

					  case 3: $split.=" (PS)"; break;

					  }

					  echo "<td class='s".$rcls."_l'>$split</a></td>";

					  break;

				  default:

					  echo "<td class='s".$rcls."_l'>$split</a></td>";

					  break;

				  }

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

				  echo "</tr>\n";



				  $rowCnt++;

			  }



			  ## Display Totals Row

			  if ($totQuery!="")

			  {

				  if ($_GET['showq']==1) {echo $totQuery;}

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

				  $row=mysqli_fetch_array($result);



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

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

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

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



			  }



	      		  ## Close Table

			  echo "   </table>\n";

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

			  echo "  </div>  <!-- end batting stat div -->\n";

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

		  }

	 	  echo "  </table>\n";

		  echo " </div>  <!-- end batting splits div -->\n";

   	  }

  }



  if ($players[$player_id]['position']==1)

  {

	  ## Get Opponents' Record

	  $query="SELECT tr.team_id,tr.w,tr.l,tbs.r,tps.r as ra FROM team_record as tr,team_batting_stats as tbs,team_pitching_stats as tps WHERE tr.team_id=tbs.team_id AND tbs.team_id=tps.team_id AND tbs.league_id=$lgid;";

	  if ($_GET['showq']==1) {echo $query;}

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

	  if (mysqli_num_rows($result))

	  { 

		  while ($row=mysqli_fetch_array($result))

		  {

			  $tid=$row['team_id'];

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

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

			  $teams[$tid]['g']=$row['w']+$row['l'];

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

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

		  }

	  }

  

	  ## Get Pitching Stats

	  $statArray=Array('w','l','s','hld','cg','sho','er','ip','g','gs','ha','r','hra','bb','k','ab','sf');

	  $dispArray=Array('cg','sho','era','g','gs','ip','ha','r','er','hra','bb','k','whip','oavg','babip');

	  $query="SELECT g.game_id,team_id,g.date as game_date,g.time as game_time,home_team,away_team,runs0,runs1,game_type,0 as ipf";

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

	  $query.=" FROM players_game_pitching_stats as pg,games as g WHERE g.league_id=$lgid AND pg.game_id=g.game_id AND player_id=$player_id";

	  if ($scope=="LastSim") {$query.=" AND played=1 AND DATEDIFF('".$lgdate."',g.date)<".$simLen;}

	  elseif ($scope=="dRange") {$query.=" AND played=1 AND g.date>='$lgyear-$frDay' AND g.date<='$lgyear-$toDay'";}

	  else {$query.=" AND game_type=0";}

	  if ($oppTmID!="All") {$query.=" AND ((home_team=$oppTmID AND team_id!=home_team) OR (away_team=$oppTmID AND team_id!=away_team))";}

	  $query.=" GROUP BY g.game_id ORDER BY game_date";

	  

    	  if ($_GET['showq']==1) {echo $query;}

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

    	  ## Display Stats

	  if (mysqli_num_rows($result))

   	  {

		  ## Display Game Logs

		  echo " <div class='textbox'>\n";

		  echo "  <table cellpadding=0 cellspacing=0 border=0><tr class='title2'><td style='padding:2px;'>Game Logs</td></tr>\n";

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

		  echo "     <table cellpadding=2 cellspacing=0 border=0 class='sortable' style='width:935px;'>\n";

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

		  echo "       <td class='hsc2_l'>Date</td><td class='hsc2_l'>Opp</td><td class='hsc2_l'>Result</td><td class='hsc2_l'>Type</td><td class='hsc2_l'>Dec</td><td class='hsc2'>CG</td><td class='hsc2'>SHO</td><td class='hsc2'>ERA</td><td class='hsc2'>G</td><td class='hsc2'>GS</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'>WHIP</td><td class='hsc2'>OAVG</td><td class='hsc2'>BABIP</td>\n";

		  echo "<td class='hsc2' title='Game Score'>GmS</td>";

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

		  $cnt=0;

	 	  $prevGtype="";

	 

		  while ($row=mysqli_fetch_array($result))

		  {

	      		  $tid=$row['team_id'];

			  $gid=$row['game_id'];

			  $hid=$row['home_team'];

			  $aid=$row['away_team'];

			  $aruns=$row['runs0'];

			  $hruns=$row['runs1'];

			  

	      		  unset($gdate);

			  $gdate=new Date($row['game_date']);

			  $gtype=$row['game_type'];

			  switch ($gtype)

			  {

			  case 0: $gtAbbr="REG"; break;

	   		  case 2: $gtAbbr="ST"; break;

			  case 3: $gtAbbr="PS"; break;

	     		  }

			  if ($tid==$hid)

			  { 

				  $oppID=$aid;

		   		  $oppAbbr=$teams[$aid]['abbr'];

				  if ($hruns>$aruns) {$score="Win, $hruns-$aruns";} else {$score="Loss, $hruns-$aruns";}

	     		  }

			  else

	     		  {

		   		  $oppID=$hid;

				  $oppAbbr="@ ".$teams[$hid]['abbr'];

		   		  if ($aruns>$hruns) {$score="Win, $aruns-$hruns";} else {$score="Loss, $aruns-$hruns";}

			  }

			  $OppW=$OppW+$teams[$oppID]['w'];

			  $OppL=$OppL+$teams[$oppID]['l'];

			  $OppR=$OppR+$teams[$oppID]['r'];

			  $OppRA=$OppRA+$teams[$oppID]['ra'];

      

			  ## Display Game Logs

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

			  if (($prevGtype!="")&&($prevGtype!=$gtype)) {$style=" style='border-top:3px double black;'";unset($statTotal);}

			  else {$style="";}



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

			  echo "<td class='".$cls."_l'$style sorttable_customkey='".$gdate->format("Ymd")."'><a href='$lgpath/box_scores/game_box_$gid.html'>".$gdate->format("m-d-Y")."</a></td>";

			  echo "<td class='".$cls."_l'$style><a href='$lgpath/teams/team_$oppID.html'>$oppAbbr</a></td>";

			  echo "<td class='".$cls."_l'$style>$score</td>";

			  echo "<td class='".$cls."_l'$style>$gtAbbr</td>";



			  ## Decision Column

			  $decision="";

			  if ($row['w']==1)

			  {

				  $decision="W (";

				  $recQuery="SELECT COUNT(DISTINCT game_id) as w FROM games WHERE winning_pitcher=$player_id AND game_type=$gtype AND games.date<'".$row['game_date']."' AND league_id=$lgid";

				  $recResult=mysqli_query($db,$recQuery);

				  $recRow=mysqli_fetch_array($recResult);

				  $decision.=$recRow['w']+1;

				  $recQuery="SELECT COUNT(DISTINCT game_id) as l FROM games WHERE losing_pitcher=$player_id AND game_type=$gtype AND games.date<'".$row['game_date']."' AND league_id=$lgid";

				  $recResult=mysqli_query($db,$recQuery);

				  $recRow=mysqli_fetch_array($recResult);

				  $decision.="-".$recRow['l'];

				  $decision.=")";

			  }

			  elseif ($row['l']==1)

			  {

				  $decision="L (";

				  $recQuery="SELECT COUNT(DISTINCT game_id) as w FROM games WHERE winning_pitcher=$player_id AND game_type=$gtype AND games.date<'".$row['game_date']."' AND league_id=$lgid";

				  $recResult=mysqli_query($db,$recQuery);

				  $recRow=mysqli_fetch_array($recResult);

				  $decision.=$recRow['w']."-";

				  $recQuery="SELECT COUNT(DISTINCT game_id) as l FROM games WHERE losing_pitcher=$player_id AND game_type=$gtype AND games.date<'".$row['game_date']."' AND league_id=$lgid";

				  $recResult=mysqli_query($db,$recQuery);

				  $recRow=mysqli_fetch_array($recResult);

				  $decision.=$recRow['l']+1;

				  $decision.=")";

			  }

			  elseif ($row['s']==1)

			  {

				  $decision="S (";

				  $recQuery="SELECT COUNT(DISTINCT game_id) as s FROM games WHERE save_pitcher=$player_id AND game_type=$gtype AND games.date<'".$row['game_date']."' AND league_id=$lgid";

				  $recResult=mysqli_query($db,$recQuery);

				  $recRow=mysqli_fetch_array($recResult);

				  $decision.=$recRow['s']+1;

				  $decision.=")";

			  }

			  if ($row['hld']==1)

			  {

				  if (($row['w']==1)||($row['L']==1)||($row['s']==1)) {$decision.=", HLD (";}

				  else {$decision="HLD (";}

				  $recQuery="SELECT SUM(hld) as hld FROM games,players_game_pitching_stats as pcs WHERE games.game_id=pcs.game_id AND player_id=$player_id AND game_type=$gtype AND games.date<'".$row['game_date']."' AND games.league_id=$lgid";



				  $recResult=mysqli_query($db,$recQuery);

				  $recRow=mysqli_fetch_array($recResult);

				  $decision.=$recRow['hld']+1;

				  $decision.=")";

			  }

	     		  if (($row['w']==0)&&($row['l']==0)&&($row['s']==0)&&($row['hld']==0)) {$decision="ND";}

			  echo "<td class='".$cls."_l'$style>$decision</td>";



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

			  {

				  if ((!in_array($statLbl,$dispArray))||($statLbl=='er')||($statLbl=='ip')) {$statTotal[$statLbl]=$statTotal[$statLbl]+$row[$statLbl];}

			  }

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

			  {

				  switch ($statLbl)

				  {

				  case 'era':

					  if ($statTotal['ip']==0) {$statTotal['era']=0;}

					  else {$statTotal['era']=(9*$statTotal['er'])/$statTotal['ip'];}

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

					  break;

				  case 'whip':

					  if ($statTotal['ip']==0) {$statTotal['whip']=0;}

					  else {$statTotal['whip']=($statTotal['ha']+$statTotal['bb'])/$statTotal['ip'];}

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

					  break;

				  case 'oavg':

					  if ($statTotal['ab']==0) {$statTotal['oavg']=0;}

					  else {$statTotal['oavg']=$statTotal['ha']/$statTotal['ab'];}

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

					  break;

				  case 'babip':

					  $bip=$statTotal['ab']-$statTotal['k']-$statTotal['hra']-$statTotal['sf'];

					  if ($bip==0) {$statTotal['babip']=0;}

					  else {$statTotal['babip']=($statTotal['ha']-$statTotal['hra'])/$bip;}

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

					  break;

				  default:

					  if (($statLbl!='er')&&($statLbl!='ip')) {$statTotal[$statLbl]=$statTotal[$statLbl]+$row[$statLbl];}

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

					  break;

				  }

			  }

			  if ($row['gs']==1)

			  {

				  $gmScore=50;

				  $gmScore+=round(1*3*$row['ip'],0);

				  if ($row['ip']>=5) {$gmScore+=2*(floor($row['ip'])-4);}

				  $gmScore+=1*$row['k'];

				  $gmScore+=-2*$row['ha'];

				  $gmScore+=-4*$row['er'];

				  $gmScore+=-2*($row['r']-$row['er']);

				  $gmScore+=-1*$row['bb'];

				  echo "<td sorttable_customkey='$gmScore'>$gmScore</td>\n";

			  }

			  else

			  {

				  echo "<td sorttable_customkey='0'>-</td>\n";

			  }

			  echo "</tr>\n";

		      

			  $prevGtype=$gtype;

			  $cnt++;

		  }

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

		  echo "<td colspan=8 class='hsc2' title='$OppW-$OppL'>Opponents' Season Win Pct: ".sprintf("%.3f",($OppW/($OppW+$OppL)))."</td>";

		  echo "<td class='hsc2'>&nbsp;</td>";

		  $pythExp=pow(($OppR+$OppRA)/($OppW+$OppL),0.287);

		  $pythPct=pow($OppR,$pythExp)/(pow($OppR,$pythExp)+pow($OppRA,$pythExp));

		  echo "<td colspan=12 class='hsc2_l' title='Pythagenpat, RF:$OppR RA:$OppRA'>Opponents' Season Pyth Pct: ".sprintf("%.3f",$pythPct)."</td>";

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

		  echo "     </table>\n";

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

		  echo "  </table>\n";

		  echo " </div>\n";



		  ## Display Splits

		  $dispArray=Array('w','l','s','cg','sho','era','g','gs','ip','ha','r','er','hra','bb','k','hld','whip','oavg','babip');

		  $coreQuery=$query;



		  echo " <div class='textbox'>\n";

	 	  echo "  <table cellpadding=0 cellspacing=0 border=0><tr class='title2'><td>Pitching Splits</td></tr>\n";

		  if (isset($as_date)) {$headings=Array('Season','Home/Away','By Month','By Half','Day/Night','vs. Opponent');}

		  else {$headings=Array('Season','Home/Away','By Month','Day/Night','vs. Opponent');}

		 

		  foreach ($headings as $key => $header)

		  {

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

			  echo " <div class='tablebox' style='width:915px;'>\n";

	      		  echo "  <table cellpadding=0 cellspacing=0 border=0><tr class='title'><td>$header</td></tr><tr><td>\n";

			  echo "   <table cellspacing=0 class='sortable' style='width:915px;'>\n";

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

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

	      		  echo "<td class='hsc2'>W</td><td class='hsc2'>L</td><td class='hsc2'>SV</td><td class='hsc2'>CG</td><td class='hsc2'>SHO</td><td class='hsc2'>ERA</td><td class='hsc2'>G</td><td class='hsc2'>GS</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'>WHIP</td><td class='hsc2'>OAVG</td><td class='hsc2'>BABIP</td>\n";

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

	      

			  $query="";

			  $totQuery="";

			  unset($splits);

			  switch ($header)

	     		  {

			  case 'Season'      :

				  $query="SELECT game_type as split";

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

				  $query.=" FROM ($coreQuery) as t";

				  $totQuery=$query;

				  $query.=" GROUP BY game_type";



				  $splits[0]='Regular Season';

				  $splits[2]='Spring Training';

				  $splits[3]='Postseason';

				  break;

			  case 'Home/Away'   :

				  $query="SELECT if(team_id=home_team,'Home','Away') as split";

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

				  $query.=" FROM ($coreQuery) as t";

				  $query.=" GROUP BY split ORDER BY split DESC";

				  break;

			  case 'By Month'    :

				  $query="SELECT MONTH(game_date) as split,YEAR(game_date) as sYear";

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

				  $query.=" FROM ($coreQuery) as t";

				  $query.=" GROUP BY split ORDER BY sYear,split";



				  $splits=Array("??","January","February","March","April","May","June","July","August","September","October","November","December");

				  break;

			  case 'By Half'     :

				  $query="SELECT if(game_date<'$as_date',0,1) as split";

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

				  $query.=" FROM ($coreQuery) as t";

				  $query.=" GROUP BY split ORDER BY split";



				  $splits=Array("Pre All-Star Break","Post All-Star Break");

				  break;

			  case 'Day/Night'   :

				  $query="SELECT if(game_time<1700,0,1) as split";

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

				  $query.=" FROM ($coreQuery) as t";

				  $query.=" GROUP BY split ORDER BY split";

				 

				  $splits=Array("Day","Night");

				  break;

			  case 'vs. Opponent':

				  $query="SELECT name,nickname,y.* FROM teams as t,(";

				  $query.="SELECT if(team_id=home_team,away_team,home_team) as split,game_type";

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

				  $query.=" FROM ($coreQuery) as x";

				  $query.=" GROUP BY split,game_type";

				  $query.=") as y WHERE t.team_id=y.split ORDER BY name,nickname,game_type";

			 	  break;

	     		  }



			  ## Display Data by Split

			  if ($_GET['showq']==1) {echo $query;}

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

			  $rowCnt=0;

			  while ($row=mysqli_fetch_array($result))

			  {

				  $split=$row['split'];

				  if (isset($splits[$split])) {$split=$splits[$split];}



				  $rcls=$rowCnt%2+1;

				  echo "    <tr class='s".$rcls."'>";

				  switch ($header)

				  {

				  case 'vs. Opponent':

					  $oppID=$split;

					  $split="<a href='$lgpath/teams/team_$oppID.html'>".$row['name']." ".$row['nickname']."</a>";

					  switch ($row['game_type'])

					  {

					  case 0: break;

					  case 2: $split.=" (ST)"; break;

					  case 3: $split.=" (PS)"; break;

					  }

					  echo "<td class='s".$rcls."_l'>$split</a></td>";

					  break;

				  default:

					  echo "<td class='s".$rcls."_l'>$split</a></td>";

					  break;

				  }

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

				  echo "</tr>\n";



				  $rowCnt++;

			  }



			  ## Display Totals Row

			  if ($totQuery!="")

			  {

				  if ($_GET['showq']==1) {echo $totQuery;}

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

				  $row=mysqli_fetch_array($result);



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

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

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

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

			  }

		

			  ## Close Table

			  echo "   </table>\n";

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

			  echo "  </div>  <!-- end pitching stat div -->\n";

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

		  }

	 	  echo "  </table>\n";

		  echo " </div>  <!-- end pitching splits div -->\n";

	  }

  }   ### End of Team Split Stats



  mysqli_close($db);



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

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

  page_foot($_SESSION['lgpath']);





?>

