<?php

  include("html_functions.php");



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

  $lgid=$_SESSION['lgid'];

  $lgpath=$_SESSION['lgpath'];

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

  $lgyear=$_SESSION['lgyear'];



  $page=$_GET['page'];

  $pageLimit=100;

  if ($page=="") {$page=0;}

  

  $view=$_GET['view'];

  $stat=$_GET['stat'];

  $scope=$_GET['scope'];

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

  $listing=$_GET['listing'];

  if ($listing=="") {$listing="top100";}

  $sub_league_id=$_GET['sub_league_id'];

  if ($sub_league_id=="") {$sub_league_id="ALL";}

  $team_id=$_GET['team_id'];

  if ($team_id=="") {$team_id="ALL";}

  $statSplit=$_GET['split'];

  if ($statSplit=="") {$statSplit='regular';}

  $who=$_GET['who'];

  if ($who=="") {$who="ALL";}

  $pos=$_GET['pos'];

  if ($pos=="") {$pos="ALL";}

  $ageStart=$_GET['ageFrom'];

  $ageEnd=$_GET['ageTo'];

  if ($ageStart>$ageEnd)

  {

	  $tmpAge=$ageEnd;

	  $ageEnd=$ageStart;

	  $ageStart=$tmpAge;

  }

  if (($ageStart=="")||($ageStart<15)) {$ageStart=15;}

  if (($ageEnd=="")||($ageEnd>45)) {$ageEnd=45;}

  $startYr=$_GET['from'];

  $endYr=$_GET['to'];

  if ($startYr>$endYr)

  {

	  $tmpYr=$endYr;

	  $endYr=$startYr;

	  $startYr=$tmpYr;

  }

  $dRnd1=$_GET['draftFrom'];

  $dRnd2=$_GET['draftTo'];

  if ($dRnd1=="") {$dRnd1=1;}

  $dtid=$_GET['draft_team_id'];

  if ($dtid=="") {$dtid="ALL";}

  $ovrMinPT=$_GET['ovrMinPT'];

  if ($ovrMinPT<0) {$ovrMinPT="";}

  $minStat=$_GET['minStat'];

  $minStat2=$_GET['minStat2'];

  $minStat2Lbl=$_GET['minStat2Lbl'];

  $minStat2dir=$_GET['minStat2dir'];



  ## Set defaults for special stats

  switch ($stat)

  {

  case 'bink':

  case 'gink':

	  $scope='career';

	  break;

  }



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

  ## Get Team Abbreviations

  $query="SELECT team_id,year,name,nickname,abbr FROM team_history WHERE league_id=$lgid UNION SELECT team_id,'$lgyear' as year,name,nickname,abbr FROM teams WHERE 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'];

	  $yr=$row['year'];

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

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

  }

  ## Get Max/Min Years

  if (($minYr==0)||($maxYr==0))

  {

	  $query="SELECT MAX(year) as maxYr,MIN(year) as minYr FROM ";

	  if ($view=='teams') {$query.="team_history_batting_stats";}

	  else {$query.="players_career_batting_stats";}

	  $query.=" WHERE league_id=$lgid;";

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

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

	  $row=mysqli_fetch_array($result);			

	  $minYr=$row['minYr'];

	  $maxYr=$row['maxYr'];

  }

  if ($startYr=="") {$startYr=$minYr;}

  if ($endYr=="") {$endYr=$maxYr;}



  mysqli_close($db);



  # Title Bar

  $title="";

  if ($view!="") {$title.=ucwords($view)." ";}

  $title.="Leaderboards";



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

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

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

  nav_toolbar("history","History");

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

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



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

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



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

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

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

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

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

  echo "   <tr>\n";



  ## Show Type Selection

  echo "     <td style='border-bottom:1px solid gray;'><label><b>View:</b></label></td>";

  echo "     <td style='border-bottom:1px solid gray;'><input type='radio' name='view' value='players' id='players'";

  if ($view=='players') {echo " checked='checked'";}

  echo " onclick=\"window.location='./leaderboards.php?view=players'\"></td>";

  echo "     <td style='border-bottom:1px solid gray;'><label for='players'>Players</label></td>";

  echo "     <td style='border-bottom:1px solid gray;'><input type='radio' name='view' value='teams' id='teams'";

  if ($view=='teams') {echo " checked='checked'";}

  echo " onclick=\"window.location='./leaderboards.php?view=teams'\"></td>";

  echo "     <td style='border-bottom:1px solid gray;'><label for='teams'>Teams</label></td>";

  echo "     <td style='border-bottom:1px solid gray;'><input type='radio' name='view' id='progressive' onclick=\"window.location='./progLeaders.php";

  if ($view!="") {echo "?view=$view";}

  echo "'\"></td>";

  echo "     <td style='border-bottom:1px solid gray;'><label for='progressive'>Progressive</label></td>";

  echo "     <td style='border-bottom:1px solid gray;'><input type='radio' name='view' id='annual' onclick=\"window.location='./seasonal_leaders.php";

  if ($view!="") {echo "?view=$view";}

  echo "'\"></td>";

  echo "     <td style='border-bottom:1px solid gray;'><label for='annual'>Annual</label></td>";



  switch ($view)

  {

  case 'players':

	  $statArray=array('batters'=>'Batting','ab'=>'AB','h'=>'H','d'=>'2B','t'=>'3B','hr'=>'HR','rbi'=>'RBI','r'=>'R','sb'=>'SB','cs'=>'CS','bb'=>'BB','k'=>'K','sf'=>'SF','sh'=>'SH','ibb'=>'IBB','hp'=>'HBP','gdp'=>'GIDP','pa'=>'PA','outs'=>'Outs','ebh'=>'EBH','tb'=>'TB','tob'=>'TOB','tto'=>'TTO','pitches_seen'=>'Pitches Seen','pipa'=>'PS/PA','abhr'=>'AB/HR','pahr'=>'PA/HR','bbk'=>'BB/K','avg'=>'AVG','obp'=>'OBP','slg'=>'SLG','ops'=>'OPS','iso'=>'ISO','bbabip'=>'BABIP','wOBA'=>'wOBA','war'=>"WAR",'pwrspd'=>'PwrSpd','bsba'=>'SBA','sbPct'=>'SB%','rc'=>'RC','rc27'=>'RC/27','ows'=>'OWS','pitchers'=>'Pitching','w'=>'W','l'=>'L','s'=>'SV','ip'=>'IP','g'=>'G','gs'=>'GS','gf'=>'GF','cg'=>'CG','sho'=>'SHO','qs'=>'QS','pk'=>'K','pbb'=>'BB','ha'=>'HA','hra'=>'HR','pr'=>'R','er'=>'ER','hld'=>'HLD','svo'=>'SVO','bs'=>'BS','da'=>'2BA','ta'=>'3BA','bk'=>'BK','wp'=>'WP','hp'=>'HP','bf'=>'BF','gb'=>'GB','fb'=>'FB','ptto'=>'TTO','pi'=>'Pitches Thrown','era'=>'ERA','whip'=>'WHIP','pwar'=>'WAR','kper9'=>'K/9IP','bbper9'=>'BB/9IP','hper9'=>'H/9IP','rper9'=>'R/9IP','hrper9'=>'HR/9IP','kperbb'=>'K/BB','gbPct'=>'GB%','babip'=>'BABIP','winpct'=>'Win %','gmovr500'=>'Gms Over .500','pws'=>'PWS','fielders'=>'Fielding','fgs'=>'GS','po'=>'PO','a'=>'A','dp'=>'DP','tp'=>'TP','tc'=>'TC','e'=>'E','fip'=>'Inn','fpct'=>'Pct','rng'=>'Range','zr'=>'ZR','pb'=>'PB','sba'=>'RSTA','rto'=>'RTO','rtoPct'=>'RTO%','fws'=>'FWS','career'=>'Career','bink'=>'Black Ink','gink'=>'Gray Ink','wsTot'=>'WS');



	  echo "    <td style='border-bottom:1px solid gray;' colspan=2>&nbsp;</td>\n";

	  echo "   </tr>\n";

	  echo "   <tr>\n";



	  ## Show Scope Filter

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

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

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

	  echo " onclick=\"setPTind('c')\"></td><td valign=top><label for='career'>Career</label></td>\n";

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

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

	  echo " onclick=\"setPTind('s')\"></td><td valign=top><label for='season'>Seasonal</label></td>\n";



	  ## Get Subleagues

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

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

	  while ($row=mysqli_fetch_array($result))

	  {

		  $slid=$row['sub_league_id'];

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

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

	  }



	  ## Show Subleague Filter

	  echo "    <td colspan=2 style='text-align:right;'><b>League:</b></td>\n";

	  echo "    <td";

	  if ($view=='teams') {echo " colspan=4";}

	  echo ">\n";

	  echo "     <select name='sub_league_id' id='sub_league_id' onchange=\"if(this[this.selectedIndex].value!='ALL') {document.getElementById('team_id').selectedIndex=0;}\">\n";

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

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

	  {

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

		  if (($sub_league_id==$slid) && ($sub_league_id!="ALL")) {echo " selected";}

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

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";

			

	  echo "   </tr>\n";

	  echo "   <tr>\n";



	  ## Show Listing Filter

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

	  echo "    <td><input type='radio' name='listing' value='top100' id='top100'";

	  if ($listing=='top100') {echo " checked='checked'";}

	  echo " onclick=\"document.getElementById('statCondDir').innerHTML=' greater than';\"></td><td valign=top><label for='top100'>Top</label></td>\n";

	  echo "    <td><input type='radio' name='listing' value='bot100' id='bot100'";

	  if ($listing=='bot100') {echo " checked='checked'";}

	  echo " onclick=\"document.getElementById('statCondDir').innerHTML=' worse than';\"></td><td valign=top><label for='bot100'>Bottom</label></td>\n";



	  ## Get Current Teams

	  $query="SELECT team_id,name,nickname,abbr,level,sub_league_id 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'];

		  $slid=$row['sub_league_id'];

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

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

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

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

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

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

		  $LGtmList.=",$tid";

	  }

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

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



	  ## Show Team Filter

	  echo "    <td colspan=2 style='text-align:right;'><b>Team:</b></td>\n";

	  echo "    <td>\n";

	  echo "     <select name='team_id' id='team_id' onchange=\"if(this[this.selectedIndex].value!='ALL') {document.getElementById('sub_league_id').selectedIndex=0;}\">\n";

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

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

	  {

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

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

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

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";



	  echo "   </tr>\n";

	  echo "   <tr>\n";



	  ## Show Split Filter

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

	  echo "    <td><input type='radio' name='split' value='regular' id='regular'";

	  if ($statSplit=='regular') {echo " checked='checked'";}

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

	  echo "    <td><input type='radio' name='split' value='postseason' id='postseason'";

	  if ($statSplit=='postseason') {echo " checked='checked'";}

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



	  ## Stat Filter

	  echo "    <td colspan=2 style='text-align:right;'><b>Stat:</b></td>\n";

	  echo "    <td>\n";

	  echo "     <select name='stat' id='stat' onchange=\"setPTstatType(this[this.selectedIndex].value);document.getElementById('statCond').innerHTML=this[this.selectedIndex].text;\">\n";

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

	  {

		  if (($key=='batters')||($key=='pitchers')||($key=='fielders')||($key=='career')) {echo "      <optgroup label='$val'>\n";}

		  else

		  {

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

			  if ($stat==$key) {echo " selected";}

			  echo ">$val</option>\n";

		  }

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";



	  echo "   </tr>\n";

	  echo "   <tr>\n";



	  ## Show Who Filter

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

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

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

	  $whoArray=array('ALL'=>'All Players','active'=>'Active Players','retired'=>'Retired Players','hof'=>'Hall of Fame Players');

	  foreach ($whoArray as $key => $dispName)

	  {

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

		  if ($who==$key) {echo " selected";}

		  echo ">$dispName</option>\n";

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";



	  ## Show Position Filter

	  echo "    <td colspan=3 style='text-align:right;'><b>Position:</b></td>\n";

	  echo "    <td>\n";

	  echo "     <select name='pos' id='pos'";

	  if ($disablePosFilt==1) {echo " disabled='disabled'";}

	  echo ">\n";

	  $posArray=Array("ALL"=>"All","1"=>"P","2"=>"C","3"=>"1B","4"=>"2B","5"=>"3B","6"=>"SS","7"=>"LF","8"=>"CF","9"=>"RF","10"=>"DH","IF"=>"IF","CI"=>"CI","MI"=>"MI","OF"=>"OF","SP"=>"SP","RP"=>"RP","MR"=>"MR","CL"=>"CL");

	  foreach ($posArray as $key => $val)

	  {

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

		  if ($pos==$key) {echo " selected";}

		  echo ">$val</option>\n";

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";

			

	  echo "   </tr>\n";

	  echo "   <tr>\n";



	  ## Year Filter

	  echo "    <td colspan=2><b>Year From:</b></td>\n";

	  echo "    <td>\n";

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

	  for ($i=$minYr;$i<=$maxYr;$i++)

	  {

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

		  if ($startYr==$i) {echo " selected";}

		  echo ">$i</option>\n";

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";

	  echo "    <td colspan=2 style='text-align:right;'><b>To:</b></td>\n";

	  echo "    <td>\n";

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

	  for ($i=$minYr;$i<=$maxYr;$i++)

	  {

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

		  if ($endYr==$i) {echo " selected";}

		  echo ">$i</option>\n";

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";

			

	  echo "   </tr>\n";

	  echo "   <tr>\n";

			

	  ## Age Filter

	  echo "    <td colspan=2><b>Age From:</b></td>\n";

	  echo "    <td>\n";

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

	  for ($i=15;$i<=45;$i++)

	  {

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

		  if ($ageStart==$i) {echo " selected";}

		  echo ">";

		  if ($i==15) {echo "<=";}

		  if ($i==45) {echo ">=";}

		  echo "$i</option>\n";

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";

	  echo "    <td colspan=2 style='text-align:right;'><b>To:</b></td>\n";

	  echo "    <td>\n";

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

	  for ($i=15;$i<=45;$i++)

	  {

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

		  if ($ageEnd==$i) {echo " selected";}

		  echo ">";

		  if ($i==15) {echo "<=";}

		  if ($i==45) {echo ">=";}

		  echo "$i</option>\n";

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";



	  echo "   </tr>\n";

	  echo "   <tr>\n";



	  ## Show draft filter

	  $query="SELECT MAX(draft_round) as dmax FROM players WHERE draft_year!=0 AND draft_league_id=$lgid;";

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

	  $row=mysqli_fetch_array($result);		

	  $drndMax=$row['dmax'];

	  if (($drndMax!="")&&($drndMax>=1))

	  {

		  echo "    <td colspan=2><b>Drafted From Round:</b></td>\n";

		  echo "    <td>\n";

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

		  if ($dRnd2=="") {$dRnd2=$drndMax;}

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

		  {

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

			  if ($dRnd1==$i) {echo " selected";}

			  echo ">$i</option>\n";

		  }

		  echo "     </select>\n";

		  echo "    </td>\n";

		  echo "    <td colspan=2 style='text-align:right;'><b>To Round:</b></td>\n";

		  echo "    <td>\n";

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

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

		  {

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

			  if ($dRnd2==$i) {echo " selected";}

			  echo ">$i</option>\n";

		  }

		  echo "     </select>\n";

		  echo "    </td>\n";



		  echo "    <td style='text-align:right;'><b>By:</b></td>\n";

		  echo "    <td>\n";

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

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

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

		  {

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

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

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

		  }

		  echo "     </select>\n";

		  echo "    </td>\n";

				

		  ## Start New Row

		  echo "   </tr>\n";

		  echo "   <tr>\n";

	  }



	  ## Alternate Stat Adjustment

	  echo "    <td colspan=2 title='While having'><b>While Having</b></td>\n";

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

	  echo "     <select name='minStat2Lbl' id='minStat2Lbl' title='This stat must be from same table as search stat (i.e. batting w/ batting, no batting w/ fielding)'>\n";

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

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

	  {

		  if (($key=='ows')||($key=='pws')||($key=='fws')||($key=='wsTot')||($key=='adj_ops_plus')||($key=='EqR')||($key=='EqA')||($key=='bSSdiff')||($key=='adj_era_plus')||($key=='cERA')||($key=='pSSdiff')) {continue;}

		  if ($key=='career') {break;}



		  if (($key=='batters')||($key=='pitchers')||($key=='fielders')||($key=='career')) {echo "      <optgroup label='$val'>\n";}

		  else

		  {

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

			  if ($minStat2Lbl==$key) {echo " selected";}

			  echo ">$val</option>\n";

		  }

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";

	  echo "    <td>\n";

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

	  $dirArray=array("",">=","<=","=");

	  foreach ($dirArray as $key => $val)

	  {

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

		  if ($minStat2dir==$val) {echo " selected";}

		  echo ">$val</option>\n";

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";

	  echo "    <td title='Leave blank to ignore'><input type='text' maxlength=5 size=5 name='minStat2' id='minStat2' value='$minStat2' /></td>\n";

	  echo "    <td title='While having' style='text-align:right;'><b>, <span id='statCond'>".$statArray[$stat]."</span> <span id='statCondDir'>";

	  if ($listing=='top100') {echo " greater than";} else {echo " worse than";}

	  echo "</span></b></td>\n";

	  echo "    <td title='Leave blank to ignore'><input type='text' maxlength=5 size=5 name='minStat' id='minStat' value='$minStat' /></td>\n";



	  echo "   </tr>\n";

	  echo "   <tr>\n";

			

	  ## Minimum PT Adjustment

	  echo "<td colspan=2 title='Minimum playing time'><b>Minimum Playing Time:</b></td>\n";

	  echo "<td title='Leave blank for defaults:\n3.1 PA/g\n1.0 IP/g\n3.1 Inn/g'><input type='text' maxlength=5 size=5 name='ovrMinPT' id='ovrMinPT' value='$ovrMinPT' /></td>\n";

	  echo "<td colspan=4><span id='ptStat'>";

	  if ($stat=="") {echo "PA";}

	  echo "</span> <span id='ptIndicator'>";

	  if ($scope=='season') {echo " per team game";}

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

			

	  ## Submission button

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



	  ## Start New Row

	  echo "   </tr>\n";

	  echo "   <tr>\n";



	  ## Resets

	  echo "    <td style='border-top:1px solid gray;'>Resets:</td>\n";

	  echo "    <td style='border-top:1px solid gray;'><input type='button' onclick=\"window.location='./leaderboards.php?view=$view'\" value='Reset All' /></td>\n";

	  echo "    <td colspan=2 style='border-top:1px solid gray;'><input type='button' onclick=\"document.getElementById('from').value=$minYr;document.getElementById('to').value=$maxYr;\" value='Reset Years' /></td>\n";

	  echo "    <td colspan=2 style='border-top:1px solid gray;'><input type='button' onclick=\"document.getElementById('ageFrom').value=15;document.getElementById('ageTo').value=45;\" value='Reset Ages' /></td>\n";

	  if (($drndMax!="")&&($drndMax>=1))

	  {

		  echo "    <td colspan=2 style='border-top:1px solid gray;'><input type='button' onclick=\"document.getElementById('draftFrom').value=1;document.getElementById('draftTo').value=$drndMax;document.getElementById('draft_team_id').value='ALL';\" value='Reset Draft Settings' /></td>\n";

	  }

	  else {echo "    <td colspan=2 style='border-top:1px solid gray;'>&nbsp;</td>\n";} 

	  break;



  case 'teams':

	  #### Check for Enabled Reports ####

	  $query="SHOW TABLES LIKE 'ootp_sql_admin';";

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

	  if (mysqli_num_rows($result)) 

	  {

		  $query="SELECT * FROM ootp_sql_admin WHERE setting='finEnable';";

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

				  $finEnable=$val;

			  }

		  }

	  }

	  $statArray=array('batters'=>'Batting','ab'=>'AB','h'=>'H','d'=>'2B','t'=>'3B','hr'=>'HR','rbi'=>'RBI','r'=>'R','sb'=>'SB','cs'=>'CS','bb'=>'BB','k'=>'K','sf'=>'SF','sh'=>'SH','ibb'=>'IBB','hp'=>'HBP','gdp'=>'GIDP','pa'=>'PA','outs'=>'Outs','ebh'=>'EBH','tb'=>'TB','tob'=>'TOB','tto'=>'TTO','pitches_seen'=>'Pitches Seen','pipa'=>'PS/PA','bsba'=>'SBA','sbPct'=>'SB%','abhr'=>'AB/HR','pahr'=>'PA/HR','bbk'=>'BB/K','avg'=>'AVG','obp'=>'OBP','slg'=>'SLG','ops'=>'OPS','iso'=>'ISO','bbabip'=>'BABIP','wOBA'=>'wOBA','pwrspd'=>'PwrSpd','bsba'=>'SBA','sbPct'=>'SB%','rc'=>'RC','rc27'=>'RC/27','pitchers'=>'Pitching','w'=>'W','l'=>'L','s'=>'SV','ip'=>'IP','g'=>'G','gs'=>'GS','gf'=>'GF','cg'=>'CG','sho'=>'SHO','qs'=>'QS','pk'=>'K','pbb'=>'BB','ha'=>'HA','hra'=>'HR','pr'=>'R','er'=>'ER','hld'=>'HLD','svo'=>'SVO','bs'=>'BS','da'=>'2BA','ta'=>'3BA','bk'=>'BK','wp'=>'WP','hp'=>'HP','bf'=>'BF','gb'=>'GB','fb'=>'FB','ptto'=>'TTO','pi'=>'Pitches Thrown','era'=>'ERA','whip'=>'WHIP','kper9'=>'K/9IP','bbper9'=>'BB/9IP','hper9'=>'H/9IP','rper9'=>'R/9IP','hrper9'=>'HR/9IP','kperbb'=>'K/BB','gbPct'=>'GB%','babip'=>'BABIP','fielders'=>'Fielding','fgs'=>'GS','po'=>'PO','a'=>'A','dp'=>'DP','tp'=>'TP','tc'=>'TC','e'=>'E','fip'=>'Inn','fpct'=>'Pct','rng'=>'Range','pb'=>'PB','sba'=>'RSTA','rto'=>'RTO','rtoPct'=>'RTO%','other'=>'Other','winpct'=>'Win %','gmovr500'=>'Games Over .500','attendance'=>'Attendance');

	  if ($finEnable==1) 

	  {

		  $statArray['budget']="Budget";

		  $statArray['gate_revenue']="Gate Revenue";

		  $statArray['merchandising_revenue']="Merchandising Revenue";

		  $statArray['media_revenue']="Media Revenue";

		  $statArray['playoff_revenue']="Playoff Revenue";

		  $statArray['revenue_sharing']="Revenue Sharing";

		  $statArray['tot_revenue']="Total Revenue";

		  $statArray['player_expenses']="Player Payroll";

		  $statArray['staff_expenses']="Staff Payroll";

		  $statArray['tot_expenses']="Total Payroll";

		  $statArray['profit']="Profit";

	  }



	  echo "    <td style='border-bottom:1px solid gray;' colspan=2>&nbsp;</td>\n";

	  echo "   </tr>\n";

	  echo "   <tr>\n";



	  ## Show Scope Filter

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

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

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

	  echo " onclick=\"setPTind('c')\"></td><td valign=top><label for='career'>Cumulative</label></td>\n";

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

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

	  echo " onclick=\"setPTind('s')\"></td><td valign=top><label for='season'>Seasonal</label></td>\n";



	  ## Get Subleagues

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

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

	  while ($row=mysqli_fetch_array($result))

	  {

		  $slid=$row['sub_league_id'];

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

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

	  }



	  ## Show Subleague Filter

	  echo "    <td colspan=2 style='text-align:right;'><b>League:</b></td>\n";

	  echo "    <td";

	  if ($view=='teams') {echo " colspan=4";}

	  echo ">\n";

	  echo "     <select name='sub_league_id' id='sub_league_id' onchange=\"if(this[this.selectedIndex].value!='ALL') {document.getElementById('team_id').selectedIndex=0;}\">\n";

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

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

	  {

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

		  if (($sub_league_id==$slid) && ($sub_league_id!="ALL")) {echo " selected";}

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

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";

			

	  echo "   </tr>\n";

	  echo "   <tr>\n";

			

	  ## Show Listing Filter

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

	  echo "    <td><input type='radio' name='listing' value='top100' id='top100'";

	  if ($listing=='top100') {echo " checked='checked'";}

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

	  echo "    <td><input type='radio' name='listing' value='bot100' id='bot100'";

	  if ($listing=='bot100') {echo " checked='checked'";}

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

			

	  ## Get Current Teams

	  $query="SELECT team_id,name,nickname,abbr,level,sub_league_id 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'];

		  $slid=$row['sub_league_id'];

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

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

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

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

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

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

		  $LGtmList.=",$tid";

	  }

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

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



	  ## Show Team Filter

	  echo "    <td colspan=2 style='text-align:right;'><b>Team:</b></td>\n";

	  echo "    <td>\n";

	  echo "     <select name='team_id' id='team_id' onchange=\"if(this[this.selectedIndex].value!='ALL') {document.getElementById('sub_league_id').selectedIndex=0;}\">\n";

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

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

	  {

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

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

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

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";



	  echo "   </tr>\n";

	  echo "   <tr>\n";

						

	  ## Year Filter

	  echo "    <td colspan=2><b>Year From:</b></td>\n";

	  echo "    <td>\n";

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

	  for ($i=$minYr;$i<=$maxYr;$i++)

	  {

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

		  if ($startYr==$i) {echo " selected";}

		  echo ">$i</option>\n";

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";

	  echo "    <td style='text-align:right;'><b>To:</b></td>\n";

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

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

	  for ($i=$minYr;$i<=$maxYr;$i++)

	  {

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

		  if ($endYr==$i) {echo " selected";}

		  echo ">$i</option>\n";

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";



	  ## Stat Filter

	  echo "    <td style='text-align:right;'><b>Stat:</b></td>\n";

	  echo "    <td>\n";

	  echo "     <select name='stat' id='stat' onchange=\"setPTstatType(this[this.selectedIndex].value);\">\n";

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

	  {

		  if (($key=='batters')||($key=='pitchers')||($key=='fielders')||($key=='other')) {echo "      <optgroup label='$val'>\n";}

		  else

		  {

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

			  if ($stat==$key) {echo " selected";}

			  echo ">$val</option>\n";

		  }

	  }

	  echo "     </select>\n";

	  echo "    </td>\n";

			

	  echo "   </tr>\n";

	  echo "   <tr>\n";

			

	  ## Resets

	  echo "    <td>Resets:</td>\n";

	  echo "    <td><input type='button' onclick=\"window.location='./leaderboards.php?view=$view'\" value='Reset All' /></td>\n";

	  echo "    <td><input type='button' onclick=\"document.getElementById('from').value=$minYr;document.getElementById('to').value=$maxYr;\" value='Reset Years' /></td>\n";



	  ## Submission button

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

			

	  break;

  }		



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

  echo "   </tr>\n";

  echo "  </table>\n";

  echo "  </form>\n";

  echo " </div>\n";



  if ($stat=="")		## Close out page

  {

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

	  if ($view=='players') {echo dispPTJava();}

	  page_foot($lgpath);

	  exit;

  }



  ## Get Team List

  $tQuery="";

  if ($sub_league_id!="ALL") {$tQuery=" AND team_id IN (".$subleagues[$sub_league_id]['teams'].")";}

  if ($team_id!="ALL") {$tQuery=" AND team_id=$team_id";}

  

  ##### Display results #####

  if ($view=='players')

  {

	  ## Check for fielding related stat (to ignore positional determination based on innings played)

	  switch ($stat)

	  {

  	  case 'fgs':

	  case 'po':

	  case 'a':

	  case 'dp':

	  case 'tp':

	  case 'tc':

	  case 'e':

	  case 'fip':

	  case 'fpct':

	  case 'rng':

	  case 'zr':

	  case 'pb':

	  case 'sba':

	  case 'rto':

	  case 'rtoPct':

	  case 'fws':

		  $fldStat=1;

		  break;

	  default:

		  $fldStat=0;

	  }



	  ## Position Query   (only for batters)

	  $posQuery="";

	  if (($pos!='ALL')&&($pos!=1)&&($pos!='SP')&&($pos!='RP')&&($pos!='MR')&&($pos!='CL')&&($fldStat!=1))

	  {

		  $posQuery.="SELECT player_id";

		  if ($scope=='season') {$posQuery.=",year";}

		  $posQuery.=",position,ip,SUM(ip) as totalIP FROM (SELECT player_id";

		  if ($scope=='season') {$posQuery.=",year";}

		  $posQuery.=",position,SUM(ip)+SUM(ipf)/3 as ip FROM players_career_fielding_stats WHERE league_id=$lgid AND split_id<=1";

		  if ($startYr>$minYr) {$posQuery.=" AND year>=$startYr";}

		  if ($endYr<$maxYr) {$posQuery.=" AND year<=$endYr";}

		  $posQuery.=$tQuery." GROUP BY player_id,position";

		  if ($scope=='season') {$posQuery.=",year";}

		  $posQuery.=" ORDER BY player_id";

		  if ($scope=='season') {$posQuery.=",year";}

		  $posQuery.=",ip DESC) as y GROUP BY player_id";

		  if ($scope=='season') {$posQuery.=",year";}

	  }



	  ## Player Query   (for everyone)

	  $pQuery="";

	  if (($who!="ALL")||($ageStart>15)||($ageEnd<45)||($pos==1)||($pos=='SP')||($pos=='RP')||($pos=='MR')||($pos=='CL')||($dtid!='ALL')||($dRnd1>1)||($dRnd2<$drndMax))

	  {

		  $pQuery.="SELECT player_id,first_name,last_name,($lgyear-YEAR(date_of_birth)-(RIGHT(date_of_birth,5)>'07-01')) as ageNow,hall_of_fame,retired,position,role";

		  $pQuery.=" FROM players WHERE 1";

		  //$pQuery.=" FROM players WHERE league_id=$lgid";

		  if ($who=='active') {$pQuery.=" AND retired=0";}

		  if ($who=='retired') {$pQuery.=" AND retired=1";}

		  if ($who=='hof') {$pQuery.=" AND hall_of_fame=1";}

		  if ($dtid!='ALL') {$pQuery.=" AND draft_team_id=$dtid";}

		  if ($dRnd1>1) {$pQuery.=" AND draft_round>=$dRnd1";}

		  if ($dRnd2<$drndMax) {$pQuery.=" AND draft_round<=$dRnd2";}

		  if (($dRnd1>1)||($dRnd2<$drndMax)) {$pQuery.=" AND draft_league_id=$lgid";}

		  if ($pos==1) {$pQuery.=" AND position=1";}

		  if ($pos=='SP') {$pQuery.=" AND position=1 AND role=11";}

		  if ($pos=='RP') {$pQuery.=" AND position=1 AND role IN (12,13)";}

		  if ($pos=='MR') {$pQuery.=" AND position=1 AND role=12";}

		  if ($pos=='CL') {$pQuery.=" AND position=1 AND role=13";}

	  }



	  ## Combine Selection Criteria

	  $selectionQuery="";

	  if (($posQuery!="")&&($pQuery!=""))

	  {

		  $selectionQuery="SELECT first_name,last_name,ageNow,hall_of_fame,retired,pf.* FROM ($pQuery) as p,($posQuery) as pf WHERE p.player_id=pf.player_id";

		  if (($pos!='ALL')&&($pos!=1)&&($pos!='SP')&&($pos!='RP')&&($pos!='MR')&&($pos!='CL')&&($fldStat!=1))

		  {

			  if ((is_numeric($pos))&&($pos!=10)) {$selectionQuery.=" AND pf.position=$pos";}

			  if ($pos=='IF') {$selectionQuery.=" AND pf.position IN (3,4,5,6)";}

			  if ($pos=='CI') {$selectionQuery.=" AND pf.position IN (3,5)";}

			  if ($pos=='MI') {$selectionQuery.=" AND pf.position IN (4,6)";}

			  if ($pos=='OF') {$selectionQuery.=" AND pf.position IN (7,8,9)";}

		  }

	  }

	  elseif ($posQuery!="")

	  {

		  $selectionQuery="SELECT * FROM ($posQuery) as pf WHERE 1";

		  if (($pos!='ALL')&&($pos!=1)&&($pos!='SP')&&($pos!='RP')&&($pos!='MR')&&($pos!='CL')&&($fldStat!=1))

		  {

			  if ((is_numeric($pos))&&($pos!=10)) {$selectionQuery.=" AND pf.position=$pos";}

			  if ($pos=='IF') {$selectionQuery.=" AND pf.position IN (3,4,5,6)";}

			  if ($pos=='CI') {$selectionQuery.=" AND pf.position IN (3,5)";}

			  if ($pos=='MI') {$selectionQuery.=" AND pf.position IN (4,6)";}

			  if ($pos=='OF') {$selectionQuery.=" AND pf.position IN (7,8,9)";}

		  }

	  }

	  elseif ($pQuery!="") {$selectionQuery=$pQuery;}



	  ## Determine PT Condition

	  switch ($stat)

  	  {

	  case 'pipa':

	  case 'abhr':

	  case 'pahr':

	  case 'bbk':

	  case 'avg':

	  case 'obp':

	  case 'slg':

	  case 'ops':

	  case 'iso':

	  case 'bbabip':

	  case 'wOBA':

	  case 'pwrspd':

	  case 'bsba':

	  case 'sbPct':

	  case 'rc':

	  case 'rc27':

	  case 'era':

	  case 'whip':

	  case 'kper9':

	  case 'bbper9':

	  case 'hper9':

	  case 'rper9':

	  case 'hrper9':

	  case 'kperbb':

	  case 'gbPct':

	  case 'babip':

	  case 'winpct':

	  case 'fpct':

	  case 'rng':

	  case 'rtoPct':

	  case 'adj_ops_plus':

	  case 'EqR':

	  case 'EqA':

	  case 'adj_era_plus':

	  case 'cERA':			

		  $ptCond=1;

		  break;

	  }

	  if ($listing=='bot100') {$ptCond=1;}



	  if ((is_numeric($ovrMinPT))&&($ovrMinPT>0)&&($scope=='career'))

	  {

		  $ptCond=1;

		  $minCarPA=$ovrMinPT;		  

		  $minCarIP=$ovrMinPT;		  

		  $minCarInn=$ovrMinPT;		  

	  }

	  elseif (($ptCond==1)&&($scope=='career'))

	  {

		  $cumG=0;

		  

		  if (($startYr==$endYr)&&($endYr==$lgyear))  //This year only

		  {

			  $ptQuery="";

			  $ptQuery.="SELECT ROUND(AVG(g)) as g FROM teams as t,team_record as tr WHERE t.team_id=tr.team_id AND t.league_id=$lgid AND allstar_team=0";

		  }

		  else  //Historical years included

		  {

			  $ptQuery="";

			  $ptQuery.="SELECT year,ROUND(AVG(g)) as g FROM team_history_record WHERE league_id=$lgid";

			  if ($startYr>$minYr) {$ptQuery.=" AND year>=$startYr";}

			  if ($endYr<$maxYr) {$ptQuery.=" AND year<=$endYr";}

			  $ptQuery.=" GROUP BY year ORDER BY year";

		  }

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

  		  while ($row=mysqli_fetch_array($result))

		  {

  			  $yr=$row['year'];

			  $g=$row['g'];

			  $years[$yr]['g']=$g;

			  $cumG+=$g;

		  }

		  $years[$lgyear]['g']=$g;

		  $nYrs=count($years);

		  $gPerYr=$cumG/$nYrs;



		  #PA Adj

		  $minCarPA=3.1*$cumG;

		  if ($minCarPA>2000) {$minCarPA=2000;}

		  elseif ($nYrs>4)

		  {

			  $minCarPA=floor($minCarPA/500)*500;

			  $minCarPA=max($minCarPA,200);

		  }

		  #IP Adj

		  $minCarIP=1.0*$cumG;

		  if ($minCarIP>1000) {$minCarIPA=1000;}

		  elseif ($nYrs>7)

		  {

			  $minCarIP=floor($minCarIP/250)*250;

			  $minCarIP=max($minCarIP,100);

		  }

		  #Inn Adj

		  $minCarInn=3.1*$cumG;

		  if ($minCarInn>2000) {$minCarInn=2000;}

		  elseif ($nYrs>4)

		  {

			  $minCarInn=floor($minCarInn/500)*500;

			  $minCarInn=max($minCarInn,200);

		  }

	  }

	  elseif ($ptCond==1)    ## Scope = 'season'

	  {

		  ## Team Games Played

		  if (($startYr==$endYr)&&($endYr==$lgyear))  //This year only

		  {

			  $tmGQuery="SELECT team_id,$lgyear as year,g FROM team_record WHERE 1$tQuery";

		  }

		  else  //Historical years included

		  {

			  $tmGQuery="SELECT team_id,year,g FROM team_history_record WHERE league_id=$lgid$tQuery";

			  if ($startYr>$minYr) {$tmGQuery.=" AND year>=$startYr";}

			  if ($endYr<$maxYr) {$tmGQuery.=" AND year<=$endYr";}

		  }

	  }



	  ## Set Default Lower Limit for Stats

	  if (!is_numeric($minStat))

	  {

		  switch ($stat)

		  {

		  case 'gmovr500':

		  case 'war':

		  case 'pwar':

		  case 'zr':

			  break;

		  case 'ows':

		  case 'fws':

		  case 'pws':

		  case 'wsTot':

			  if ($listing=='top100') {$minStat=0.05;}

			  break;

	  	  case 'abhr':

		  case 'pahr':

	  	  case 'era':

		  case 'whip':

	  	  case 'bbper9':	   

		  case 'hper9':	   

	  	  case 'rper9':	   

		  case 'hrper9':	   

		  case 'babip':

	  	  case 'cERA':

			  if ($listing=='bottom100') {$minStat=0.0001;}

			  break;

		  default:

			  if ($listing=='top100') {$minStat=0.0001;}

			  break;

		  }

	  }



	  ## Stats Query

	  $statQuery="";

	  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 'outs':

	  case 'ebh':

	  case 'tb':

	  case 'tob':

	  case 'tto':

	  case 'pitches_seen':

	  case 'pipa':

	  case 'abhr':

	  case 'pahr':

	  case 'bbk':

	  case 'avg':

	  case 'obp':

	  case 'slg':

	  case 'ops':

	  case 'iso':

	  case 'bbabip':

	  case 'wOBA':

	  case 'war':

	  case 'pwrspd':

	  case 'bsba':

	  case 'sbPct':

	  case 'rc':

	  case 'rc27':

		  $table='players_career_batting_stats';

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

		  if ((!in_array($minStat2Lbl,$statArray))&&($minStat2Lbl!="")) {array_push($statArray,$minStat2Lbl);}

		  if (!in_array($stat,$statArray)) {array_push($statArray,$stat);}

		  $minCarPT=$minCarPA;

		  $ptLbl="pa";

		  if ((is_numeric($ovrMinPT))&&($ovrMinPT>0))

		  {

			  $ptDef=$ovrMinPT;

		  }

		  else

		  {

			  $ptDef=3.1;

		  }

		  break;

  	  case 'fgs':

	  case 'po':

	  case 'a':

	  case 'dp':

	  case 'tp':

	  case 'tc':

	  case 'e':

	  case 'fip':

	  case 'fpct':

	  case 'rng':

	  case 'zr':

	  case 'pb':

	  case 'sba':

	  case 'rto':

	  case 'rtoPct':

		  $table='players_career_fielding_stats';

		  if (($pos==2)||($stat=='pb')||($stat=='sba')||($stat=='rto')||($stat=='rtoPct'))

		  {

			  $statArray=Array('g','fgs','po','a','dp','tc','e','fpct','ip','rng','zr','pb','sba','rto','rtoPct');

		  }

	    	  else

		  {

			  $statArray=Array('g','fgs','po','a','dp','tc','e','fpct','ip','rng','zr');

		  }

		  if ((!in_array($minStat2Lbl,$statArray))&&($minStat2Lbl!="")) {array_push($statArray,$minStat2Lbl);}

		  if (!in_array($stat,$statArray)) {array_push($statArray,$stat);}

		  $minCarPT=$minCarInn;

		  $ptLbl="ip";

		  if ((is_numeric($ovrMinPT))&&($ovrMinPT>0))

		  {

			  $ptDef=$ovrMinPT;

		  }

		  else

		  {

			  $ptDef=3.1;

		  }

		  break;

	  case 'ows':

	  case 'fws':

	  case 'pws':

	  case 'wsTot':

		  $table='players_win_shares';

		  $statArray=Array('ows','fwsTot','pws','wsTot');

		  if (($stat=='fws')&&($pos!='ALL')) {array_push($statArray,$stat);}

		  $ptCond=0;

		  break;

	  case 'bink':

	  case 'gink':

		  $statArray=Array('bink','gink');

		  $ptCond=0;

		  break;

	  default:        ## Pitching Stats

		  $table='players_career_pitching_stats';

		  $statArray=Array('g','gs','w','l','s','era','ip','ha','pr','er','hra','pbb','pk','hld','cg','sho','whip','war');

		  if ((!in_array($minStat2Lbl,$statArray))&&($minStat2Lbl!="")) {array_push($statArray,$minStat2Lbl);}

		  if (!in_array($stat,$statArray)) {array_push($statArray,$stat);}

		  $minCarPT=$minCarIP;

		  $ptLbl="ip";

		  if ((is_numeric($ovrMinPT))&&($ovrMinPT>0))

		  {

			  $ptDef=$ovrMinPT;

		  }

		  else

		  {

			  $ptDef=1.0;

		  }

		  break;



	  }



	  ## Create Stat Query

	  $statQuery.="SELECT player_id,team_id,COUNT(DISTINCT team_id) as nTeams";

	  if ($scope=='season') {$statQuery.=",year";}

	  else {$statQuery.=",MIN(year) as year,MAX(year) as year2";}

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

	  {

		  switch ($stat)

		  {

		  case 'fws':

			  $statQuery.=",".stat_query($statLbl,"","","",$pos)." as $statLbl";

			  if (($statLbl=='fws')&&($pos!='ALL')) {$statQuery.=$pos;}

			  break;

		  default:

			  $statQuery.=",".stat_query($statLbl)." as $statLbl";

			  break;

		  }

	  }

	  if ($ptLbl!="") {$statQuery.=",".stat_query($ptLbl)." as pt";}

	  $statQuery.=" FROM $table WHERE league_id=$lgid";

	  if (($stat=='ows')||($stat=='fws')||($stat=='pws')||($stat=='wsTot')) {1;}  #No split

	  elseif ($fldStat==1) {$statQuery.=" AND split_id<=1";}

	  elseif ($statSplit=='postseason') {$statQuery.=" AND split_id=21";}

	  else {$statQuery.=" AND split_id=1";}

	  if (($fldStat==1)&&($pos!='ALL')&&($table!='players_win_shares'))

	  {

		  switch ($pos)

		  {

		  case 'IF': $statQuery.=" AND position IN (3,4,5,6)"; break;

		  case 'CI': $statQuery.=" AND position IN (3,5)";     break;

		  case 'MI': $statQuery.=" AND position IN (4,6)";     break;

		  case 'OF': $statQuery.=" AND position IN (7,8,9)";   break;

		  case 'SP': 

		  case 'RP': 

		  case 'MR': 

		  case 'CL': $statQuery.=" AND position=1";            break;

		  default:   $statQuery.=" AND position=$pos";         break;

		  }

	  }

	  $statQuery.=$tQuery;

	  if ($startYr>$minYr) {$statQuery.=" AND year>=$startYr";}

	  if ($endYr<$maxYr) {$statQuery.=" AND year<=$endYr";}

	  $statQuery.=" GROUP BY player_id";

	  if ($scope=='season') {$statQuery.=",year";}

	  if (is_numeric($minStat))

	  {

		  switch ($stat)

		  {

		  case 'fws':

			  $statQuery.=" HAVING ".stat_query($stat,"","","",$pos);

			  break;

		  default:

			  $statQuery.=" HAVING ".stat_query($stat);

			  break;

		  }

		  if ($listing=='top100') {$statQuery.=stat_sort($stat,1,1);}

		  else {$statQuery.=stat_sort($stat,1,0);}

		  $statQuery.=$minStat;



		  if ((is_numeric($minStat2))&&($minStat2Lbl!="")&&($minStat2dir!=""))

		  {

			  $statQuery.=" AND ".stat_query($minStat2Lbl).$minStat2dir.$minStat2;

		  }



		  if (($ptCond==1)&&($scope=='career')) {$statQuery.=" AND ".stat_query($ptLbl).">=$minCarPT";}

	  }

	  elseif ((is_numeric($minStat2))&&($minStat2Lbl!="")&&($minStat2dir!=""))

	  {

		  $statQuery.=" HAVING ".stat_query($minStat2Lbl).$minStat2dir.$minStat2;

		  if (($ptCond==1)&&($scope=='career')) {$statQuery.=" AND ".stat_query($ptLbl).">=$minCarPT";}

	  }

	  elseif (($ptCond==1)&&($scope=='career')) {$statQuery.=" HAVING ".stat_query($ptLbl).">=$minCarPT";}

  

	  ## Wrap team games query around for PT qualification on season

	  if (($ptCond==1)&&($scope=='season'))

	  {

		  $statQuery="SELECT sq.* FROM ($statQuery) as sq,($tmGQuery) as tgq WHERE sq.team_id=tgq.team_id AND sq.year=tgq.year AND sq.pt>=($ptDef*tgq.g)";

	  }



	  ## Special Case Queries

	  switch ($stat)

	  {

	  case 'bink':

	  case 'gink':

		  $statQuery="";

		  $statQuery.="SELECT player_id,MIN(year) as year,MAX(year) as year2,SUM(bink) as bink,SUM(gink) as gink FROM (";

		  $statQuery.="SELECT player_id,year,sub_league_id,category,place,if(place=1,1,0) as bink,if(place<11,1,0) as gink FROM players_league_leader WHERE league_id=$lgid AND category IN (0,2,7,27,28,56) AND year>=$minYr AND year<=$maxYr";

		  $statQuery.=" UNION ";

		  $statQuery.="SELECT player_id,year,sub_league_id,category,place,if(place=1,2,0) as bink,if(place<11,2,0) as gink FROM players_league_leader WHERE league_id=$lgid AND category IN (6,9,12,46,47,54) AND year>=$minYr AND year<=$maxYr";

		  $statQuery.=" UNION ";

		  $statQuery.="SELECT player_id,year,sub_league_id,category,place,if(place=1,3,0) as bink,if(place<11,3,0) as gink FROM players_league_leader WHERE league_id=$lgid AND category IN (3,11,20,31,32,34) AND year>=$minYr AND year<=$maxYr";

		  $statQuery.=" UNION ";

		  $statQuery.="SELECT player_id,year,sub_league_id,category,place,if(place=1,4,0) as bink,if(place<11,4,0) as gink FROM players_league_leader WHERE league_id=$lgid AND category IN (8,10,18,29,38,40) AND year>=$minYr AND year<=$maxYr";

		  $statQuery.=") as t GROUP BY player_id HAVING SUM($stat)>0";

		  break;

	  }



	  ## Create Final Query

	  $query="";

	  if ($pQuery!="")

	  {

		  $query.="SELECT first_name,last_name,ageNow,hall_of_fame,retired,position,role,x.* FROM ($selectionQuery) as p1,($statQuery) as x WHERE p1.player_id=x.player_id";

		  if (($scope=='season')&&($posQuery!="")) {$query.=" AND p1.year=x.year";}

		  if ($pos==10) {$query.=" AND p1.totalIP<x.pt";}

		  if ($ageStart>15) {$query.=" AND (ageNow+year-$lgyear)>=$ageStart";}

		  if ($ageEnd<45) {$query.=" AND (ageNow+year-$lgyear)<=$ageEnd";}

	  }

	  elseif ($posQuery!="")

	  {

		  $query.="SELECT position,x.* FROM ($selectionQuery) as p1,($statQuery) as x WHERE p1.player_id=x.player_id";

		  if ($scope=='season') {$query.=" AND p1.year=x.year";}

		  if ($pos==10) {$query.=" AND p1.totalIP<x.pt";}

	  }

	  else {$query=$statQuery;}



  

	  ## Get total number of rows here if not looking for DH's

	  $cntQuery="SELECT COUNT(*) as cnt FROM ($query) as ttt";

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

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

	  $row=mysqli_fetch_array($result);

	  $totCnt=$row['cnt'];

	  $pgCnt=ceil($totCnt/$pageLimit);



	  ## Apply sort and limit results

	  $query.=" ORDER BY $stat";

	  if (($stat=='fws')&&($pos!='ALL')) {$query.=$pos;}

	  if ($listing=='top100') {$query.=" ".stat_sort($stat);}

	  else {$query.=" ".stat_sort($stat,0,1);}

	  $query.=",year";

	  if (($fldStat!=1)&&($stat!='bink')&&($table!='players_win_shares')) {$query.=",war DESC";}

	  if ($pQuery!="") {$query.=",last_name,first_name";}

	  $query.=" LIMIT ".($page*$pageLimit).",$pageLimit";



	  ## Wrap players if we don't already have them and resort

	  if ($pQuery=="")

	  {

		  $innerQuery=$query;

		  $query="SELECT first_name,last_name,($lgyear-YEAR(date_of_birth)-(RIGHT(date_of_birth,5)>'07-01')) as ageNow,hall_of_fame,retired,";

		  if (($posQuery=="")||($stat=='bink')||($stat=='gink')) {$query.="p1.";} else {$query.="x2.";}

		  $query.="position,role,x2.* FROM players as p1,($innerQuery) as x2 WHERE p1.player_id=x2.player_id";

		  $query.=" ORDER BY $stat";

		  if (($stat=='fws')&&($pos!='ALL')) {$query.=$pos;}

		  if ($listing=='top100') {$query.=" ".stat_sort($stat);}

		  else {$query.=" ".stat_sort($stat,0,1);}

		  $query.=",year";

		  if (($fldStat!=1)&&($stat!='bink')&&($stat!='gink')&&($table!='players_win_shares')) {$query.=",war DESC";}

		  $query.=",last_name,first_name";

	  }







	  ##### Run Query #####

	  if ($_GET['showq']==1)

	  {

		  echo "<div class='textbox' style='width:935px;'>\n";

		  echo " $posQuery<br/>\n";

		  echo " $pQuery<br/>\n";

		  echo " $statQuery<br/>\n";

		  echo " $cntQuery<br/>\n";

		  echo " $query<br/>\n";

		  echo "</div>\n";

	  }



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

	  if (mysqli_num_rows($result))

	  {

		  ## Notes

		  switch ($stat)

		  {

		  case 'bink':

		  case 'gink':

			  echo "<div class='textbox' style='border:0;'><b>Note:</b> Not all filters apply to ".stat_text($stat)." searches.</div>\n";

			  break;

		  }



		  echo "<div class='textbox' id='graph_link' style='float:right;border:0;display:none;' title='Note that some search criteria will be lost when graphing'></div>\n";



	  	  ## Start Table

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

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

		  echo "  <tr class='title2'>\n";

		  echo "   <td style='padding:2px;'>";

		  if ($startYr==$endYr) {echo "$startYr ";}

	  	  if ($sub_league_id!="ALL") {echo $subleagues[$sub_league_id]['name']." ";}

		  if ($team_id!="ALL") {echo $teams[$team_id]['name']." ";}

	  	  if ($listing=='top100') {echo "Top ";}

		  else {echo "Bottom ";}

	  	  if ($scope=='season') {echo "Seasonal ";}

		  else {echo "Career ";}

	  	  if ($stat!="") {echo stat_text($stat)." ";}

		  if ($startYr!=$endYr) {echo "Leaders From $startYr to $endYr";} else {echo "Leaders";}

	  	  if ($pos!="ALL") {echo " by ".get_pos($pos,"",1);}

		  echo "<br/>(*=Active Player, +=Hall of Famer";

	  	  if ($ptCond==1)

		  {

	  		  echo ", Minimum ";

			  if ($scope=='season') {echo number_format($ptDef,1,".",",")." ".stat_text($ptLbl,1)." / TmG";}

	 		  else {echo number_format($minCarPT,0,".",",")." ".stat_text($ptLbl,1);}

		  }

	  	  if (($minStat2!="")&&($minStat2Lbl!="")&&($minStat2dir!="")) 

		  {

	  		  echo ", with ".stat_text($minStat2Lbl,2);

			  echo htmlspecialchars($minStat2dir);

	  		  echo stat_format($minStat2Lbl,$minStat2);

		  } 

	  	  echo ")";

		  echo "</td>\n";

		  if ($pgCnt>1)

		  {

			  echo "   <td style='text-align:right;vertical-align:top;margin-bottom:0px;padding-bottom:0px;padding-right:2px;' title='$totCnt $view found'>\n";

			  echo "    <table border=0 cellpadding=0 cellspacing=0 style='float:right;'>\n";

			  echo "     <tr class='title2'><td>Page</td>\n";

			  echo "     <td>\n";

			  echo "      <form action='./leaderboards.php' method='GET'>\n";

			  foreach ($_GET as $setting => $val) {echo "       <input type='hidden' name='$setting' value='$val' >\n";}

			  echo "       <select name='page' onchange='this.form.submit()' style='float:right;clear:none;'>\n";

			  for ($i=0;$i<$pgCnt;$i++)

			  {

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

				  if ($page==$i) {echo " selected='selected'";}

				  echo ">".($i+1)."</option>\n";

			  }

			  echo "       </select>\n";

			  echo "      </form>\n";

			  echo "     </td>\n";

			  echo "     <td style='text-align:left;'>of $pgCnt</td></tr>\n";

			  echo "    </table>\n";

			  echo "   </td>\n";

		  }

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

		  echo "  </tr>\n";

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

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

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

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

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

	  	  switch ($stat)

		  {

  		  case 'bink':

		  case 'gink':

			  if (($pos==1)||((!is_numeric($pos))&&($pos!="SP")&&($pos!="MR")&&($pos!="CL"))) {echo "<td class='hsc2'>Pos</td>";}

			  break;

  		  case 'hof_standards':

		  case 'bSSdiff':

  		  case 'pSSdiff':

			  break;

  		  default:

			  if ($team_id=="ALL") {echo "<td class='hsc2_l'>Team</td>";}

			  if (($pos==1)||((!is_numeric($pos))&&($pos!="SP")&&($pos!="MR")&&($pos!="CL"))) {echo "<td class='hsc2'>Pos</td>";}

			  if ($scope=='season') {echo "<td class='hsc2'>Age</td>";}

			  break;

	  	  }

		  if ($scope=='season') {echo "<td class='hsc2'>Year</td>";}

		  else {echo "<td class='hsc2'>Years</td>";}

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

		  {

			  if (($statLbl=='fws')&&($pos!='ALL')) {echo "<td class='hsc2'>".stat_text($statLbl.$pos,2)."</td>";}

			  else {echo "<td class='hsc2'>".stat_text($statLbl,2)."</td>";}

		  }

		  #Display Stat Header

		  if (!in_array($stat,$statArray)) {echo "<td class='hsc2'>".stat_text($stat,2)."</td>";}

		  #Display Second condition stat

		  if (($minStat2!="")&&($minStat2Lbl!="")&&($minStat2dir!="")&&(!in_array($minStat2Lbl,$statArray))) 

		  {

	  		  echo "<td class='hsc2'>".stat_text($minStat2Lbl,2)."</td>";

		  } 	

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





		  ## Display Data Rows

		  $cnt=0;

		  $rnk=0;

		  $prevStat="";

		  while ($row=mysqli_fetch_array($result))

		  {

  			  $pid=$row['player_id'];

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

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

			  $hof=$row['hall_of_fame'];

  			  $tid=$row['team_id'];

			  $nTeams=$row['nTeams'];

  			  $active=$row['retired'];

			  $year=$row['year'];

  			  $statVal=$row[$stat];

			  $ageNow=$row['ageNow'];

			  $age=$ageNow-$lgyear+$year;



			  if (!isset($graphPids)||(count($graphPids)<5)) {$graphPids[$pid]=1;}



			  switch ($stat)

			  {

			  case 'bink':

			  case 'gink':

				  $statVal=$row[$stat];

				  break;

			  case 'fws':

				  if ($pos!='ALL') {$statLbl=$stat.$pos;} else {$statLbl=$stat;}

				  $statVal=$row[$statLbl];

				  break;

			  }



			  ## Update Rank

			  if (($page>0)&&($cnt==0))

			  {

				  $rnkQuery=$cntQuery.=" WHERE $stat";

				  if (($stat=='fws')&&($pos!='ALL')) {$rnkQuery.=$pos;}

				  if ($listing=='top100')

				  {

					  if (stat_sort($stat,0,1)=="DESC") {$rnkQuery.="<";}

					  else {$rnkQuery.=">";}

				  }

				  else

				  {

					  if (stat_sort($stat,0,0)=="DESC") {$rnkQuery.=">";}

					  else {$rnkQuery.="<";}

				  }

				  $rnkQuery.=$statVal;

				  $rnkQuery.=" AND player_id!=$pid";

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

				  $rnkResult=mysqli_query($db,$rnkQuery);

				  $rnkRow=mysqli_fetch_array($rnkResult);

				  $rnk=$rnkRow['cnt']+1;

				  $prevStat=$statVal;

			  }

			  elseif ($prevStat!=$statVal)

			  {

  				  $rnk=$page*$pageLimit+$cnt+1;

				  $prevStat=$statVal;

			  }

		  

			  ## Start Row			

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

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

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

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

			  if ($hof==1) {echo "+";}

  			  if ($active==0) {echo "*";}

			  echo "</td>";

  			  switch ($stat)

			  {

			  case 'bink':

			  case 'gink':

				  $pPos=$row['position'];

				  if ($pPos==1) {$posDisp=get_pos($row['role'],1);}

				  else {$posDisp=get_pos($pPos,1);}

				  if (($pos==1)||((!is_numeric($pos))&&($pos!="SP")&&($pos!="MR")&&($pos!="CL"))) {echo "<td class='hsc2' sorttable_customkey=\"".$pPos."\">".$posDisp."</td>";}

				  break;

			  case 'hof_standards':

			  case 'bSSdiff':

			  case 'pSSdiff':

				  break;

			  default:

				  if ($team_id=="ALL") 

				  {

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

					  if ($nTeams>1) {echo " title='Played for $nTeams teams'";}

					  echo ">";

					  if ($tid==0)

					  {

						  if ($active==1) {echo "Ret";}

						  else {echo "FA";}

					  }

					  else

					  {

						  $tabbr=$teams[$tid][$year]['abbr'];

						  echo "<a href='./team_hist.php?team_id=$tid";

						  if (($scope=='season')||($year==$row['year2'])) {echo "&page=year&year=$year";}

						  else {echo "&page=index";}

						  echo "'>$tabbr</a>";

						  if ($nTeams>1) {echo "<sup>($nTeams)</sup>";}

					  }

					  echo "</td>";

				  }

				  $pPos=$row['position'];

				  if ($pPos==1) {$posDisp=get_pos($row['role'],1);}

				  else {$posDisp=get_pos($pPos,1);}

				  if (($pos==1)||((!is_numeric($pos))&&($pos!="SP")&&($pos!="MR")&&($pos!="CL"))) {echo "<td class='hsc2' sorttable_customkey=\"".$pPos."\">".$posDisp."</td>";}

				  break;

			  }

			  if ($scope=='season') {echo "<td>$age</td>";}

			  echo "<td>$year";

			  if (($scope=='career')&&(isset($row['year2']))&&($row['year2']!=$year)) {echo "-".$row['year2'];}

			  echo "</td>";

	  

			  ## Display Default Stats

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

			  {

				  if (($statLbl=='fws')&&($pos!='ALL')) {$statLbl.=$pos;}

  				  $statVal2=$row[$statLbl];

				  $statVal2=stat_format($statLbl,$statVal2);			

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

			  }

  			  ## Display Sorted on Stat

			  if (!in_array($stat,$statArray)) 

  			  {

				  $statVal=stat_format($stat,$statVal);

  				  echo "<td valign='top'>$statVal</td>";

			  }

  			  ## Display Second Condition Stat

			  if (($minStat2!="")&&($minStat2Lbl!="")&&($minStat2dir!="")&&(!in_array($minStat2Lbl,$statArray))) 

  			  {

				  $statVal=$row['stat2'];

  				  $statVal=stat_format($minStat2Lbl,$statVal);

				  echo "<td valign='top'>$statVal</td>";

  			  } 	

			  #End row

			  echo "</tr>\n";

			  $cnt++;

		  }

	  	  ## Close Table

		  echo "   </table>\n";



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

	  	  echo " </table>\n";

		  echo "</div>\n";

	  }		

  	  else

	  {

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

	  }

  }



  

  ##Display results

  if ($view=='teams')

  {

	  switch ($stat)

	  {

	  case 'gmovr500':

		  break;

	  case 'abhr':

	  case 'pahr':

	  case 'era':

	  case 'whip':

	  case 'bbper9':	   

	  case 'hper9':	   

	  case 'rper9':	   

	  case 'hrper9':	   

	  case 'babip':

	  case 'cERA':

		  if ($listing=='bottom100') {$minStat=0.0001;}

		  break;

	  default:

		  if ($listing=='top100') {$minStat=0.0001;}

		  break;

	  }



  	  ## Get SQL Table

	  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 'outs':

	  case 'ebh':

	  case 'tb':

	  case 'tob':

	  case 'tto':

	  case 'pitches_seen':

	  case 'pipa':

	  case 'abhr':

	  case 'pahr':

	  case 'bbk':

	  case 'avg':

	  case 'obp':

	  case 'slg':

	  case 'ops':

	  case 'iso':

	  case 'bbabip':

	  case 'wOBA':

	  case 'pwrspd':

	  case 'bsba':

	  case 'sbPct':

	  case 'rc':

	  case 'rc27':

		  $table='team_history_batting_stats';

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

		  if (!in_array($stat,$statArray)) {array_push($statArray,$stat);}

		  $statType='bStat';

		  break;

	  case 'fgs':

	  case 'po':

	  case 'a':

	  case 'dp':

	  case 'tp':

	  case 'tc':

	  case 'e':

	  case 'fip':

	  case 'fpct':

	  case 'rng':

	  case 'pb':

	  case 'sba':

	  case 'rto':

	  case 'rtoPct':

		  $table='team_history_fielding_stats_stats';

		  $statArray=Array('g','gs','po','a','dp','tc','e','fpct','ip','rng');

		  if (!in_array($stat,$statArray)) {array_push($statArray,$stat);}

		  $statType='fStat';

		  break;

	  case 'attendance':

	  case 'budget':

	  case 'gate_revenue':

	  case 'merchandising_revenue':

	  case 'media_revenue':

	  case 'playoff_revenue':

	  case 'revenue_sharing':

	  case 'tot_revenue':

	  case 'player_expenses':

	  case 'staff_expenses':

	  case 'tot_expenses':

	  case 'profit':

		  $table='team_history_financials';

		  $statArray=Array('gate_revenue','media_revenue','merchandising_revenue','player_expenses');

		  if (!in_array($stat,$statArray)) {array_push($statArray,$stat);}

		  $statType='finStat';

		  break;

	  default:

		  $table='team_history_pitching_stats';

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

		  if (!in_array($stat,$statArray)) {array_push($statArray,$stat);}

		  $statType='pStat';

		  break;

	  }



	  if ($listing=='top100') {$orderClause=stat_sort($stat);}

	  else {$orderClause=stat_sort($stat,"",1);}



  

	  ## Generate Query

	  $query="SELECT team_id";

  	  if ($scope=='season') {$query.=",year";}

	  else {$query.=",MIN(year) as year,MAX(year) as year2";}

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

	  {

		  $query.=",".stat_query($statLbl)." as $statLbl";

	  }

  	  $query.=" FROM $table WHERE league_id=$lgid AND year>=$startYr AND year<=$endYr$tQuery GROUP BY team_id";

	  if ($scope=='season') {$query.=",year";}

	  if (is_numeric($minStat))

	  {

		  if ($orderClause=='DESC') {$query.=" HAVING ".stat_query($stat).">$minStat";}

	  }





	  ## Get total number of rows here if not looking for DH's

	  $cntQuery="SELECT COUNT(*) as cnt FROM ($query) as ttt";

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

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

	  $row=mysqli_fetch_array($result);

	  $totCnt=$row['cnt'];

	  $pgCnt=ceil($totCnt/$pageLimit);

		  

	  $query.=" ORDER BY $stat $orderClause,year";

	  $query.=" LIMIT ".($page*$pageLimit).",$pageLimit";



	  ##### Run Query #####

	  if ($_GET['showq']==1)

	  {

		  echo "<div class='textbox' style='width:935px;'>\n";

		  echo " $cntQuery<br/>\n";

		  echo " $query<br/>\n";

		  echo "</div>\n";

	  }



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

	  if (mysqli_num_rows($result))

	  {

		  echo "<div class='textbox' id='graph_link' style='float:right;border:0;display:none;' title='Note that some search criteria will be lost when graphing'></div>\n";



		  ## Start Table

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

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

		  echo "  <tr class='title2'>\n";

		  echo "   <td style='padding:2px;'>";

		  if ($startYr==$endYr) {echo "$startYr ";}

	  	  if ($sub_league_id!="ALL") {echo $subleagues[$sub_league_id]['name']." ";}

		  if ($team_id!="ALL") {echo $teams[$team_id]['name']." ";}

	  	  if ($listing=='top100') {echo "Top ";}

		  else {echo "Bottom ";}

		  if ($scope=='season') {echo "Seasonal ";}

		  else {echo "Cumulative ";}

	  	  if ($stat!="") {echo stat_text($stat)." ";}

		  if ($startYr!=$endYr) {echo "Leaders From $startYr to $endYr";} else {echo "Leaders";}

		  echo "</td>\n";

		  if ($pgCnt>1)

		  {

			  echo "   <td style='text-align:right;vertical-align:top;margin-bottom:0px;padding-bottom:0px;padding-right:2px;' title='$totCnt $view found'>\n";

			  echo "    <table border=0 cellpadding=0 cellspacing=0 style='float:right;'>\n";

			  echo "     <tr class='title2'><td>Page</td>\n";

			  echo "     <td>\n";

			  echo "      <form action='./leaderboards.php' method='GET'>\n";

			  foreach ($_GET as $setting => $val) {echo "       <input type='hidden' name='$setting' value='$val' >\n";}

			  echo "       <select name='page' onchange='this.form.submit()' style='float:right;clear:none;'>\n";

			  for ($i=0;$i<$pgCnt;$i++)

			  {

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

				  if ($page==$i) {echo " selected='selected'";}

				  echo ">".($i+1)."</option>\n";

			  }

			  echo "       </select>\n";

			  echo "      </form>\n";

			  echo "     </td>\n";

			  echo "     <td style='text-align:left;'>of $pgCnt</td></tr>\n";

			  echo "    </table>\n";

			  echo "   </td>\n";

		  }

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

		  echo "  </tr>\n";

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

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

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

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

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

	  	  if ($scope=='season') {echo "<td class='hsc2'>Year</td>";}

		  else {echo "<td class='hsc2'>Years</td>";}

	  	  foreach ($statArray as $key => $statLbl) {echo "<td class='hsc2'>".stat_text($statLbl,2)."</td>";}

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



		  $cnt=0;

  		  $rnk=0;

		  $prevStat="";

  		  while ($row=mysqli_fetch_array($result))

		  {

  			  $tid=$row['team_id'];

			  $year=$row['year'];

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

			  if (($scope=='career')&&(isset($row['year2']))&&($row['year2']!=$year))

  			  {

				  $year2=$row['year2'];

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

			  }

			  $statVal=$row[$stat];



  			  if (count($graphPids)<5) {$graphPids[$tid]=1;}

  

			  ## Update Rank

			  if (($page>0)&&($cnt==0))

			  {

				  $rnkQuery=$cntQuery.=" WHERE $stat";

				  if ($listing=='top100')

				  {

					  if (stat_sort($stat,0,1)=="DESC") {$rnkQuery.="<";}

					  else {$rnkQuery.=">";}

				  }

				  else

				  {

					  if (stat_sort($stat,0,0)=="DESC") {$rnkQuery.=">";}

					  else {$rnkQuery.="<";}

				  }

				  $rnkQuery.=$statVal;

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

				  $rnkResult=mysqli_query($db,$rnkQuery);

				  $rnkRow=mysqli_fetch_array($rnkResult);

				  $rnk=$rnkRow['cnt']+1;

				  $prevStat=$statVal;

			  }

			  elseif ($prevStat!=$statVal)

			  {

  				  $rnk=$page*$pageLimit+$cnt+1;

				  $prevStat=$statVal;

			  }



			  ## Start Row			

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

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

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

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

			  echo "<a href='./team_hist.php?team_id=$tid";

  			  if (($scope=='season')||($year==$row['year2'])) {echo "&page=year&year=$year";}

			  else {echo "&page=index";}

  			  echo "'>$name</a>";

			  echo "</td>";

  			  echo "<td>$year";

			  if (($scope=='career')&&(isset($row['year2']))&&($row['year2']!=$year)) {echo "-".$row['year2'];}

			  echo "</td>";		  



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

			  {

				  $statVal2=$row[$statLbl];

				  $statVal2=stat_format($statLbl,$statVal2);			

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

			  }

  

			  #End row

			  echo "</tr>\n";

  			  $cnt++;

		  }

	  

		  ## Close Table

		  echo "   </table>\n";



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

	  	  echo " </table>\n";

		  echo "</div>\n";

	  }

  	  else

	  {

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

	  }





  }  

		

		

  mysqli_close($db);





  ##### Create Graph Link

  switch ($view)

  {

  case 'players':

	  $statArray=array('batters'=>'Batters','ab'=>'AB','h'=>'H','d'=>'2B','t'=>'3B','hr'=>'HR','rbi'=>'RBI','r'=>'R','sb'=>'SB','cs'=>'CS','bb'=>'BB','k'=>'K','sf'=>'SF','sh'=>'SH','ibb'=>'IBB','hp'=>'HBP','gdp'=>'GIDP','pa'=>'PA','outs'=>'Outs','ebh'=>'EBH','tb'=>'TB','tob'=>'TOB','tto'=>'TTO','pitches_seen'=>'Pitches Seen'                                                              ,'avg'=>'AVG','obp'=>'OBP','slg'=>'SLG','ops'=>'OPS'                                                                                                         ,'pitchers'=>'Pitchers','w'=>'W','l'=>'L','s'=>'SV','ip'=>'IP','g'=>'G','gs'=>'GS','gf'=>'GF','cg'=>'CG','sho'=>'SHO','qs'=>'QS','pk'=>'K','pbb'=>'BB','ha'=>'HA','hra'=>'HR','pr'=>'R','er'=>'ER','hld'=>'HLD','svo'=>'SVO','bs'=>'BS','da'=>'2BA','ta'=>'3BA','bk'=>'BK','wp'=>'WP','hp'=>'HP','bf'=>'BF'                                                           ,'era'=>'ERA','whip'=>'WHIP','kper9'=>'K/9IP','bbper9'=>'BB/9IP','hper9'=>'H/9IP'                                    ,'kperbb'=>'K/BB');

	  break;

  case 'teams':

	  $statArray=array('record'=>'Record','w'=>'Wins','l'=>'Losses','pos'=>'Finish','winpct'=>'Win%','gb'=>'GB','gmovr500'=>'Games over .500','batting'=>'Batting','ab'=>'AB','h'=>'H','d'=>'2B','t'=>'3B','hr'=>'HR','rbi'=>'RBI','r'=>'R','sb'=>'SB','cs'=>'CS','bb'=>'BB','k'=>'K','sf'=>'SF','sh'=>'SH','ibb'=>'IBB','hp'=>'HBP','gdp'=>'GIDP','pa'=>'PA','outs'=>'Outs','ebh'=>'EBH','tb'=>'TB','tob'=>'TOB','tto'=>'TTO','pitches_seen'=>'Pitches Seen'                                                              ,'avg'=>'AVG','obp'=>'OBP','slg'=>'SLG','ops'=>'OPS'                                                                                            ,'pitching'=>'Pitching'                  ,'s'=>'SV','ip'=>'IP','g'=>'G','gs'=>'GS','gf'=>'GF','cg'=>'CG','sho'=>'SHO','qs'=>'QS','pk'=>'K','pbb'=>'BB','ha'=>'HA','hra'=>'HR','pr'=>'R','er'=>'ER','hld'=>'HLD','svo'=>'SVO','bs'=>'BS','da'=>'2BA','ta'=>'3BA','bk'=>'BK','wp'=>'WP','hp'=>'HP','bf'=>'BF'                                                           ,'era'=>'ERA','whip'=>'WHIP','kper9'=>'K/9IP','bbper9'=>'BB/9IP','hper9'=>'H/9IP'                                    ,'kperbb'=>'K/BB');

	  break;

  }

  if (isset($graphPids)&&(count($graphPids)>1)&&($statSplit!='postseason')&&(isset($statArray[$stat])))

  {

	  $pList="";

	  foreach ($graphPids as $pid => $key) {$pList.="|$pid";}

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

	  $link="./carGraphs.php?view=$view&scope=$scope&from=$startYr&to=$endYr&stat=$stat&zeroStats=1&pList=$pList";

	  if (is_numeric($team_id)) {$link.="&team_id=$team_id";}



	  echo "<script type='text/javascript'>";

	  echo " document.getElementById('graph_link').style.display='block';\n";

	  echo " document.getElementById('graph_link').innerHTML=\"<a href='$link'>Graph the Top 5</a>\";\n";

	  echo "</script>\n";

  }





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

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

  if ($view=='players') {echo dispPTJava();}

  page_foot($_SESSION['lgpath']);

  exit;









function dispPTJava()

{

  $txt="";

	## Sorting Javascript

	$txt.="<script type='text/javascript'>\n";

	$txt.="  function setPTstatType(stat) {\n";

	$txt.="	  switch (stat)\n";

	$txt.="	  {\n";

	$txt.="       case 'ab':\n";

	$txt.="       case 'h':\n";

	$txt.="	     case 'd':\n";

	$txt.="	     case 't':\n";

	$txt.="	     case 'hr':\n";

	$txt.="	     case 'rbi':\n";

	$txt.="	     case 'r':\n";

	$txt.="	     case 'sb':\n";

	$txt.="	     case 'cs':\n";

	$txt.="	     case 'bb':\n";

	$txt.="	     case 'k':\n";

	$txt.="	     case 'sf':\n";

	$txt.="	     case 'sh':\n";

	$txt.="	     case 'ibb':\n";

	$txt.="	     case 'hp':\n";

	$txt.="	 	   case 'gdp':\n";

	$txt.="	     case 'pa':\n";

	$txt.="	     case 'outs':\n";

	$txt.="	     case 'ebh':\n";

	$txt.="	     case 'tb':\n";

	$txt.="	     case 'tob':\n";

	$txt.="	     case 'tto':\n";

	$txt.="	     case 'pitches_seen':\n";

	$txt.="	     case 'pipa':\n";

	$txt.="	     case 'abhr':\n";

	$txt.="	     case 'pahr':\n";

	$txt.="	     case 'bbk':\n";

	$txt.="	     case 'avg':\n";

	$txt.="	     case 'obp':\n";

	$txt.="	     case 'slg':\n";

	$txt.="	     case 'ops':\n";

	$txt.="	     case 'iso':\n";

	$txt.="	     case 'bbabip':\n";

	$txt.="	     case 'wOBA':\n";

	$txt.="	     case 'war':\n";

	$txt.="	     case 'pwrspd':\n";

	$txt.="      case 'bsba':\n";

	$txt.="      case 'sbPct':\n";

	$txt.="	     case 'rc':\n";

	$txt.="	     case 'rc27':\n";

	$txt.="	     case 'adj_ops_plus':\n";

	$txt.="	     case 'EqR':\n";

	$txt.="	     case 'EqA':\n";

	$txt.="	       document.getElementById('ptStat').innerHTML='PA';\n";

	$txt.="	       break;\n";

	$txt.="	     case 'fgs':\n";

	$txt.="	     case 'po':\n";

	$txt.="	     case 'a':\n";

	$txt.="	     case 'dp':\n";

	$txt.="	     case 'tp':\n";

	$txt.="	     case 'tc':\n";

	$txt.="	     case 'e':\n";

	$txt.="	     case 'fip':\n";

	$txt.="	     case 'fpct':\n";

	$txt.="	     case 'rng':\n";

	$txt.="	     case 'zr':\n";

	$txt.="	     case 'pb':\n";

	$txt.="	     case 'sba':\n";

	$txt.="	     case 'rto':\n";

	$txt.="	     case 'rtoPct':\n";

	$txt.="	       document.getElementById('ptStat').innerHTML='Inn';\n";

	$txt.="	       break;\n";

	$txt.="	     case 'bink':\n";

	$txt.="	     case 'gink':\n";

	$txt.="	     case 'hof_standards':\n";

	$txt.="	     case 'bSSdiff':\n";

	$txt.="	     case 'pSSdiff':\n";

	$txt.="	       document.getElementById('ptStat').innerHTML='N/A';\n";

	$txt.="	       break;\n";

	$txt.="	     default:\n";

	$txt.="	       document.getElementById('ptStat').innerHTML='IP';\n";

	$txt.="	       break;\n";

	$txt.="	   }\n";

	$txt.="	}\n";

	$txt.="	function setPTind(to) {\n";

	$txt.="	  if (to=='s') {document.getElementById('ptIndicator').innerHTML=' per team game';}\n";

	$txt.="	  else {document.getElementById('ptIndicator').innerHTML='';}\n";

	$txt.="	}\n";

	$txt.="  setPTstatType(document.getElementById('stat')[document.getElementById('stat').selectedIndex].value);\n";

	$txt.="</script>\n";

	return $txt;

}



?>

