<?php
header("Content-type: text/html");

include("html_functions.php");

##### Open connection to db #####
set_adminpath();

##### Get parameters #####
$topX=$_GET['topX'];
$stat=$_GET['stat'];
$sub_league_id=$_GET['sub_league'];
$rawDiv=$_GET['division'];
$division_id=$sub_league_id."_".$rawDiv;
$lgid=$_GET['league_id'];
$show=$_GET['show'];
$lastX=$_GET['lastX'];
$nextX=$_GET['nextX'];
$divName=$_GET['divName'];
$wdgCSSFile=$_GET['wdgCSS'];
if (($stat=="")&&($show==""))
{
	echo "No stat defined";
	exit;
}

if ($sub_league_id=="") {$comb=1;}
 else {$comb=0;}
switch ($show)
 {
   case 'standings': $divs=1; break;
   case 'leaders':$leaders=1; break;
   default: break;
 }
if (($topX=="")||($topX<=0)) {$topX=3;}

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

##### Check if admin table exists #####
$query="SHOW TABLES LIKE 'ootp_sql_admin';";
$result=mysqli_query($db,$query);
if (mysqli_num_rows($result)) 
 {
   $query="SELECT setting,value FROM ootp_sql_admin WHERE module='admin' AND setting IN ('HTMLRoot','HTMLPath','ServerURL','StatsLabPath','priLgID')";
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result)) 
    {
      while ($row=mysqli_fetch_array($result))
       {
         $field=$row['setting'];
	 $val=$row['value'];
	 $val=stripslashes($val);
	 switch ($field)
	  {
	    case 'HTMLRoot' : $htmlroot=$val; break;
	    case 'HTMLPath' : $htmlpath=$val; break;
		  case 'ServerURL': $serverURL=$val;break;
		  case 'StatsLabPath': $StatsLabPath=$val;break;
	    case 'priLgID'  : if ($lgid=="") {$lgid=$val;}break;
	  }
       }
      $lgpath=$serverURL.$_SESSION['htmlpath'];
      if (strtolower(substr($StatsLabPath,0,4))!="http") {$StatsLabPath=$serverURL.$StatsLabPath;}
    }
 }

##### Add CSS #####
if ($wdgCSSFile!="")
{
	echo "<style>\n";
	include("./".$wdgCSSFile);
	echo "</style>\n";
}
if ($divName!="")
{
	echo "<div id='$divName'>\n";
}

##### Get League Date #####
$query="SHOW TABLES LIKE 'leagues';";
$result=mysqli_query($db,$query);
if (mysqli_num_rows($result))
 {
   $query="SELECT name,season_year,leagues.current_date FROM leagues WHERE league_id=$lgid GROUP BY leagues.current_date;";
   $result=mysqli_query($db,$query);
   $row=mysqli_fetch_array($result);
   $lgdate=$row[2];
   $lgyear=$row['season_year'];
 }
$date=new Date($_SESSION['lgdate']);
//$lgyear=$date->format("Y");

##### Get League and Division Names and Abbreviations #####
$query="SELECT sl.sub_league_id as slid,sl.name as sl_name,sl.abbr sl_abbr,d.division_id as divID,d.name as d_name FROM sub_leagues as sl,divisions as d WHERE sl.league_id=$lgid AND d.league_id=$lgid AND sl.sub_league_id=d.sub_league_id ORDER BY sl.sub_league_id,division_id;";
$result=mysqli_query($db,$query);
while ($row=mysqli_fetch_array($result))
 {
   $slid=$row['slid'];
   $divID=$slid."_".$row['divID'];
   $subleagues[$slid]['name']=$row['sl_name'];
   $subleagues[$slid]['abbr']=$row['sl_abbr'];
   if ($row['sl_abbr']==$sub_league_id)
    {
      $sub_league_id=$slid;
      $division_id=$sub_league_id."_".$rawDiv;
    }
   $divisions[$divID]['name']=$row['d_name'];
 }

##### Get Teams #####
$query="SELECT t.team_id,t.name,t.abbr,t.nickname,t.sub_league_id,t.logo_file_name,tr.division_id FROM teams as t,team_relations as tr WHERE t.team_id=tr.team_id AND t.league_id=$lgid AND allstar_team=0 ORDER BY team_id;";
$result=mysqli_query($db,$query);
while ($row=mysqli_fetch_array($result))
 {
   $tid=$row['team_id'];
   $slid=$row['sub_league_id'];
   $divID=$slid."_".$row['division_id'];
   $teams[$tid]['city']=$row['name'];
   $teams[$tid]['abbr']=$row['abbr'];
   $teams[$tid]['nickname']=$row['nickname'];
   $teams[$tid]['logo']=$row['logo_file_name'];
   $teams[$tid]['slid']=$slid;
   $teams[$tid]['divID']=$divID;

   $subleagues[$slid]['teams']=$subleagues[$slid]['teams'].",".$tid;
 }
foreach ($subleagues as $slid => $val) {$subleagues[$slid]['teams']=trim($subleagues[$slid]['teams'],",");}

switch ($show)
 {
   ##### Get Standings #####
   case 'standings':
     $query="SELECT t.team_id,w,l,gb,sub_league_id,division_id FROM team_record as t,team_relations as tr WHERE t.team_id=tr.team_id AND tr.league_id=$lgid";
     $query.=" AND sub_league_id=$sub_league_id AND division_id=$rawDiv";
     $query.=" ORDER BY sub_league_id,division_id,gb;";
     if ($_GET['showq']==1) {echo "$query<br/>\n";}
     $result=mysqli_query($db,$query);
     $prevDiv="";
     while ($row=mysqli_fetch_array($result))
      {
        $tid=$row['team_id'];
	$wins=$row['w'];
  	$loss=$row['l'];
	$gb=$row['gb'];
  	if ($gb==0) {$gb="-";}
	$slid=$row['sub_league_id'];
  	$divID=$slid."_".$row['division_id'];

	if ($prevDiv!=$divID) {$cnt=0;}
  	$cls='wdg'.($cnt%2+1);
	$divisions[$divID]['standings']=$divisions[$divID]['standings']." <tr class='$cls'><td class='".$cls."_l'><a href='$lgpath/teams/team_$tid.html'>".$teams[$tid]['city']."</a></td><td>$wins</td><td>$loss</td><td>$gb</td></tr>\n";
  	if (($gb=="-")&&(!isset($divisions[$divID]['leader']))) {$divisions[$divID]['leader']=$divisions[$divID]['leader']."<li class='wdgLI'>".$subleagues[$slid]['abbr']." ".$divisions[$divID]['name'].": <a href='$lgpath/teams/team_$tid.html'>".$teams[$tid]['city']."</a></li>\n";}
	$prevDiv=$divID;
  	$cnt++;
      }
     echo "<table class='wdgT'>\n";
     echo " <thead><tr class='wdgH'><td class='wdgH_l'>".$subleagues[$sub_league_id]['abbr']." ".$divisions[$division_id]['name']."</td><td>W</td><td>L</td><td>GB</td></tr></thead>\n";
     echo $divisions[$division_id]['standings'];
     echo "</table>";
     break;
   case 'leaders':
     $query="SELECT t.team_id,w,l,gb,sub_league_id,division_id FROM team_record as t,team_relations as tr WHERE t.team_id=tr.team_id AND tr.league_id=$lgid ORDER BY sub_league_id,division_id,gb;";
     if ($_GET['showq']==1) {echo "$query<br/>\n";}
     $result=mysqli_query($db,$query);
     $prevDiv="";
     while ($row=mysqli_fetch_array($result))
      {
        $tid=$row['team_id'];
	$wins=$row['w'];
  	$loss=$row['l'];
	$gb=$row['gb'];
  	if ($gb==0) {$gb="-";}
	$slid=$row['sub_league_id'];
  	$divID=$slid."_".$row['division_id'];

	if ($prevDiv!=$divID) {$cnt=0;}
  	$cls='wdg'.($cnt%2+1);
	$divisions[$divID]['standings']=$divisions[$divID]['standings']." <tr class='$cls'><td class='".$cls."_l'><a href='$lgpath/teams/team_$tid.html'>".$teams[$tid]['city']."</a></td><td>$wins</td><td>$loss</td><td>$gb</td></tr>\n";
  	if (($gb=="-")&&(!isset($divisions[$divID]['leader']))) {$divisions[$divID]['leader']=$divisions[$divID]['leader']."<li class='wdgLI'>".$subleagues[$slid]['abbr']." ".$divisions[$divID]['name'].": <a href='$lgpath/teams/team_$tid.html'>".$teams[$tid]['city']."</a></li>\n";}
	$prevDiv=$divID;
  	$cnt++;
      }
     foreach ($divisions as $divID => $val)
      {
        $leaderText.=$divisions[$divID]['leader'];
      }
     echo "<ul class='wdgUL'>\n";
     echo $leaderText;
     echo "</ul>";
     break;
   case 'draftList':
		 $cnt=0;
		 $query="SELECT p.player_id,first_name,last_name,position,role,round,supplemental,pick_round,x.team_id FROM players as p,(SELECT player_id,round,supplemental,pick_round,team_id FROM amateur_draft WHERE league_id=$lgid AND player_id IS NOT NULL AND player_id!=-999 ORDER BY round DESC,supplemental DESC,pick_round DESC LIMIT $lastX) as x WHERE p.player_id=x.player_id ORDER BY round,supplemental,pick_round;";
		 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'];
				 $pname=$row['first_name']." ".$row['last_name'];
				 $tid=$row['team_id'];
				 $tabbr=$teams[$tid]['abbr'];
	 
				 $cls='wdg'.($cnt%2+1);
				 $lastText.=" <tr class='$cls'><td class='".$cls."_l'>";
				 if ($row['supplemental']==1) {$lastText.="S";}
				 $lastText.=$row['round']."</td><td class='".$cls."_l'>".$row['pick_round']."</td><td>".get_pos(($row['position']==1?$row['role']:$row['position']),1)."</td><td class='".$cls."_l'><a href='$lgpath/players/player_$pid.html'>$pname</a></td><td><a href='$lgpath/teams/team_$tid.html'>$tabbr</td></tr>\n";
				 $cnt++;
	 
			 }
		 }
		 $query="SELECT round,supplemental,pick_round,team_id FROM amateur_draft WHERE league_id=$lgid AND player_id IS NULL ORDER BY round,supplemental,pick_round LIMIT $nextX;";
		 if ($_GET['showq']==1) {echo "$query<br/>\n";}
			 $result=mysqli_query($db,$query);
		 if (mysqli_num_rows($result))
		 {
			 while ($row=mysqli_fetch_array($result))
			 {
				 $tid=$row['team_id'];
				 $tname=$teams[$tid]['city']." ".$teams[$tid]['nickname'];
	 
				 $cls='wdg'.($cnt%2+1);
				 $nextText.=" <tr class='$cls'><td class='".$cls."_l'>";
				 if ($row['supplemental']==1) {$nextText.="S";}
				 $nextText.=$row['round']."</td><td class='".$cls."_l'>".$row['pick_round']."</td><td colspan=3 style='text-align:center;'><a href='$lgpath/teams/team_$tid.html'>$tname</a></td></tr>\n";
				 $cnt++;		 
			 }
		 }
		 ## Display results	    
		 echo "<table class='wdgT'>\n";
		 echo " <thead><tr class='wdgH'><td class='wdgH_l'>Rnd</td><td class='wdgH_l'>Pck</td><td>Pos</td><td class='wdgH_l'>Player</td><td>Tm</td></tr></thead>\n";
		 echo $lastText;
		 echo $nextText;
		 echo "</table>";
		 break;
   case 'potw':
   case 'botm':
   case 'potm':
   case 'rotm':
	   switch ($show)
	   {
	   case 'potw': $awID=0; break;
	   case 'potm': $awID=1; break;
	   case 'botm': $awID=2; break;
	   case 'rotm': $awID=3; break;
	   }
	   $query="SELECT p.player_id,first_name,last_name,p.position,pa.team_id,pa.year as awYear,pa.month as awMonth,pa.day as awDay FROM players as p,players_awards as pa WHERE p.player_id=pa.player_id AND pa.league_id=$lgid AND pa.sub_league_id=$sub_league_id AND award_id=$awID ORDER BY pa.year DESC,pa.month DESC,pa.day DESC LIMIT 1";
	   if ($_GET['showq']==1) {echo "$query<br/>\n";}
	   $result=mysqli_query($db,$query);
	   if (mysqli_num_rows($result))
	   {
		   $row=mysqli_fetch_array($result);
		   $pid=$row['player_id'];
		   $tid=$row['team_id'];
		   $tabbr=$teams[$tid]['abbr'];
		   $awYear =$row['awYear'];
		   $awMonth=$row['awMonth'];
		   $awDay  =$row['awDay'];
		   $name=$row['first_name']." ".$row['last_name'];
		   $pos=$row['position'];

		   if ($pos>1)
		   {
			   $query="SELECT player_id,ps.team_id,if(SUM(ab)=0,0,SUM(h)/SUM(ab)) as avg,SUM(h) as h,SUM(hr) as hr,SUM(ab) as ab,SUM(rbi) as rbi,SUM(sb) as sb FROM players_game_batting as ps,games as g WHERE ps.player_id=$pid AND ps.game_id=g.game_id AND game_type=0";
			   if ($show=='potw')
			   {
				   $query.=" AND DATEDIFF('$awYear-$awMonth-$awDay',g.date)<9 AND DATEDIFF('$awYear-$awMonth-$awDay',g.date)>1";
			   }
			   else
			   {
				   $query.=" AND g.date LIKE '".(($awMonth==1)?($awYear-1):$awYear)."-".str_pad((($awMonth==1)?12:($awMonth-1)),2,0,STR_PAD_LEFT)."-%'";
			   }
			   $query.=" GROUP BY player_id";
			   if ($_GET['showq']==1) {echo "$query<br/>\n";}
			   $result=mysqli_query($db,$query);
			   $row=mysqli_fetch_array($result);

			   echo "<div style='text-align:center;'>";
			   echo "<img src='".get_player_pic($lgpath,$pid)."'><br/>";
			   echo "<a href='$StatsLabPath/player.php?player_id=$pid'>$name</a> - <a href='$lgpath/teams/team_$tid.html'>$tabbr</a><br/>".stat_format('avg',$row['avg']).", ".$row['hr']." HR, ".$row['rbi']." RBI";
			   echo "</div>\n";
		   }
		   else
		   {
			   $query="SELECT player_id,ps.team_id,if(SUM(ip)+SUM(ipf)/3=0,0,9*SUM(er)/(SUM(ip)+SUM(ipf)/3)) as era,SUM(w) as w,SUM(l) as l,SUM(k) as k,SUM(s) as s FROM players_game_pitching_stats as ps,games as g WHERE ps.player_id=$pid AND ps.game_id=g.game_id AND game_type=0";
			   if ($show=='potw')
			   {
				   $query.=" AND DATEDIFF('$awYear-$awMonth-$awDay',g.date)<9 AND DATEDIFF('$awYear-$awMonth-$awDay',g.date)>1";
			   }
			   else
			   {
				   $query.=" AND g.date LIKE '".(($awMonth==1)?($awYear-1):$awYear)."-".str_pad((($awMonth==1)?12:($awMonth-1)),2,0,STR_PAD_LEFT)."-%'";
			   }
			   $query.=" GROUP BY player_id";
			   if ($_GET['showq']==1) {echo "$query<br/>\n";}
			   $result=mysqli_query($db,$query);
			   $row=mysqli_fetch_array($result);

			   echo "<div style='text-align:center;'>";
			   echo "<img src='".get_player_pic($lgpath,$pid)."'><br/>";
			   echo "<a href='$StatsLabPath/player.php?player_id=$pid'>$name</a> - <a href='$lgpath/teams/team_$tid.html'>$tabbr</a><br/>".$row['w']."-".$row['l'].", ";
			   if ($row['s']>0) {echo $row['s']." SV, ";}
			   echo stat_format('era',$row['era'])." ERA, ".$row['k']." K";
			   echo "</div>\n";
		   }
	   }
	   else
	   {
		   echo "No player of the week found";
	   }
	   break;
   case 'botm':
	   break;
   case 'potm':
	   break;
   case 'rotm':
	   break;
   default:
     ##### Get Player Stats #####
     unset($query);    
     switch ($stat)
      {
        case 'avg':
        case 'obp':
        case 'slg':
        case 'ops':
        case 'wOBA':
        case 'era':
	case 'whip':
	case 'svPct':
	case 'kper9':
	case 'bbper9':
	case 'hper9':
	case 'rper9':
	case 'hrper9':
	case 'kperbb':
          $query.="SELECT *  FROM team_record as t,(";
	  break;
      }
     $query.="SELECT p.player_id,p.organization_id,pcb.team_id as statTeam,first_name,last_name";
     switch ($stat)
      {
        case 'avg' : $query.=",if(SUM(ab)=0,0,SUM(h)/SUM(ab)) as stat,SUM(pa) as pt"; break;
	case 'obp' : $query.=",if((SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))=0,0,((SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf)))) as stat,SUM(pa) as pt"; break;
	case 'slg' : $query.=",if(SUM(ab)=0,0,((SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab))) as stat,SUM(pa) as pt"; break;
	case 'ops' : $query.=",if(SUM(ab)=0,0,((SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab))+((SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf)))) as stat,SUM(pa) as pt"; break;
	case 'tb'  : $query.=",(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr)) as stat"; break;
	case 'ebh' : $query.=",SUM(d)+SUM(t)+SUM(hr) as stat"; break;
  	case 'wOBA': $query.=",if(SUM(pa)=0,0,(0.72*SUM(bb)+0.75*SUM(hp)+0.9*(SUM(h)-SUM(d)-SUM(t)-SUM(hr))+0.92*0+1.24*SUM(d)+1.56*SUM(t)+1.95*SUM(hr))/SUM(pa)) as stat,SUM(pa) as pt"; break;
	case 'era' : $query.=",if((SUM(ip)+SUM(ipf)/3)=0,0,9*SUM(er)/(SUM(ip)+SUM(ipf)/3)) as stat,(SUM(ip)+SUM(ipf)/3) as pt"; break;
  	case 'whip': $query.=",if((SUM(ip)+SUM(ipf)/3)=0,0,(SUM(ha)+SUM(bb))/(SUM(ip)+SUM(ipf)/3)) as stat,(SUM(ip)+SUM(ipf)/3) as pt"; break;
	case 'svPct': $query.=",if((SUM(s)+SUM(bs))=0,0,100*SUM(s)/(SUM(s)+SUM(bs))) as stat,SUM(s)+SUM(bs) as svOpp,(SUM(ip)+SUM(ipf)/3) as pt"; break;
	case 'kper9': $query.=",if((SUM(ip)+SUM(ipf)/3)=0,0,9*SUM(k)/(SUM(ip)+SUM(ipf)/3)) as stat,(SUM(ip)+SUM(ipf)/3) as pt"; break;
	case 'bbper9': $query.=",if((SUM(ip)+SUM(ipf)/3)=0,0,9*SUM(bb)/(SUM(ip)+SUM(ipf)/3)) as stat,(SUM(ip)+SUM(ipf)/3) as pt"; break;
	case 'hper9': $query.=",if((SUM(ip)+SUM(ipf)/3)=0,0,9*SUM(ha)/(SUM(ip)+SUM(ipf)/3)) as stat,(SUM(ip)+SUM(ipf)/3) as pt"; break;
	case 'rper9':  $query.=",if((SUM(ip)+SUM(ipf)/3)=0,0,9*SUM(r)/(SUM(ip)+SUM(ipf)/3)) as stat,(SUM(ip)+SUM(ipf)/3) as pt"; break;
	case 'hrper9': $query.=",if((SUM(ip)+SUM(ipf)/3)=0,0,9*SUM(hra)/(SUM(ip)+SUM(ipf)/3)) as stat,(SUM(ip)+SUM(ipf)/3) as pt"; break;
	case 'kperbb': $query.=",if(SUM(bb)=0,0,SUM(k)/SUM(bb)) as stat,(SUM(ip)+SUM(ipf)/3) as pt"; break;
	case 'ip': $query.=",SUM(ip)+SUM(ipf)/3 as stat"; break;
	case 'pk': $query.=",SUM(k) as stat"; break;
	case 'pbb': $query.=",SUM(bb) as stat"; break;
	case 'pr': $query.=",SUM(r) as stat"; break;
	case 'pg': $query.=",SUM(g) as stat"; break;
	case 'pgs': $query.=",SUM(gs) as stat"; break;
	case 'php': $query.=",SUM(hp) as stat"; break;
	case 'pwar': $query.=",SUM(war) as stat"; break;
	case 'pwpa': $query.=",SUM(wpa) as stat"; break;
  	default: $query.=",SUM($stat) as stat"; break;
      }
     $query.=" FROM players as p";
     switch ($stat)
      {
        case 'ab':
        case 'h':
        case 'd':
        case 't':
        case 'hr':
        case 'rbi':
        case 'r':
        case 'sb':
        case 'cs':
        case 'bb':
        case 'k':
        case 'sf':
        case 'sh':
        case 'ibb':
        case 'hp':
	case 'gdp':
        case 'pa':
        case 'avg':
        case 'obp':
        case 'slg':
        case 'ops':
        case 'wOBA':
	case 'war':
	case 'tb':
	case 'ebh':
	case 'wpa':
          $query.=",players_career_batting_stats";
	  break;
        default:
          $query.=",players_career_pitching_stats";
	  break;
      }
     $query.=" as pcb WHERE p.player_id=pcb.player_id AND pcb.league_id=$lgid AND split_id=1 AND year=$lgyear";
     if ($sub_league_id!="") {$query.=" AND pcb.team_id IN (".$subleagues[$sub_league_id]['teams'].")";}
     $query.=" GROUP BY player_id";
     switch ($stat)
      {
        case 'avg':
        case 'obp':
        case 'slg':
        case 'ops':
        case 'wOBA':
          $query.=") as tmp WHERE t.team_id=tmp.statTeam AND tmp.pt>=(3.1*t.g)";
	  break;
        case 'era':
        case 'whip':
	case 'kper9':
	case 'bbper9':
	case 'hper9':
	case 'rper9':
	case 'hrper9':
	case 'kperbb':
          $query.=") as tmp WHERE t.team_id=tmp.statTeam AND tmp.pt>=(1.0*t.g)";
          break;
        case 'svPct':
          $query.=") as tmp WHERE t.team_id=tmp.statTeam AND tmp.pt>=(.3*t.g) AND tmp.svOpp>=(.06*t.g)";
          break;
      }
     switch ($stat)
     {
        case 'era':
        case 'whip':
	case 'bbper9':
	case 'hper9':
	case 'rper9':
	case 'hrper9':
		$query.=" ORDER BY stat";
		break;
	default:
		$query.=" ORDER BY stat DESC";
		break;
     }
     $query.=" LIMIT $topX;";

     if ($_GET['showq']==1) {echo "$query <br/>\n";}
     $result=mysqli_query($db,$query);
     $nRows=mysqli_num_rows($result);
     if ($nRows<1)
      {
        $query=str_replace(" year=$lgyear"," year=".($lgyear-1),$query);
	$query=str_replace("team_record","team_history_record",$query);
	$query=str_replace("as tmp WHERE t.team_id=tmp.statTeam","as tmp WHERE t.year=".($lgyear-1)." AND t.team_id=tmp.statTeam",$query);
  	if ($_GET['showq']==1) {echo "$query <br/>\n";}
	$result=mysqli_query($db,$query);
	$showLast=1;
      }
     $cnt=0;
     if (mysqli_num_rows($result))
      {
        unset($lText);
        while ($row=mysqli_fetch_array($result))
 	 {
       	   $pid=$row['player_id'];
	   $fname=$row['first_name'];
  	   $lname=$row['last_name'];
	   $fi=$fname[0];
  	   $pname=$fi.". ".$lname;
	   $tid=$row['statTeam'];
  	   $tabbr=$teams[$tid]['abbr'];
	   $statVal=$row['stat'];
  	   switch ($stat)
	    {
	      case 'avg':
	      case 'obp':
      	      case 'slg':
              case 'ops':
	      case 'wOBA':
	        $statVal=sprintf("%.3f",$statVal);
                if ($statVal<1) {$statVal=strstr($statVal,".");}
		break;
	      case 'era':
              case 'whip':
	      case 'kper9':
      	      case 'bbper9':
	      case 'hper9':
      	      case 'rper9':
	      case 'hrper9':
      	      case 'kperbb':
	        $statVal=sprintf("%.2f",$statVal);
	        break;
	      case 'wpa':
              case 'war':
              case 'ip':
	      case 'pwar':
	      case 'svPct':
	      case 'pwpa':
	        $statVal=sprintf("%.1f",$statVal);
	        break;
	    }
  	   $cls='wdg'.($cnt%2+1);
	   $lText.=" <tr class='$cls'><td class='".$cls."_l'><a href='$StatsLabPath/player.php?player_id=$pid'>$pname</a></td><td><a href='$lgpath/teams/team_$tid.html'>$tabbr</a></td><td>$statVal</td></tr>\n";
  	   $cnt++;
	 }
      }
      else {$lText=" <tr class='$cls'><td class='".$cls."_l' colspan=3>No data found</td></tr>\n";}

     ## Display results	    
     echo "<table class='wdgT'>\n";
     echo " <thead><tr class='wdgH'><td class='wdgH_l'>Player</td><td>Tm</td><td>";
     switch ($stat)
      {
		  case 'wOBA' : echo "wOBA";            break;
		  case 's'    : echo "SV";              break;
		  case 'pwar': echo "WAR";            break;
		  case 'pk': echo "K"; break;
		  case 'pbb': echo "BB"; break;
		  case 'pr': echo "RA"; break;
		  case 'pg': echo "GP"; break;
		  case 'pgs': echo "GS"; break;
		  case 'php': echo "HBP"; break;
		  case 'pwpa': echo "WPA"; break;
		  case 'svPct': echo "<span title='To qualify: 10 save opportunities per 162 team games'>SV%</span>"; break;
		  case 'kper9': echo "K/9IP"; break;
	  	  case 'bbper9': echo "BB/9IP"; break;
		  case 'hper9': echo "H/9IP"; break;
	  	  case 'rper9': echo "R/9IP"; break;
		  case 'hrper9': echo "HR/9IP"; break;
	  	  case 'kperbb': echo "K/BB"; break;
		  default:
	  if ($showLast==1) 
	   {
	     if (($lgyear%100)==0) {$lastYr=99;} else {$lastYr=substr($lgyear-1,2);}
	     echo "'".$lastYr." ";
	   }
	  echo strtoupper($stat); 
	  break;
      }
     echo "</td></tr></thead>\n";
     echo $lText;
     echo "</table>";
     break;
 }

##### Add CSS #####
if ($divName!="")
{
	echo "\n</div>\n";
}

mysqli_close($db);

?>
