<?php
  include("html_functions.php");

  ################## PAGE INITIALIZATION #########################
  $lgid=$_SESSION['lgid'];
  $lgdate=$_SESSION['lgdate'];
  $lgpath=$_SESSION['lgpath'];
  $date=new DateTime($_SESSION['lgdate']);
  $lgyear=$date->format("Y");
  $hmid=$_SESSION['user_id'];
  $orgid=$_SESSION['user_team_id'];
  
  ## Get Draft Date
  include($_SESSION['adminpath']."/dbopen.php");
  $query="SELECT draft_date,DATEDIFF(draft_date,'$lgdate') as diff FROM leagues WHERE league_id=$lgid;";
  $result=mysqli_query($db,$query);
  $row=mysqli_fetch_array($result);
  $ddate=$row['draft_date'];
  $ddateDiff=$row['diff'];
  if ($ddateDiff<0) {$refresh="";}
  else {$refresh="";}
	
  ## Get Ratings Config
  $query="SELECT setting,value FROM ootp_sql_admin WHERE scope IN ('ALL',$lgid) AND module IN ('users','admin','Draft') AND identifier IN (-1,$hmid) AND setting IN ('Ratings','Talents','Others','scoutsOn','rawRatings','auto','auto_list','autoRnd','draftSubscribe','draftOn','timerEnable','showAllUsers')";
  $result=mysqli_query($db,$query);
  if (mysqli_num_rows($result))
  {
	  while ($row=mysqli_fetch_array($result))
	  {
		  $setting=$row['setting'];
		  $settings[$setting]=$row['value'];
	  }
  }
  if (!isset($settings['rawRatings'])) {$settings['rawRatings']=0;}


  ## Check if team is current pick
  $activeTeam=0;
  if ($settings['draftOn']==1)
  {
	  $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 1";
	  if ($_GET['showq']==1) {echo "$query<br/>\n";}
	  $result=mysqli_query($db,$query);
	  if (mysqli_num_rows($result)>0)
	  {
		  $row=mysqli_fetch_array($result);

		  if ($row['team_id']==$orgid)
		  {
			  $TMrnd=$row['round'];
			  $TMsupp=$row['supplemental'];
			  $TMpick=$row['pick_round'];

			  $activeTeam=1;
		  }
	  }
  }

  mysqli_close($db);

  ## Get Team
  if (($_SESSION['user_team_id']>0)&&($_SESSION['user_league_id']==$lgid))  //Controls a team
  {
	  $team_id=$_SESSION['user_team_id'];
  }
  else
  {
	  $hmid=-999;
  }

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

  ## Get Filter Settings
  $rev=0;
  (!isset($_GET['listView'])?$listView='':$listView=$_GET['listView']);
  (!isset($_GET['showPID'])?$showPID='':$showPID=$_GET['showPID']);
  (!isset($_GET['who'])?$who='batters':$who=$_GET['who']);
  (!isset($_GET['view'])?$view='':$view=$_GET['view']);
  (!isset($_GET['statLg'])?$statLg='':$statLg=$_GET['statLg']);
  (!isset($_GET['statView'])?$statView='':$statView=$_GET['statView']);
  (!isset($_GET['minPT'])?$minPT='':$minPT=$_GET['minPT']);
  (!isset($_GET['sort1'])?$sort1='':$sort1=$_GET['sort1']);
  (!isset($_GET['sort2'])?$sort2='':$sort2=$_GET['sort2']);
  (!isset($_GET['sort3'])?$sort3='':$sort3=$_GET['sort3']);
  
  if ($listView=="") {$listView='All';     }
  if ($who=="")      {$who     ="batters"; }
  if ($view=="")
  {
	  if ((!isset($settings['Talents']))||($settings['Talents']=='Hidden')) {$view='stats';}
	  else {$view='talent';}
  }
  if ($statLg=="")   {$statLg  ='All';     }
  if ($statView=="") {$statView='career';  }

  $pview="";
  if ($view=='talent') {$pview='talent_';}
	
  //Sort defaults
  switch ($who)
  {
  case 'pitchers':
  case 11:
  case 12:
  case 13:
	  switch ($view)
	  {
	  case 'overall':
	  case 'talent':
		  $sortList=Array("pitching_ratings_talent_stuff","pitching_ratings_talent_movement","pitching_ratings_talent_control","pitching_ratings_misc_velocity","pitching_ratings_misc_stamina","last_name,first_name","age","lvl","porder");
		  $ratArray=Array("pitching_ratings_".$view."_stuff","pitching_ratings_".$view."_movement","pitching_ratings_".$view."_control","pitching_ratings_misc_velocity","pitching_ratings_misc_stamina","pitching_ratings_pitches_".$pview."fastball","pitching_ratings_pitches_".$pview."slider","pitching_ratings_pitches_".$pview."curveball","pitching_ratings_pitches_".$pview."screwball","pitching_ratings_pitches_".$pview."forkball","pitching_ratings_pitches_".$pview."changeup","pitching_ratings_pitches_".$pview."sinker","pitching_ratings_pitches_".$pview."splitter","pitching_ratings_pitches_".$pview."knuckleball","pitching_ratings_pitches_".$pview."cutter","pitching_ratings_pitches_".$pview."circlechange","pitching_ratings_pitches_".$pview."knucklecurve","pitching_ratings_misc_ground_fly");
		  break;
	  case 'stats':
		  $sortList=Array('pk','era','whip','w','l','s','cg','sho','pg','gs','ip','ha','pr','er','hra','pbb','oavg','babip',"last_name,first_name","age","lvl","porder");
		  $statArray=Array('w','l','s','cg','sho','era','g','gs','ip','ha','r','er','hra','bb','k','whip','oavg','babip');
		  break;
	  }
	  break;
  default:
	  switch ($view)
	  {
	  case 'overall':
	  case 'talent':
		  $sortList=Array('batting_ratings_talent_contact','batting_ratings_talent_power','batting_ratings_talent_eye','batting_ratings_talent_gap','batting_ratings_talent_strikeouts','running_ratings_speed','running_ratings_stealing','running_ratings_baserunning',"last_name,first_name","age","lvl","porder");
		  $ratArray=Array("batting_ratings_".$view."_contact","batting_ratings_".$view."_gap","batting_ratings_".$view."_power","batting_ratings_".$view."_eye","batting_ratings_".$view."_strikeouts");
		  $runArray=Array('running_ratings_speed','running_ratings_stealing','running_ratings_baserunning');
		  $fldArray=Array('fielding_rating_pos2','fielding_rating_pos3','fielding_rating_pos4','fielding_rating_pos5','fielding_rating_pos6','fielding_rating_pos7','fielding_rating_pos8','fielding_rating_pos9','fielding_ratings_catcher_arm','fielding_ratings_infield_arm','fielding_ratings_outfield_arm');
		  break;
	  case 'stats':
		  $sortList=Array('h','hr','bb','g','ab','r','d','t','rbi','k','sb','cs','avg','obp','slg','ops','wOBA',"last_name,first_name","age","lvl","porder");
		  $statArray=Array('g','ab','r','h','d','t','hr','rbi','bb','k','sb','cs','avg','obp','slg','ops','wOBA');
		  $fldArray=Array('fielding_rating_pos2','fielding_rating_pos3','fielding_rating_pos4','fielding_rating_pos5','fielding_rating_pos6','fielding_rating_pos7','fielding_rating_pos8','fielding_rating_pos9','fielding_ratings_catcher_arm','fielding_ratings_infield_arm','fielding_ratings_outfield_arm');
		  break;
	  }
	  break;
  }
  if (!in_array($sort1,$sortList)) {$sort1=$sortList[0];}
  if (!in_array($sort2,$sortList)) {$sort2=$sortList[1];}
  if (!in_array($sort3,$sortList)) {$sort3=$sortList[2];}
	  
  $goName='Go';
  $sortMeth="F";
  if (isset($_GET['sortMeth'])) {$sortMeth=$_GET['sortMeth'];}
  if ($sortMeth=="") {$sortMeth="F";}
  if ($sortMeth=="F") {$nextSort="R";$goName='Reverse';} else {$nextSort="F";}
	
  # Title Bar
  $title='Draft War Room';

  page_head($title,$_SESSION['lgpath'],$refresh,"","./draft.js|https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js|//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js");
  echo " <div id='topbar'>\n";
  main_titlebar($lgid,$_SESSION['lgpath'],$title,$team_id);
  nav_toolbar("draft","Draft");
  echo " </div>   <!-- END topbar DIV -->\n";
  echo " <div id='contentpane'>\n";

  echo " <script type='text/javascript'>\n";
  echo "  var confirmVal=0;\n";
  echo " </script>\n";

  ################## START OF PAGE CONTENT #########################
  if (($_SESSION['user_league_id']!=$lgid)&&($_SESSION['user_is_commish']!=1))
  {
	  echo "<div class='textbox' style='border:0;'>You do not manage a team in this league</div>\n";
	
	  ################## END OF PAGE #########################
	  echo " </div>   <!-- END contentpane DIV -->\n";
	  page_foot($_SESSION['lgpath']);
	  exit;
  }

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

  ## Get player info
    $query="SELECT p.player_id,first_name,last_name,role,position,age";
    $query.=" FROM players as p JOIN ootp_sql_draft_pool as dp ON p.player_id=dp.player_id WHERE dp.league_id=$lgid";
    if ($_GET['showq']==1) {echo "$query<br/>\n";}
    $result=mysqli_query($db,$query);
    if (mysqli_num_rows($result)>0)
    {
        while ($row=mysqli_fetch_array($result))
        {
            $pid=$row['player_id'];
            $players[$pid]['first_name']=$row['first_name'];
            $players[$pid]['last_name']=$row['last_name'];
            $players[$pid]['role']=$row['role'];
            $players[$pid]['position']=$row['position'];
            $players[$pid]['age']=$row['age'];
        }
    }
    
  ## Act As Setting
  if ($_SESSION['user_is_commish']==1)
  {
	  echo "   <div class='textbox' style='float:right;clear:right;width:400px;'>\n";
	  echo "    <table cellpadding=2 cellspacing=0 style='width:100%'>";
	  echo "     <TR class='title'><TD colspan=2>Login As</TD></TR>\n";
	  // Login as
	  echo "     <tr class='s2'>\n";
	  echo "      <td>\n";
	  echo "       <form method='post' onsubmit=\"return checkSelect(document.getElementById('loginAsUser'),document.getElementById('loginPass'));\" action='login.php'>\n";
	  echo "        <input type='hidden' name='login' value='loginAsUser'>\n";
	  echo "        <input type='hidden' name='actAs' value='1'>\n";
	  echo "        <input type='hidden' name='redirect_to' value='./draftWarroom.php'>\n";
	  echo "        <select name='username' id='loginAsUser'>\n";
	  echo "         <option value=0>Please Select User</option>\n";
	  $lastLgID=-1;
	  $query="SELECT hm.*,t.abbr,t.name,t.nickname FROM teams as t RIGHT JOIN (SELECT human_manager_id,is_commish,first_name,last_name,team_id,if(league_id=0,9999,league_id) as league_id FROM human_managers";
	  if ($settings['showAllUsers']!=1) {$query.=" WHERE is_commish=1 OR league_id=$lgid";}
	  $query.=") as hm ON t.team_id=hm.team_id ORDER BY league_id,last_name,first_name";
	  if ($_GET['showq']==1) {echo "$query<br/>\n";}
	  $result=mysqli_query($db,$query);
	  if (mysqli_num_rows($result)>0)
	  {
		  while ($row=mysqli_fetch_array($result))
		  {
			  if ($row['team_id']>0) {$tname=$row['abbr'];}
			  elseif ($row['is_commish']==1) {$tname="CMSH";}
			  else {$tname="N/A";}
		
			  $human_manager_id=$row['human_manager_id'];

			  $league_id=$row['league_id'];
			  if (($lastLgID!=$league_id)&&($league_id==9999)) {echo "      <optgroup label='Unaffiliated'>\n";}

			  echo "         <option value='$human_manager_id'>";
			  echo $row['first_name']." ".$row['last_name']." (".$row['name']." ".$row['nickname'].")";
			  echo "</option>\n";

			  $lastLgID=$league_id;
		  }
	  }
	  echo "        </select>\n";
	  echo "       </td>\n";
	  echo "       <td>\n";
	  echo "        <input type='submit' value='Go'>\n";
	  echo "       </form>\n";
	  echo "      </td></tr>\n";
	  echo "    </table>\n";
	  echo "   </div>\n";
  }

  ## User Draft List & Settings
  echo "<div class='textbox' style='clear:both;'>\n";
  echo "  <form method='post' action='save_settings.php'>\n";
  echo "   <input type='hidden' name='module' value='Draft_Warroom' />\n";
  echo "   <input type='hidden' name='hmid' value='".$_SESSION['user_id']."' />\n";
  echo "   <input type='hidden' name='redirect_to' value='./draftWarroom.php";
  $cnt=0;
  foreach ($_GET as $key => $val)
  {
	  if ($cnt==0) {echo "?";} else {echo "&";}
	  echo "$key=$val";
	  $cnt++;
  }
  echo "' />\n";
  if ($_GET['showq']==1) {echo "   <input type='hidden' name='debug' value='1' />\n";}
  echo " <table cellpadding=2 cellspacing=0 style='width:100%'>";
  echo "  <tr class='title'><td colspan=5>Team Settings</td></tr>\n";
  echo "  <tr>\n";
  echo "   <td colspan=2><b>Draft List</b></td>\n";
  echo "   <td colspan=3><b>Preferences</b></td>\n";
  echo "  </tr>\n";
  echo "  <tr>\n";
  //Draft List
  $noDL=0;
  echo "   <td rowspan=5>\n";
  echo "    <input type='hidden' name='dList' id='dList' />\n";
  echo "    <select id='draftList' name='draftList[]' multiple='multiple' size=10 style='width:200px;'";
  if ($activeTeam==1) {echo " onchange=\"listClick(this,'$lgpath');\"";}
  echo ">\n";
  //$query="SELECT position,role,p.player_id,first_name,last_name,porder FROM players as p,(";
  //$query.="SELECT dl.player_id,porder FROM ootp_sql_draft_list as dl LEFT JOIN amateur_draft as ad ON dl.player_id=ad.player_id WHERE human_manager_id=$hmid AND ad.player_id IS NULL";
  //$query.=") as x WHERE p.player_id=x.player_id ORDER BY porder";
    $query="SELECT dl.player_id,porder FROM ootp_sql_draft_list as dl LEFT JOIN amateur_draft as ad ON dl.player_id=ad.player_id WHERE human_manager_id=$hmid AND ad.player_id IS NULL ORDER BY porder";
    if ($_GET['showq']==1) {echo "$query<br/>\n";}
  $result=mysqli_query($db,$query);
  if (mysqli_num_rows($result)>0)
  {
	  $rowCnt=1;
	  while ($row=mysqli_fetch_array($result))
	  {
		  $pid=$row['player_id'];
		  $listOrder[$pid]=$rowCnt;

		  echo "     <option value=$pid>$rowCnt. ";
		  if ($players[$pid]['position']==1) {echo get_pos($players[$pid]['role'],1);} else {echo get_pos($players[$pid]['position'],1);}
		  echo " ".$players[$pid]['first_name']." ".$players[$pid]['last_name'];
		  echo "</option>\n";

		  $rowCnt++;
	  }
  }
  else
  {
	  echo "      <option value=0>Select a player below</option>\n";
	  $noDL=1;
  }
  echo "    </select>\n";
  echo "   </td>\n";
  echo "    <td><input type='button' onclick=\"view(document.getElementById('draftList'),'".$lgpath."/players/player_');\" value='View'></input></td>\n";
  echo "    <td><input type='checkbox' name='auto_list' value=1";
  if ($settings['auto_list']==1) {echo " checked";}
  echo "></td>\n";
  echo "    <td colspan=2>Auto Draft From List</td>\n";
  echo "   </tr>\n";
  echo "   <tr>\n";
  echo "    <td><input type='button' onclick=\"moveUp(document.getElementById('draftList'));confirmVal=1;\" value='Up'></input></td>\n";
  echo "    <td><input type='checkbox' name='auto' value=1";
  if ($settings['auto']==1) {echo " checked";}
  echo "></td>\n";
  echo "    <td>Auto Draft After Round</td>\n";
  echo "    <td>";
  echo "     <select name='autoRnd'>\n";
  echo "      <option value=0>All</option>\n";
  $query="SELECT round,supplemental FROM amateur_draft WHERE league_id=100 GROUP BY round,supplemental ORDER BY round,supplemental";
  if ($_GET['showq']==1) {echo "$query<br/>\n";}
  $result=mysqli_query($db,$query);
  if (mysqli_num_rows($result)>0)
  {
	  $rowCnt=1;
	  while ($row=mysqli_fetch_array($result))
	  {
		  $rnd=$row['round'];
		  if ($row['supplemental']==1) {$rnd="S".$rnd;}
		  echo "      <option value=$rnd";
		  if ($rnd==$settings['autoRnd']) {echo " selected";}
      		  echo ">$rnd</option>\n";
	  }
  }
  echo "     </select>\n";
  echo "    </td>\n";
  echo "   </tr>\n";
  echo "   <tr>\n";
  echo "    <td><input type='button' onclick=\"moveDown(document.getElementById('draftList'));confirmVal=1;\" value='Down'></input></td>\n";
  echo "    <td><input type='checkbox' name='draftSubscribe' value=1";
  if ($settings['draftSubscribe']==1) {echo " checked";}
  echo "></td>\n";
  echo "    <td colspan=2>Subscribe to draft updates</td>\n";
  echo "   </tr>\n";
  echo "   <tr>\n";
  echo "    <td><input type='button' onclick=\"removeFromList(document.getElementById('draftList'));confirmVal=1;\" value='Remove'></input></td>\n";
  echo "    <td colspan=3 style='padding-left:8px'><a href='./draft_results_export.php'>Export Draft Order & Results</a></td>\n";
  echo "   </tr>\n";
  echo "   <tr>\n";
  echo "    <td><input type='submit' onclick=\"moveList(document.getElementById('draftList'), document.getElementById('dList'));\" value='Save'></input>\n";
  echo "    <td colspan=3 style='padding-left:8px'>Export: <a href='./draft_list_export.php'>Draft List</a> / <a href='./draft_pool_export.php'>Entire Draft Pool</a></td>\n";
  echo "   </tr>\n";
  echo "  </form>\n";
  echo " </table>\n";
  echo " <hr>\n";
  echo "  <table cellspacing=0 cellpadding=2 border=0>\n";
  echo "   <tr>\n";
  echo "    <td>\n";
  echo "     <form enctype=\"multipart/form-data\" action=\"draft_list_import.php\" method=\"POST\" onsubmit=\"return confirm('Are you sure you want to overwrite your draft list and replace it with the uploaded file?')\">\n";
  echo "      <label for='uploaded'>Import Draft List:</label> <input name=\"uploaded\" type=\"file\" />\n";
  echo "      <input type=\"submit\" value=\"Upload\" />\n";
  echo "     </form>\n";
  echo "    </td>\n";
  echo "   </tr>\n";
  echo "  </table>\n";
  echo "</div>\n";

  ## User Draft Picks
  echo "<div class='textbox' style='float:right;clear:right;width:400px;max-height:280px;overflow:auto;'>\n";
  echo " <table cellpadding=2 cellspacing=0 style='width:100%'>";
  echo "  <tr class='title'><td colspan=4>Draft Picks</td></tr>\n";
  echo "  <tr class='headline'>\n";
  echo "   <td class='hsc2'>Rnd</td>\n";
  echo "   <td class='hsc2'>Pick</td>\n";
  echo "   <td class='hsc2'>Pos</td>\n";
  echo "   <td class='hsc2_l'>Player</td>\n";
  echo "  </tr>\n";
    //$query="SELECT position,role,first_name,last_name,x.* FROM players as p RIGHT JOIN (SELECT round,supplemental,pick_round,player_id,pick_time FROM amateur_draft WHERE league_id=$lgid AND team_id=".max(0,$team_id).") as x ON p.player_id=x.player_id ORDER BY round,supplemental,pick_round";
    $query="SELECT round,supplemental,pick_round,player_id,pick_time FROM amateur_draft WHERE league_id=$lgid AND team_id=".max(0,$team_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)>0)
  {
	  $rowCnt=0;
	  while ($row=mysqli_fetch_array($result))
	  {
		  $rnd=$row['round'];
		  $supp=$row['supplemental'];
		  $pick=$row['pick_round'];
			  
		  $pid=$row['player_id'];
		  $dueTime=$row['pick_time'];

		  $cls='s'.($rowCnt%2+1);
		  
		  echo "  <tr class='$cls'>";
		  echo "<td>";
		  if ($supp==1) {echo "S";}
		  echo "$rnd</td>";
		  echo "<td>$pick</td>";
		  if ((is_numeric($pid))&&($pid>0))
		  {
			  $pos=$players[$pid]['position'];
			  if ($pos==1) {$pos=get_pos($players[$pid]['role'],1);} else {$pos=get_pos($pos,1);}
			  echo "<td>$pos</td>";
			  echo "<td class='".$cls."_l'><a href='$lgpath/players/player_$pid.html'>".$players[$pid]['first_name']." ".$players[$pid]['last_name']."</a></td>";
		  }
		  elseif ($pid<0)
		  {
			  echo "<td>&nbsp;</td>";
			  echo "<td class='".$cls."_l'>";
			  switch ($pid)
			  {
			  case -998: echo " - Passed - "; break;
			  case -999: echo " - Skipped - "; break;
			  }
			  echo "</td>";
		  }
		  else
		  {
              echo "<td colspan=2 style='text-align:center;'>";
              if ($settings['timerEnable']==1) {echo "$dueTime";} else {echo "&nbsp;";}
              echo "</td>";
		  }
		  echo "</tr>\n";

		  $rowCnt++;
	  }
  }
  else {echo "  <tr><td colspan=4 style='text-align:center;'>You have no picks</td></tr>\n";}
  echo " </table>\n";
  echo "</div>\n";

  ## Filters
  echo "<div class='textbox'>\n";
  echo " <table cellpadding=0 cellspacing=0 border=0 width='935px'>\n";
  echo "  <tr class='title'><td style='padding:2px;'>Action</td><td colspan=10 style='padding:2px;'>Filters</td></tr>\n";
  echo "  <tr>\n";
  echo "   <td rowspan=2 style='border-right:1px solid #AAAAAA;'>\n";

  echo "    <table cellpadding=0 cellspacing=0 border=0>\n";
  echo "     <tr><td><div class='draftSelection' id='draftSelection'></div></td></tr>\n";
  echo "     <tr>\n";
  echo "      <td>\n";
  if ($activeTeam==1)
  {
	  echo "   <form method='get' onsubmit=\"return pickPlayer();\" action='draftProcess.php'>\n";
	  echo "    <input type='hidden' name='rnd' value=$TMrnd></input>\n";
	  echo "    <input type='hidden' name='supp' value=$TMsupp></input>\n";
	  echo "    <input type='hidden' name='pick' value=$TMpick></input>\n";
	  echo "    <input type='hidden' name='team_id' value=$orgid></input>\n";
	  echo "    <input type='hidden' name='player_id' id='draftPID' value=0></input>\n";
	  echo "    <input type='hidden' name='player_name' id='draftName' value=''></input>\n";
	  echo "    <input type='submit' value='Draft Player' />\n";
	  echo "   </form>\n";

	  echo "   <form method='get' action='draftProcess.php'>\n";
	  echo "    <input type='hidden' name='rnd' value=$TMrnd></input>\n";
	  echo "    <input type='hidden' name='supp' value=$TMsupp></input>\n";
	  echo "    <input type='hidden' name='pick' value=$TMpick></input>\n";
	  echo "    <input type='hidden' name='team_id' value=$orgid></input>\n";
	  echo "    <input type='hidden' name='player_id' id='draftPID' value=-998></input>\n";
	  echo "    <input type='submit' value='Pass' />\n";
	  echo "   </form>\n";
  }
  else {echo "&nbsp;";}
  echo "      </td>\n";
  echo "     </tr>\n";
  echo "    </table>\n";

  echo "   </td>\n";
  echo "  <form method='get' id='draftFilters' action='draftWarroom.php' class='inline' onsubmit=\"if (confirmVal==1) {return confirm('Are you sure you wish to continue?\\n\\nYou will lose any unsaved draft list changes!');} else {return 1;}\">\n";
  echo "   <td><label for='listView'>Show:</label></td>\n";
  echo "   <td colspan=2>\n";
  echo "    <select name='listView' id='listView' onchange=\"document.getElementById('sortMethObj').value='F'; document.getElementById('filterGo').value='Go';\">\n";
  echo "     <option value='All'";
  if ($listView=="All") {echo " selected";}
  echo ">All Players</option>\n";
  if ($noDL!=1)
  {
	  echo "     <option value='NonList'";
	  if ($listView=="NonList") {echo " selected";}
	  echo ">Exclude Players On Draft List</option>\n";
	  echo "     <option value='List'";
	  if ($listView=="List") {echo " selected";}
	  echo ">Only Players On Draft List</option>\n";
  }
  echo "    </select>\n";
  echo "   </td>\n";
  echo "   <td colspan=2>&nbsp;</td>\n";
  echo "   <td><input type='checkbox' name='showPID' id='showPID' value=1";
  if ($showPID==1) {echo " checked='yes' ";}
  echo " onchange=\"document.getElementById('sortMethObj').value='F'; document.getElementById('filterGo').value='Go';\" /></td>\n";
  echo "   <td><label for='showPID' title='Show Player ID - use with draft list import'>Show PID</label></td>\n";
  echo "   <td>&nbsp;</td>\n";

  echo "  </tr><tr>\n";
  
  echo "   <td><label for='who'>Who:</label></td>\n";
  echo "   <td>\n";
  echo "    <select name='who' id='whoObj' onchange=\"whoChange(); document.getElementById('sortMethObj').value='F'; document.getElementById('filterGo').value='Go';\"";
  echo " title='Position determined by defensive ratings, except for stats view, where it's determined by player setting'";
  echo ">\n";
  echo "     <option value='batters'";
  if ($who=="batters") {echo " selected";}
  echo ">Batters</option>\n";
  echo "     <option value='pitchers'";
  if ($who=="pitchers") {echo " selected";}
  echo ">Pitchers</option>\n";
  for ($i=2;$i<=13;$i++)
  {
	  echo "     <option value=".$i;
       	  if ($who==$i) {echo " selected";}
	  echo ">".get_pos($i,1)."</option>\n";
  }
  echo "    </select>\n";
  echo "   </td>\n";
  echo "   <td>\n";
  echo "    <select name='view' id='viewObj' onchange=\"whoChange(); document.getElementById('sortMethObj').value='F'; document.getElementById('filterGo').value='Go';\" >\n";
  if (($settings['Ratings']!=0)||($settings['Others']!=0))
  {
	  echo "     <option value='overall'";
 	  if ($view=="overall") {echo " selected";}
	  echo ">Ratings</option>\n";
  }
  if (($settings['Talents']!=0)||($settings['Others']!=0))
  {
	  echo "     <option value='talent'";
 	  if ($view=="talent") {echo " selected";}
	  echo ">Potential</option>\n";
  }
  echo "     <option value='stats'";
  if ($view=="stats") {echo " selected";}
  echo ">Stats</option>\n";
  echo "    </select>\n";
  echo "   </td>\n";
  
  ## Stats Filter
  echo "   <td><label>Stats From:</td>\n";
  echo "   <td colspan>\n";
  echo "    <select name='statLg' id='statLg' onchange=\"document.getElementById('sortMethObj').value='F'; document.getElementById('filterGo').value='Go';\" title='League level'>\n";
  echo "     <option value='All'";
  if ($statLg=="All") {echo " selected";}
  echo ">All</option>\n";
  echo "     <option value='9'";
  if ($statLg=="9") {echo " selected";}
  echo ">COL</option>\n";
  echo "     <option value='10'";
  if ($statLg=="10") {echo " selected";}
  echo ">HS</option>\n";
  echo "    </select>\n";
  echo "   </td>\n";
  echo "   <td colspan>\n";
  echo "    <select name='statView' id='statView' onchange=\"document.getElementById('sortMethObj').value='F'; document.getElementById('filterGo').value='Go';\" title='Stats to display'>\n";
  echo "     <option value='career'";
  if ($statView=="career") {echo " selected";}
  echo ">Career</option>\n";
  echo "     <option value='lastyr'";
  if ($statView=="lastyr") {echo " selected";}
  echo ">Last Year</option>\n";
  echo "     <option value='thisyr'";
  if ($statView=="thisyr") {echo " selected";}
  echo ">This Year</option>\n";
  echo "    </select>\n";
  echo "   </td>\n";
  echo "   <td><label for='minPT'>Min PA/IP:</label></td>\n";
  echo "   <td><input type='text' name='minPT' id='minPT' maxlength=4 size=4 value='$minPT' onchange=\"document.getElementById('sortMethObj').value='F'; document.getElementById('filterGo').value='Go';\" title='Minimum playing time for inclusion' /></td>\n";

  echo "  </tr><tr>\n";
  echo "   <td style='border-right:1px solid #AAAAAA;border-top:1px dotted #AAAAAA;'>\n";
  echo "    <input type='button' onclick=\"addToList(document.getElementById('draftList'),document.getElementById('plisting'));confirmVal=1;\" value='Add To List'></input>\n";
  echo "   </td>\n";
  
  ## Data Sorts
  $dataSorts=array('both'=>'Both','last_name,first_name'=>'Name','age'=>'Age','porder'=>'Draft List','batters'=>'Batters','batting_ratings_talent_contact'=>'Contact','batting_ratings_talent_gap'=>'Gap','batting_ratings_talent_power'=>'Power','batting_ratings_talent_eye'=>'Eye','batting_ratings_talent_strikeouts'=>'Strikeouts','running_ratings_speed'=>'Speed','running_ratings_stealing'=>'Stealing','running_ratings_baserunning'=>'Baserunning','pitchers'=>'Pitchers','pitching_ratings_talent_stuff'=>'Stuff','pitching_ratings_talent_movement'=>'Movement','pitching_ratings_talent_control'=>'Control','pitching_ratings_misc_velocity'=>'Velocity','pitching_ratings_misc_stamina'=>'Stamina','bStats'=>'Batter Stats','g'=>'G','ab'=>'AB','r'=>'R','h'=>'H','d'=>'2B','t'=>'3B','hr'=>'HR','rbi'=>'RBI','bb'=>'BB','k'=>'K','sb'=>'SB','cs'=>'CS','avg'=>'AVG','obp'=>'OBP','slg'=>'SLG','ops'=>'OPS','wOBA'=>'wOBA','pStats'=>'Pitcher Stats','w'=>'W','l'=>'L','s'=>'SV','cg'=>'CG','sho'=>'SHO','era'=>'ERA','pg'=>'G','gs'=>'GS','ip'=>'IP','ha'=>'HA','pr'=>'R','er'=>'ER','hra'=>'HR','pbb'=>'BB','pk'=>'K','whip'=>'WHIP','oavg'=>'OAVG','babip'=>'BABIP');

  echo "    <td><label for='sort1'>Sort by:</label><input type='hidden' value='$nextSort' name='sortMeth' id='sortMethObj' /></td>\n";
  echo "    <td>\n";
  echo "     <select name='sort1' id='sort1Obj' onchange=\"document.getElementById('sortMethObj').value='F'; document.getElementById('filterGo').value='Go';\" >\n";
  foreach ($dataSorts as $key=>$val)
  {
       	  if (($key=='both')||($key=='batters')||($key=='pitchers')||($key=='bStats')||($key=='pStats')) {echo "      <optgroup label='$val'>\n";}
	  else
      	  {
		  echo "      <option value='$key'";
		  if ($sort1==$key) {echo " selected";}
		  if ((!in_array($key,$sortList))&&($val!="Name")) {echo " disabled style='color:graytext;'";}
		  echo ">$val</option>\n";
      	  }
  }
  echo "     </select>\n";
  echo "    </td>\n";
  echo "    <td><label for='sort2'>then by:</label></td>\n";
  echo "    <td>\n";
  echo "     <select name='sort2' id='sort2Obj' onchange=\"document.getElementById('sortMethObj').value='F'; document.getElementById('filterGo').value='Go';\" >\n";
  foreach ($dataSorts as $key=>$val)
  {
	  if (($key=='both')||($key=='batters')||($key=='pitchers')||($key=='bStats')||($key=='pStats')) {echo "      <optgroup label='$val'>\n";}
      	  else
	  {
	    	  echo "      <option value='$key'";
		  if ($sort2==$key) {echo " selected";}
		  if ((!in_array($key,$sortList))&&($val!="Name")) {echo " disabled style='color:graytext;'";}
		  echo ">$val</option>\n";
      	  }
  }
  echo "     </select>\n";
  echo "    </td>\n";
  echo "    <td><label for='sort3'>then by:</label></td>\n";
  echo "    <td>\n";
  echo "     <select name='sort3' id='sort3Obj' onchange=\"document.getElementById('sortMethObj').value='F'; document.getElementById('filterGo').value='Go';\" >\n";
  foreach ($dataSorts as $key=>$val)
  {
	  if (($key=='both')||($key=='batters')||($key=='pitchers')||($key=='bStats')||($key=='pStats')) {echo "      <optgroup label='$val'>\n";}
      	  else
	  {
	    	  echo "      <option value='$key'";
		  if ($sort3==$key) {echo " selected";}
		  if ((!in_array($key,$sortList))&&($val!="Name")) {echo " disabled style='color:graytext;'";}
		  echo ">$val</option>\n";
      	  }
  }
  echo "     </select>\n";
  echo "    </td>\n";
  
  ## Close Form
  echo "   <td colspan=2>\n";
  if ($_GET['showq']==1) {echo "    <input type='hidden' name='showq' value=1></input>\n";}
  echo "    <input type='submit' class='submitButton' id='filterGo' value='$goName' />\n";
  echo "   </td>\n";
  echo "  </form>\n";
  echo "  </tr>\n";
  echo " </table>\n";
  echo "</div>\n";

  ##### Player Listing #####
  # Adjust sorts if needed
  if ($view=="overall")
  {
	  $sort1=str_replace("_talent_","_overall_",$sort1);
	  $sort2=str_replace("_talent_","_overall_",$sort2);
	  $sort3=str_replace("_talent_","_overall_",$sort3);
  }
  switch ($sort1)
  {
  case 'pk': $sort1="k"; break;
  case 'pg': $sort1="g"; break;
  case 'pr': $sort1="r"; break;
  case 'pbb': $sort1="bb"; break;
  }
  switch ($sort2)
  {
  case 'pk': $sort2="k"; break;
  case 'pg': $sort2="g"; break;
  case 'pr': $sort2="r"; break;
  case 'pbb': $sort2="bb"; break;
  }
  switch ($sort3)
  {
  case 'pk': $sort3="k"; break;
  case 'pg': $sort3="g"; break;
  case 'pr': $sort3="r"; break;
  case 'pbb': $sort3="bb"; break;
  }

  ## Get Player Query
  $pQuery="";
  switch ($who)
  {
  case 'batters':
  case 'pitchers':
  case 11:
  case 12:
  case 13:
	  $pQuery.="SELECT p.player_id FROM players as p,(";
	  break;
  default:
	  $pQuery.="SELECT p.player_id FROM players_fielding as p,(";
	  break;
  }
  switch ($listView)
  {
  case 'All':
	  $pQuery.="SELECT dp.player_id FROM ootp_sql_draft_pool as dp LEFT JOIN amateur_draft as ad ON dp.player_id=ad.player_id WHERE dp.league_id=$lgid AND ad.player_id IS NULL";
	  break;
  case 'List':
	  $pQuery.="SELECT dp1.player_id FROM (SELECT dp.player_id,dp.league_id FROM ootp_sql_draft_pool as dp,ootp_sql_draft_list as dl WHERE dp.league_id=$lgid AND dp.player_id=dl.player_id AND human_manager_id=$hmid) as dp1 LEFT JOIN amateur_draft as ad ON dp1.player_id=ad.player_id WHERE dp1.league_id=$lgid AND ad.player_id IS NULL";
	  break;
  case 'NonList':
	  $pQuery.="SELECT dp1.player_id FROM (SELECT dp.player_id,porder FROM (SELECT player_id FROM ootp_sql_draft_pool WHERE league_id=$lgid) as dp LEFT JOIN (SELECT player_id,porder FROM ootp_sql_draft_list WHERE human_manager_id=$hmid AND league_id=$lgid) as dl ON dp.player_id=dl.player_id) as dp1 LEFT JOIN amateur_draft as ad ON dp1.player_id=ad.player_id WHERE ad.player_id IS NULL AND porder IS NULL";
	  break;
  }
  $pQuery.=") as pqp WHERE p.player_id=pqp.player_id";
  switch ($who)
  {
  case 'batters':
      $pQuery.=" AND position!=1";
      break;
  case 'pitchers':
	  $pQuery.=" AND position=1";
	  break;
  case 11:
  case 12:
  case 13:
	  $pQuery.=" AND role=$who";
	  break;
	  break;
  default:
	  $pQuery.=" AND fielding_rating_pos$who>0";
	  break;
  }

  ## Generate Query
  # Get Fielding Ratings
  if ($view!="stats")
  {
	$query="";
	switch ($who)
	{
		case 'pitchers':
		case 11:
		case 12:
		case 13:
			break;
		default:
			$query.="SELECT pf.* FROM (";
			# Fielding Ratings Query
			$query.="SELECT player_id";
			foreach ($fldArray as $key => $ratLbl)
			{
                # Get scale
                if ($settings['rawRatings']==1)
                {
                    $ratScale=get_scale($ratLbl);
                    $scale=$settings[$ratScale];
                }
                else {$scale='Raw';}

				# Add to query
				$query.=",";
				$query.=ratings_query($ratLbl,$scale);
				$query.=" as $ratLbl";
			}
			$query.=" FROM players_fielding";
			if ($settings['scoutsOn']==1) {$query.="_scouted";}
			$query.=") as pf";
	  
			$query.=" JOIN (";
			$query.=$pQuery;
			$query.=") as pool ON pf.player_id=pool.player_id";
	  
			if ($_GET['showq']==1) {echo "$query<br/>\n";}
			$result=mysqli_query($db,$query);

			if (mysqli_num_rows($result)>0)
			{
				while ($row=mysqli_fetch_array($result))
				{
					$pid=$row['player_id'];
					foreach ($fldArray as $key => $ratLbl) {$players[$pid][$ratLbl]=$row[$ratLbl];}
				}
			}
			break;
		}
  }
  
  # Get Primary Stats/Ratings
  $query="";
  $query.="SELECT px.player_id,first_name,last_name,position,role,age,porder,slot";
  if (isset($statArray)) {foreach ($statArray as $key => $statLbl) {$query.=",$statLbl";}}
  if (isset($ratArray)) {foreach ($ratArray as $key => $statLbl) {$query.=",$statLbl";}}
  if (isset($runArray)) {foreach ($runArray as $key => $statLbl) {$query.=",$statLbl";}}
  $query.=" FROM (";
  switch ($view)
  {
  case 'stats':
	  $query.="SELECT player_id";
	  foreach ($statArray as $key => $statLbl) {$query.=",".stat_query($statLbl)." as $statLbl";}
	  $query.=" FROM ";
	  switch ($who)
	  {
	  case 'pitchers':
	  case 11:
	  case 12:
	  case 13:
		  $query.="players_career_pitching_stats";
		  break;
	  default:
		  $query.="players_career_batting_stats";
		  break;
	  }
	  $query.=" WHERE split_id=1";
	  if (is_numeric($statLg)) {$query.=" AND level_id=$statLg";} else {$query.=" AND level_id IN (10,11)";}
	  switch ($statView)
	  {
	  case 'thisyr':
		  $query.=" AND year=$lgyear";
		  break;
	  case 'lastyr':
		  $query.=" AND year=".($lgyear-1);
		  break;
	  }
	  $query.=" GROUP BY player_id";
	  if ((is_numeric($minPT))&&($minPT>0))
	  {
		  switch ($who)
		  {
		  case 'pitchers':
		  case 11:
		  case 12:
		  case 13:
			  $query.="HAVING ".stat_query("ip").">$minPT";
			  break;
		  default:
			  $query.="HAVING ".stat_query("pa").">$minPT";
			  break;
		  }
	  }
	  break;
  default:
	  $query.="SELECT player_id";
	  foreach ($ratArray as $key => $ratLbl)
	  {
		  if ($view=='overall')
		  {
			  $ratLbl=str_replace("_pitches_talent_","_pitches_",$ratLbl);
			  $ratLbl=str_replace("_talent_","_overall_",$ratLbl);
		  }

          # Get scale
          if ($settings['rawRatings']==1)
          {
              $ratScale=get_scale($ratLbl);
              $scale=$settings[$ratScale];
          }
          else {$scale='Raw';}

		  # Add to query
		  $query.=",";
		  $query.=ratings_query($ratLbl,$scale);
		  $query.=" as $ratLbl";
	  }
	  switch ($who)
	  {
	  case 'pitchers':
	  case 11:
	  case 12:
	  case 13:
          $query.=" FROM ";
		  $query.="players_pitching";
		  break;
	  default:
          foreach ($runArray as $key => $ratLbl)
          {
              # Get scale
              if ($settings['rawRatings']==1)
              {
                  $ratScale=get_scale($ratLbl);
                  $scale=$settings[$ratScale];
              }
              else {$scale='Raw';}

              # Add to query
              $query.=",";
              $query.=ratings_query($ratLbl,$scale);
              $query.=" as $ratLbl";
          }
          $query.=" FROM ";
		  $query.="players_batting";
		  break;
	  }
	  if ($settings['scoutsOn']==1) {$query.="_scouted";}
	  break;

  }
  $query.=") as ps RIGHT JOIN (";
  # Get Player Info
  $query.="SELECT first_name,last_name,position,role,age";
  $query.=",pp.* FROM players as p,(";
  # Get Player Pool
  switch ($listView)
  {
  case 'All':
	  $query.="SELECT dp2.* FROM (SELECT dp1.player_id,if(dl.human_manager_id<0,999999,if(porder IS NULL,999999,porder)) as porder,slot FROM (SELECT dp.player_id,slot FROM ootp_sql_draft_pool as dp LEFT JOIN amateur_draft as ad ON dp.player_id=ad.player_id WHERE dp.league_id=$lgid AND ad.player_id IS NULL) as dp1 LEFT JOIN ootp_sql_draft_list as dl ON dp1.player_id=dl.player_id WHERE human_manager_id IN ($hmid,-999,NULL) ORDER BY porder) as dp2 GROUP BY player_id";
	  break;
  case 'List':
	  $query.="SELECT dp1.player_id,if(porder IS NULL,999999,porder) as porder,slot FROM (SELECT dp.player_id,dp.league_id,porder,slot FROM ootp_sql_draft_pool as dp,ootp_sql_draft_list as dl WHERE dp.league_id=$lgid AND dp.player_id=dl.player_id AND human_manager_id=$hmid) as dp1 LEFT JOIN amateur_draft as ad ON dp1.player_id=ad.player_id WHERE dp1.league_id=$lgid AND ad.player_id IS NULL";
	  break;
  case 'NonList':
	  $query.="SELECT dp1.player_id,999999 as porder,slot FROM (SELECT dp.player_id,dp.league_id,porder,slot FROM ootp_sql_draft_pool as dp LEFT JOIN (SELECT player_id,league_id,porder FROM ootp_sql_draft_list WHERE human_manager_id=$hmid AND league_id=$lgid) as dl ON dp.player_id=dl.player_id WHERE dp.league_id=$lgid) as dp1 LEFT JOIN amateur_draft as ad ON dp1.player_id=ad.player_id WHERE dp1.league_id=$lgid AND ad.player_id IS NULL AND porder IS NULL";
	  break;
  }
  $query.=") as pp";
  # Combine with players
  $query.=" WHERE p.player_id=pp.player_id";
  switch ($who)
  {
  case 'batters':
      $query.=" AND position!=1";
      break;
  case 'pitchers':
	  $query.=" AND position=1";
	  break;
  case 11:
  case 12:
  case 13:
	  $query.=" AND role=$who";
	  break;
	  break;
  default:
      $query.=" AND position=$who";
	  break;
  }
  $query.=") as px";
  # Combine with stats
  $query.=" ON ps.player_id=px.player_id";

  
  # Apply Sorts
  if ($sortMeth=="R") {$rev=1;}
  $query.=" ORDER BY ";
  if ($sort1=="last_name,first_name")
  {
	  if ($sortMeth=="R") {$query.="last_name DESC,first_name DESC";}
	  else {$query.=$sort1;}
  }
  else
  {
	  $query.="$sort1 ".stat_sort($sort1,"",$rev);
  }
  if ($sort2=="last_name,first_name")
  {
	  if ($sortMeth=="R") {$query.=",last_name DESC,first_name DESC";}
	  else {$query.=",".$sort2;}
  }
  else
  {
	  $query.=",$sort2 ".stat_sort($sort2,"",$rev);
  }
  if ($sort3=="last_name,first_name")
  {
	  if ($sortMeth=="R") {$query.=",last_name DESC,first_name DESC";}
	  else {$query.=",".$sort3;}
  }
  else
  {
	  $query.=",$sort3 ".stat_sort($sort3,"",$rev);
  }
  if (($sort1!="last_name,first_name")&&($sort2!="last_name,first_name")&&($sort3!="last_name,first_name")) {$query.=",last_name,first_name";}
  	
  # Run Query
  if ($_GET['showq']==1) {echo "$query<br/>\n";}
  $result=mysqli_query($db,$query);

  # Display Results
  echo "<div class='textbox noborder' style='width:100%;'>\n";
  echo " <div class='title2' style='width:100%;margin:0;padding:2px;'>";
  if (is_numeric($who)) {echo get_pos($who);}
  else {echo ucwords($who);}
  switch ($view)
  {
  case 'overall':
	  echo " Ratings (Overall)";
	  if ($settings['scoutsOn']==1) {echo " - Scouted by StatsLab";}
	  break;
  case 'talent':
	  echo " Ratings (Potential)";
	  if ($settings['scoutsOn']==1) {echo " - Scouted by StatsLab";}
	  break;
  case 'stats':
	  echo " Stats";
	  break;
  }
  echo "</div>\n";
  echo " <div style='width:100%;margin:0;padding:2px;'>\n";
  echo "<a href='draft_pool_export_data.php?";
  echo "listView=$listView";
  echo "&who=$who";
  echo "&view=$view";
  echo "&statLg=$statLg";
  echo "&statView=$statView";
  echo "&minPT=$minPT";
  echo "&sort1=$sort1";
  echo "&sort2=$sort2";
  echo "&sort3=$sort3";
  echo "'>Export these results</a>";
  echo "</div>\n";
  
  echo "<form id='plisting'>\n";
  echo " <table id=\"draftPoolTable\" class='dataTable'>\n";
  echo "  <thead>\n";
  echo "   <tr>";
  echo "<th>&nbsp;</th>";
  echo "<th>ListSort</th>";
  echo "<th>List</th>";
  echo "<th>PlayerSort</th>";
  echo "<th class='left'>Player</th>";
  echo "<th>Age</th>";
  echo "<th>PosSort</th>";
  echo "<th>Pos</th>";
  switch ($view)
  {
  case 'stats':
	  foreach ($statArray as $key => $val)
	  {
		  echo "     <th>".stat_text($val,2)."</th>\n";
	  }
	  break;
  default:
	  foreach ($ratArray as $key => $val)
	  {
		  echo "     <th>".stat_text($val,2)."</th>\n";
	  }
	  switch ($who)
	  {
		  case 'pitchers':
		  case 11:
		  case 12:
		  case 13:
			  break;
		  default:
			  foreach ($runArray as $key => $val)
			  {
				  echo "     <th>".stat_text($val,2)."</th>\n";
			  }
			  foreach ($fldArray as $key => $val)
			  {
				  echo "     <th>".stat_text($val,2)."</th>\n";
			  }
			  break;
	  }
	  break;
  }
  if ($showPID==1) {echo "<th>PID</th>";}
  echo "</tr>\n";
  echo "  </thead>\n";


  ### Display Data ###
  echo "  <tbody>\n";
  if (mysqli_num_rows($result))
  {
	  $rowCnt=0;
	  while ($row=mysqli_fetch_array($result))
	  {
		  $pid=$row['player_id'];
		  $pos=$players[$pid]['position'];
		  if ($pos==1) {$pos=$players[$pid]['role'];}
			  
		  $pval=$pid.",".get_pos($pos,1)." ".$players[$pid]['first_name']." ".$players[$pid]['last_name'];

		  $cls='s'.($rowCnt%2+1);
		  echo "    <tr class='$cls'>";
		  echo "<td><input type='checkbox' name='player' value='$pval' ";
		  if ($activeTeam==1) {echo "onclick=\"listingClick(this,'$lgpath');\" ";}
		  echo "/></td>";
		  echo "<td>".(isset($listOrder[$pid])?$listOrder[$pid]:-9999)."</td>";
		  echo "<td>".(isset($listOrder[$pid])?$listOrder[$pid]:"")."</td>";
		  echo "<td>".$players[$pid]['last_name'].",".$players[$pid]['first_name']."</td>";
		  echo "<td class='left'><a href='$lgpath/players/player_$pid.html'>".$players[$pid]['first_name']." ".$players[$pid]['last_name']."</a>";
		  if ($row['slot']>0) {echo " <span title='Slot Demand: $".number_format($row['slot'])."'>($)</span>";}
		  echo "</td>";
		  echo "<td>".$players[$pid]['age']."</td>";
		  echo "<td>$pos</td>";
		  echo "<td>".get_pos($pos,1)."</td>";
		  switch ($view)
		  {
		  case 'stats':
			  foreach ($statArray as $key => $val)
			  {
				  echo "<td>".stat_format($val,$row[$val])."</td>";
			  }
			  break;
		  default:
			  foreach ($ratArray as $key => $ratLbl)
			  {
				  if ($view=='overall')
				  {
                      $ratLbl=str_replace("_pitches_talent_","_pitches_",$ratLbl);
                      $ratLbl=str_replace("_talent_","_overall_",$ratLbl);
				  }
                  switch ($ratLbl)
                  {
                  case 'pitching_ratings_misc_velocity':
                  case 'pitching_ratings_misc_ground_fly':
                      echo "<td sorttable_customkey='".$row[$ratLbl]."'>".stat_format($ratLbl,$row[$ratLbl])."</td>";
                      break;
                  default:
                      $ratVal=$row[$ratLbl];
                      echo "<td";
                      if ($ratVal!="-")
                      {
                          $ratScale=get_scale($ratLbl);
                          $scale=$settings[$ratScale];
                          echo " class='dc ".rat_class($scale,$ratVal)."'";
                      }
                      echo ">".$ratVal."</td>";
                      break;
                  }
			  }
			  switch ($who)
			  {
			  case 'pitchers':
			  case 11:
			  case 12:
			  case 13:
				  break;
			  default:
				  foreach ($runArray as $key => $ratLbl)
				  {
                      $ratVal=$row[$ratLbl];
                      echo "<td";
                      if ($ratVal!="-")
                      {
                          $ratScale=get_scale($ratLbl);
                          $scale=$settings[$ratScale];
                          echo " class='dc ".rat_class($scale,$ratVal)."'";
                      }
                      echo ">".$ratVal."</td>";
				  }
				  foreach ($fldArray as $key => $ratLbl)
				  {
                      $ratVal=$players[$pid][$ratLbl];
                      echo "<td";
                      if ($ratVal!="-")
                      {
                          $ratScale=get_scale($ratLbl);
                          $scale=$settings[$ratScale];
                          echo " class='dc ".rat_class($scale,$ratVal)."'";
                      }
                      echo ">".$ratVal."</td>";
				  }
				  break;
			  }
			  break;
		  }
		  if ($showPID==1) {echo "<td>$pid</td>";}
		  echo "</tr>\n";		  
		  $rowCnt++;
	  }
  }
  else {echo "<tr><td colspan=$colCnt style='text-align:center;'>No players found</td></tr>\n";}
  echo "  </tbody>\n";
  echo " </table>\n";
  echo "</form>\n";
  echo "</div>\n";

  mysqli_close($db);

  ################## END OF PAGE #########################
  echo " </div>   <!-- END contentpane DIV -->\n";
?>
  
  <script type='text/javascript'>
	$(document).ready( function () {
		var dpTable = $('#draftPoolTable').DataTable( {
			'bPaginate': true,
			'sPaginationType': 'full_numbers',
			'iDisplayLength': 100,
			'sDom': '<"top"fl>rt<"bottom"ip>',
			'aoColumnDefs': [
				{'bVisible': false, 'aTargets': [1,3,6]},
				{'aDataSort': [1], 'aTargets':[2]},    //List Ranking
				{'aDataSort': [3], 'aTargets':[4]},    //Player Name
				{'aDataSort': [6], 'aTargets':[7]}     //Position
			]
		} );
	} );
  </script>
  
<?php
  page_foot($_SESSION['lgpath']);


?>
