<?php

  include("html_functions.php");



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

  $lgid=$_SESSION['lgid'];

  $lgdate=$_SESSION['lgdate'];

  $lgpath=$_SESSION['lgpath'];

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

  $lgyear=$_SESSION['lgyear'];

  $lgMo=$date->format("m");

  $lgDay=$date->format("d");



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

  

  ##### Get Report Settings #####

  $view=$_GET['view'];

  if ($view=="") {$view='versus';}

  if ((isset($_SESSION['user_league_id']))&&($_SESSION['user_league_id']==$lgid)) {$team_id1=$_SESSION['user_team_id'];}

  if (isset($_GET['team_id1'])) {$team_id1=$_GET['team_id1'];}

  $team_id2=$_GET['team_id2'];

  if ($team_id1==$team_id2) {$team_id2="";}

	  

  $scope=$_GET['scope'];

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

  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;

  }





  

  # Title Bar

  $title='Matchups';



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

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



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

  

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

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

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

  while ($row=mysqli_fetch_array($result))

  {

	  $tid=$row['team_id'];

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

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

  }

  

  ##### Display Filters #####

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

  echo "  <form method='get' action='matchups.php' style='clear:left;'>\n";

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

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

  

  ## Show Team Filter

  echo "   <tr>\n";

  echo "     <td><label><b>Teams:</b></label></td>\n";

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

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

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

  {

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

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

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

  }

  echo "      </select>\n";

  echo "     </td>\n";

  echo "     <td>vs.</td>\n";

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

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

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

  {

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

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

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

  }

  echo "      </select>\n";

  echo "     </td>\n";



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

  

  ## Show Scope Filter

  echo "    <td><label><b>Scope:</b></label></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>";

  

  ## Submission button

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

  echo "    </tr>\n";

  

  ##### Close Form #####

  echo "  </table>\n";

  echo "  </form>\n";

  echo " </div>\n";

  

  if (($view=="")||($team_id1=="")||($team_id2==""))

  {

	  mysqli_close($db);

	  ## Close out page

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

	  page_foot($_SESSION['lgpath']);

       	  exit;

  }

  

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

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



  ##### Get DH Setting #####

  $showDH=0;

  $query="SELECT sl.sub_league_id,designated_hitter FROM sub_leagues as sl,teams as t WHERE t.sub_league_id=sl.sub_league_id AND team_id IN ($team_id1,$team_id2) AND sl.league_id=$lgid";

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

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

  while ($row=mysqli_fetch_array($result))

  {

    	  if ($row['designated_hitter']==1) {$showDH=1;}

  }



  ##### Get Team Info #####

  $query="SELECT t.team_id,abbr,name,nickname,level,logo_file_name,w,l,pos,text_color_id,background_color_id FROM teams as t,team_record as tr WHERE t.team_id=tr.team_id AND (t.team_id IN ($team_id1,$team_id2) OR t.parent_team_id IN ($team_id1,$team_id2));";

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

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

  while ($row=mysqli_fetch_array($result))			    

  {

	  $tid=$row['team_id'];

    	  $tname=$row['name']." ".$row['nickname'];

	  $teams[$tid]['name']=$tname;

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

	  $teams[$tid]['level']=get_level($row['level']);

    	  $teams[$tid]['logo']=urlencode($row['logo_file_name']);

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

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

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

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

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

	  $teamcity[$tid]=$row['name'];

  }



  ##### Get Games #####

  $gList="";

  $pList="";

  $query="SELECT game_id,game_type,games.date,played,games.time,home_team,away_team,innings,runs0,runs1,hits0,hits1,errors0,errors1,winning_pitcher,losing_pitcher,save_pitcher FROM games WHERE league_id=$lgid AND ((home_team=$team_id1 AND away_team=$team_id2) OR (home_team=$team_id2 AND away_team=$team_id1))";

  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 IN (0,3)";}

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

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

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

  if (mysqli_num_rows($result))

  {

	  $pcnt=0;

	  while ($row=mysqli_fetch_array($result))

	  {

		  $gid=$row['game_id'];

		  $gdate=$row['date'];



		  $gtype=$row['game_type'];

		  $gtypes[$gtype]=1;



		  $games[$gid][$gdate]=1;

		  $gList.=",$gid";



		  $played=$row['played'];

		  $runs0=$row['runs0'];

		  $runs1=$row['runs1'];

		  $hid=$row['home_team'];

		  $aid=$row['away_team'];



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

		  $games[$gid]['played']=$played;

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

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

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

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

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

		  $games[$gid]['runs0']=$runs0;

		  $games[$gid]['runs1']=$runs1;

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

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

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

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



		  if ($played==1)

		  {

			  $pcnt++;

			  if ($runs0>$runs1)

			  {

				  $series[$aid]['ovr']['w']=$series[$aid]['ovr']['w']+1;

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

			  }

			  else

			  {

				  $series[$hid]['ovr']['w']=$series[$hid]['ovr']['w']+1;

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

			  }

		  }



		  $wp=$row['winning_pitcher'];

		  $lp=$row['losing_pitcher'];

		  $sp=$row['save_pitcher'];

		  $games[$gid]['winning_pitcher']=$wp;

		  $games[$gid]['losing_pitcher']=$lp;

		  $games[$gid]['save_pitcher']=$sp;



		  $players[$wp]['fnd']=1;

		  $players[$lp]['fnd']=1;

		  $players[$sp]['fnd']=1;

	  }

  }

  else

  {

	  echo "<p>The ".$teams[$team_id1]['name']." do not play the ".$teams[$team_id2]['name']." this season.</p>";

	

	  mysqli_close($db);

	

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

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

	  page_foot($_SESSION['lgpath']);

	  exit;

  }



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



  ##### Begin Matchup Display #####

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

  echo " <table cellpadding=0 cellspacing=0 border=0 width='935px'>\n";

  $fldName="round_names".($round-1);

  echo "  <tr class='title2'><td colspan=7>$lgyear Season Matchup</td></tr>\n";

  echo "  <tr>\n";

  echo "   <td style='width:110px;background-color:".$teams[$team_id1]['background_color_id'].";' align='left'><img src='$lgpath/images/team_logos/".str_replace(".png","_110.png",$teams[$team_id1]['logo'])."' width=110 height=110></td>\n";

  echo "   <td style='width:280px;background-color:".$teams[$team_id1]['background_color_id'].";' align='center'><a href='$lgpath/teams/team_$team_id1.html' style='font-size:2em;color:".$teams[$team_id1]['text_color_id'].";'>".$teams[$team_id1]['name']."</a><br/><span style='font-size:1em;color:".$teams[$team_id1]['text_color_id'].";'>".ordinal_suffix($teams[$team_id1]['pos'])." place, ".$teams[$team_id1]['w']."-".$teams[$team_id1]['l']."</span></td>\n";

  echo "   <td style='width:50px;font-size:3em;background-color:".$teams[$team_id1]['background_color_id'].";color:".$teams[$team_id1]['text_color_id'].";' align='center'>".$series[$team_id1]['ovr']['w']."</td>\n";

  echo "   <td style='width:55px;' align='center' class='icgb'>vs.</td>\n";

  echo "   <td style='width:50px;font-size:3em;background-color:".$teams[$team_id2]['background_color_id'].";color:".$teams[$team_id2]['text_color_id'].";' align='center'>".$series[$team_id2]['ovr']['w']."</td>\n";

  echo "   <td style='width:280px;background-color:".$teams[$team_id2]['background_color_id'].";' align='center'><a href='$lgpath/teams/team_$team_id2.html' style='font-size:2em;color:".$teams[$team_id2]['text_color_id'].";'>".$teams[$team_id2]['name']."</a><br/><span style='font-size:1em;color:".$teams[$team_id2]['text_color_id'].";'>".ordinal_suffix($teams[$team_id2]['pos'])." place, ".$teams[$team_id2]['w']."-".$teams[$team_id2]['l']."</span></td>\n";

  echo "   <td style='width:110px;background-color:".$teams[$team_id2]['background_color_id'].";' align='right'><img src='$lgpath/images/team_logos/".str_replace(".png","_110.png",$teams[$team_id2]['logo'])."' width=110 height=110></td>\n";

  echo "  </tr>\n";

  if (count($gtypes)>1)

  {

    	  echo "  <tr>\n";

	  echo "   <td style='border-top:1px solid grey;text-align:center;' colspan=7>\n";

    	  $cnt=0;

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

   	  {

		  if ($cnt>0) {echo "<br/>";} else {echo "    ";}

		 	  switch ($gtype)

			  {

	      		  case 0: echo "Reg: "; break;

			  case 3: echo "PS: ";  break;

			  }

			  echo max(0,$series[$team_id1][$gtype]['w'])."-".max(0,$series[$team_id2][$gtype]['w']);

		 	  $cnt++;

	  }

    	  echo "\n";

	  echo "   </td>\n";

    	  echo "  </tr>\n";

  }

  echo " </table>\n";

  echo "</div>\n";



  if ($pcnt>0)

  {

  	  ##### Get Home Runs #####

	  $query="SELECT player_id,team_id,game_id,hr FROM players_game_batting WHERE hr>0 AND game_id IN ($gList)";

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

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

	  if (mysqli_num_rows($result))

	  {

		  while ($row=mysqli_fetch_array($result))

		  {

			  $pid=$row['player_id'];

			  $tid=$row['team_id'];

			  $gid=$row['game_id'];

			  $hr=$row['hr'];



			  $players[$pid]['fnd']=1;



			  $games[$gid]['hrs'][$tid][$pid]=$hr;

		  }

	  }

	

	  ##### Get Player Names #####

	  if (isset($players))

	  {

		  foreach ($players as $pid => $val) {$pList.=",$pid";}

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

	

		  $query="SELECT player_id,first_name,last_name FROM players WHERE player_id IN ($pList)";

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

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

		  if (mysqli_num_rows($result))

		  {

			  while ($row=mysqli_fetch_array($result))

			  {

				  $pid=$row['player_id'];

				  $fi=$row['first_name'];

				  $fi=$fi[0];

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

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

			  }

		  }

	  }

	

	  ##### Get Inning-by-Inning Scores #####

	  $query="SELECT game_id,team,inning,score FROM games_score WHERE game_id IN ($gList) ORDER BY game_id,team,inning";

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

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

	  if (mysqli_num_rows($result))

	  {

		  $prevGid=-1;

		  while ($row=mysqli_fetch_array($result))

		  {

			  $gid=$row['game_id'];

			  $tid=$row['team'];

			  $inn=$row['inning'];



			  $score=$row['score'];



			  if ($inn<=($games[$gid]['innings']-12)) {continue;}



			  if ($tid==0)

			  {

				  if ($prevGid!=$gid) {$innText[$gid]['inn']="<td class='hc' width=18>&#160;</td>";}

				  $innText[$gid]['inn'].="<td class='hc' width=15>$inn</td>";

			  }

			  elseif (($games[$gid]['runs1']>$games[$gid]['runs0'])&&($row['inning']>8)&&($row['inning']==$games[$gid]['innings'])&&($score==0)) {$score="X";}

		

				  $innText[$gid][$tid]=$innText[$gid][$tid]."<td class='ic' width=15>$score</td>";

	

			  $prevGid=$gid;

		  }

	  }

	

	  ##### Get Games w/ Great Ind Performances #####

	  # Batting Performances

	  $query="SELECT game_id,pgb.player_id,pgb.team_id,first_name,last_name,h,d,t,hr,rbi,sb FROM players_game_batting as pgb,players as p WHERE pgb.player_id=p.player_id AND pgb.league_id=".$lgid." AND (hr>2 OR h>4 OR rbi>5 or sb>2 OR ((h-d-t-hr)>0 AND d>0 AND t>0 AND hr>0)) AND game_id IN ($gList);";

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

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

	  while ($row=mysqli_fetch_array($result))

	  {

		  $gid=$row['game_id'];

		  $pid=$row['player_id'];

		  $tid=$row['team_id'];

		  $fi=$row['first_name'];

		  $fi=$fi[0];

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

		  $h=$row['h'];

		  $d=$row['d'];

		  $t=$row['t'];

		  $hr=$row['hr'];

		  $s=$h-$d-$t-$hr;

		  $rbi=$row['rbi'];

		  $sb=$row['sb'];



		  if ($hr>2) 

		  {

			  $games[$gid]['note']=$games[$gid]['note'].", <a href='./player.php?player_id=$pid'>$name</a> belts $hr HR's";

		  }

		  if ($h>4)

		  {

			  $games[$gid]['note']=$games[$gid]['note'].", <a href='./player.php?player_id=$pid'>$name</a> knocks $h hits";

		  }

		  if ($rbi>5)

		  {

			  $games[$gid]['note']=$games[$gid]['note'].", <a href='./player.php?player_id=$pid'>$name</a> plates $rbi";

		  }

		  if ($sb>2)

		  {

			  $games[$gid]['note']=$games[$gid]['note'].", <a href='./player.php?player_id=$pid'>$name</a> steals $sb bases";

		  }

		  if (($s>0)&&($d>0)&&($t>0)&&($hr>0))

		  {

			  $games[$gid]['note']=$games[$gid]['note'].", <a href='./player.php?player_id=$pid'>$name</a> hits for the cycle";

		  }

	  }

	

	  # Pitching Performances

	  $query="SELECT game_id,pgp.player_id,pgp.team_id,first_name,last_name,k,(ip*3+ipf)/3 as ip,ha,cg,sho FROM players_game_pitching_stats as pgp,players as p WHERE pgp.player_id=p.player_id AND pgp.league_id=".$lgid." AND (k>9 OR ((ip*3+ipf)/3)>9 OR (ha=0 AND ((ip*3+ipf)/3)>7) OR (ha<3 AND cg=1 AND sho=1)) AND game_id IN ($gList);";

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

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

	  while ($row=mysqli_fetch_array($result))

	  {

		  $gid=$row['game_id'];

		  $pid=$row['player_id'];

		  $tid=$row['team_id'];

		  $fi=$row['first_name'];

		  $fi=$fi[0];

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

		  $k=$row['k'];

		  $ip=$row['ip'];

		  $ha=$row['ha'];

		  $cg=$row['cg'];

		  $sho=$row['sho'];

		  if (floor($ip)==$ip) {$dispIP=round($ip,0);} else {$dispIP=round(floor($ip),0)." ".round((3*($ip-floor($ip))),0)."/3";}



			  if ($k>9)

			  {

				  $games[$gid]['note']=$games[$gid]['note'].", <a href='./player.php?player_id=$pid'>$name</a> strikes out $k";

			  }

			  if ($ip>9)

			  {

				  $games[$gid]['note']=$games[$gid]['note'].", <a href='./player.php?player_id=$pid'>$name</a> goes ".$dispIP." innings";

			  }

			  if (($ha==0)&&($ip>7))

			  {

				  if ($cg==1) {$games[$gid]['note']=$games[$gid]['note'].", <a href='./player.php?player_id=$pid'>$name</a> pitches a no-hitter";}

				  else {$games[$gid]['note']=$games[$gid]['note'].", <a href='./player.php?player_id=$pid'>$name</a> fails to allow a hit";}

			  }

			  if (($ha<3)&&($cg==1)&&($sho==1)&&($ha!=0))

			  {

				  $games[$gid]['note']=$games[$gid]['note'].", <a href='./player.php?player_id=$pid'>$name</a> pitches a $ha-hit shutout";

			  }

	  }

  }



  ##### Get Team Situational Records #####

  $query="SELECT game_id,home_team,away_team,runs0,runs1 FROM games WHERE game_type=0 AND league_id=$lgid AND played=1 AND (home_team=$team_id1 OR home_team=$team_id2 OR away_team=$team_id1 OR away_team=$team_id2);";

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

  while ($row=mysqli_fetch_array($result))

  {

	  $hid=$row['home_team'];

    	  $aid=$row['away_team'];

	  if ($row['runs0']>$row['runs1'])

   	  {

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

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

	  }

   	  else

	  {

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

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

   	  }

  }



  echo "<div>\n";



  ##### Display Games #####

  echo " <div id='first' class='boxscores'><table cellpadding=2 cellspacing=0 border=0 style='border:0;margin:0;width:100%;'><tr class='title'><td>Box Scores</td></tr></table>\n";

  foreach ($games as $gid => $val)

  {

       $played=$games[$gid]['played'];

       if ($played==1)   ## Played Games

       {

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

	  $hname=$teams[$hid]['name'];

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

	  $aname=$teams[$aid]['name'];

	  $inns=$games[$gid]['innings'];



	  # Inning-by-Inning

	  $inntxt=$innText[$gid]['inn'];

	  $ainn=$innText[$gid][0];

	  $hinn=$innText[$gid][1];



	  for ($i=0;$i<(12-$inns);$i++)

   	  {

		  $inntxt.="<td class='hc' width=15>&#160;</td>";

	 	  $ainn.="<td class='ic' width=15>&#160;</td>";

		  $hinn.="<td class='ic' width=15>&#160;</td>";

   	  }

	  $inntxt.="<td class='hc' width=15>R</td><td class='hc' width=15>H</td><td class='hc' width=15>E</td>";

    	  $ainn.="<td class='icgb' width=15>".$games[$gid]['runs0']."</td><td class='ic' width=15>".$games[$gid]['hits0']."</td><td class='ic' width=15>".$games[$gid]['errors0']."</td>";

	  $hinn.="<td class='icgb' width=15>".$games[$gid]['runs1']."</td><td class='ic' width=15>".$games[$gid]['hits1']."</td><td class='ic' width=15>".$games[$gid]['errors1']."</td>";



	  # Pitchers

	  $wp=$games[$gid]['winning_pitcher'];

	  $lp=$games[$gid]['losing_pitcher'];

	  $sp=$games[$gid]['save_pitcher'];



	  $ptxt="W: <a href='./player.php?player_id=$wp'>".$players[$wp]['name']."</a> L: <a href='./player.php?player_id=$lp'>".$players[$lp]['name']."</a>";

    	  if ($sp!=0) {$ptxt.=" S: <a href='./player.php?player_id=$sp'>".$players[$sp]['name']."</a>";}



	  # HR Text

	  unset($hrtxt);

	  if (isset($games[$gid]['hrs'][$aid]))

	  {

		  $hrtxt[$aid]=$teams[$aid]['abbr'].": ";

		  $hrCnt=0;

		  foreach ($games[$gid]['hrs'][$aid] as $pid => $hr)

		  {

			  if ($hrCnt>0) {$hrtxt[$aid].=", ";}

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

			  if ($hr>1) {$hrtxt[$aid].=" ($hr)";}

			  $hrCnt++;

		  }

	  }

	  if (isset($games[$gid]['hrs'][$hid]))

	  {

		  $hrtxt[$hid]=$teams[$hid]['abbr'].": ";

		  $hrCnt=0;

		  foreach ($games[$gid]['hrs'][$hid] as $pid => $hr)

		  {

			  if ($hrCnt>0) {$hrtxt[$hid].=", ";}

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

			  if ($hr>1) {$hrtxt[$hid].=" ($hr)";}

			  $hrCnt++;

		  }

	  }

    	  if ((isset($games[$gid]['hrs'][$aid]))||(isset($games[$gid]['hrs'][$hid])))

	  {

		  $hrNote="HR - ".$hrtxt[$aid]." ".$hrtxt[$hid];

	  }

	  else {$hrNote="";}



	  # Game Note

    	  if (isset($games[$gid]['note']))

	  {

	 	  $gnote=$games[$gid]['note'];

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

	 	  $gnote="<br />Notes: ".$gnote;

	  }

   	  else {$gnote="";}

	    

	  unset($gdate);

	  $gDate=new Date($games[$gid]['date']);

    	  echo " <table cellspacing=0 cellpadding=0 style='border:0px;width:430px;margin:10px;'>\n";

	  echo "  <tr>\n";

    	  echo "   <td class='hl'>\n";

 	  if ($games[$gid]['type']==3) {echo "    Postseason: ";}

	  echo "    ".$gDate->format("M j, Y");

    	  echo ": <a href='$lgpath/box_scores/game_box_$gid.html'>Box Score</a>";

	  echo " | <a href='$lgpath/game_logs/log_$gid.html'>Game Log</a>";

	  echo " | <a href='./matchups.php?team_id1=$hid&team_id2=$aid'>Season Series</a>";

	  echo "   </td>\n";

    	  echo "  </tr>\n";

	  echo "  <tr>\n";

    	  echo "   <td>\n";

	  echo "    <table cellpadding=0 cellspacing=0 style='border:1px black solid;width:430px;margin-top:2px;margin-left:0px;'>\n";

    	  echo "     <tr>\n";

	  echo "      <td style='padding:1px;width:44px;border-right:1px solid #999999;'>\n";

    	  echo "       <img src='$lgpath/images/team_logos/".str_replace(".png","_40.png",$teams[$aid]['logo'])."' width=40 height=40><br>\n";

	  echo "       <img src='$lgpath/images/team_logos/".str_replace(".png","_40.png",$teams[$hid]['logo'])."' width=40 height=40>\n";

    	  echo "      </td>\n";

	  echo "      <td valign='top' style='padding:0px;margin:0px'>\n";

    	  echo "       <table cellspacing=0 cellpadding=1 style='width:100%;margin:0px;border:0px'>\n";

	  echo "        <tr>$inntxt</tr>\n";

    	  echo "        <tr><td class='gl'><a href='$lgpath/teams/team_$aid.html'>".$teamcity[$aid]."</a></td>";

	  echo "$ainn</tr>\n";

    	  echo "        <tr><td class='gl'><a href='$lgpath/teams/team_$hid.html'>".$teamcity[$hid]."</a></td>";

	  echo "$hinn</tr>\n";

    	  echo "        <tr><td colspan=16 class='gl' style='padding:6px 4px 4px 4px;'>".$ptxt."<br />".$hrNote.$gnote."</td></tr>\n";

	  echo "       </table>\n";

    	  echo "      </td>\n";

	  echo "     </tr>\n";

    	  echo "    </table>\n";

	  echo "   </td>\n";

    	  echo "  </tr>\n";

	  echo " </table>\n";

       }

       else  ## Unplayed Games

       {

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

         $hname=$teams[$hid]['name'];

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

	 $aname=$teams[$aid]['name'];



	 unset($date);

	 $date=new Date($games[$gid]['date']." ".$games[$gid]['time']);

	 echo "<table cellspacing=0 cellpadding=0 style='border:0px;width:430px;margin:10px;'>\n";

	 echo " <tr>\n";

	 echo "   <td class='hl'>\n    ";

	 if ($games[$gid]['type']==3) {echo "Postseason: ";}

	 echo $date->format("M j, Y")."\n";

	 echo "  </td>\n";

	 echo " </tr>\n";

	 echo " <tr>\n";

	 echo "  <td>\n";

	 echo "    <table cellpadding=0 cellspacing=0 style='border:1px black solid;width:430px;margin-top:2px;margin-left:0px;'>\n";

	 echo "     <tr>\n";

	 echo "      <td style='padding:1px;width:44px;border-right:1px solid #999999;'>\n";

	 echo "       <img src='$lgpath/images/team_logos/".str_replace(".png","_40.png",$teams[$aid]['logo'])."' width=40 height=40><br>\n";

	 echo "       <img src='$lgpath/images/team_logos/".str_replace(".png","_40.png",$teams[$hid]['logo'])."' width=40 height=40>\n";

	 echo "      </td>\n";

	 echo "        <td valign='top' style='padding:0px;margin:0px'>\n";

	 echo "       <table cellspacing=0 cellpadding=1 style='width:386px;margin:0px;border:0px'>\n";

   

	 echo "        <tr><td class='hl' colspan=2>".$date->format("g:i a")."</td></tr>\n";

	 echo "        <tr><td class='gl' width=175><a href='$lgpath/teams/team_$aid.html'>$aname</a></td>\n";

	 echo "            <td class='gl' width=175>".$teams[$aid]['w']."-".$teams[$aid]['l'].", On Road: ".$teams[$aid]['rw']."-".$teams[$aid]['rl']."</td></tr>\n";

	 echo "        <tr><td class='gl' width=175><a href='$lgpath/teams/team_$hid.html'>$hname</a></td>\n";

	 echo "            <td class='gl' width=175>".$teams[$hid]['w']."-".$teams[$hid]['l'].", At Home: ".$teams[$hid]['hw']."-".$teams[$hid]['hl']."</td></tr>\n";

	 echo "        <tr><td class='gl' colspan=2 style='padding:6px 4px 4px 4px;'>&nbsp;<br />&nbsp;</td></tr>\n";

	 echo "       </table>\n";

	 echo "      </td>\n";

	 echo "     </tr>\n";

	 echo "    </table>\n";

	 echo "   </td>\n";

	 echo "  </tr>\n";

   	 echo " </table>\n";

      }

    }

   echo " </div>\n";



   if ($pcnt==0)

    {

      echo "</div>\n";

      return $text;

    }



   ##### Get Top Players #####

   echo "<div class='textbox' style='margin-left:10px;clear:right;'>\n";

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

   echo "  <tr class='title'><td style='padding:2px;'>Top Performers</td></tr>\n";

   echo "  <tr>\n";

   echo "   <td>\n";

   

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

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

   echo "   <tr class='title'><td style='padding:2px;'>Batters</td></tr>\n";

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

   $query="SELECT p.player_id,first_name,last_name,t.* FROM players as p,(SELECT player_id,team_id,sum(h) as h,sum(hr) as hr,sum(rbi) as rbi,sum(r) as r,sum(sb) as sb,(sum(h)/sum(ab)) as avg,(sum(h)+sum(bb)+sum(hp))/(sum(ab)+sum(bb)+sum(hp)+sum(sf)) as obp,(sum(h)+sum(d)+2*sum(t)+3*sum(hr))/sum(ab) as slg,if(SUM(pa)<(2*$pcnt),-99,0.47*(sum(h)-sum(d)-sum(t)-sum(hr)) + .78*sum(d) + 1.09*sum(t) + 1.4*sum(hr) + .33*(sum(bb)-sum(hp)) + .3*sum(sb) - .52*sum(cs) - .26*(sum(ab)-sum(h)-sum(gdp)) - .72*sum(gdp)) as lw FROM players_game_batting WHERE game_id IN ($gList) GROUP BY player_id ORDER BY lw DESC LIMIT 5) as t WHERE p.player_id=t.player_id ORDER BY last_name,first_name";

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

   echo "   <table class='sortable' width=440>\n";

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

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

   echo "<td class='hsc2'>AVG</td>";

   echo "<td class='hsc2'>R</td>";

   echo "<td class='hsc2'>H</td>";

   echo "<td class='hsc2'>HR</td>";

   echo "<td class='hsc2'>RBI</td>";

   echo "<td class='hsc2'>SB</td>";

   echo "<td class='hsc2'>OPS</td>";

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

   $rownum=0;

   while ($row=mysqli_fetch_array($result))

    {

      $cls=$rownum%2+1;

      $tid=$row['team_id'];

      echo "    <tr>";

      echo "<td class='s".$cls."_l'><a href='./player.php?player_id=".$row['player_id']."'>".$row['first_name']." ".$row['last_name']."</a>, <a href='".$lgpath."/teams/team_".$tid.".html'>".$teams[$tid]['abbr']."</a></td>";

      echo "<td class='s".$cls."'>".strstr(sprintf("%.3f",$row['avg']),".")."</td>";

      echo "<td class='s".$cls."'>".$row['r']."</td>";

      echo "<td class='s".$cls."'>".$row['h']."</td>";

      echo "<td class='s".$cls."'>".$row['hr']."</td>";

      echo "<td class='s".$cls."'>".$row['rbi']."</td>";

      echo "<td class='s".$cls."'>".$row['sb']."</td>";

      $ops=sprintf("%.3f",$row['obp']+$row['slg']);

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

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

      echo "</tr>\n";

      $rownum++;

    }

   echo "   </table>\n";

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

   echo "  </table>\n";

   echo " </div>\n";



   echo " </td></tr><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;'>Pitchers</td></tr>\n";

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

   $query="SELECT p.player_id,first_name,last_name,t.* FROM players as p,(SELECT player_id,team_id,((SUM(ip)*3+SUM(ipf))/3) as ip,sum(w) as w,sum(l) as l,sum(s) as sv,sum(k) as k,9*sum(er)/((SUM(ip)*3+SUM(ipf))/3) as era,(sum(bb)+sum(ha)+sum(hp))/((SUM(ip)*3+SUM(ipf))/3) as whip,sum(ha)/sum(ab) as oavg,(((sum(ha)+sum(bb)+sum(hp))*(0.89*(1.255*(sum(ha)-sum(hra))+4*sum(hra))+0.56*(sum(bb)+sum(hp)-sum(iw))))/(sum(bf)*((SUM(ip)*3+SUM(ipf))/3)))*9*0.75 as erc,if(SUM(ip)<($pcnt-1),-99,3*((SUM(ip)*3+SUM(ipf))/3)+4*sum(w)-4*sum(l)+5*sum(s)+sum(k)-2*sum(ha)-2*sum(bb)) as score FROM players_game_pitching_stats WHERE game_id IN ($gList) GROUP BY player_id ORDER BY score DESC LIMIT 5) as t WHERE p.player_id=t.player_id ORDER BY last_name,first_name";

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

   echo "   <table class='sortable' width=440>\n";

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

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

   echo "<td class='hsc2'>W</td>";

   echo "<td class='hsc2'>L</td>";

   echo "<td class='hsc2'>SV</td>";

   echo "<td class='hsc2'>IP</td>";

   echo "<td class='hsc2'>ERA</td>";

   echo "<td class='hsc2'>K</td>";

   echo "<td class='hsc2'>WHIP</td>";

   echo "<td class='hsc2'>OAVG</td>";

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

   $rownum=0;

   while ($row=mysqli_fetch_array($result))

    {

      $cls=$rownum%2+1;

      $tid=$row['team_id'];

      echo "    <tr>";

      echo "<td class='s".$cls."_l'><a href='./player.php?player_id=".$row['player_id']."'>".$row['first_name']." ".$row['last_name']."</a>, <a href='".$lgpath."/teams/team_".$tid.".html'>".$teams[$tid]['abbr']."</a></td>";

      echo "<td class='s".$cls."'>".$row['w']."</td>";

      echo "<td class='s".$cls."'>".$row['l']."</td>";

      echo "<td class='s".$cls."'>".$row['sv']."</td>";

      echo "<td class='s".$cls."'>".sprintf("%.1f",$row['ip'])."</td>";

      echo "<td class='s".$cls."'>".sprintf("%.2f",$row['era'])."</td>";

      echo "<td class='s".$cls."'>".$row['k']."</td>";

      echo "<td class='s".$cls."'>".sprintf("%.2f",$row['whip'])."</td>";

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

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

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

      echo "</tr>\n";

      $rownum++;

    }

   echo "   </table>\n";

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

   echo "  </table>\n";

   echo " </div>\n";



   echo "   </td>\n";

   echo "  </tr>\n";						 

   echo " </table>\n";



   echo "</div>\n";

   echo "</div>\n";

   

   ##### Get PA/G for DH determination #####

   if ($showDH==1)

    {

      $query="SELECT player_id,team_id,SUM(pa) as pa,SUM(g) as g FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND team_id IN ($team_id1,$team_id2) AND year=$lgyear GROUP BY player_id,team_id HAVING SUM(g)>0;";

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

      while ($row=mysqli_fetch_array($result))

       {

         $pid=$row['player_id'];

	 $tid=$row['team_id'];

	 $players[$tid][$pid]['paPerG']=$row['pa']/$row['g'];

       }

    }



   ##### Get Fielding Stats #####

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

    {

      if ($i==1) {$tid=$team_id1;} else {$tid=$team_id2;}

      $query="SELECT player_id,team_id,position,(ip*3+ipf)/3 as ip,g FROM players_career_fielding_stats WHERE team_id=$tid AND year=$lgyear ORDER BY position,ip DESC;";

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

      if (mysqli_num_rows($result))

       {

         ## Get position

         while ($row=mysqli_fetch_array($result))

          {

            $pid=$row['player_id'];

            $tid=$row['team_id'];

	    $pos=$row['position'];

	    $g=$row['g'];

	    $ip=$row['ip'];

   	

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

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

   	    if (($maxFIP<$ip)&&($pos!=10))

	     {

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

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

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

	     }

  	     elseif (($maxFG<$g)&&($pos==10))

	     {

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

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

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

	     }



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

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

   	    $players[$tid][$pid]['totIP']=$players[$tid][$pid]['totIP']+$ip;

   	    $players[$tid][$pid]['totG']=$players[$tid][$pid]['totG']+$g;

	  }

	 ## Store positions by team

	 foreach ($players[$tid] as $pid => $val)

	  {

 	    if ($showDH)

	     {

               if(isset($players[$tid][$pid]['paPerG'])) {$paPerG=$players[$tid][$pid]['paPerG'];} else {$paPerG=0;}

	       if(isset($players[$tid][$pid]['totIP'])) {$ipPerG=$players[$tid][$pid]['totIP']/$players[$tid][$pid]['totG'];} else {$ipPerG=0;}

	       if (($ipPerG<4)&&($paPerG>2)) {$pos=10;}

 	        else {$pos=$players[$tid][$pid]['pos'];}

	     }

	     else

	     {

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

	     }

	    $teams[$tid][$pos]=$teams[$tid][$pos].",".$pid;

	  }

       }

    }



   ##### Get Current Roster Status #####

   $query="SELECT p.player_id,p.team_id,p.organization_id,is_active,injury_is_injured,is_on_dl FROM players as p,players_roster_status as prs WHERE p.player_id=prs.player_id AND p.organization_id IN ($team_id1,$team_id2);";

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

   while ($row=mysqli_fetch_array($result))

    {

      $pid=$row['player_id'];

      $tid=$row['team_id'];

      $pstatus[$pid]['organization']=$row['organization_id'];

      if (($row['is_on_dl']==1)&&($row['injury_is_injured']==1))  ## On DL and still injured

       {

         $pstatus[$pid]['status']="<sup><span style='color:#990000'>DL</span></sup>";

       }

       elseif ($row['is_on_dl']==1)  ## On DL but not injured anymore

       {

         $pstatus[$pid]['status']="<sup><span>DL!</span></sup>";

       }

       elseif ($row['injury_is_injured']==1)  ## Injured but not on DL

       {

         $pstatus[$pid]['status']="<sup><span style='font-weight:bold;color:#990000'>!</span></sup>";

       }

       elseif (($tid!=$team_id1)&&($tid!=$team_id2))  ## In minors

       {

         $pstatus[$pid]['status']="<sup>".$teams[$tid]['level']."</sup>";

       }

       else 

       {

         $pstatus[$pid]['status']="act";

       }

    }



   ##### Display Batting Stats #####

   if ($showDH==1) {$posArray=array("2"=>"Catchers","3"=>"First Basemen","4"=>"Second Basemen","5"=>"Third Basemen","6"=>"Shortstops","7"=>"Left Fielders","8"=>"Center Fielders","9"=>"Right Fielders","10"=>"Designated Hitters");}

    else {$posArray=array("2"=>"Catchers","3"=>"First Basemen","4"=>"Second Basemen","5"=>"Third Basemen","6"=>"Shortstops","7"=>"Left Fielders","8"=>"Center Fielders","9"=>"Right Fielders");}

   foreach ($posArray as $pos => $posName)

    {

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

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

      echo "   <tr class='title2'><td colspan=2 style='padding:2px;'>Batting Stats for $posName</td></tr>\n";

      echo "   <tr>\n";

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

       {

         if ($i==1) {$tid=$team_id1;}

          else

          {

            $tid=$team_id2;

	    echo "      </tr>\n";

	    echo "     </table>\n";

	    echo "    </td>\n";

 	  }

         echo "    <td valign='top'>\n";

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

	 echo "      <table cellpadding=0 cellspacing=0 border=0><tr><td style='padding:2px;color:".$teams[$tid]['text_color_id'].";background-color:".$teams[$tid]['background_color_id'].";'>".$teams[$tid]['name']."</td></tr>\n";

   	 echo "       <tr>\n";

	 echo "        <td>\n";

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

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

   	 echo "           <td class='hsc2_l'>Player</td><td class='hsc2'>G</td><td class='hsc2'>AB</td><td class='hsc2'>R</td><td class='hsc2'>H</td><td class='hsc2'>HR</td><td class='hsc2'>RBI</td><td class='hsc2'>BB</td><td class='hsc2'>SB</td><td class='hsc2'>AVG</td><td class='hsc2'>OPS</td>\n";

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



	 $Tg=0;

   	 $Tab=0;

	 $Th=0;

   	 $Td=0;

	 $Tt=0;

   	 $Thr=0;

	 $Trbi=0;

   	 $Tr=0;

	 $Tsb=0;

   	 $Tbb=0;

	 $Thp=0;

   	 $Tsf=0;

	 $rownum=0;

	 $pList=trim($teams[$tid][$pos],",");

	 if ($pList=="") {$pList=-999;}

	 $query="SELECT p.player_id,p.first_name,p.last_name,pgb.team_id,SUM(g) as g,SUM(ab) as ab,SUM(h) as h,SUM(hr) as hr,SUM(rbi) as rbi,SUM(r) as r,SUM(sb) as sb,SUM(bb) as bb,SUM(hp) as hp,SUM(sf) as sf,SUM(d) as d,SUM(t) as t FROM players_game_batting as pgb,players as p WHERE p.player_id=pgb.player_id AND pgb.team_id=$tid AND game_id IN ($gList) AND p.player_id IN ($pList) GROUP BY player_id ORDER BY ab DESC,last_name,first_name;";

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

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

	 while ($row=mysqli_fetch_array($result))

	  {

 	    $pid=$row['player_id'];

            $g=$row['g'];

	    $ab=$row['ab'];

   	    $h=$row['h'];

	    $d=$row['d'];

   	    $t=$row['t'];

	    $hr=$row['hr'];

   	    $rbi=$row['rbi'];

	    $r=$row['r'];

   	    $sb=$row['sb'];

	    $bb=$row['bb'];

   	    $hbp=$row['hbp'];

	    $sf=$row['sf'];

	    $Tg+=$g;

   	    $Tab+=$ab;

	    $Th+=$h;

   	    $Td+=$d;

	    $Tt+=$t;

   	    $Thr+=$hr;

	    $Trbi+=$rbi;

   	    $Tr+=$r;

	    $Tsb+=$sb;

	    $Tbb+=$bb;

   	    $Thbp+=$hbp;

	    $Tsf+=$sf;



	    $rcls=$rownum%2+1;

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

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

	    if ((!isset($pstatus[$pid]['status']))||($pstatus[$pid]['organization']!=$row['team_id']))

	     {

	       echo "<sup>@</sup>";

	     }

	     elseif ((isset($pstatus[$pid]['status']))&&($pstatus[$pid]['status']!='act'))

	     {

	       echo $pstatus[$pid]['status'];

	     }

	    echo "</td>";

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

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

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

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

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

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

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

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

   	    if ($ab==0)

	     {

	       $avg=round(0,3);

	       $slg=round(0,3);

  	     }

	     else

	     {

	       $avg=$h/$ab;

	       $slg=($h+$d+2*$t+3*$hr)/$ab;

   	     }

	    if (($ab+$bb+$hbp+$sf)==0) {$obp=0;}

   	     else {$obp=($h+$bb+$hbp)/($ab+$bb+$hbp+$sf);}

            $ops=$obp+$slg;

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

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

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

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

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

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

   	    echo "</tr>\n";

	    $rownum++;

   	  }

   	 if ($rownum==0) {echo "         <tr><td colspan=11 align=center>-- No stats recorded --</td></tr>\n";}

         ## Display Team Totals

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

	 echo "<td class='hsc2_l'>Totals</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'>".$Thr."</td>";

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

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

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

	 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 ($ops<1) {$ops=strstr(sprintf("%.3f",$ops),".");}

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

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

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

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

	 echo "         </table>\n";

	 echo "        </div>\n";

	 echo "       </td>\n";

       }

      echo "      </tr>\n";

      echo "     </table>\n";

      echo "    </td>\n";

      echo "   </tr>\n";

      echo "  </table>\n";

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

    }



   ##### Display Pitching Stats #####

   $posArray=array("11"=>"Starting Pitchers","12"=>"Middle Relievers","13"=>"Closers");

   foreach ($posArray as $pos => $posName)

    {

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

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

      echo "   <tr class='title2'><td colspan=2 style='padding:2px;'>Pitching Stats for $posName</td></tr>\n";

      echo "   <tr>\n";

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

       {

         if ($i==1) {$tid=$team_id1;}

          else

          {

            $tid=$team_id2;

	    echo "      </tr>\n";

	    echo "     </table>\n";

	    echo "    </td>\n";

 	  }

         echo "    <td valign='top'>\n";

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

	 echo "      <table cellpadding=0 cellspacing=0 border=0><tr><td style='padding:2px;color:".$teams[$tid]['text_color_id'].";background-color:".$teams[$tid]['background_color_id'].";'>".$teams[$tid]['name']."</td></tr>\n";

   	 echo "       <tr>\n";

	 echo "        <td>\n";

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

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

   	 echo "           <td class='hsc2_l'>Player</td><td class='hsc2'>G</td><td class='hsc2'>GS</td><td class='hsc2'>W</td><td class='hsc2'>L</td><td class='hsc2'>SV</td><td class='hsc2'>IP</td><td class='hsc2'>K</td><td class='hsc2'>ERA</td><td class='hsc2'>WHIP</td><td class='hsc2'>OAVG</td>\n";

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



	 $Tg=0;

   	 $Tgs=0;

	 $Tip=0;

   	 $Tw=0;

	 $Tl=0;

   	 $Tsv=0;

	 $Tr=0;

   	 $Ter=0;

	 $Tk=0;

   	 $Tha=0;

	 $Tbba=0;

   	 $Thra=0;

	 $Tcg=0;

   	 $Tsho=0;

	 $Tab=0;

   	 $Tsf=0;

   	 $rownum=0;

     $query="SELECT p.player_id,p.first_name,p.last_name,pgp.team_id,SUM(g) as g,SUM(gs) as gs,SUM(w) as w,SUM(l) as l,SUM(s) as sv,((SUM(IP)*3+SUM(ipf))/3) as ip,SUM(k) as k,SUM(er) as er,SUM(ha) as ha,SUM(bb) as bba,SUM(ab) as ab FROM players_game_pitching_stats as pgp,players as p WHERE p.player_id=pgp.player_id AND pgp.team_id=$tid and p.role=$pos AND game_id IN ($gList) GROUP BY player_id ORDER BY ip DESC,last_name,first_name;";

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

	 while ($row=mysqli_fetch_array($result))

	  {

 	    $pid=$row['player_id'];

            $g=$row['g'];

	    $gs=$row['gs'];

   	    $ip=$row['ip'];

	    $w=$row['w'];

   	    $l=$row['l'];

	    $sv=$row['sv'];

	    $er=$row['er'];

   	    $k=$row['k'];

	    $ha=$row['ha'];

   	    $bba=$row['bba'];

   	    $ab=$row['ab'];

   	    $Tg+=$g;

	    $Tgs+=$gs;

   	    $Tip+=$ip;

	    $Tw+=$w;

   	    $Tl+=$l;

	    $Tsv+=$sv;

	    $Ter+=$er;

   	    $Tk+=$k;

	    $Tha+=$ha;

   	    $Tbba+=$bba;

   	    $Tab+=$ab;



	    $rcls=$rownum%2+1;

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

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

	    if ((!isset($pstatus[$pid]['status']))||($pstatus[$pid]['organization']!=$row['team_id']))

	     {

	       echo "<sup>@</sup>";

	     }

	     elseif ((isset($pstatus[$pid]['status']))&&($pstatus[$pid]['status']!='act'))

	     {

	       echo $pstatus[$pid]['status'];

	     }

	    echo "</td>";

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

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

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

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

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

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

	     else 

  	     {

              $era=$er*9/$ip;

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

             }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	    echo "</tr>\n";

	    $rownum++;

   	  }

   	 if ($rownum==0) {echo "         <tr><td colspan=11 align=center>-- No stats recorded --</td></tr>\n";}

         ## Display Team Totals

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

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

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

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

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

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

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

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

          else 

          {

            $era=$Ter*9/$Tip;

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

          }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   	 echo "         </table>\n";

   	 echo "        </div>\n";

	 echo "       </td>\n";

       }

      echo "      </tr>\n";

      echo "     </table>\n";

      echo "    </td>\n";

      echo "   </tr>\n";

      echo "  </table>\n";

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

    }



   echo "<div class='textbox' style='border:0;width:935px'>DL indicates player on DL<br/>DL! indicates player is on DL but no longer injured<br/>! indicates player is injured but not on DL<br/>AAA, AA, A, etc. indicates player now assigned to minors<br/>@ indicates player no longer in organization</div>\n";

   

  mysqli_close($db);



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

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

  page_foot($_SESSION['lgpath']);



?>

