<?php

  include("html_functions.php");



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

  $lgid=$_SESSION['lgid'];

  $lgpath=$_SESSION['lgpath'];

  $lgdate=$_SESSION['lgdate'];

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

  $lgyear=$_SESSION['lgyear'];

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

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



  # Title Bar

  $title="Sim Preview";



  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 Season Completion Percentage #####

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

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

  if ($result)

  {

	  while ($row=mysqli_fetch_array($result))

  	  {

		  switch ($row['played'])

       		  {

		  case 0: $unPlayGm=$row['g']; break;

     		  case 1: $playGm=$row['g']; break;

		  }

  	  }

	  $seaCompPct=$playGm/($unPlayGm+$playGm);

  }

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



  if ($seaCompPct>=1)

  {

	  echo "<div class='textbox' style='border:0px;'>The season is over.</div>\n";

	  mysqli_close($db);

	

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

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

	  page_foot($_SESSION['lgpath']);

	  exit;

  }



  echo "<div style='float:left;margin:0px;padding:0px;width:935px;'>\n";    # Container Div



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

  $tidList="";

  $query="SELECT t.team_id,abbr,name,nickname,level,logo_file_name,w,l,pos,sub_league_id,text_color_id,background_color_id FROM teams as t,team_record as tr WHERE t.team_id=tr.team_id AND t.league_id=$lgid AND allstar_team=0;";

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

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

  while ($row=mysqli_fetch_array($result))			    

  {

    	  $tid=$row['team_id'];

	  $slid=$row['sub_league_id'];

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

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

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

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

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

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

    	  $teams[$tid]['logo']=$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'];

	  $teams[$tid]['rw']=0;

	  $teams[$tid]['rl']=0;

	  $teams[$tid]['hw']=0;

	  $teams[$tid]['hl']=0;



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



	  $tidList.=",$tid";

  }

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



  ##### Get Sub League Info #####

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

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

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

    	  $subleagues[$slid]['teams']=trim($subleagues[$slid]['teams'],",");

  }

  ksort($subleagues);



  ##### Get games played #####

  $query="SELECT AVG(g) as avgG,SUM(g) as totG,MIN(g) as minG,MAX(g) as maxG FROM team_record as tr,teams as t WHERE t.team_id=tr.team_id AND allstar_team=0 AND league_id=$lgid;";

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

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

  $row=mysqli_fetch_array($result);

  if ($row['avgG']<5) {$useLastYr=1;}

  else {$useLastYr=0;}

       

  ##### Get Team Alignment, Record #####

  $query="SELECT t.team_id,sub_league_id,division_id,w,l,pos,pct,gb FROM team_relations as t,";

  if ($useLastYr==1) {$query.="team_history_record";} else {$query.="team_record";}

  $query.=" as tr WHERE t.team_id=tr.team_id AND t.league_id=$lgid";

  if ($useLastYr==1) {$query.=" AND year=".($lgyear-1);}

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

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

  if ($result)

  {

    	  while ($row=mysqli_fetch_array($result))

	  {

	 	  $tid=$row['team_id'];

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

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

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

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

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

	 	  $teams[$tid]['ratpct']=$row['pct'];

		  $teams[$tid]['ratgb']=$row['gb'];

	 	  $teams[$tid]['topSer']=0;

	  }

  }



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

  $query="SELECT game_id,home_team,away_team,games.date,time,game_type FROM games WHERE league_id=$lgid AND played=0 AND DATEDIFF('$lgdate',games.date)<=0 AND DATEDIFF('$lgdate',games.date)>-".($simLen-1)." ORDER BY date,time;";

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

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

  if (mysqli_num_rows($result))

  {

	  while ($row=mysqli_fetch_array($result))

   	  {

		  $gid=$row['game_id'];

	 	  $hid=$row['home_team'];

		  $aid=$row['away_team'];

	 	  $gtype=$row['game_type'];

	 

		  if (!isset($teams[$hid]['nextOpp']))

		  {

	      		  $teams[$hid]['nextOpp']=$aid;

			  $teams[$hid]['nextOppLoc']=0;

		  }

		  if (!isset($teams[$aid]['nextOpp']))

		  {

			  $teams[$aid]['nextOpp']=$hid;

	      		  $teams[$aid]['nextOppLoc']=1;

		  }



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

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

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

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

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



		  $serID=min($hid,$aid).":".max($hid,$aid);

	 

		  ## All-Star Game

		  if ($game_type==4) 

		  {

			  $series[$serID]['firstGame']=$gid;

	      		  $series[$serID]['gmCnt']=1;

			  $serRats[$serID]=-100;

	      		  continue;

		  }



		  ## Regular Game

		  if (!isset($series[$serID]['firstGame']))

		  {

	      		  $series[$serID]['firstGame']=$gid;

			  $series[$serID]['gmCnt']=1;

			  $matchRat=0;

	      		  ## Determine if in same league, division

			  if ($teams[$aid]['slid']==$teams[$hid]['slid'])   ## Same league

	     		  {

				  if ($teams[$aid]['divid']==$teams[$hid]['divid'])  ## Same division

		  		  {

					  $divComp=1;

		  		  }

				  else {$divComp=2;}

	     		  }

			  else {$divComp=3;}

		     	  ## Adjust for difference in games behind between teams

			  switch ($divComp)

			  {

	   		  case 1:   ## Same division

				  $matchRat+=abs($teams[$aid]['ratgb']-$teams[$hid]['ratgb']);

		 		  break;

			  case 2:   ## Same league

		 		  $matchRat+=5*abs($teams[$aid]['ratgb']-$teams[$hid]['ratgb']);

				  $matchRat+=5;

		 		  break;

			  case 3:   ## Interleague

		 		  $matchRat+=10*abs($teams[$aid]['ratgb']-$teams[$hid]['ratgb']);

				  $matchRat+=20;

		 		  break;

			  }

	      		  ## Adjust for games behind division leader

			  $matchRat+=2*($teams[$aid]['ratgb']+$teams[$hid]['ratgb']);

	      		  ## Adjust for difference in wins

			  $matchRat+=abs($teams[$aid]['ratw']-$teams[$hid]['ratw']);

	      		  ## Adjust for difference in losses

			  $matchRat+=abs($teams[$aid]['ratl']-$teams[$hid]['ratl']);

	      		  ## Adjust for absolute win percentage

			  $matchRat-=max($teams[$aid]['ratpct'],$teams[$hid]['ratpct']);

	      		  ## Assign rating

			  $serRats[$serID]=$matchRat;

		  }

		  else   ## Already have this series, update game count

		  {

			  $series[$serID]['gmCnt']=$series[$serID]['gmCnt']+1;

		  }

	  }

    	  ## Adjust each series score for number of games

	  foreach ($series as $serID => $val)

   	  {

		  $serRats[$serID]=$serRats[$serID]-pow(2,$series[$serID]['gmCnt']-1);

	  }

    	  ## Determine top 5 series to display

	  asort($serRats);

    	  $gidList="";

	  $gmCnt=0;

    	  foreach ($serRats as $serID => $val)

	  {

      		  $gmCnt++;

		  if (isset($dispGames)&&(count($dispGames)>=5)) {continue;}

	  	  $e=explode(":",$serID);

		  $tid1=$e[0];

	 	  $tid2=$e[1];

		  if (($teams[$tid1]['topSer']==2)||($teams[$tid2]['topSer']==2)) {continue;}   ## No more than 2 series per team

	 	  $teams[$tid1]['topSer']=$teams[$tid1]['topSer']+1;

		  $teams[$tid2]['topSer']=$teams[$tid2]['topSer']+1;

	 	  $gid=$series[$serID]['firstGame'];

		  $gidList.=",$gid";

	 	  $dispGames[$gid]=1;

	  }

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

       

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

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

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

			  $teams[$aid]['wVs'][$hid]=$teams[$aid]['wVs'][$hid]+1;

	   	  }

		  else

	   	  {

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

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

			  $teams[$hid]['wVs'][$aid]=$teams[$hid]['wVs'][$aid]+1;

	   	  }

	  }

    

	  ## Display Upcoming Series

	  echo " <div class='boxscores' style='width:440px;'><table cellpadding=2 cellspacing=0 border=0 style='border:0;margin:0;'><tr class='title'><td width='440px'>Noteworthy Matchups</td></tr></table>\n";

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

	  {

	 	  if (!isset($dispGames[$gid])) {continue;}

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

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

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

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

	 

		  $serID=min($hid,$aid).":".max($hid,$aid);

		  $nGms=$series[$serID]['gmCnt'];



		  unset($date);

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

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

	 	  echo " <tr>\n";

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

	 	  if ($_GET['showRats']==1) {echo $serRats[$serID]."::";}

		  if ($games[$gid]['gtype']==4)

		  {

			  echo "All-Star Game";

			  $query="SELECT team_id,abbr,nickname,logo_file_name FROM teams WHERE league_id=$lgid AND allstar_team=1;";

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

			  while ($asRow=mysqli_fetch_array($result))

			  {

				  $tid=$asRow['team_id'];

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

				  $teams[$tid]['logo']=$asRow['logo_file_name'];

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

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

			  }

		  }

		  else {echo "   $nGms game";}

	 	  if ($nGms>1) {echo "s starting with:";} else {echo " on:";}

		  echo "  </td>\n";

		  echo " </tr>\n";

	 	  echo " <tr>\n";

		  echo "  <td>\n";

	 	  echo "    <table cellpadding=0 cellspacing=0 style='border:1px black solid;width:400px;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:356px;margin:0px;border:0px'>\n";



		  echo "        <tr><td class='hl' colspan=2>".$date->format("M j, Y")." at ".$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>";

		  if ($games[$gid]['gtype']==4) {echo "&nbsp;";}

		  else {echo $teams[$aid]['w']."-".$teams[$aid]['l']." (".ordinal_suffix($teams[$aid]['pos'])."), 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>";

		  if ($games[$gid]['gtype']==4) {echo "&nbsp;";}

		  else {echo $teams[$hid]['w']."-".$teams[$hid]['l']." (".ordinal_suffix($teams[$hid]['pos'])."), At Home: ".$teams[$hid]['hw']."-".$teams[$hid]['hl']."</td></tr>\n";}

       		  echo "        <tr><td class='gl' colspan=2 style='padding:6px 4px 4px 4px;'>";

		  if ($games[$gid]['gtype']==4) {echo "&nbsp;";}

		  else {echo "<a href='./matchups.php?team_id1=$hid&team_id2=$aid'>Season Series</a>:<br />$aname ".max(0,$teams[$aid]['wVs'][$hid])." vs. ".max(0,$teams[$hid]['wVs'][$aid])." $hname";}

		  echo "</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";



  }

  else

  {

	  ##No games remaining

	  echo " <div class='boxscores'><table cellpadding=2 cellspacing=0 border=0 style='border:0;margin:0;'><tr class='title'><td width='420px'>Noteworthy Matchups</td></tr><tr><td>No games scheduled for the next $simLen days</td></tr></table>\n";

	  echo " </div>\n";

  }



  ##### Things To Watch For #####

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

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

  echo "  <tr class='title'><td style='padding:2px;'>Things To Watch For</td></tr>\n";

  echo "  <tr>\n";

  echo "   <td>\n";



  ##### Team Streaks #####

  $query="SELECT t.team_id,w,l,pos,gb,streak,ABS(streak) as abStr FROM teams as t,team_record as tr WHERE t.team_id=tr.team_id AND t.league_id=$lgid AND (streak>3 OR streak<-3) ORDER BY abStr DESC";

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

  if ($result)

  {

	  $tmStrk=1;

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

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

    	  echo "      <tr class='title'><td>Team Win/Loss Streaks</td></tr>\n";

	  $rownum=0;

    	  while ($row=mysqli_fetch_array($result))

	  {

	 	  $cls=$rownum%2+1;

		  $pid=$row['player_id'];

	 	  $tid=$row['team_id'];

		  $stk=$row['streak'];

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

	 

		  if (isset($teams[$tid]['nextOpp']))

		  {

	      		  $oppID=$teams[$tid]['nextOpp'];

			  echo "The <a href='$lgpath/teams/team_$tid.html'>".$teams[$tid]['nickname']."</a>";

	      		  if ($teams[$tid]['nextOppLoc']==1)

			  {

		   		  echo " take their ".abs($stk)." game ";

				  if ($stk>0) {echo "winning";} else {echo "losing";}

		   		  echo " streak to ";

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

	     		  }

			  else

	     		  {

				  echo " host ";

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

				  echo " while on a ".abs($stk)." game ";

		   		  if ($stk>0) {echo "winning";} else {echo "losing";}

				  echo " streak";

	     		  }

		  }

		  else

		  {

	      		  echo "The <a href='$lgpath/teams/team_$tid.html'>".$teams[$tid]['name']."</a> have ";

			  if ($stk>0) {echo "won ";} else {echo "lost ";}

	      		  echo abs($stk)." in a row";

		  }

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

		  $rownum++;

   	  }

	  echo "     </table>\n";

    	  echo "    </div>\n";

  }



  ##### Player Streaks #####

  # streak_id    meaning

  #         0    hits

  #         1    runs scored

  #         2    home runs

  #         3    rbi

  #         4    saves

  #         5    wins

  #         6    losses

  #         7    lossless

  $query="SELECT p.player_id,first_name,last_name,if(position=1,role,position) as position,team_id,streak_id,value,started,x.weight FROM players as p,(SELECT player_id,streak_id,value,started,if(streak_id=0,2.25,if(streak_id=2,13,if(streak_id=4,1.5,if(streak_id=5,7,if(streak_id=6,5,if(streak_id=7,2.25,4))))))*value as weight FROM players_streak WHERE league_id=$lgid AND has_ended=0 AND ((streak_id=0 AND value>10) OR (streak_id=1 AND value>5) OR (streak_id=2 AND value>2) OR (streak_id=3 AND value>5) OR (streak_id=4 AND value>10) OR (streak_id=5 AND value>3) OR (streak_id=6 AND value>3) OR (streak_id=7 AND value>5)) ORDER BY weight DESC,value DESC,streak_id) as x WHERE p.player_id=x.player_id AND p.league_id=$lgid AND (injury_is_injured=0 OR injury_dtd_injury=1) ORDER BY weight DESC,value DESC LIMIT 10;";

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

  if ($result)

  {

    	  if ($tmStrk==1) {echo "   </td></tr><tr><td>\n";}

	  else {$tmStrk=1;}

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

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

    	  echo "      <tr class='title'><td>Player Streaks</td></tr>\n";

	  $rownum=0;

    	  while ($row=mysqli_fetch_array($result))

	  {

	 	  $cls=$rownum%2+1;

		  $pid=$row['player_id'];

	 	  $tid=$row['team_id'];

		  $val=$row['value'];

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

		  echo get_pos($row['position'],1);

	 	  echo " <a href='./playerStats.php?scope=Season&player_id=".$row['player_id']."'>".$row['first_name']." ".$row['last_name']."</a> (<a href='".$lgpath."/teams/team_".$tid.".html'>".$teams[$tid]['abbr']."</a>)";

		  switch ($row['streak_id'])

		  {

		  case 0:

	    		  echo " has hit safely in $val consecutive games.";

			  break;

      		  case 1:

			  echo " has scored a run in each of his last $val games.";

	    		  break;

		  case 2:

	    		  echo " has hit a home run in $val consecutive games.";

			  break;

      		  case 3:

			  echo " record an RBI in his last $val games.";

	    		  break;

		  case 4:

	    		  echo " hasn't blown a save in $val chances.";

			  break;

      		  case 5:

			  echo " has won $val consecutive games.";

	    		  break;

		  case 6:

	    		  echo " is on a $val game losing streak.";

			  break;

      		  case 7:

			  echo " hasn't lost in $val starts.";

	    		  break;

		  }

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

		  $rownum++;

   	  }

	  echo "     </table>\n";

    	  echo "    </div>\n";

  }

  



  if (($seaCompPct>.33)&&($seaCompPct<1.0))

  {

    	  ##### Get Batting Triple Crown Contenders #####

	  foreach ($subleagues as $slid => $val)

   	  {

		  $teamList=$subleagues[$slid]['teams'];

	 	  $pidList="";

		  $leaderList="";

	   

		  ## Get Top 20 In Average

		  $query="SELECT player_id,pa,avg FROM (SELECT player_id,team_id,SUM(pa) as pa,SUM(h)/SUM(ab) as avg FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND year=$lgyear AND team_id IN ($teamList) GROUP BY player_id,year) as t1,(SELECT team_id,g FROM team_record WHERE team_id IN ($teamList)) as t2 WHERE t1.team_id=t2.team_id AND t1.pa>=3.1*t2.g ORDER BY avg DESC LIMIT 20;";

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

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

	 	  if ($result)

		  {

	      		  $rnk=0;

			  $lastAvg=-1;

	      		  while ($row=mysqli_fetch_array($result))

			  {

		   		  $pid=$row['player_id'];

				  $pa=$row['pa'];

		   		  $avg=$row['avg'];

				  if ($avg!=$lastAvg) {$rnk++;}

		   		  $lastAvg=$avg;

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

		   		  $avg=strstr($avg,".");

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

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

				  $players[$pid]['avgRnk']=$rnk;

	 			  if ($rnk==1)

				  {

	 				  $players['Leader']['avg']['pid']=$pid;

					  $leaderList.=",$pid";

	 				  $players['Leader']['avg']['val']=$avg;

				  }

	 			  $pidList.=",$pid";

			  }

		  }

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

		   

		  ## Get Top 20 in HR

		  $query="SELECT player_id,SUM(hr) as hr FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND year=$lgyear AND team_id IN ($teamList) GROUP BY player_id,year ORDER BY hr DESC LIMIT 20";

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

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

	 	  $pidList="";

		  if ($result)

		  {

			  $rnk=0;

	      		  $lastHr=-1;

			  while ($row=mysqli_fetch_array($result))

	     		  {

				  $pid=$row['player_id'];

		   		  $hr=$row['hr'];

				  if ($hr!=$lastHr) {$rnk++;}

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

				  if ($rnk==1)

	 			  {

					  $players['Leader']['hr']['pid']=$pid;

	 				  $players['Leader']['hr']['val']=$hr;

					  $leaderList.=",$pid";

	 			  }

				  if (isset($players[$pid]['avgRnk'])) 

		  		  {

					  $players[$pid]['hrRnk']=$rnk;

					  $pidList.=",$pid";

				  }

		   		  $lastHr=$hr;

			  }

		  }

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

		   

		  ## Get Top 20 in RBI

		  $query="SELECT p.player_id,first_name,last_name,p.organization_id,rbi FROM players as p,(SELECT player_id,team_id,SUM(rbi) as rbi FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND year=$lgyear AND team_id IN ($teamList) GROUP BY player_id,year ORDER BY rbi DESC LIMIT 20) as x WHERE p.player_id=x.player_id ORDER BY rbi DESC";

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

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

		  $pidList="";

	 	  if ($result)

		  {

	      		  $rnk=0;

			  $lastRbi=-1;

	      		  while ($row=mysqli_fetch_array($result))

			  {

		   		  $pid=$row['player_id'];

				  $rbi=$row['rbi'];

		   		  if ($rbi!=$lastRbi) {$rnk++;}

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

	 			  if ($rnk==1)

				  {

	 				  $players['Leader']['rbi']['pid']=$pid;

					  $leaderList.=",$pid";

	 				  $players['Leader']['rbi']['val']=$rbi;

				  }

		   		  if (isset($players[$pid]['hrRnk'])) 

				  {

					  $players[$pid]['rbiRnk']=$rnk;

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

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

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

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

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

					  $pidList.=",$pid";

				  }

		   		  $lastRbi=$rbi;

			  }

		  }

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

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

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

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

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

		  while ($row=mysqli_fetch_array($result))

		  {

			  $pid=$row['player_id'];

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

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

		  }



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

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

		  unset($tcSort);

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

		  {

	      		  $tcSort[$pid]=$players[$pid]['avgRnk']+$players[$pid]['hrRnk']+$players[$pid]['rbiRnk'];

		  }

	 	  asort($tcSort);

	 

		  ## Display Triple Crown Contenders

		  if ($tmStrk==1) {echo "   </td></tr><tr><td>\n";}

		  else {$tmStrk=1;}



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

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

		  echo "      <tr class='title'><td title='Top 20 in AVG, HR, and RBI' style='padding:2px;'>".$subleagues[$slid]['name']." Batting Triple Crown Contenders</td></tr>\n";

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

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

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

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

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

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

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

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

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

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

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

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

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

		  $rownum=0;

		  $cls=$rownum%2+1;

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

		  echo "<td class='s".$cls."_l' sorttable_customkey=\"aaa\">Leader</td>";

		  echo "<td>-</td>";

		  echo "<td>-</td>";

		  $pid=$players['Leader']['avg']['pid'];

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

		  echo "<td title='".$players[$pid]['name']." (".$teams[$tid]['abbr'].")'>".$players['Leader']['avg']['val']."</td>";

		  echo "<td>-</td>";

		  $pid=$players['Leader']['hr']['pid'];

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

		  echo "<td title='".$players[$pid]['name']." (".$teams[$tid]['abbr'].")'>".$players['Leader']['hr']['val']."</td>";

		  echo "<td>-</td>";

		  $pid=$players['Leader']['rbi']['pid'];

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

		  echo "<td title='".$players[$pid]['name']." (".$teams[$tid]['abbr'].")'>".$players['Leader']['rbi']['val']."</td>";

		  echo "<td>-</td>";

		  echo "</tr>\n";

		  $rownum++;

		  foreach ($tcSort as $pid => $val)

		  {

			  if ($rownum>5) {continue;}

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

			  $cls=$rownum%2+1;

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

			  echo "<td class='s".$cls."_l' sorttable_customkey=\"".$players[$pid]['sortname']."\"><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a></td>";

	      		  echo "<td><a href='".$lgpath."/teams/team_".$tid.".html'>".$teams[$tid]['abbr']."</a></td>";

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

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

			  echo "<td>".ordinal_suffix($players[$pid]['avgRnk'])."</td>";

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

			  echo "<td>".ordinal_suffix($players[$pid]['hrRnk'])."</td>";

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

			  echo "<td>".ordinal_suffix($players[$pid]['rbiRnk'])."</td>";

	      		  echo "</tr>\n";

			  $rownum++;				

		  }

		  echo "       </table>\n";

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

		  echo "     </table>\n";

	 	  echo "    </div>\n";			 	

	  }

    

	  ##### Get Pitching Triple Crown Contenders #####

	  foreach ($subleagues as $slid => $val)

   	  {

		  $teamList=$subleagues[$slid]['teams'];

	 	  $pidList="";

		  $leaderList="";

	 

		  ## Get Top 20 In ERA

		  $query="SELECT player_id,ip,era FROM (SELECT player_id,team_id,SUM(ip)+SUM(ipf)/3 as ip,9*SUM(er)/(SUM(ip)+SUM(ipf)/3) as era FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND year=$lgyear AND team_id IN ($teamList) GROUP BY player_id,year) as t1,(SELECT team_id,g FROM team_record WHERE team_id IN ($teamList)) as t2 WHERE t1.team_id=t2.team_id AND t1.ip>=t2.g ORDER BY era LIMIT 20;";

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

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

	 	  if ($result)

		  {

	      		  $rnk=0;

			  $lastERA=-1;

	      		  while ($row=mysqli_fetch_array($result))

			  {

		   		  $pid=$row['player_id'];

				  $ip=$row['ip'];

		   		  $era=$row['era'];

				  if ($era!=$lastERA) {$rnk++;}

		   		  $lastERA=$era;

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

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

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

		   		  $players[$pid]['eraRnk']=$rnk;

				  if ($rnk==1)

	 			  {

					  $players['Leader']['era']['pid']=$pid;

	 				  $players['Leader']['era']['val']=$era;

					  $leaderList.=",$pid";

	 			  }

				  $pidList.=",$pid";

	     		  }

		  }

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

		 

		  ## Get Top 20 in Wins

	 	  $query="SELECT player_id,SUM(w) as w FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND year=$lgyear AND team_id IN ($teamList) GROUP BY player_id,year ORDER BY w DESC LIMIT 20";

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

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

		  $pidList="";

	 	  if ($result)

		  {

	      		  $rnk=0;

			  $lastW=-1;

	      		  while ($row=mysqli_fetch_array($result))

			  {

		   		  $pid=$row['player_id'];

				  $w=$row['w'];

		   		  if ($w!=$lastW) {$rnk++;}

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

	 			  if ($rnk==1)

				  {

	 				  $players['Leader']['w']['pid']=$pid;

					  $players['Leader']['w']['val']=$w;

	 				  $leaderList.=",$pid";

				  }

	 			  if (isset($players[$pid]['eraRnk'])) 

				  {

					  $players[$pid]['wRnk']=$rnk;

					  $pidList.=",$pid";

		  		  }

				  $lastW=$w;

	     		  }

		  }

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

		 

		  ## Get Top 20 in Strikeouts

		  $query="SELECT p.player_id,first_name,last_name,p.organization_id,k FROM players as p,(SELECT player_id,team_id,SUM(k) as k FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND year=$lgyear AND team_id IN ($teamList) GROUP BY player_id,year ORDER BY k DESC LIMIT 20) as x WHERE p.player_id=x.player_id ORDER BY k DESC";

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

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

	 	  $pidList="";

		  if ($result)

		  {

			  $rnk=0;

	      		  $lastK=-1;

			  while ($row=mysqli_fetch_array($result))

	     		  {

				  $pid=$row['player_id'];

		   		  $k=$row['k'];

				  if ($k!=$lastK) {$rnk++;}

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

				  if ($rnk==1)

	 			  {

					  $players['Leader']['k']['pid']=$pid;

	 				  $players['Leader']['k']['val']=$k;

					  $leaderList.=",$pid";

	 			  }

				  if (isset($players[$pid]['wRnk'])) 

		  		  {

					  $players[$pid]['kRnk']=$rnk;

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

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

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

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

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

					  $pidList.=",$pid";

		  		  }

				  $lastK=$k;

	     		  }

		  }

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

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

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

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

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

		  while ($row=mysqli_fetch_array($result))

		  {

			  $pid=$row['player_id'];

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

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

		  }

	    

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

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

	 	  unset($tcSort);

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

		  {

			  $tcSort[$pid]=$players[$pid]['eraRnk']+$players[$pid]['wRnk']+$players[$pid]['kRnk'];

		  }

		  asort($tcSort);



		  ## Display Triple Crown Contenders

		  if ($tmStrk==1) {echo "   </td></tr><tr><td>\n";}

		  else {$tmStrk=1;}



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

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

	 	  echo "      <tr class='title'><td title='Top 20 in ERA, W, and K' style='padding:2px;'>".$subleagues[$slid]['name']." Pitching Triple Crown Contenders</td></tr>\n";

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

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

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

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

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

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

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

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

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

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

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

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

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

	 	  $rownum=0;

		  $cls=$rownum%2+1;

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

		  echo "<td class='s".$cls."_l' sorttable_customkey=\"aaa\">Leader</td>";

		  echo "<td>-</td>";

		  echo "<td>-</td>";

		  $pid=$players['Leader']['era']['pid'];

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

		  echo "<td title='".$players[$pid]['name']." (".$teams[$tid]['abbr'].")'>".$players['Leader']['era']['val']."</td>";

		  echo "<td>-</td>";

		  $pid=$players['Leader']['w']['pid'];

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

		  echo "<td title='".$players[$pid]['name']." (".$teams[$tid]['abbr'].")'>".$players['Leader']['w']['val']."</td>";

		  echo "<td>-</td>";

		  $pid=$players['Leader']['k']['pid'];

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

		  echo "<td title='".$players[$pid]['name']." (".$teams[$tid]['abbr'].")'>".$players['Leader']['k']['val']."</td>";

		  echo "<td>-</td>";

		  echo "</tr>\n";

		  $rownum++;

		  foreach ($tcSort as $pid => $val)

		  {

			  if ($rownum>5) {continue;}

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

	      		  $cls=$rownum%2+1;

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

	      		  echo "<td class='s".$cls."_l' sorttable_customkey=\"".$players[$pid]['sortname']."\"><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a></td>";

			  echo "<td><a href='".$lgpath."/teams/team_".$tid.".html'>".$teams[$tid]['abbr']."</a></td>";

	      		  echo "<td>".sprintf("%.1f",$players[$pid]['ip'])."</td>";

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

	      		  echo "<td>".ordinal_suffix($players[$pid]['eraRnk'])."</td>";

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

	      		  echo "<td>".ordinal_suffix($players[$pid]['wRnk'])."</td>";

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

	      		  echo "<td>".ordinal_suffix($players[$pid]['kRnk'])."</td>";

			  echo "</tr>\n";

	      		  $rownum++;				

		  }

	 	  echo "       </table>\n";

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

	 	  echo "     </table>\n";

		  echo "    </div>\n";			 	

   	  }

    

	  ##### Get .400 Hitter Possibilities #####

	  $query="SELECT p.player_id,first_name,last_name,p.team_id,h,ab,pa,avg,gr,hNeed,expAB,reqAVG FROM players as p,(SELECT player_id,t1.team_id,g,gr,h,ab,pa,h/ab as avg,ab/g as abPerG,h/g as hPerG,.4*(ab+(gr*ab/g))-h as hNeed,gr*ab/g as expAB,(.4*(ab+(gr*ab/g))-h)/(gr*ab/g) reqAVG,1.2*h/ab FROM (SELECT player_id,team_id,SUM(h) as h,SUM(ab) as ab,SUM(pa) as pa,SUM(h)/SUM(ab) as avg FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND year=$lgyear GROUP BY player_id,team_id ORDER BY avg DESC,h DESC) as t1,(SELECT team_id,g,162-g as gr FROM team_record) as t2 WHERE t1.team_id=t2.team_id AND pa/g>=3.1) as t3 WHERE p.player_id=t3.player_id AND reqAVG<(1.2*avg) ORDER BY avg DESC,reqAVG LIMIT 10;";

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

	  if (mysqli_num_rows($result))

	  {

		  if ($tmStrk==1) {echo "   </td></tr><tr><td>\n";}

		  else {$tmStrk=1;}



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

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

		  echo "      <tr class='title'><td style='padding:2px;'>Batters With A Chance To Hit .400</td></tr>\n";

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

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

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

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

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

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

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

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

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

		  echo "<td class='hsc2' title=\"Expected AB's remaining if current playing time pace continues\">Rem AB</td>";

	 	  echo "<td class='hsc2' title=\"Hits required in expected AB's\">Req H</td>";

		  echo "<td class='hsc2' title=\"AVG required in expected AB's\">Req AVG</td>";

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

		  $rownum=0;

	 	  while ($row=mysqli_fetch_array($result))

		  {

	      		  $pid=$row['player_id'];

			  $tid=$row['team_id'];

	      		  $cls=$rownum%2+1;

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

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

			  echo "<td><a href='".$lgpath."/teams/team_".$tid.".html'>".$teams[$tid]['abbr']."</a></td>";

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

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

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

			  $avg=$row['avg'];

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

			  $avg=strstr($avg,".");

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

			  echo "<td>".floor($row['expAB'])."</td>";

	      		  echo "<td>".floor($row['hNeed'])."</td>";

			  $avg=$row['reqAVG'];

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

			  $avg=strstr($avg,".");

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

			  echo "</tr>\n";

	      		  $rownum++;

		  }

	 	  echo "       </table>\n";

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

	 	  echo "     </table>\n";

		  echo "    </div>\n";			 

   	  }

  }



  ##### Injuries #####

  $query="SELECT p.player_id,first_name,last_name,p.team_id,injury_is_injured,injury_dtd_injury,dtd_injury_effect,is_on_dl,injury_dl_left,injury_left FROM players as p,players_roster_status as prs WHERE p.player_id=prs.player_id AND prs.league_id=$lgid AND (is_on_dl=1 OR injury_is_injured=1) AND injury_career_ending=0 AND injury_dl_left<$simLen AND injury_left<$simLen ORDER BY team_id,last_name,first_name";

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

  if ($result)

  {

	  if ($tmStrk==1) {echo "   </td></tr><tr><td>\n";}

   	  else {$tmStrk=1;}

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

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

	  echo "      <tr class='title'><td style='padding:2px;'>On Disabled List/Recovering From Injury</td></tr>\n";

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

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

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

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

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

	  echo "<td class='hsc2'>Inj Status</td>";

    	  echo "<td class='hsc2' title='Days left on DL'>DL Left</td>";

	  echo "<td class='hsc2' title='Days left injured'>Inj Left</td>";

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

	  $rownum=0;

    	  while ($row=mysqli_fetch_array($result))

       {

         $cls=$rownum%2+1;

         $pid=$row['player_id'];

	 $tid=$row['team_id'];

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

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

	 echo "<td><a href='".$lgpath."/teams/team_".$tid.".html'>".$teams[$tid]['abbr']."</a></td>";

	 echo "<td>";

	 if ($row['injury_dtd_injury']==1) {echo "DTD (".(100-$row['dtd_injury_effect'])."%)";}

	 elseif ($row['injury_is_injured']==0) {echo "Now healthy";}

	 else {echo "Out";}

	 echo "</td>";

	 if ($row['is_on_dl']==1) {echo "<td sorttable_customkey=\"".$row['injury_dl_left']."\">".$row['injury_dl_left']."</td>";} else {echo "<td sorttable_customkey=\"-1\">Not on DL</td>";}

	 echo "<td>".$row['injury_left']."</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";  # Close container for top half





  ##### Hot/Cold Lists

  if ($seaCompPct==0)

  {

	  mysqli_close($db);

	

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

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

	  page_foot($_SESSION['lgpath']);

	  exit;

  }



  echo "<div style='float:left;margin-top:10px;padding:0px;border:1px solid black'>\n";

  echo "<div style='float:left;margin-top:0px;padding:0px;width:935px;'>\n";    # Container Div

  echo " <table cellpadding=2 cellspacing=0 border=0 style='border:0px;margin:0px;width:100%;'><tr class='title'><td>Hot/Cold Lists</td></tr></table>\n";

  $gQuery="SELECT game_id FROM games WHERE league_id=$lgid AND played=1 AND DATEDIFF('$lgdate',date)<21 AND game_type=0 ORDER BY games.date";



  ##### Hot Batters #####

  $query="SELECT p.player_id,first_name,last_name,organization_id,team_id,position,r,h,hr,rbi,sb,avg,obp,slg,pa,g FROM players as p,(SELECT player_id,sum(g) as g,SUM(pa) as pa,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(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,(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 as pgs,($gQuery) as g WHERE pgs.game_id=g.game_id GROUP BY player_id ORDER BY lw DESC LIMIT 5) as x WHERE p.player_id=x.player_id ORDER BY last_name,first_name";

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

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

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

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

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

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

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

  echo "<td class='hsc2'>Tm</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 "<td class='hsc2'>Last X</td>";

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

  $rownum=0;

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

  while ($row=mysqli_fetch_array($result))

  {

	  $cls=$rownum%2+1;

    	  $pid=$row['player_id'];

	  $tid=$row['team_id'];

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

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

	  if (isset($teams[$tid]['abbr'])) {echo "<td><a href='".$lgpath."/teams/team_".$tid.".html'>".$teams[$tid]['abbr']."</a></td>";}

	  else

	  {

		  $orgID=$row['organization_id'];

		  echo "<td><a href='".$lgpath."/teams/team_".$orgID.".html'>".$teams[$orgID]['abbr']."</a><sup>~</sup></td>";

		  $mlFlg=1;

	  }

	  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 "<td class='s".$cls."' title='games played; ".$row['pa']." PA'>".$row['g']." gms</td>";

	  echo "</tr>\n";

    	  $rownum++;

  }

  echo "       </table>\n";

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

  echo "     </table>\n";

  echo "    </div>\n";



  ##### Hot Pitchers #####

  $query="SELECT p.player_id,first_name,last_name,organization_id,team_id,role,w,l,sv,ip,era,k,whip,oavg,gs,g FROM players as p,(SELECT player_id,((SUM(ip)*3+SUM(ipf))/3) as ip,SUM(g) as g,SUM(gs) as gs,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,3*((SUM(ip)*3+SUM(ipf))/3)+4*sum(w)-4*sum(l)+6*sum(s)+sum(k)-2*sum(ha)-2*sum(bb) as score FROM players_game_pitching_stats as pgs,($gQuery) as g WHERE pgs.game_id=g.game_id GROUP BY player_id ORDER BY score DESC LIMIT 5) as x WHERE p.player_id=x.player_id ORDER BY last_name,first_name";

  echo "    <div class='tablebox' style='float:right;clear:none;'>\n";

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

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

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

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

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

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

  echo "<td class='hsc2'>Tm</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 "<td class='hsc2'>Last X</td>";

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

  $rownum=0;

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

  while ($row=mysqli_fetch_array($result))

  {

    	  $cls=$rownum%2+1;

	  $pid=$row['player_id'];

    	  $tid=$row['team_id'];

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

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

	  if (isset($teams[$tid]['abbr'])) {echo "<td><a href='".$lgpath."/teams/team_".$tid.".html'>".$teams[$tid]['abbr']."</a></td>";}

	  else

	  {

		  $orgID=$row['organization_id'];

		  echo "<td><a href='".$lgpath."/teams/team_".$orgID.".html'>".$teams[$orgID]['abbr']."</a><sup>~</sup></td>";

		  $mlFlg=1;

	  }

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

    	  if ($row['role']==11) {echo "<td class='s".$cls."' title='games started'>".$row['gs']." gs</td>";} else {echo "<td class='s".$cls."' title='appearances'>".$row['g']." app</td>";}

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

    	  $rownum++;

  }

  echo "       </table>\n";

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

  echo "     </table>\n";

  echo "    </div>\n";



  echo "</div>\n";

  echo "<div style='float:left;margin:0px;padding:0px;width:935px;'>\n";    # Container Div



  ##### Cold Batters #####

  $query="SELECT p.player_id,first_name,last_name,organization_id,team_id,position,r,h,hr,rbi,sb,avg,obp,slg,pa,g FROM players as p,(SELECT player_id,sum(g) as g,SUM(pa) as pa,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(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,(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 as pgs,($gQuery) as g WHERE pgs.game_id=g.game_id GROUP BY player_id ORDER BY lw LIMIT 5) as x WHERE p.player_id=x.player_id ORDER BY last_name,first_name";

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

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

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

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

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

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

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

  echo "<td class='hsc2'>Tm</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 "<td class='hsc2'>Last X</td>";

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

  $rownum=0;

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

  while ($row=mysqli_fetch_array($result))

  {

	  $cls=$rownum%2+1;

    	  $pid=$row['player_id'];

	  $tid=$row['team_id'];

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

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

	  if (isset($teams[$tid]['abbr'])) {echo "<td><a href='".$lgpath."/teams/team_".$tid.".html'>".$teams[$tid]['abbr']."</a></td>";}

	  else

	  {

		  $orgID=$row['organization_id'];

		  echo "<td><a href='".$lgpath."/teams/team_".$orgID.".html'>".$teams[$orgID]['abbr']."</a><sup>~</sup></td>";

		  $mlFlg=1;

	  }

	  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 "<td class='s".$cls."' title='games played; ".$row['pa']." PA'>".$row['g']." gms</td>";

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

    	  $rownum++;

  }

  echo "       </table>\n";

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

  echo "     </table>\n";

  echo "    </div>\n";



  ##### Cold Pitchers #####

  $query="SELECT p.player_id,first_name,last_name,organization_id,team_id,role,w,l,sv,ip,era,k,whip,oavg,gs,g FROM players as p,(SELECT player_id,((SUM(ip)*3+SUM(ipf))/3) as ip,SUM(g) as g,SUM(gs) as gs,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,3*((SUM(ip)*3+SUM(ipf))/3)+4*sum(w)-4*sum(l)+6*sum(s)-4*sum(bs)+sum(k)-2*sum(ha)-2*sum(bb) as score FROM players_game_pitching_stats as pgs,($gQuery) as g WHERE pgs.game_id=g.game_id GROUP BY player_id ORDER BY score LIMIT 5) as x WHERE p.player_id=x.player_id ORDER BY last_name,first_name";

  echo "    <div class='tablebox' style='float:right;clear:none;'>\n";

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

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

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

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

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

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

  echo "<td class='hsc2'>Tm</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 "<td class='hsc2'>Last X</td>";

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

  $rownum=0;

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

  while ($row=mysqli_fetch_array($result))

  {

    	  $cls=$rownum%2+1;

	  $pid=$row['player_id'];

    	  $tid=$row['team_id'];

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

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

	  if (isset($teams[$tid]['abbr'])) {echo "<td><a href='".$lgpath."/teams/team_".$tid.".html'>".$teams[$tid]['abbr']."</a></td>";}

	  else

	  {

		  $orgID=$row['organization_id'];

		  echo "<td><a href='".$lgpath."/teams/team_".$orgID.".html'>".$teams[$orgID]['abbr']."</a><sup>~</sup></td>";

		  $mlFlg=1;

	  }

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

    	  if ($row['role']==11) {echo "<td class='s".$cls."' title='games started'>".$row['gs']." gs</td>";} else {echo "<td class='s".$cls."' title='appearances'>".$row['g']." app</td>";}

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

    	  $rownum++;

  }

  echo "       </table>\n";

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

  echo "     </table>\n";

  echo "    </div>\n";



  echo "</div>\n";



  if ($mlFlg==1) {echo "<div style='margin:0px;padding:2px;width:100%;'>~ indicates no longer with team (demotion, trade, etc.)</div>\n";}



  echo "</div>\n";

   

  mysqli_close($db);



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

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

  page_foot($_SESSION['lgpath']);





?>

