<?php

  include("html_functions.php");



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

  $lgid=$_SESSION['lgid'];

  $lgpath=$_SESSION['lgpath'];

  $lgdate=$_SESSION['lgdate'];

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

  $lgyear=$date->format("Y");



  $view=$_GET['view'];

  if ($view[0]=="D") {$division_id=substr($view,1);$sub_league_id="";$team_id="";}

  if ($view[0]=="S") {$sub_league_id=substr($view,1);$division_id="";$team_id="";}

  if ($view[0]=="T") {$team_id=substr($view,1);$sub_league_id="";$division_id="";}

  if ($view=="")

  {

	  if ($_SESSION['user_team_id']>0) {$team_id=$_SESSION['user_team_id'];$sub_league_id="";$division_id="";}

	  if (isset($_GET['team_id'])) {$team_id=$_GET['team_id'];$sub_league_id="";$division_id="";}

  }



  $scope=$_GET['scope'];

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

  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 DateTime($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 DateTime($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;

  }

  

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

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



  # Title Bar

  $title="Last Sim Team Statistics";



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

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

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

  nav_toolbar("season","Season");

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

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





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

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



  ##### Filters #####

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

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

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

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

  echo "   <tr>\n";



  $fndView=0;

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

  echo "    <td>\n";

  echo "     <select name='view'>\n";

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

  ## Show League Filter

  $query="SELECT sub_league_id,name,abbr FROM sub_leagues WHERE league_id=$lgid ORDER BY sub_league_id;";

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

  if (mysqli_num_rows($result)>1)

  {

	  echo "      <optgroup label='Leagues'>\n";

	  while ($row=mysqli_fetch_array($result))

	  {

		  $slid=$row['sub_league_id'];

		  $subleagues[$slid]['abbr']=$row['abbr'];

	

		  echo "      <option value='S$slid'";

		  if ($sub_league_id==$slid) {echo " selected";$fndView=1;}

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

	  }

  }

  else {$oneLg=1;}

  ## Show Division Filter

  $query="SELECT division_id,sub_league_id,name FROM divisions WHERE league_id=$lgid ORDER BY sub_league_id,division_id;";

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

  if (mysqli_num_rows($result)>1)

  {

	  echo "      <optgroup label='Divisions'>\n";

	  while ($row=mysqli_fetch_array($result))

	  {

		  $divid=$row['division_id'];

		  $slid=$row['sub_league_id'];

		  $divid=$slid."_".$divid;



		  echo "      <option value='D$divid'";

		  if ($division_id==$divid) {echo " selected";$fndView=1;}

		  echo ">".$subleagues[$slid]['abbr']." ".$row['name']."</option>\n";

	  }

  }

  else {$oneDiv=1;}

  

  ## Show Team Filter

  $query="SELECT t.team_id,name,nickname,abbr,t.sub_league_id,tr.division_id FROM teams as t,team_relations as tr WHERE t.team_id=tr.team_id AND t.league_id=$lgid AND allstar_team!=1 ORDER BY name,nickname;";

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

  echo "      <optgroup label='Teams'>\n";

  while ($row=mysqli_fetch_array($result))

  {

	  $tid=$row['team_id'];

    	  $slid=$row['sub_league_id'];

	  $divid=$row['division_id'];

    	  $divid=$slid."_".$divid;

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

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

	  $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;



	  $divisions[$divid]['teams']=$divisions[$divid]['teams'].",".$row['team_id'];

    	  $divisions[$divid]['cnt']=$divisions[$divid]['cnt']+1;

       

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

	  if ($team_id==$tid) {echo " selected";$fndView=1;}

       	  echo ">".$row['name']." ".$row['nickname']."</option>\n";

  }

  echo "     </select>\n";

  echo "    </td>\n";

  if ($fndView==0) {$view='ALL';$team_id="";$sub_league_id="";$division_id="";}

  

  ## 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";



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

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



   ##### Get Subleagues #####

   $query="SELECT sub_league_id,name,abbr FROM sub_leagues WHERE league_id=$lgid ORDER BY sub_league_id;";

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

   while ($row=mysqli_fetch_array($result))

    {

      $slid=$row['sub_league_id'];

      $subleagues[$slid]['name']=$row['name'];

      $subleagues[$slid]['abbr']=$row['abbr'];

    }



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

   if ($sub_league_id!="") {$tlist=trim($subleagues[$sub_league_id]['teams'],",");}

   if ($division_id!="") {$tlist=trim($divisions[$division_id]['teams'],",");}

   if ($team_id!="") {$tlist=$team_id;}



   ##### Team Game Log #####

   if ($team_id!="")

   {

     	   ## Get Games      

	   $query="SELECT game_id,games.date,home_team,away_team,games.time,runs0,runs1,innings,game_type,winning_pitcher,losing_pitcher,save_pitcher,attendance FROM games WHERE league_id=$lgid AND (home_team=$team_id OR away_team=$team_id) AND played=1";

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

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

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

	   $query.=" ORDER BY date,time";

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

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

     

	   if (mysqli_num_rows($result)>0)

	   {

	  	   ## Initialize Team Wins

		   $gtypes=Array(0,2,3);

	  	   foreach ($gtypes as $val => $gtype)

		   {

	       		   $teams[$team_id]['w'][$gtype]=0;

			   $teams[$team_id]['l'][$gtype]=0;

	 	   }

	  

		   ## Get Pitchers

		   $pquery="SELECT p.player_id,first_name,last_name FROM players as p,(";

	  	   $pquery.="SELECT DISTINCT pitcher FROM (";

		   $pquery.="SELECT DISTINCT winning_pitcher as pitcher FROM games WHERE (home_team=$team_id OR away_team=$team_id)";

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

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

	 	   else {$pquery.=" AND played=1 AND game_type=0";}

		   $pquery.=" UNION ";

	  	   $pquery.="SELECT DISTINCT losing_pitcher as pitcher FROM games WHERE (home_team=$team_id OR away_team=$team_id)";

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

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

		   else {$pquery.=" AND played=1 AND game_type=0";}

		   $pquery.=" UNION ";

		   $pquery.="SELECT DISTINCT save_pitcher as pitcher FROM games WHERE (home_team=$team_id OR away_team=$team_id)";

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

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

	 	   else {$pquery.=" AND played=1 AND game_type=0";}

		   $pquery.=") as t0";

	  	   $pquery.=") as t1 WHERE p.player_id=t1.pitcher";

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

	  	   $presult=mysqli_query($db,$pquery);

		   $pList="";

	  	   while ($row=mysqli_fetch_array($presult))

		   {

	       		   $pid=$row['player_id'];

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

	       		   $psort=$row['last_name'].", ".$row['first_name'];

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

	       		   $players[$pid]['sort']=$psort;

			   foreach ($gtypes as $key => $gtype)

	      		   {

				   $players[$pid]['w'][$gtype]=0;

		    		   $players[$pid]['l'][$gtype]=0;

				   $players[$pid]['s'][$gtype]=0;

	      		   }

			   $pList.=",".$pid;

	 	   }

	  

		   ## Get Team Record and Pitcher W/L/SV prior to date range

		   if ($scope!='Season')

		   {

	       		   ## Team Record

			   $twQuery="SELECT game_type,SUM(Win) as w,SUM(Loss) as l FROM (SELECT game_id,game_type,runs0>runs1 as Loss,runs0<runs1 as Win FROM games WHERE played=1 AND home_team=$team_id";

	       		   if ($scope=="LastSim") {$twQuery.=" AND DATEDIFF('".$lgdate."',games.date)>=".$simLen;}

			   elseif ($scope=="dRange") {$twQuery.=" AND games.date<'$lgyear-$frDay'";}

		       	   $twQuery.=" UNION ";

			   $twQuery.="SELECT game_id,game_type,runs1>runs0 as Loss,runs1<runs0 as Win FROM games WHERE played=1 AND away_team=$team_id";

	       		   if ($scope=="LastSim") {$twQuery.=" AND DATEDIFF('".$lgdate."',games.date)>=".$simLen;}

			   elseif ($scope=="dRange") {$twQuery.=" AND games.date<'$lgyear-$frDay'";}

		       	   $twQuery.=") as t1 GROUP BY game_type;";

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

	       		   $twResult=mysqli_query($db,$twQuery);

			   while ($row=mysqli_fetch_array($twResult))

	      		   {

				   $gtype=$row['game_type'];

		    		   $teams[$team_id]['w'][$gtype]=$row['w'];

				   $teams[$team_id]['l'][$gtype]=$row['l'];

	      		   }

	       

			   ## Pitcher W/L/SV

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

	       		   $wlQuery="SELECT player_id,game_type,SUM(w) as w,SUM(l) as l,SUM(s) as s FROM (SELECT winning_pitcher as player_id,game_type,COUNT(DISTINCT game_id) as w,0 as l,0 as s FROM games WHERE league_id=$lgid AND played=1 AND winning_pitcher IN ($pList)";

			   if ($scope=="LastSim") {$wlQuery.=" AND DATEDIFF('".$lgdate."',games.date)>=".$simLen;}

	      		   elseif ($scope=="dRange") {$wlQuery.=" AND games.date<'$lgyear-$frDay'";}

			   $wlQuery.=" GROUP BY player_id,game_type";

	       		   $wlQuery.=" UNION ";

			   $wlQuery.="SELECT losing_pitcher as player_id,game_type,0 as w,COUNT(DISTINCT game_id) as l,0 as s FROM games WHERE league_id=$lgid AND played=1 AND losing_pitcher IN ($pList)";

	       		   if ($scope=="LastSim") {$wlQuery.=" AND DATEDIFF('".$lgdate."',games.date)>=".$simLen;}

			   elseif ($scope=="dRange") {$wlQuery.=" AND games.date<'$lgyear-$frDay'";}

		       	   $wlQuery.=" GROUP BY player_id,game_type";

			   $wlQuery.=" UNION ";

	       		   $wlQuery.="SELECT save_pitcher as player_id,game_type,0 as w,0 as l,COUNT(DISTINCT game_id) as s FROM games WHERE league_id=$lgid AND played=1 AND save_pitcher IN ($pList)";

			   if ($scope=="LastSim") {$wlQuery.=" AND DATEDIFF('".$lgdate."',games.date)>=".$simLen;}

	      		   elseif ($scope=="dRange") {$wlQuery.=" AND games.date<'$lgyear-$frDay'";}

			   $wlQuery.=" GROUP BY player_id,game_type) as t1 GROUP BY player_id,game_type;";

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

			   $wlResult=mysqli_query($db,$wlQuery);

	       		   if (mysqli_num_rows($wlResult))

			   {

		    		   while ($row=mysqli_fetch_array($wlResult))

				   {

			 		   $pid=$row['player_id'];

					   $gtype=$row['game_type'];

			 		   $players[$pid]['w'][$gtype]=$players[$pid]['w'][$gtype]+$row['w'];

					   $players[$pid]['l'][$gtype]=$players[$pid]['l'][$gtype]+$row['l'];

			 		   $players[$pid]['s'][$gtype]=$players[$pid]['s'][$gtype]+$row['s'];

				   }

	      		   }

		   }

	  

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

		   echo "  <table cellpadding=0 cellspacing=0 border=0><tr class='title2'><td>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'>Time</td><td class='hsc2_l'>Result</td><td class='hsc2'>&nbsp;</td><td class='hsc2_l'>W-L</td><td class='hsc2_l'>Type</td><td class='hsc2_l'>Win</td><td class='hsc2_l'>Loss</td><td class='hsc2_l'>Save</td><td class='hsc2'>Attendance</td>\n";

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

	  

		   $cnt=0;

		   while ($row=mysqli_fetch_array($result))

	 	   {

			   $gid=$row['game_id'];

	       		   $gtype=$row['game_type'];

			   unset($gdate);

	       		   $gdate=new DateTime($row['date']);

			   $gtime=$row['time'];

	       		   $gt1=substr($gtime,0,2);

			   $gt2=substr($gtime,2,2);

	       		   if ($gt1==0) {$gtime="12:$gt2 am";}

			   elseif ($gt1==12) {$gtime="12:$gt2 pm";}

	      		   elseif ($gt1>12) {$gtime=($gt1-12).":$gt2 pm";}

			   else {$gtime="$gt1:$gt2 am";}

	       		   $gtype=$row['game_type'];

			   switch ($gtype)

	      		   {

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

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

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

	      		   }

			   $hid=$row['home_team'];

	       		   $aid=$row['away_team'];

	    $aruns=$row['runs0'];

	    $hruns=$row['runs1'];

	    if ($hid==$team_id)

	     {

			 $games[$gid]['home']=1;

 	       $opponent="<a href='$lgpath/teams/team_$aid.html'>".$teams[$aid]['abbr']."</a>";

	       if ($hruns>$aruns)

	        {

				$games[$gid]['result']='w';

		  $score="Win, $hruns-$aruns";

		  $teams[$hid]['w'][$gtype]=$teams[$hid]['w'][$gtype]+1;

	        }

	        else

	        {

				$games[$gid]['result']='l';

		  $score="Loss, $hruns-$aruns";

		  $teams[$hid]['l'][$gtype]=$teams[$hid]['l'][$gtype]+1;

	        }

	     }

	     else

	     {

			 $games[$gid]['home']=0;

	       $opponent="<a href='$lgpath/teams/team_$hid.html'>@ ".$teams[$hid]['abbr']."</a>";

	       if ($aruns>$hruns)

	        {

				$games[$gid]['result']='w';

		  $score="Win, $aruns-$hruns";

		  $teams[$aid]['w'][$gtype]=$teams[$aid]['w'][$gtype]+1;

	        }

	        else

	        {

				$games[$gid]['result']='l';

		  $score="Loss, $aruns-$hruns";

		  $teams[$aid]['l'][$gtype]=$teams[$aid]['l'][$gtype]+1;

	        }

	     }

	    $inn=$row['innings'];

	    $winP=$row['winning_pitcher'];

	    $players[$winP]['w'][$gtype]=$players[$winP]['w'][$gtype]+1;

	    $lossP=$row['losing_pitcher'];

	    $players[$lossP]['l'][$gtype]=$players[$lossP]['l'][$gtype]+1;

	    $svP=$row['save_pitcher'];

	    $players[$svP]['s'][$gtype]=$players[$svP]['s'][$gtype]+1;



	    if (($hid!=$team_id)&&($aid!=$team_id)) {continue;}



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

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

	     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>$opponent</td>";

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

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

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

	    if ($inn>9) {echo " $inn Inn";} else {echo "&nbsp;";}

	    echo "</td>";

	    echo "<td class='".$cls."_l'$style>".$teams[$team_id]['w'][$gtype]."-".$teams[$team_id]['l'][$gtype]."</td>";

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

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

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

	    echo " (".$players[$winP]['w'][$gtype]."-".$players[$winP]['l'][$gtype].")";

	    echo "</td>";

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

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

	    echo " (".$players[$lossP]['w'][$gtype]."-".$players[$lossP]['l'][$gtype].")";

	    echo "</td>";

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

	    if ($svP==0) {echo ">-";}

	     else

	     {

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

	       echo " (".$players[$svP]['s'][$gtype].")";

	     }

	    echo "</td>";

	    echo "<td$style>".number_format($row['attendance'],0,".",",")."</td>";

	    echo "</tr>\n";



	    $prevGtype=$gtype;

	    $cnt++;

	  }



	 echo "     </table>\n";

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

	 echo "  </table>\n";

	 echo " </div>\n";

       }

    }



  # Find Leagues to process

   $query="SELECT league_id,abbr,if(start_date<'$lgdate',YEAR(start_date),YEAR(start_date)-1) as start_year FROM leagues WHERE league_id=$lgid";

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

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

   if (!mysqli_num_rows($result)) {echo "ERROR: leagues table not loaded"; exit;}

   else

   {

	   $row=mysqli_fetch_array($result);

	   $lgyear=$row['start_year'];

   }



   ##### Get Seasonal Team by Team Stats #####	  

   if (($scope=="Season")&&($team_id==""))

   {



      ## Get Team Batting Stats by Subleague

      $query="SELECT team_id,g,ab,r,h,d,t,hr,rbi,bb,k,sb,cs,hp,sf FROM team_batting_stats WHERE league_id=$lgid AND year=$lgyear";

      if ($tlist!="") {$query.=" AND team_id IN ($tlist)";}

      $query.=" ORDER BY r DESC,h DESC;";

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

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

      ## Display Stats

      if (mysqli_num_rows($result))

       {

         echo " <div class='textbox' style='width:935px;margin-left:0px;margin-right:0px;'>\n";

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

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

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

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

 	 if (($sub_league_id=="")&&($division_id=="")&&($team_id=="")&&($oneLg!=1)) {echo "<td class='hsc2_l'>Lg</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";

	 $rownum=0;

 	 while ($row=mysqli_fetch_array($result))

	  {

	    $tid=$row['team_id'];

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

 	    $g=$row['g'];

	    $ab=$row['ab'];

 	    $r=$row['r'];

	    $h=$row['h'];

 	    $d=$row['d'];

	    $t=$row['t'];

 	    $hr=$row['hr'];

	    $rbi=$row['rbi'];

 	    $bb=$row['bb'];

	    $k=$row['k'];

 	    $sb=$row['sb'];

	    $cs=$row['cs'];

 	    $hp=$row['hp'];

	    $sf=$row['sf'];



	    $Tg+=$g;

 	    $Tab+=$ab;

	    $Tr+=$r;

 	    $Th+=$h;

	    $Td+=$d;

 	    $Tt+=$t;

	    $Thr+=$hr;

 	    $Trbi+=$rbi;

	    $Tbb+=$bb;

 	    $Tk+=$k;

	    $Tsb+=$sb;

 	    $Tcs+=$cs;

	    $Thp+=$hp;

 	    $Tsf+=$sf;



	    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;

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

       	     else {$avg=sprintf("%.3f",$avg);}

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

       	     else {$obp=sprintf("%.3f",$obp);}

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

       	     else {$slg=sprintf("%.3f",$slg);}

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

 	     else {$ops=sprintf("%.3f",$ops);}

	    

	    $rcls=$rownum%2+1;

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

	    echo "<td class='s".$rcls."_l'><a href='$lgpath/teams/team_$tid.html'>".$teams[$tid]['name']."</a></td>";

     	    if (($sub_league_id=="")&&($division_id=="")&&($team_id=="")&&($oneLg!=1)) {echo "<td class='hsc2_l'>".$subleagues[$slid]['abbr']."</td>";}

	    echo "<td>".$g."</td>";

	    echo "<td>".$ab."</td>";

 	    echo "<td>".$r."</td>";

	    echo "<td>".$h."</td>";

 	    echo "<td>".$d."</td>";

	    echo "<td>".$t."</td>";

 	    echo "<td>".$hr."</td>";

	    echo "<td>".$rbi."</td>";

 	    echo "<td>".$bb."</td>";

	    echo "<td>".$k."</td>";

 	    echo "<td>".$sb."</td>";

	    echo "<td>".$cs."</td>";

 	    echo "<td>".$avg."</td>";

	    echo "<td>".$obp."</td>";

 	    echo "<td>".$slg."</td>";

	    echo "<td>".$ops."</td>";

 	    echo "</tr>\n";

	    $rownum++;

 	  }

 

	 ## Display Team Totals

	 if ($team_id=="")

	  {

            if ($Tab==0)

             {

               $avg=round(0,3);

               $slg=round(0,3);

	     } 

       	     else

	     {

	       $avg=$Th/$Tab;

	       $slg=($Th+$Td+2*$Tt+3*$Thr)/$Tab;

       	     }

	    $pa=$Tab+$Tbb+$Thbp+$Tsf;

	    if ($pa==0) {$obp=0;}

  	     else {$obp=($Th+$Tbb+$Thbp)/$pa;}

	    $ops=$obp+$slg;

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

	     else {$avg=sprintf("%.3f",$avg);}

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

	     else {$obp=sprintf("%.3f",$obp);}

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

	     else {$slg=sprintf("%.3f",$slg);}

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

	     else {$ops=sprintf("%.3f",$ops);}

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

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

  	    if (($sub_league_id=="")&&($division_id=="")&&($team_id=="")&&($oneLg!=1)) {echo "<td class='hsc2_l'>&nbsp;</td>";}

	    echo "<td class='hsc2'>".$Tg."</td>";

	    echo "<td class='hsc2'>".$Tab."</td>";

 	    echo "<td class='hsc2'>".$Tr."</td>";

	    echo "<td class='hsc2'>".$Th."</td>";

 	    echo "<td class='hsc2'>".$Td."</td>";

	    echo "<td class='hsc2'>".$Tt."</td>";

 	    echo "<td class='hsc2'>".$Thr."</td>";

	    echo "<td class='hsc2'>".$Trbi."</td>";

 	    echo "<td class='hsc2'>".$Tbb."</td>";

	    echo "<td class='hsc2'>".$Tk."</td>";

 	    echo "<td class='hsc2'>".$Tsb."</td>";

	    echo "<td class='hsc2'>".$Tcs."</td>";

 	    echo "<td class='hsc2'>".$avg."</td>";

	    echo "<td class='hsc2'>".$obp."</td>";

 	    echo "<td class='hsc2'>".$slg."</td>";

	    echo "<td class='hsc2'>".$ops."</td>";

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

	  }

 	 ## Close Table

	 echo "   </table>\n";

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

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

       }



      ## Get Team Pitching Stats by Subleague

      $Tw=0;

      $Tl=0;

      $Ts=0;

      $Tcg=0;

      $Tsho=0;

      $Ter=0;

      $Tip=0;

      $Tg=0;

      $Tgs=0;

      $Tha=0;

      $Tr=0;

      $Thra=0;

      $Tbb=0;

      $Tk=0;

      $Tab=0;

      $Tsf=0;

      $query="SELECT team_id,w,l,s,cg,sho,er,(3*ip+ipf)/3 as ip,g,gs,ha,r,hra,bb,k,ab,sf FROM team_pitching_stats WHERE league_id=$lgid AND year=$lgyear";

      if ($tlist!="") {$query.=" AND team_id IN ($tlist)";}

      $query.=" ORDER BY r,er,ha;";

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

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

      ## Display Stats

      if (mysqli_num_rows($result))

       {

         echo " <div class='textbox' style='width:935px;margin-left:0px;margin-right:0px;'>\n";

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

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

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

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

 	 if (($sub_league_id=="")&&($division_id=="")&&($team_id=="")&&($oneLg!=1)) {echo "<td class='hsc2_l'>Lg</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'>WHIP</td><td class='hsc2'>OAVG</td><td class='hsc2'>BABIP</td>\n";

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

	 $rownum=0;

 	 while ($row=mysqli_fetch_array($result))

	  {

	    $tid=$row['team_id'];

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

	    $w=$row['w'];

 	    $l=$row['l'];

	    $s=$row['s'];

	    $cg=$row['cg'];

 	    $sho=$row['sho'];

	    $er=$row['er'];

 	    $ip=$row['ip'];

	    $g=$row['g'];

 	    $gs=$row['gs'];

	    $ha=$row['ha'];

 	    $r=$row['r'];

	    $hra=$row['hra'];

 	    $bb=$row['bb'];

	    $k=$row['k'];

 	    $ab=$row['ab'];

	    $sf=$row['sf'];



	    $Tw+=$w;

 	    $Tl+=$l;

	    $Ts+=$s;

 	    $Tcg+=$cg;

	    $Tsho+=$sho;

 	    $Ter+=$er;

	    $Tip+=$ip;

 	    $Tg+=$g;

	    $Tgs+=$gs;

 	    $Tha+=$ha;

	    $Tr+=$r;

 	    $Thra+=$hra;

	    $Tbb+=$bb;

 	    $Tk+=$k;

	    $Tab+=$ab;

 	    $Tsf+=$sf;



	    if ($ip==0) {$era=0;$whip=0;}

	     else 

	     {

  	       $era=$er*9/$ip;

	       $whip=($ha+$bb)/$ip;

	     }

     	    $era=sprintf("%.2f",$era);

	    $ip=sprintf("%.1f",$ip);

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

	    $whip=sprintf("%.2f",$whip);

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

     	    if ($ab==0) {$oavg=0;}

	     else {$oavg=$ha/$ab;}

	    if ($oavg<1) {$oavg=strstr(sprintf("%.3f",$oavg),".");}

	     else {$oavg=sprintf("%.3f",$oavg);}

	    $bip=$ab-$k-$hra+$sf;

     	    if ($bip==0) {$babip=0;}

	     else {$babip=($ha-$hra)/$bip;}

	    if ($babip<1) {$babip=strstr(sprintf("%.3f",$babip),".");}

	     else {$babip=sprintf("%.3f",$babip);}



	    $rcls=$rownum%2+1;

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

	    echo "<td class='s".$rcls."_l'><a href='$lgpath/teams/team_$tid.html'>".$teams[$tid]['name']."</a></td>";

     	    if (($sub_league_id=="")&&($division_id=="")&&($team_id=="")&&($oneLg!=1)) {echo "<td class='hsc2_l'>".$subleagues[$slid]['abbr']."</td>";}

	    echo "<td>".$w."</td>";

	    echo "<td>".$l."</td>";

 	    echo "<td>".$s."</td>";

	    echo "<td>".$cg."</td>";

 	    echo "<td>".$sho."</td>";

	    echo "<td>".$era."</td>";

 	    echo "<td>".$g."</td>";

	    echo "<td>".$gs."</td>";

 	    echo "<td>".$ip."</td>";

	    echo "<td>".$ha."</td>";

 	    echo "<td>".$r."</td>";

	    echo "<td>".$er."</td>";

 	    echo "<td>".$hra."</td>";

	    echo "<td>".$bb."</td>";

 	    echo "<td>".$k."</td>";

	    echo "<td>".$whip."</td>";

 	    echo "<td>".$oavg."</td>";

	    echo "<td>".$babip."</td>";

 	    echo "</tr>\n";

	    $rownum++;

 	  }

 

	 ## Display Team Totals

	 if ($team_id=="")

	  {

	    if ($Tip==0) {$era=0;$whip=0;}

	     else 

       	     {

               $era=$Ter*9/$Tip;

	       $whip=($Tha+$Tbb)/$Tip;

	     }

	    $era=sprintf("%.2f",$era);

	    $ip=sprintf("%.1f",$Tip);

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

	    $whip=sprintf("%.2f",$whip);

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

	    if ($Tab==0) {$oavg=0;}

	     else {$oavg=$Tha/$Tab;}

	    if ($oavg<1) {$oavg=strstr(sprintf("%.3f",$oavg),".");}

	     else {$oavg=sprintf("%.3f",$oavg);}

	    $bip=$Tab-$Tk-$Thra+$Tsf;

	    if ($bip==0) {$babip=0;}

	     else {$babip=($Tha-$Thra)/$bip;}

	    if ($babip<1) {$babip=strstr(sprintf("%.3f",$babip),".");}

	     else {$babip=sprintf("%.3f",$babip);}



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

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

  	    if (($sub_league_id=="")&&($division_id=="")&&($team_id=="")&&($oneLg!=1)) {echo "<td class='hsc2_l'>&nbsp;</td>";}

	    echo "<td class='hsc2'>".$Tw."</td>";

	    echo "<td class='hsc2'>".$Tl."</td>";

 	    echo "<td class='hsc2'>".$Ts."</td>";

	    echo "<td class='hsc2'>".$Tcg."</td>";

 	    echo "<td class='hsc2'>".$Tsho."</td>";

	    echo "<td class='hsc2'>".$era."</td>";

	    echo "<td class='hsc2'>".$Tg."</td>";

 	    echo "<td class='hsc2'>".$Tgs."</td>";

	    echo "<td class='hsc2'>".$ip."</td>";

 	    echo "<td class='hsc2'>".$Tha."</td>";

	    echo "<td class='hsc2'>".$Tr."</td>";

 	    echo "<td class='hsc2'>".$Ter."</td>";

	    echo "<td class='hsc2'>".$Thra."</td>";

 	    echo "<td class='hsc2'>".$Tbb."</td>";

	    echo "<td class='hsc2'>".$Tk."</td>";

 	    echo "<td class='hsc2'>".$whip."</td>";

	    echo "<td class='hsc2'>".$oavg."</td>";

 	    echo "<td class='hsc2'>".$babip."</td>";

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

 	  }

	 ## Close Table

	 echo "   </table>\n";

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

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

       }

    }   ### End of Seasonal Team by Team Stats



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

   if (($scope!="Season")&&($team_id==""))

    {

      ## Get Games

      $lgdate=$_SESSION['lgdate'];

      $query="SELECT game_id,date,time,home_team,away_team,game_type FROM games WHERE league_id=$lgid";

      if ($tlist!="") {$query.=" AND (home_team IN ($tlist) OR away_team IN ($tlist))";}

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

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

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

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

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

      $glist="";

      if (mysqli_num_rows($result))

       {

         while ($row=mysqli_fetch_array($result))

	  {

 	    $gid=$row['game_id'];

            $games[$gid]['date']=$row['date'];

	    $games[$gid]['time']=$row['time'];

 	    $hid=$row['home_team'];

	    $aid=$row['away_team'];

 	    $games[$gid]['home_team']=$hid;

	    $games[$gid]['away_team']=$aid;

	    $teams[$hid]['gp']=$teams[$hid]['gp']+1;

	    $teams[$aid]['gp']=$teams[$aid]['gp']+1;

	    $games[$gid]['game_type']=$row['game_type'];

	    $glist.=",$gid";

 	  }

       }

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

      if ($glist=="")

      {

	      mysqli_close($db);



	      echo " <div class='textbox' style='border:0;'>No games found</div>\n";

	    

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

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

	      page_foot($_SESSION['lgpath']);

	      exit;

      }



      ## Get Batting Stats

      $query="SELECT team_id,SUM(g) as g,SUM(ab) as ab,SUM(r) as r,SUM(h) as h,SUM(d) as d,SUM(t) as t,SUM(hr) as hr,SUM(rbi) as rbi,SUM(bb) as bb,SUM(k) as k,SUM(sb) as sb,SUM(cs) as cs,SUM(hp) as hp,SUM(sf) as sf FROM players_game_batting as pgb WHERE league_id=$lgid AND year=$lgyear";

      $query.=" AND game_id IN ($glist) GROUP BY team_id ORDER BY r DESC,h DESC;";

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

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

      ## Display Stats

      if (mysqli_num_rows($result))

       {

         echo " <div class='textbox' style='width:935px;margin-left:0px;margin-right:0px;'>\n";

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

	 if ($scope=='LastSim') {echo "Last Sim Batting Totals";}

 	  else {echo "Batting Totals From ".str_replace("-","/",$frDay)." to ".str_replace("-","/",$toDay);}

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

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

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

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

 	 if (($sub_league_id=="")&&($division_id=="")&&($team_id=="")&&($oneLg!=1)) {echo "<td class='hsc2_l'>Lg</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";

	 $rownum=0;

 	 while ($row=mysqli_fetch_array($result))

	  {

	    $tid=$row['team_id'];

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

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

	    if (($division_id!="")&&($divid!=$division_id)) {continue;}

            $g=$teams[$tid]['gp'];

	    $ab=$row['ab'];

	    $r=$row['r'];

	    $h=$row['h'];

	    $d=$row['d'];

	    $t=$row['t'];

	    $hr=$row['hr'];

	    $rbi=$row['rbi'];

	    $bb=$row['bb'];

	    $k=$row['k'];

	    $sb=$row['sb'];

	    $cs=$row['cs'];

	    $hp=$row['hp'];

	    $sf=$row['sf'];



	    $Tg+=$g;

 	    $Tab+=$ab;

	    $Tr+=$r;

 	    $Th+=$h;

	    $Td+=$d;

 	    $Tt+=$t;

	    $Thr+=$hr;

 	    $Trbi+=$rbi;

	    $Tbb+=$bb;

 	    $Tk+=$k;

	    $Tsb+=$sb;

 	    $Tcs+=$cs;

	    $Thp+=$hp;

 	    $Tsf+=$sf;



	    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;

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

       	     else {$avg=sprintf("%.3f",$avg);}

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

       	     else {$obp=sprintf("%.3f",$obp);}

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

       	     else {$slg=sprintf("%.3f",$slg);}

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

 	     else {$ops=sprintf("%.3f",$ops);}

	    

	    $rcls=$rownum%2+1;

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

	    echo "<td class='s".$rcls."_l'><a href='$lgpath/teams/team_$tid.html'>".$teams[$tid]['name']."</a></td>";

     	    if (($sub_league_id=="")&&($division_id=="")&&($team_id=="")&&($oneLg!=1)) {echo "<td class='hsc2_l'>".$subleagues[$slid]['abbr']."</td>";}

	    echo "<td>".$g."</td>";

	    echo "<td>".$ab."</td>";

 	    echo "<td>".$r."</td>";

	    echo "<td>".$h."</td>";

 	    echo "<td>".$d."</td>";

	    echo "<td>".$t."</td>";

 	    echo "<td>".$hr."</td>";

	    echo "<td>".$rbi."</td>";

 	    echo "<td>".$bb."</td>";

	    echo "<td>".$k."</td>";

 	    echo "<td>".$sb."</td>";

	    echo "<td>".$cs."</td>";

 	    echo "<td>".$avg."</td>";

	    echo "<td>".$obp."</td>";

 	    echo "<td>".$slg."</td>";

	    echo "<td>".$ops."</td>";

 	    echo "</tr>\n";

	    $rownum++;

	  }



	 ## Display Team Totals

	 if ($team_id=="")

	  {

            if ($Tab==0)

             {

               $avg=round(0,3);

               $slg=round(0,3);

	     } 

       	     else

	     {

	       $avg=$Th/$Tab;

	       $slg=($Th+$Td+2*$Tt+3*$Thr)/$Tab;

       	     }

	    $pa=$Tab+$Tbb+$Thbp+$Tsf;

	    if ($pa==0) {$obp=0;}

  	     else {$obp=($Th+$Tbb+$Thbp)/$pa;}

	    $ops=$obp+$slg;

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

	     else {$avg=sprintf("%.3f",$avg);}

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

	     else {$obp=sprintf("%.3f",$obp);}

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

	     else {$slg=sprintf("%.3f",$slg);}

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

	     else {$ops=sprintf("%.3f",$ops);}

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

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

  	    if (($sub_league_id=="")&&($division_id=="")&&($team_id=="")&&($oneLg!=1)) {echo "<td class='hsc2_l'>&nbsp;</td>";}

	    echo "<td class='hsc2'>".$Tg."</td>";

	    echo "<td class='hsc2'>".$Tab."</td>";

 	    echo "<td class='hsc2'>".$Tr."</td>";

	    echo "<td class='hsc2'>".$Th."</td>";

 	    echo "<td class='hsc2'>".$Td."</td>";

	    echo "<td class='hsc2'>".$Tt."</td>";

 	    echo "<td class='hsc2'>".$Thr."</td>";

	    echo "<td class='hsc2'>".$Trbi."</td>";

 	    echo "<td class='hsc2'>".$Tbb."</td>";

	    echo "<td class='hsc2'>".$Tk."</td>";

 	    echo "<td class='hsc2'>".$Tsb."</td>";

	    echo "<td class='hsc2'>".$Tcs."</td>";

 	    echo "<td class='hsc2'>".$avg."</td>";

	    echo "<td class='hsc2'>".$obp."</td>";

 	    echo "<td class='hsc2'>".$slg."</td>";

	    echo "<td class='hsc2'>".$ops."</td>";

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

	  }

 	 ## Close Table

	 echo "   </table>\n";

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

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

       }



      ## Get Team Pitching Stats by Subleague

      $Tw=0;

      $Tl=0;

      $Ts=0;

      $Tcg=0;

      $Tsho=0;

      $Ter=0;

      $Tip=0;

      $Tg=0;

      $Tgs=0;

      $Tha=0;

      $Tr=0;

      $Thra=0;

      $Tbb=0;

      $Tk=0;

      $Tab=0;

      $Tsf=0;

      $query="SELECT team_id,SUM(w) as w,SUM(l) as l,SUM(s) as s,SUM(cg) as cg,SUM(sho) as sho,SUM(er) as er,(3*SUM(ip)+SUM(ipf))/3 as ip,SUM(g) as g,SUM(gs) as gs,SUM(ha) as ha,SUM(r) as r,SUM(hra) as hra,SUM(bb) as bb,SUM(k) as k,SUM(ab) as ab,SUM(sf) as sf FROM players_game_pitching_stats as pgb WHERE league_id=$lgid AND year=$lgyear";

      $query.=" AND game_id IN ($glist) GROUP BY team_id ORDER BY r,er,ha;";

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

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

      ## Display Stats

      if (mysqli_num_rows($result))

       {

         echo " <div class='textbox' style='width:935px;margin-left:0px;margin-right:0px;'>\n";

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

	 if ($scope=='LastSim') {echo "Last Sim Pitching Totals";}

 	  else {echo "Pitching Totals From ".str_replace("-","/",$frDay)." to ".str_replace("-","/",$toDay);}

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

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

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

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

 	 if (($sub_league_id=="")&&($division_id=="")&&($team_id=="")&&($oneLg!=1)) {echo "<td class='hsc2_l'>Lg</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'>WHIP</td><td class='hsc2'>OAVG</td><td class='hsc2'>BABIP</td>\n";

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

	 $rownum=0;

 	 while ($row=mysqli_fetch_array($result))

	  {

	    $tid=$row['team_id'];

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

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

	    if (($division_id!="")&&($divid!=$division_id)) {continue;}

	    $w=$row['w'];

 	    $l=$row['l'];

	    $s=$row['s'];

	    $cg=$row['cg'];

 	    $sho=$row['sho'];

	    $er=$row['er'];

 	    $ip=$row['ip'];

	    $g=$teams[$tid]['gp'];

 	    $gs=$row['gs'];

	    $ha=$row['ha'];

 	    $r=$row['r'];

	    $hra=$row['hra'];

 	    $bb=$row['bb'];

	    $k=$row['k'];

 	    $ab=$row['ab'];

	    $sf=$row['sf'];



	    $Tw+=$w;

 	    $Tl+=$l;

	    $Ts+=$s;

 	    $Tcg+=$cg;

	    $Tsho+=$sho;

 	    $Ter+=$er;

	    $Tip+=$ip;

 	    $Tg+=$g;

	    $Tgs+=$gs;

 	    $Tha+=$ha;

	    $Tr+=$r;

 	    $Thra+=$hra;

	    $Tbb+=$bb;

 	    $Tk+=$k;

	    $Tab+=$ab;

 	    $Tsf+=$sf;



	    if ($ip==0) {$era=0;$whip=0;}

	     else 

	     {

  	       $era=$er*9/$ip;

	       $whip=($ha+$bb)/$ip;

	     }

     	    $era=sprintf("%.2f",$era);

	    $ip=sprintf("%.1f",$ip);

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

	    $whip=sprintf("%.2f",$whip);

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

     	    if ($ab==0) {$oavg=0;}

	     else {$oavg=$ha/$ab;}

	    if ($oavg<1) {$oavg=strstr(sprintf("%.3f",$oavg),".");}

	     else {$oavg=sprintf("%.3f",$oavg);}

	    $bip=$ab-$k-$hra+$sf;

     	    if ($bip==0) {$babip=0;}

	     else {$babip=($ha-$hra)/$bip;}

	    if ($babip<1) {$babip=strstr(sprintf("%.3f",$babip),".");}

	     else {$babip=sprintf("%.3f",$babip);}



	    $rcls=$rownum%2+1;

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

	    echo "<td class='s".$rcls."_l'><a href='$lgpath/teams/team_$tid.html'>".$teams[$tid]['name']."</a></td>";

     	    if (($sub_league_id=="")&&($division_id=="")&&($team_id=="")&&($oneLg!=1)) {echo "<td class='hsc2_l'>".$subleagues[$slid]['abbr']."</td>";}

	    echo "<td>".$w."</td>";

	    echo "<td>".$l."</td>";

 	    echo "<td>".$s."</td>";

	    echo "<td>".$cg."</td>";

 	    echo "<td>".$sho."</td>";

	    echo "<td>".$era."</td>";

 	    echo "<td>".$g."</td>";

	    echo "<td>".$gs."</td>";

 	    echo "<td>".$ip."</td>";

	    echo "<td>".$ha."</td>";

 	    echo "<td>".$r."</td>";

	    echo "<td>".$er."</td>";

 	    echo "<td>".$hra."</td>";

	    echo "<td>".$bb."</td>";

 	    echo "<td>".$k."</td>";

	    echo "<td>".$whip."</td>";

 	    echo "<td>".$oavg."</td>";

	    echo "<td>".$babip."</td>";

 	    echo "</tr>\n";

	    $rownum++;

 	  }

 

	 ## Display Team Totals

	 if ($team_id=="")

	  {

	    if ($Tip==0) {$era=0;$whip=0;}

	     else 

       	     {

               $era=$Ter*9/$Tip;

	       $whip=($Tha+$Tbb)/$Tip;

	     }

	    $era=sprintf("%.2f",$era);

	    $ip=sprintf("%.1f",$Tip);

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

	    $whip=sprintf("%.2f",$whip);

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

	    if ($Tab==0) {$oavg=0;}

	     else {$oavg=$Tha/$Tab;}

	    if ($oavg<1) {$oavg=strstr(sprintf("%.3f",$oavg),".");}

	     else {$oavg=sprintf("%.3f",$oavg);}

	    $bip=$Tab-$Tk-$Thra+$Tsf;

	    if ($bip==0) {$babip=0;}

	     else {$babip=($Tha-$Thra)/$bip;}

	    if ($babip<1) {$babip=strstr(sprintf("%.3f",$babip),".");}

	     else {$babip=sprintf("%.3f",$babip);}



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

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

  	    if (($sub_league_id=="")&&($division_id=="")&&($team_id=="")&&($oneLg!=1)) {echo "<td class='hsc2_l'>&nbsp;</td>";}

	    echo "<td class='hsc2'>".$Tw."</td>";

	    echo "<td class='hsc2'>".$Tl."</td>";

 	    echo "<td class='hsc2'>".$Ts."</td>";

	    echo "<td class='hsc2'>".$Tcg."</td>";

 	    echo "<td class='hsc2'>".$Tsho."</td>";

	    echo "<td class='hsc2'>".$era."</td>";

	    echo "<td class='hsc2'>".$Tg."</td>";

 	    echo "<td class='hsc2'>".$Tgs."</td>";

	    echo "<td class='hsc2'>".$ip."</td>";

 	    echo "<td class='hsc2'>".$Tha."</td>";

	    echo "<td class='hsc2'>".$Tr."</td>";

 	    echo "<td class='hsc2'>".$Ter."</td>";

	    echo "<td class='hsc2'>".$Thra."</td>";

 	    echo "<td class='hsc2'>".$Tbb."</td>";

	    echo "<td class='hsc2'>".$Tk."</td>";

 	    echo "<td class='hsc2'>".$whip."</td>";

	    echo "<td class='hsc2'>".$oavg."</td>";

 	    echo "<td class='hsc2'>".$babip."</td>";

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

 	  }

	 ## Close Table

	 echo "   </table>\n";

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

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

       }

    }   ### End of Last Sim Team by Team Stats



   ##### Generate Splits for Teams #####

   if ($team_id!="")

    {

      ## 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=new DateTime($row['date']);

       }



      ## Get Games

      $lgdate=$_SESSION['lgdate'];

      $query="SELECT game_id,date,time,home_team,away_team,game_type FROM games WHERE league_id=$lgid";

      if ($tlist!="") {$query.=" AND (home_team IN ($tlist) OR away_team IN ($tlist))";}

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

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

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

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

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

      $glist="";

      if (mysqli_num_rows($result))

       {

         while ($row=mysqli_fetch_array($result))

	  {

 	    $gid=$row['game_id'];

            $games[$gid]['date']=$row['date'];

	    $games[$gid]['time']=$row['time'];

 	    $games[$gid]['home_team']=$row['home_team'];

	    $games[$gid]['away_team']=$row['away_team'];

 	    $games[$gid]['game_type']=$row['game_type'];

	    $glist.=",$gid";

 	  }

       }

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

      if ($glist=="")

      {

	      mysqli_close($db);



	      echo " <div class='textbox' style='border:0;'>No games found</div>\n";

	    

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

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

	      page_foot($_SESSION['lgpath']);

	      exit;

      }



      ## Get Batting Stats

      $query="SELECT player_id,team_id,game_id,position,g,ab,r,h,d,t,hr,rbi,bb,k,sb,cs,hp,sf FROM players_game_batting as pgb WHERE league_id=$lgid AND year=$lgyear";

      $query.=" AND game_id IN ($glist);";

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

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

      ## Display Stats

      if (mysqli_num_rows($result))

       {

 	 while ($row=mysqli_fetch_array($result))

	  {

	    $pid=$row['player_id'];

	    $tid=$row['team_id'];

	    $gid=$row['game_id'];

 	    $hid=$games[$gid]['home_team'];

	    $aid=$games[$gid]['away_team'];

 	    unset($gdate);

	    $gdate=new DateTime($games[$gid]['date']);

 	    $gtime=$games[$gid]['time'];

	    if ($gtime>1699) {$daynight="Night";}

	     else {$daynight="Day";}

            $month=$gdate->format("F");

            $monthID=$gdate->format("n");

	    $gtype=$games[$gid]['game_type'];

 	    if (($gtype!=0)&&($gtype!=2)&&($gtype!=3)) {continue;}

	    switch ($gtype)

	     {

	       case 0: $gtype="Regular Season"; break;

	       case 2: $gtype="Spring Training"; break;

	       case 3: $gtype="Postseason"; break;

	     }

	    if ($tid==$hid)

	     { 

	       $homeaway="Home";

	       switch ($gtype)

	        {

	          case 'Spring Training': $opponent="Ops^".$aid; $oppname=$teams[$aid]['name']."a"; break;

	          case 'Regular Season' : $opponent="Opr^".$aid; $oppname=$teams[$aid]['name']."b"; break;

	          case 'Postseason'     : $opponent="Opp^".$aid; $oppname=$teams[$aid]['name']."c"; break;

		}

	       

 	     }

	     else

	     {

	       $homeaway="Away";

	       switch ($gtype)

	        {

	          case 'Spring Training': $opponent="Ops^".$hid; $oppname=$teams[$hid]['name']."a"; break;

	          case 'Regular Season' : $opponent="Opr^".$hid; $oppname=$teams[$hid]['name']."b"; break;

	          case 'Postseason'     : $opponent="Opp^".$hid; $oppname=$teams[$hid]['name']."c"; break;

		}

	     }

	    if (isset($as_date))

	     {

	       if (($gdate->getTimestamp())>($as_date->getTimestamp())) {$allstar="Post All-Star Break";}

	        else {$allstar="Pre All-Star Break";}

	     }

            $pos=$row['position'];

	    $position=get_pos($pos,1);



            $g=$row['g'];

	    $ab=$row['ab'];

	    $r=$row['r'];

	    $h=$row['h'];

	    $d=$row['d'];

	    $t=$row['t'];

	    $hr=$row['hr'];

	    $rbi=$row['rbi'];

	    $bb=$row['bb'];

	    $k=$row['k'];

	    $sb=$row['sb'];

	    $cs=$row['cs'];

	    $hp=$row['hp'];

	    $sf=$row['sf'];



            unset($splits);

	    if ($team_id!="")

	     {

	       $splits=Array('Total',$month,$homeaway,$daynight,$opponent,$position,$gtype);

	       if (isset($as_date)) {array_push($splits,$allstar);}

	     }

	     else {$splits=Array('Total');}



	    foreach ($splits as $key => $split)

	     {

               ## Only include ST and PS games in Season splits when viewing Seasonal scope

	       if (($scope!='LastSim')&&($gtype=='Spring Training')&&($split!='Spring Training')&&($split!='Total')) {continue;}

	       if (($scope!='LastSim')&&($gtype=='Postseason')&&($split!='Postseason')&&($split!='Total')&&(!(strpos($split,"^")>0))) {continue;}

	

	       if (!isset($teams[$tid]['gtype'][$gtype])&&(($split=='Spring Training')||($split=='Regular Season')||($split=='Postseason'))) {$teams[$tid]['gtype'][$gtype]=$gtype;}

	       if (!isset($teams[$tid]['months'][$monthID])&&(($split=='January')||($split=='February')||($split=='March')||($split=='April')||($split=='May')||($split=='June')||($split=='July')||($split=='August')||($split=='September')||($split=='October')||($split=='November')||($split=='December'))) {$teams[$tid]['months'][$monthID]=$month;}

	       if (!isset($teams[$tid]['opps'][$oppname])&&(strpos($split,"^")>0)) {$teams[$tid]['opps'][$oppname]=$opponent;}

	       if (!isset($teams[$tid]['position'][$pos])&&(($split=='P')||($split=='C')||($split=='1B')||($split=='2B')||($split=='3B')||($split=='SS')||($split=='LF')||($split=='CF')||($split=='RF')||($split=='DH')||($split=='PH'))) {$teams[$tid]['position'][$pos]=$position;}



	       $teams[$tid][$split]['g'][$gid]=$gid;

               $teams[$tid][$split]['ab']=$teams[$tid][$split]['ab']+$ab;

	       $teams[$tid][$split]['r']=$teams[$tid][$split]['r']+$r;

 	       $teams[$tid][$split]['h']=$teams[$tid][$split]['h']+$h;

	       $teams[$tid][$split]['d']=$teams[$tid][$split]['d']+$d;

 	       $teams[$tid][$split]['t']=$teams[$tid][$split]['t']+$t;

	       $teams[$tid][$split]['hr']=$teams[$tid][$split]['hr']+$hr;

 	       $teams[$tid][$split]['rbi']=$teams[$tid][$split]['rbi']+$rbi;

	       $teams[$tid][$split]['bb']=$teams[$tid][$split]['bb']+$bb;

 	       $teams[$tid][$split]['k']=$teams[$tid][$split]['k']+$k;

	       $teams[$tid][$split]['sb']=$teams[$tid][$split]['sb']+$sb;

 	       $teams[$tid][$split]['cs']=$teams[$tid][$split]['cs']+$cs;

	       $teams[$tid][$split]['hp']=$teams[$tid][$split]['hp']+$hp;

 	       $teams[$tid][$split]['sf']=$teams[$tid][$split]['sf']+$sf;

	     }

 	  }

 

	 if ($team_id!="")

          {

      	    if (isset($teams[$team_id]['months'])) {ksort($teams[$team_id]['months']);}

	    if (isset($teams[$team_id]['opps'])) {ksort($teams[$team_id]['opps']);}

	    if (isset($teams[$team_id]['position'])) {ksort($teams[$team_id]['position']);}

	  }



	 ## Display Splits

	 if ($team_id!="")

	  {

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

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

	    if ($team_id!="")

	     {

	       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');}

	     }

	     else {$headings="Tot";}



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

	     {

	       if (($scope!='LastSim')&&(($header=='Home/Away')||($header=='By Month')||($header=='By Half')||($header=='Day/Night')||($header=='By Position'))) {$dispHeader=$header." (regular season games only)";}

	        elseif (($scope=='LastSim')&&(($header=='Home/Away')||($header=='By Month')||($header=='By Half')||($header=='Day/Night')||($header=='By Position'))) {$dispHeader=$header." (includes all games played)";}

	        else {$dispHeader=$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';>$dispHeader</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'>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";

    

	       unset($splits);

	       switch ($header)

	        {

                  case 'Season'      :

		     $splits=Array();

                     if (isset($teams[$team_id]['gtype']['Spring Training'])) {array_push($splits,'Spring Training');}

                     if (isset($teams[$team_id]['gtype']['Regular Season'])) {array_push($splits,'Regular Season');}

                     if (isset($teams[$team_id]['gtype']['Postseason'])) {array_push($splits,'Postseason');}

                     array_push($splits,'Total');

		     break;

	          case 'Home/Away'   : $splits=Array("Home","Away"); break;

		  case 'By Month'    :

		     $splits=Array();

		     for ($i=1;$i<=12;$i++)

		      {

                        if (isset($teams[$team_id]['months'][$i])) {array_push($splits,$teams[$team_id]['months'][$i]);}

		      }

		     break;

	          case 'By Half'     : $splits=Array("Pre All-Star Break","Post All-Star Break"); break;

	          case 'Day/Night'   : $splits=Array("Day","Night"); break;

	          case 'vs. Opponent': 

		     foreach ($teams[$team_id]['opps'] as $data => $val) {$splits[$data]=$val;}

		     break;

	          case 'By Position' :

                     $splits=Array();

		     for ($i=1;$i<=10;$i++)

		      {

                        if (isset($teams[$team_id]['position'][$i])) {array_push($splits,$teams[$team_id]['position'][$i]);}

		      }

                     if (isset($teams[$team_id]['position'][0])) {array_push($splits,$teams[$team_id]['position'][0]);}

		     break;

	          default            : $splits=Array('Total'); break;

	        }

   

	       $rownum=0;

	       foreach ($splits as $key => $split)

	        {
		  if (!isset($teams[$team_id][$split])) {continue;}
	 	  $g=count($teams[$team_id][$split]['g']);

   		  $ab=$teams[$team_id][$split]['ab'];

		  $r=$teams[$team_id][$split]['r'];

 		  $h=$teams[$team_id][$split]['h'];

		  $d=$teams[$team_id][$split]['d'];

 		  $t=$teams[$team_id][$split]['t'];

		  $hr=$teams[$team_id][$split]['hr'];

 		  $rbi=$teams[$team_id][$split]['rbi'];

		  $bb=$teams[$team_id][$split]['bb'];

 		  $k=$teams[$team_id][$split]['k'];

		  $sb=$teams[$team_id][$split]['sb'];

 		  $cs=$teams[$team_id][$split]['cs'];

		  $hp=$teams[$team_id][$split]['hp'];

 		  $sf=$teams[$team_id][$split]['sf'];

		  unset($teams[$team_id][$split]);

		  

		  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;

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

		   else {$avg=sprintf("%.3f",$avg);}

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

		   else {$obp=sprintf("%.3f",$obp);}

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

		   else {$slg=sprintf("%.3f",$slg);}

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

		   else {$ops=sprintf("%.3f",$ops);}



	          if ($split=="Total")

	 	   {

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

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

	 	     echo "<td class='hsc2'>".$g."</td>";

 		     echo "<td class='hsc2'>".$ab."</td>";

		     echo "<td class='hsc2'>".$r."</td>";

 		     echo "<td class='hsc2'>".$h."</td>";

		     echo "<td class='hsc2'>".$d."</td>";

 		     echo "<td class='hsc2'>".$t."</td>";

		     echo "<td class='hsc2'>".$hr."</td>";

 		     echo "<td class='hsc2'>".$rbi."</td>";

		     echo "<td class='hsc2'>".$bb."</td>";

 		     echo "<td class='hsc2'>".$k."</td>";

		     echo "<td class='hsc2'>".$sb."</td>";

 		     echo "<td class='hsc2'>".$cs."</td>";

		     echo "<td class='hsc2'>".$avg."</td>";

 		     echo "<td class='hsc2'>".$obp."</td>";

		     echo "<td class='hsc2'>".$slg."</td>";

 		     echo "<td class='hsc2'>".$ops."</td>";

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

 		   }

		   else

		   {

		     $rcls=$rownum%2+1;

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

		     if (strpos($split,"^")>0)

  		      {

		        $e=explode("^",$split);

                        $gt=$e[0];

			$oppID=$e[1];

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

			switch ($gt)

			 {

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

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

			 }

		      }

		     if ($split=="PH") {$split="PH/PR/Subs";}

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

		     if ($g==0)

		      {

		        echo "<td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td>";

		        echo "<td>".$avg."</td>";

			echo "<td>".$obp."</td>";

 			echo "<td>".$slg."</td>";

			echo "<td>".$ops."</td>";

 			echo "</tr>\n";

			$rownum++;

 			continue;

		      }



		     echo "<td>".$g."</td>";

		     echo "<td>".$ab."</td>";

   		     echo "<td>".$r."</td>";

 		     echo "<td>".$h."</td>";

		     echo "<td>".$d."</td>";

 		     echo "<td>".$t."</td>";

		     echo "<td>".$hr."</td>";

		     echo "<td>".$rbi."</td>";

		     echo "<td>".$bb."</td>";

 		     echo "<td>".$k."</td>";

		     echo "<td>".$sb."</td>";

 		     echo "<td>".$cs."</td>";

		     echo "<td>".$avg."</td>";

 		     echo "<td>".$obp."</td>";

		     echo "<td>".$slg."</td>";

 		     echo "<td>".$ops."</td>";

		     echo "</tr>\n";

 		   }

		  $rownum++;

 		}



	       ## 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";

	  }

       }

 

      ## Get Pitching Stats

      $query="SELECT player_id,team_id,game_id,w,l,s,cg,sho,er,(3*ip+ipf)/3 as ip,g,gs,ha,r,hra,bb,k,ab,sf FROM players_game_pitching_stats as pgb WHERE league_id=$lgid AND year=$lgyear";

      $query.=" AND game_id IN ($glist);";

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

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

      ## Display Stats

      if (mysqli_num_rows($result))

       {

         while ($row=mysqli_fetch_array($result))

	  {

	    $pid=$row['player_id'];

	    $tid=$row['team_id'];

	    $gid=$row['game_id'];

 	    $hid=$games[$gid]['home_team'];

	    $aid=$games[$gid]['away_team'];

 	    unset($gdate);

	    $gdate=new DateTime($games[$gid]['date']);

 	    $gtime=$games[$gid]['time'];

	    if ($gtime>1699) {$daynight="Night";}

	     else {$daynight="Day";}

            $month=$gdate->format("F");

            $monthID=$gdate->format("n");

	    $gtype=$games[$gid]['game_type'];

 	    if (($gtype!=0)&&($gtype!=2)&&($gtype!=3)) {continue;}

	    switch ($gtype)

	     {

	       case 0: $gtype="Regular Season"; break;

	       case 2: $gtype="Spring Training"; break;

	       case 3: $gtype="Postseason"; break;

	     }

	    if ($tid==$hid)

	     { 

	       $homeaway="Home";

	       switch ($gtype)

	        {

	          case 'Spring Training': $opponent="Ops^".$aid; $oppname=$teams[$aid]['name']."a"; break;

	          case 'Regular Season' : $opponent="Opr^".$aid; $oppname=$teams[$aid]['name']."b"; break;

	          case 'Postseason'     : $opponent="Opp^".$aid; $oppname=$teams[$aid]['name']."c"; break;

		}

	       

 	     }

	     else

	     {

	       $homeaway="Away";

	       switch ($gtype)

	        {

	          case 'Spring Training': $opponent="Ops^".$hid; $oppname=$teams[$hid]['name']."a"; break;

	          case 'Regular Season' : $opponent="Opr^".$hid; $oppname=$teams[$hid]['name']."b"; break;

	          case 'Postseason'     : $opponent="Opp^".$hid; $oppname=$teams[$hid]['name']."c"; break;

		}

	     }

	    if (isset($as_date))

	     {

	       if (($gdate->getTimestamp())>($as_date->getTimestamp())) {$allstar="Post All-Star Break";}

	        else {$allstar="Pre All-Star Break";}

	     }



       	    $w=$row['w'];

      	    $l=$row['l'];

	    $s=$row['s'];

 	    $cg=$row['cg'];

	    $sho=$row['sho'];

 	    $er=$row['er'];

	    $ip=$row['ip'];

 	    $g=$row['g'];

	    $gs=$row['gs'];

 	    $ha=$row['ha'];

	    $r=$row['r'];

 	    $hra=$row['hra'];

	    $bb=$row['bb'];

 	    $k=$row['k'];

	    $ab=$row['ab'];

 	    $sf=$row['sf'];

		  if ($gs==1) {$role='Starters';} else {$role='Relievers';}



	    unset($splits);

	    if ($team_id!="")

	     {

	       $splits=Array('Total',$month,$homeaway,$daynight,$opponent,$gtype,$role);

	       if (isset($as_date)) {array_push($splits,$allstar);}

	     }

	     else {$splits=Array('Total');}



	    foreach ($splits as $key => $split)

	     {

               ## Only include ST and PS games in Season splits when viewing Seasonal scope

	       if (($scope!='LastSim')&&($gtype=='Spring Training')&&($split!='Spring Training')&&($split!='Total')) {continue;}

	       if (($scope!='LastSim')&&($gtype=='Postseason')&&($split!='Postseason')&&($split!='Total')&&(!(strpos($split,"^")>0))) {continue;}

	

	       if (!isset($teams[$tid]['gtype'][$gtype])&&(($split=='Spring Training')||($split=='Regular Season')||($split=='Postseason'))) {$teams[$tid]['gtype'][$gtype]=$gtype;}

	       if (!isset($teams[$tid]['months'][$monthID])&&(($split=='January')||($split=='February')||($split=='March')||($split=='April')||($split=='May')||($split=='June')||($split=='July')||($split=='August')||($split=='September')||($split=='October')||($split=='November')||($split=='December'))) {$teams[$tid]['months'][$monthID]=$month;}

	       if (!isset($teams[$tid]['opps'][$oppname])&&(strpos($split,"^")>0)) {$teams[$tid]['opps'][$oppname]=$opponent;}

	

	       $teams[$tid][$split]['g'][$gid]=$gid;

               $teams[$tid][$split]['w']=$teams[$tid][$split]['w']+$w;

	       $teams[$tid][$split]['l']=$teams[$tid][$split]['l']+$l;

 	       $teams[$tid][$split]['s']=$teams[$tid][$split]['s']+$s;

	       $teams[$tid][$split]['cg']=$teams[$tid][$split]['cg']+$cg;

 	       $teams[$tid][$split]['sho']=$teams[$tid][$split]['sho']+$sho;

	       $teams[$tid][$split]['er']=$teams[$tid][$split]['er']+$er;

 	       $teams[$tid][$split]['ip']=$teams[$tid][$split]['ip']+$ip;

	       $teams[$tid][$split]['gs']=$teams[$tid][$split]['gs']+$gs;

 	       $teams[$tid][$split]['ha']=$teams[$tid][$split]['ha']+$ha;

	       $teams[$tid][$split]['r']=$teams[$tid][$split]['r']+$r;

 	       $teams[$tid][$split]['hra']=$teams[$tid][$split]['hra']+$hra;

	       $teams[$tid][$split]['bb']=$teams[$tid][$split]['bb']+$bb;

 	       $teams[$tid][$split]['k']=$teams[$tid][$split]['k']+$k;

	       $teams[$tid][$split]['ab']=$teams[$tid][$split]['ab']+$ab;

 	       $teams[$tid][$split]['sf']=$teams[$tid][$split]['sf']+$sf;

	     }

 	  }

 

	 if ($team_id!="")

	  {

	    if (isset($teams[$team_id]['months'])) {ksort($teams[$team_id]['months']);}

	    if (isset($teams[$team_id]['opps'])) {ksort($teams[$team_id]['opps']);}

	  }



	 ## Display Splits

	 if ($team_id!="")

	  {

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

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

	    if ($team_id!="")

	     {

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

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

	     }

	     else {$headings="Tot";}



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

	     {

               if (($scope!='LastSim')&&(($header=='Home/Away')||($header=='By Month')||($header=='By Half')||($header=='Day/Night')||($header=='By Role'))) {$dispHeader=$header." (regular season games only)";}

                elseif (($scope=='LastSim')&&(($header=='Home/Away')||($header=='By Month')||($header=='By Half')||($header=='Day/Night')||($header=='By Role'))) {$dispHeader=$header." (includes all games played)";}

	        else {$dispHeader=$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';>$dispHeader</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'>WHIP</td><td class='hsc2'>OAVG</td><td class='hsc2'>BABIP</td>\n";

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

    

	       unset($splits);

	       switch ($header)

	        {

                  case 'Season'      :

		     $splits=Array();

                     if (isset($teams[$team_id]['gtype']['Spring Training'])) {array_push($splits,'Spring Training');}

                     if (isset($teams[$team_id]['gtype']['Regular Season'])) {array_push($splits,'Regular Season');}

                     if (isset($teams[$team_id]['gtype']['Postseason'])) {array_push($splits,'Postseason');}

                     array_push($splits,'Total');

		     break;

	          case 'Home/Away'   : $splits=Array("Home","Away"); break;

		  case 'By Month'    :

		     $splits=Array();

		     for ($i=1;$i<=12;$i++)

		      {

                        if (isset($teams[$team_id]['months'][$i])) {array_push($splits,$teams[$team_id]['months'][$i]);}

		      }

		     break;

	          case 'By Half'     : $splits=Array("Pre All-Star Break","Post All-Star Break"); break;

				case 'Day/Night'   : $splits=Array("Day","Night"); break;

				case 'By Role'   : $splits=Array("Starters","Relievers"); break;

	          case 'vs. Opponent': 

		     foreach ($teams[$team_id]['opps'] as $data => $val) {$splits[$data]=$val;}

		     break;

	          default            : $splits=Array('Total'); break;

	        }

   

	       $rownum=0;

	       foreach ($splits as $key => $split)

	        {
				if (!isset($teams[$team_id][$split])) {continue;}
	 	  
	 	  $w=$teams[$team_id][$split]['w'];

		  $l=$teams[$team_id][$split]['l'];

		  $s=$teams[$team_id][$split]['s'];

 		  $cg=$teams[$team_id][$split]['cg'];

		  $sho=$teams[$team_id][$split]['sho'];

 		  $er=$teams[$team_id][$split]['er'];

		  $ip=$teams[$team_id][$split]['ip'];

 		  $g=count($teams[$team_id][$split]['g']);

		  $gs=$teams[$team_id][$split]['gs'];

 		  $ha=$teams[$team_id][$split]['ha'];

		  $r=$teams[$team_id][$split]['r'];

 		  $hra=$teams[$team_id][$split]['hra'];

		  $bb=$teams[$team_id][$split]['bb'];

 		  $k=$teams[$team_id][$split]['k'];

		  $ab=$teams[$team_id][$split]['ab'];

 		  $sf=$teams[$team_id][$split]['sf'];

		  unset($teams[$team_id][$split]);

 

		  if ($ip==0) {$era=0;$whip=0;}

		   else 

		   {

		     $era=$er*9/$ip;

	   	     $whip=($ha+$bb)/$ip;

		   }

      		  $era=sprintf("%.2f",$era);

		  $ip=sprintf("%.1f",$ip);

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

		  $whip=sprintf("%.2f",$whip);

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

		  if ($ab==0) {$oavg=0;}

     		   else {$oavg=$ha/$ab;}

		  if ($oavg<1) {$oavg=strstr(sprintf("%.3f",$oavg),".");}

	     	   else {$oavg=sprintf("%.3f",$oavg);}

		  $bip=$ab-$k-$hra+$sf;

      		  if ($bip==0) {$babip=0;}

		   else {$babip=($ha-$hra)/$bip;}

	      	  if ($babip<1) {$babip=strstr(sprintf("%.3f",$babip),".");}

		   else {$babip=sprintf("%.3f",$babip);}



	          if ($split=="Total")

	 	   {

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

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

		     echo "<td class='hsc2'>".$w."</td>";

 		     echo "<td class='hsc2'>".$l."</td>";

		     echo "<td class='hsc2'>".$s."</td>";

 		     echo "<td class='hsc2'>".$cg."</td>";

		     echo "<td class='hsc2'>".$sho."</td>";

 		     echo "<td class='hsc2'>".$era."</td>";

		     echo "<td class='hsc2'>".$g."</td>";

 		     echo "<td class='hsc2'>".$gs."</td>";

		     echo "<td class='hsc2'>".$ip."</td>";

 		     echo "<td class='hsc2'>".$ha."</td>";

		     echo "<td class='hsc2'>".$r."</td>";

 		     echo "<td class='hsc2'>".$er."</td>";

		     echo "<td class='hsc2'>".$hra."</td>";

 		     echo "<td class='hsc2'>".$bb."</td>";

		     echo "<td class='hsc2'>".$k."</td>";

 		     echo "<td class='hsc2'>".$whip."</td>";

		     echo "<td class='hsc2'>".$oavg."</td>";

 		     echo "<td class='hsc2'>".$babip."</td>";

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

 		   }

		   else

		   {

		     $rcls=$rownum%2+1;

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

		     if (strpos($split,"^")>0)

  		      {

		        $e=explode("^",$split);

                        $gt=$e[0];

			$oppID=$e[1];

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

			switch ($gt)

			 {

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

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

			 }

		      }

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

		     if ($g==0)

		      {

		        echo "<td>0</td><td>0</td><td>0</td><td>0</td><td>0</td>";

		        echo "<td>".$era."</td>";

			echo "<td>0</td><td>0</td>";

 			echo "<td>".$ip."</td>";

			echo "<td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td>";

 			echo "<td>".$whip."</td>";

			echo "<td>".$oavg."</td>";

 			echo "<td>".$babip."</td>";

			echo "</tr>\n";

 			$rownum++;

			continue;

 		      }

   

		     echo "<td>".$w."</td>";

		     echo "<td>".$l."</td>";

		     echo "<td>".$s."</td>";

 		     echo "<td>".$cg."</td>";

		     echo "<td>".$sho."</td>";

 		     echo "<td>".$era."</td>";

		     echo "<td>".$g."</td>";

 		     echo "<td>".$gs."</td>";

		     echo "<td>".$ip."</td>";

 		     echo "<td>".$ha."</td>";

		     echo "<td>".$r."</td>";

 		     echo "<td>".$er."</td>";

		     echo "<td>".$hra."</td>";

 		     echo "<td>".$bb."</td>";

		     echo "<td>".$k."</td>";

 		     echo "<td>".$whip."</td>";

		     echo "<td>".$oavg."</td>";

 		     echo "<td>".$babip."</td>";

		     echo "</tr>\n";

 		   }

		  $rownum++;

 		}



	       ## 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";

	  }

       }

		

	

		

		## Display Splits

		if ($team_id!="")

		{

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

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



			$query="SELECT game_id,team,inning,score FROM games_score WHERE game_id IN ($glist) ORDER BY game_id,inning,team;";

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

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

			if (mysqli_num_rows($result))

			{

				$prevInn=0;

				$prevGid=0;

				$maxInn=9;

				while ($row=mysqli_fetch_array($result))

				{

					$gid=$row['game_id'];

					$team=$row['team'];

					$inning=$row['inning'];

					if ($inning>$maxInn) {$maxInn=$inning;}

					$score=$row['score'];

					$gameResult=$games[$gid]['result'];

					if (!isset($inningScore['gcnt'][$inning])) {$inningScore['gcnt'][$inning]=0;}

					if (!isset($inningScore['ra'][$inning])) {$inningScore['ra'][$inning]=0;}

					if (!isset($inningScore['rf'][$inning])) {$inningScore['rf'][$inning]=0;}

					if (!isset($inningScore['ra']['tot'])) {$inningScore['ra']['tot']=0;}

					if (!isset($inningScore['rf']['tot'])) {$inningScore['rf']['tot']=0;}

					if (!isset($winning[$inning]['w'])) {$winning[$inning]['w']=0;}

					if (!isset($winning[$inning]['l'])) {$winning[$inning]['l']=0;}

					if (!isset($losing[$inning]['w'])) {$losing[$inning]['w']=0;}

					if (!isset($losing[$inning]['l'])) {$losing[$inning]['l']=0;}

					if (!isset($tied[$inning]['w'])) {$tied[$inning]['w']=0;}

					if (!isset($tied[$inning]['l'])) {$tied[$inning]['l']=0;}

					if ($games[$gid]['home']==1)

					{

						if ($team==0)

						{

							$inningScore['gcnt'][$inning]=$inningScore['gcnt'][$inning]+1;

							$inningScore['ra'][$inning]=$inningScore['ra'][$inning]+$score;

							$inningScore['ra']['tot']=$inningScore['ra']['tot']+$score;

							$games[$gid]['totalscore']=$games[$gid]['totalscore']-$score;

						}

						else

						{

							$inningScore['rf'][$inning]=$inningScore['rf'][$inning]+$score;

							$inningScore['rf']['tot']=$inningScore['rf']['tot']+$score;

							$games[$gid]['totalscore']=$games[$gid]['totalscore']+$score;

							if ($games[$gid]['totalscore']>0)

							{

								$winning[$inning][$gameResult]+=1;

							}

							elseif ($games[$gid]['totalscore']<0)

							{

								$losing[$inning][$gameResult]+=1;

							}

							else  ##tied

							{

								$tied[$inning][$gameResult]+=1;

							}

						}

					}

					else

					{

						if ($team==0)

						{

							$inningScore['gcnt'][$inning]=$inningScore['gcnt'][$inning]+1;

							$inningScore['rf'][$inning]=$inningScore['rf'][$inning]+$score;

							$inningScore['rf']['tot']=$inningScore['rf']['tot']+$score;

							$games[$gid]['totalscore']=$games[$gid]['totalscore']+$score;

						}

						else

						{

							$inningScore['ra'][$inning]=$inningScore['ra'][$inning]+$score;

							$inningScore['ra']['tot']=$inningScore['ra']['tot']+$score;

							$games[$gid]['totalscore']=$games[$gid]['totalscore']-$score;

							if ($games[$gid]['totalscore']>0)

							{

								$winning[$inning][$gameResult]+=1;

							}

							elseif ($games[$gid]['totalscore']<0)

							{

								$losing[$inning][$gameResult]+=1;

							}

							else  ##tied

							{

								$tied[$inning][$gameResult]+=1;

							}

						}	

					}

					$prevInn=$inning;

					$prevGid=$gid;

				}

			}

			

			## Display Inning Splits

			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';>Runs By Inning</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>";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td class='hsc2'>$i</td>";}

			echo "<td class='hsc2'>Tot</td></tr></thead>\n";

			$cnt=0;

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

			echo "    <tr class='$cls'><td class='".$cls."_l'>Total Runs For</td>\n";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td>".$inningScore['rf'][$i]."</td>";}

			echo "<td>".$inningScore['rf']['tot']."</td></tr>\n";

			$cnt++;

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

			echo "    <tr class='$cls'><td class='".$cls."_l'>Total Runs Allowed</td>\n";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td>".$inningScore['ra'][$i]."</td>";}

			echo "<td>".$inningScore['ra']['tot']."</td></tr>\n";

			$cnt++;

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

			echo "    <tr class='$cls'><td class='".$cls."_l'>Games Played</td>\n";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td>".$inningScore['gcnt'][$i]."</td>";}

			echo "<td>".$inningScore['gcnt'][1]."</td></tr>\n";

			$cnt++;

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

			echo "    <tr class='$cls'><td class='".$cls."_l'>Per Game Runs For</td>\n";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td>".sprintf("%.2f",$inningScore['rf'][$i]/$inningScore['gcnt'][$i])."</td>";}

			echo "<td>".sprintf("%.2f",$inningScore['rf']['tot']/$inningScore['gcnt'][1])."</td></tr>\n";

			$cnt++;

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

			echo "    <tr class='$cls'><td class='".$cls."_l'>Per Game Runs Allowed</td>\n";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td>".sprintf("%.2f",$inningScore['ra'][$i]/$inningScore['gcnt'][$i])."</td>";}

			echo "<td>".sprintf("%.2f",$inningScore['ra']['tot']/$inningScore['gcnt'][1])."</td></tr>\n";

			## Close Table

			echo "   </table>\n";

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

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

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

			

			## Display Winning Splits

			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';>Record When Winning After X Innings</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>";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td class='hsc2'>$i</td>";}

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

			$cnt=0;

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

			echo "    <tr class='$cls'><td class='".$cls."_l'>Wins</td>\n";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td>".$winning[$i]['w']."</td>";}

			echo "</tr>\n";

			$cnt++;

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

			echo "    <tr class='$cls'><td class='".$cls."_l'>Losses</td>\n";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td>".$winning[$i]['l']."</td>";}

			echo "</tr>\n";

			$cnt++;

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

			echo "    <tr class='$cls'><td class='".$cls."_l'>Win Pct</td>\n";

			for ($i=1;$i<=$maxInn;$i++)

			{

				if (($winning[$i]['w']+$winning[$i]['l'])==0) {$winPct=sprintf("%.3f",0);} else {$winPct=sprintf("%.3f",$winning[$i]['w']/($winning[$i]['w']+$winning[$i]['l']));}

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

				echo "<td>".$winPct."</td>";

			}

			echo "</tr>\n";

			## Close Table

			echo "   </table>\n";

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

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

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

			

			## Display Losing Splits

			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';>Record When Losing After X Innings</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>";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td class='hsc2'>$i</td>";}

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

			$cnt=0;

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

			echo "    <tr class='$cls'><td class='".$cls."_l'>Wins</td>\n";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td>".$losing[$i]['w']."</td>";}

			echo "</tr>\n";

			$cnt++;

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

			echo "    <tr class='$cls'><td class='".$cls."_l'>Losses</td>\n";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td>".$losing[$i]['l']."</td>";}

			echo "</tr>\n";

			$cnt++;

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

			echo "    <tr class='$cls'><td class='".$cls."_l'>Win Pct</td>\n";

			for ($i=1;$i<=$maxInn;$i++)

			{

				if (($losing[$i]['w']+$losing[$i]['l'])==0) {$winPct=sprintf("%.3f",0);} else {$winPct=sprintf("%.3f",$losing[$i]['w']/($losing[$i]['w']+$losing[$i]['l']));}

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

				echo "<td>".$winPct."</td>";

			}

			echo "</tr>\n";

			## Close Table

			echo "   </table>\n";

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

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

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

			

			## Display Tied Splits

			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';>Record When Tied After X Innings</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>";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td class='hsc2'>$i</td>";}

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

			$cnt=0;

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

			echo "    <tr class='$cls'><td class='".$cls."_l'>Wins</td>\n";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td>".$tied[$i]['w']."</td>";}

			echo "</tr>\n";

			$cnt++;

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

			echo "    <tr class='$cls'><td class='".$cls."_l'>Losses</td>\n";

			for ($i=1;$i<=$maxInn;$i++) {echo "<td>".$tied[$i]['l']."</td>";}

			echo "</tr>\n";

			$cnt++;

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

			echo "    <tr class='$cls'><td class='".$cls."_l'>Win Pct</td>\n";

			for ($i=1;$i<=$maxInn;$i++)

			{

				if (($tied[$i]['w']+$tied[$i]['l'])==0) {$winPct=sprintf("%.3f",0);} else {$winPct=sprintf("%.3f",$tied[$i]['w']/($tied[$i]['w']+$tied[$i]['l']));}

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

				echo "<td>".$winPct."</td>";

			}

			echo "</tr>\n";

			## Close Table

			echo "   </table>\n";

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

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

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

			

			echo "  </table>\n";

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

		}

		

    }   ### End of Team Split Stats



  ##### Head to Head Records #####

  if ($team_id=="")

  {

    	  $query="SELECT game_id,away_team,home_team,runs0,runs1 FROM games WHERE league_id=$lgid";

	  if ($tlist!="") {$query.=" AND (home_team IN ($tlist) OR away_team IN ($tlist))";}

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

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

   	  elseif ($scope=="Season") {$query.=" AND played=1 AND game_type=0";}

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

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

	  if (mysqli_num_rows($result))

   	  {

		  while ($row=mysqli_fetch_array($result))

		  {

			  $aid=$row['away_team'];

	      		  $hid=$row['home_team'];

			  $aSL=$teams[$aid]['slid'];

	      		  $hSL=$teams[$hid]['slid'];

			  $subleagues[$aSL]['found']=1;

	      		  $subleagues[$hSL]['found']=1;

			  if ($aSL!=$hSL) {$interLg[$hSL][$aSL]=1;}

	      		  if ($row['runs1']>$row['runs0'])   ## Home Team Win

			  {

		   		  $wins[$hid][$aid]=$wins[$hid][$aid]+1;

				  $losses[$aid][$hid]=$losses[$aid][$hid]+1;

	     		  }

			  else   ## Away Team Win

	     		  {

				  $losses[$hid][$aid]=$losses[$hid][$aid]+1;

		   		  $wins[$aid][$hid]=$wins[$aid][$hid]+1;

			  }

		  }

	 

		  if ($division_id!="")

		  {

	      		  $query="SELECT name FROM divisions WHERE league_id=$lgid AND sub_league_id=".substr($division_id,0,strpos($division_id,"_"))." AND division_id=".substr($division_id,strpos($division_id,"_")+1).";";

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

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

			  $row=mysqli_fetch_array($result);

	      		  $divName=$row['name'];

		  }

	 	  echo " <div class='textbox' style='width:935px;margin-left:0px;margin-right:0px;'>\n";

		  echo "  <table cellpadding=0 cellspacing=0 border=0 style='width:935px;'><tr class='title'><td style='padding:2px';>Head-to-Head Records</td></tr>\n";

	   

		  foreach ($subleagues as $slid => $val)

		  {

	      		  if (($subleagues[$slid]['found']!=1)||(($sub_league_id!="")&&($sub_league_id!=$slid))) {continue;}

			  if (($division_id!="")&&(substr($division_id,0,strpos($division_id,"_"))!=$slid)) {continue;}

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

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

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

			  echo "      <tr class='title'><td style='padding:2px';>".$subleagues[$slid]['name'];

			  if ($division_id!="") {echo " (Only games involving ".$subleagues[substr($division_id,0,strpos($division_id,"_"))]['abbr']." $divName teams)";}

			  if ($oneLg==1) {echo "All Teams";}

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

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

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

		

			  $cnt=0;

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

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

			  $teamArray=explode(",",trim($subleagues[$slid]['teams'],","));

	      		  foreach ($teamArray as $key => $tid)

			  {

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

			  }

	      		  echo "</tr>\n";

			  $cnt++;

	      		  foreach ($teamArray as $key => $tid1)

			  {  

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

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

				  echo "<td class='".$cls."_l'><b>".$teams[$tid1]['abbr']."</b></td>";

				  foreach ($teamArray as $key => $tid2)

		  		  {

					  if ($cnt==0) {echo "<td><b>".$teams[$tid2]['abbr']."</b></td>";}

		       			  else

					  {

			     			  if ($tid1==$tid2) {echo "<td>-</td>";continue;}

						  if ((isset($wins[$tid1][$tid2]))||(isset($losses[$tid1][$tid2])))

				    		  {

							  echo "<td>";

							  if (isset($wins[$tid1][$tid2])) {echo $wins[$tid1][$tid2];} else {echo "0";}

							  echo "-";

							  if (isset($losses[$tid1][$tid2])) {echo $losses[$tid1][$tid2];} else {echo "0";}

							  echo "</td>";

			    			  }

						  else {echo "<td>0-0</td>";}

		       			  }

				  }

		   		  echo "</tr>\n";

				  $cnt++;

	     		  }

	      

			  echo "       </table>\n";

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

			  echo "     </table\n";

	      		  echo "    </div>\n";

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

		  }

	 

		  foreach ($subleagues as $slid1 => $val)

		  {

	      		  foreach ($subleagues as $slid2 => $val)

			  {

		   		  if ($interLg[$slid1][$slid2]!=1) {continue;}

			   

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

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

		   		  echo "     <table cellpadding=0 cellspacing=0 border=0><tr class='title'><td style='padding:2px';>Interleague: ".$subleagues[$slid1]['abbr']." vs. ".$subleagues[$slid2]['abbr'];

				  if ($division_id!="") {echo " (Only games involving ".$subleagues[substr($division_id,0,strpos($division_id,"_"))]['abbr']." $divName teams)";}

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

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



				  $cnt=0;

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

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



				  $teamArray1=explode(",",trim($subleagues[$slid1]['teams'],","));

		   		  $teamArray2=explode(",",trim($subleagues[$slid2]['teams'],","));

		      

				  foreach ($teamArray2 as $key => $tid)

				  {

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

				  }



				  echo "</tr>\n";

		   		  $cnt++;

				  foreach ($teamArray1 as $key => $tid1)

		  		  {

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

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

					  echo "<td class='".$cls."_l'><b>".$teams[$tid1]['abbr']."</b></td>";

					  foreach ($teamArray2 as $key => $tid2)

					  {

			     			  if ($cnt==0) {echo "<td><b>".$teams[$tid2]['abbr']."</b></td>";}

						  else

			    			  {

							  if ($tid1==$tid2) {echo "<td>-</td>";continue;}

					  		  if ((isset($wins[$tid1][$tid2]))||(isset($losses[$tid1][$tid2])))

							  {

				       				  echo "<td>";

								  if (isset($wins[$tid1][$tid2])) {echo $wins[$tid1][$tid2];} else {echo "0";}

				       				  echo "-";

								  if (isset($losses[$tid1][$tid2])) {echo $losses[$tid1][$tid2];} else {echo "0";}

				       				  echo "</td>";

							  }

				 			  else {echo "<td>0-0</td>";}

						  }

		       			  }

					  echo "</tr>\n";

					  $cnt++;

				  }



				  echo "      </table>\n";

		   		  echo "     </table\n";

				  echo "    </div>\n";

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

			  }

		  }

		  ## Close Table

		  echo "   </table>\n";

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

	  }

	  $row['runs0']=$Awayteam;

  }





  mysqli_close($db);



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

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

  page_foot($_SESSION['lgpath']);





?>

