<?php

  include("html_functions.php");



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

  $lgid=$_SESSION['lgid'];

  $lgpath=$_SESSION['lgpath'];

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

  $lgyear=$_SESSION['lgyear'];



  $hmid=$_SESSION['user_id'];

  $pageView=$_GET['page'];

  $slid=$_GET['slid'];



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



  # Check if awards vote table exists

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

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

  if (!mysqli_num_rows($result))

  {

	  ##### Initialize Table #####

	  $query="CREATE TABLE IF NOT EXISTS awards_vote (player_id INT, league_id INT, sub_league_id INT, year SMALLINT, human_manager_id INT, award_id SMALLINT, position SMALLINT, vote INT DEFAULT 0, PRIMARY KEY (player_id, league_id, sub_league_id, year, human_manager_id, award_id));";

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

  }

  # Check Admin Table

  $module='All-Star';

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

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

  if (mysqli_num_rows($result)) 

  {

	  # Get Settings

	  $query="SELECT setting,value FROM ootp_sql_admin WHERE scope IN ('ALL',$lgid) AND module='$module'";

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

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

	  if (mysqli_num_rows($result))

	  {

		  while ($row=mysqli_fetch_array($result))

		  {

			  $field=$row['setting'];

		 	  $val=$row['value'];

			  $val=stripslashes($val);

		 	  switch ($field)

			  {

	  		  case 'asVotingOn' : $asVotingOn=$val;  break;

	  		  case 'asModEnable': $asModEnable=$val; break;

			  case 'asResults'  : $asResults=$val;   break;

	  		  case 'minPA'      : $minPA=$val;       break;

			  case 'minFIP'     : $minFIP=$val;      break;

	  		  case 'qOnTotFIP'  : $qOnTotFIP=$val;   break;

			  case 'splitOF'    : $splitOF=$val;     break;

      			  case 'DHconfig'   : $DHconfig=$val;    break;

			  case 'minGS'      : $minGS=$val;       break;

	  		  case 'minIPs'     : $minIPs=$val;      break;

			  case 'minIPr'     : $minIPr=$val;      break;

	  		  case 'minSV'      : $minSV=$val;       break;

			  case 'maxGSpct'   : $maxGSpct=$val;    break;

	  		  case 'showAllUsers': $showAllUsers=$val; break;

			  }

		  }

	  }

  }

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

  if (($DHconfig!=1)&&($DHconfig!=2)) {$DHconfig=0;}



  #Configure position array

  if ($splitOF==1) {$posArray=Array(2,3,4,5,6,7,8,9);}

  else  {$posArray=Array(2,3,4,5,6,20);}

  if ($DHconfig<2) {array_push($posArray,10);}

  array_push($posArray,11);

  array_push($posArray,21);



  # Get leagues

  $showDH=0;

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

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

  $prevSL=0;

  $SLcnt=0;

  while ($row=mysqli_fetch_array($result))

  {

	  $sub_league_id=$row['sub_league_id'];

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

	  $subleagues[$sub_league_id]['origDH']=$row['dh'];

	  $slName=str_replace(".","",$slName);

    	  $slName=str_replace(" ","_",$slName);

	  $subleagues[$sub_league_id]['imgname']=$slName;

	  switch ($DHconfig)

	  {

	  case 1: $subleagues[$sub_league_id]['dh']=1; break;

	  case 2: $subleagues[$sub_league_id]['dh']=0; break;

	  default: $subleagues[$sub_league_id]['dh']=$row['dh']; break;

	  }

	  if ($subleagues[$sub_league_id]['dh']==1) {$showDH=1;}

	  $SLcnt++;

  }



  # Check to see if user has already voted

  if ($hmid!="")

  {

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

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

       	  if (mysqli_num_rows($result))

	  {

  		  $query="SELECT sub_league_id,player_id,position FROM awards_vote WHERE league_id=$lgid AND year=$lgyear AND award_id=9 AND human_manager_id=$hmid GROUP BY award_id,sub_league_id,position;";

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

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

		  if (mysqli_num_rows($result))

  		  {

			  while ($row=mysqli_fetch_array($result))

  			  {

				  $awID=$row['award_id'];

				  $sub_league_id=$row['sub_league_id'];

				  $pos=$row['position'];

  				  $voted[$pos][$sub_league_id]=1;			

			  }

  		  }

	  }

  }

 

  mysqli_close($db);



  # Title Bar

  if (is_numeric($pageView))

  {

	  $title=$subleagues[$slid]['name']." All-Stars - ".get_pos($pageView);

	  page_head($title,$_SESSION['lgpath'],"","","./awValidate.js");

  }

  else

  {

	  $title="All-Star Voting";

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

  }



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

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

  nav_toolbar("allstar","All-Star Voting");

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

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

  

  ## Exit Conditions

  if ($asVotingOn!=1)

  {

	  echo "  <p>All-Star voting is not enabled.</p>";

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

	  page_foot($lgpath);

      	  exit;

  }

  if (($hmid=="")&&($pageView!='results'))

  {

	  echo "  <p>You must be logged in to vote.</p>";

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

       	  page_foot($lgpath);

	  exit;

  }

  if (($hmid=="")&&($pageView=='results'))

  {

	  echo "  <p>You must be logged in to see current season results.</p>";

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

       	  page_foot($lgpath);

	  exit;

  }



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

  if (is_numeric($pageView))

  {

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



	  switch ($pageView)

	  {

	  case 20: $numVotes=3; break;

	  case 11:

	  case 21: $numVotes=5; break;

	  default: $numVotes=1; break;

	  }



	  echo "<form method='post' action='asSubmit.php' id='plisting' name='draft' onsubmit=\"return asFormValidation(this,$numVotes);\">\n";

	  echo " <input type='hidden' name='hmid' value=$hmid />\n";

	  echo " <input type='hidden' name='slid' value=$slid />\n";

	  echo " <input type='hidden' name='position' value='$pageView' />\n";

	  echo " <input type='hidden' name='dList' id='dList' />\n";



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

	  echo "  <tr>\n";

	  echo "   <td>";

	  echo "    <img src='./images/";

	  switch ($pageView)

	  {

	  case 2: echo "c"; break;

	  case 3: echo "1b"; break;

	  case 4: echo "2b"; break;

	  case 5: echo "3b"; break;

	  case 6: echo "ss"; break;

	  case 7: echo "lf"; break;

	  case 8: echo "cf"; break;

	  case 9: echo "rf"; break;

	  case 10: echo "dh"; break;

	  case 20: echo "of"; break;

	  case 11: echo "sp"; break;

	  case 21: echo "rp"; break;

	  }

	  echo ".png' />";

	  echo "   </td>\n";

	  $imgFile="$lgpath/images/team_logos/".$subleagues[$sub_league]['imgname']."_All-Stars.png";

	  $locFile=$htmlroot."$htmlpath/images/team_logos/".$subleagues[$sub_league]['imgname']."_All-Stars.png";

	  if (!file_exists($locFile))

	  {

		  $imgFile="$lgpath/images/league_logos/".$subleagues[$sub_league]['imgname'].".png";

   		  $locFile=$htmlroot."$htmlpath/images/league_logos/".$subleagues[$sub_league]['imgname'].".png";

	  }

	  if (file_exists($locFile)) {$text.="     <td style='font-size:2.5em;font-weight:bold;text-align:center;vertical-align:middle;'>".$subleagues[$sub_league]['name']."</td><td rowspan=2><img src='$imgFile' style='float:right;' /></td>\n";}

	  else {$text.="     <td style='font-size:2.5em;font-weight:bold;text-align:center;vertical-align:middle;' colspan=2>".$subleagues[$sub_league]['name']."</td>\n";}

	  echo "  </tr>\n";

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

	  echo gen_as_ballot($lgid,$slid,$pageView);

	  echo "   </td>\n";

	  echo "  </tr>\n";

	  echo "  <tr><td><input type='submit' onclick=\"moveASList(document.getElementById('plisting'),document.getElementById('dList'),$numVotes);\" value='Submit Vote' /></td></tr>\n";

	  echo " </table>\n";

	  echo "</form>\n";

	  echo "</div>\n";

  }

  elseif ($pageView=='results')

  {

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



	  if ((isset($_GET['human_manager_id']))&&($_SESSION['user_is_commish']==1)) {$gmID=$_GET['human_manager_id'];}

  

	  $showGMVote=0;

	  if (($gmID=="")&&($hmid!="")) {$showGMVote=1;}

  

	  ## Check voting history

	  if (($asResults==0)&&($_SESSION['user_is_commish']!=1))

	  {

		  $query="SELECT human_manager_id,position,sub_league_id FROM awards_vote WHERE league_id=$lgid AND year=$lgyear AND award_id=9 AND human_manager_id=$hmid GROUP BY human_manager_id,position,sub_league_id";

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

		  if (mysqli_num_rows($result))

		  {

			  while ($row=mysqli_fetch_array($result))

			  {

				  $pos=$row['position'];

				  $slid=$row['sub_league_id'];

				  $voted[$hmid][$pos][$slid]=1;

			  }

		  }			

	  }

  

	  # Get Teams  

	  $query="SELECT team_id,abbr,sub_league_id FROM teams WHERE league_id=$lgid AND allstar_team=0;";

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

  	  while ($row=mysqli_fetch_array($result))

	  {

  		  $tid=$row['team_id'];

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

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

	  }



	  # Votes

	  $query="SELECT first_name,last_name,team_id,organization_id,x.* FROM players as p,(SELECT position,sub_league_id,player_id,SUM(vote) as vote,MAX(who) as who FROM (SELECT player_id,sub_league_id,position,vote,if(human_manager_id=$hmid,1,0) as who FROM awards_vote WHERE league_id=$lgid AND year=$lgyear AND award_id=9";

	  $showGM=$_GET['human_manager_id'];

	  if (($showGM!="")&&($_SESSION['user_is_commish']==1)) {$query.=" AND human_manager_id=$showGM";}

	  $query.=") as t GROUP BY position,sub_league_id,player_id) as x WHERE p.player_id=x.player_id ORDER BY position,sub_league_id,vote DESC,last_name,first_name";

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

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

	  if (mysqli_num_rows($result))

	  {

		  echo "<div class='tablebox' style='border:0px;'>\n";



		  while ($row=mysqli_fetch_array($result))

		  {

			  $pos=$row['position'];

			  $slid=$row['sub_league_id'];

			  $pid=$row['player_id'];

			  $tid=$row['organization_id'];

			  if ($row['who']==1) {$who='X';} else {$who="&nbsp;";}



			  # Determine max votes between leagues for a position

			  $subleagues[$slid][$pos]['asCnt']=$subleagues[$slid][$pos]['asCnt']+1;

			  $maxPos[$pos]=max($subleagues[$slid][$pos]['asCnt'],$maxPos[$pos]);



			  # Get Row Text

			  $cls='s'.(($subleagues[$slid][$pos]['asCnt']-1)%2+1);

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

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

			  $rowTxt.="<td class='".$cls."_l'><a href='./team_summary.php?team_id=$tid&year=$lgyear'>".$teams[$tid]['abbr']."</a>";

			  if ($slid!=$teams[$tid]['slid']) {$rowTxt.="<sup title='Traded to other league'>T</sup>";}

			  $rowTxt.="</td>";

			  $rowTxt.="<td>".$row['vote']."</td>";

			  if ($showGMVote==1) {$rowTxt.="<td>".$who."</td>";}

			  $rowTxt.="</tr>\n";

			  $subleagues[$slid][$pos]['posTxt']=$subleagues[$slid][$pos]['posTxt'].$rowTxt;

		  }



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

		  echo "  <tr>\n";

		  $slCnt=0;

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

		  {

			  echo "   <td valign='top' style='border:1px solid black;'>\n";

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

			  echo "     <tr class='title'><td colspan=".(3+$showGMVote).">".$subleagues[$slid]['name']."</td></tr>\n";

	     		  echo "     <tr class='headline'><td class='hsc2_l'>Player</td><td class='hsc2'>Team</td><td class='hsc2'>Votes</td>";

			  if ($showGMVote==1) {echo "<td class='hsc2'>Your Vote</td>";}

			  echo "</tr>\n";



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

			  {

				  if (($showDH!=1)&&($pos==10)) {continue;}

				  echo "     <tr class='headline'><td colspan=".(3+$showGMVote).">".get_pos($pos)."</td></tr>\n";

				  if (!isset($subleagues[$slid][$pos]['asCnt']))

				  {

					  echo "     <tr class='s1_l'><td colspan=".(3+$showGMVote).">No votes have been cast for this position</td></tr>\n";

					  for ($i=1;$i<$maxPos[$pos];$i++) {echo "     <tr><td colspan=".(3+$showGMVote).">&nbsp;</td></tr>\n";}

				  }

				  elseif (($voted[$hmid][$pos][$slid]==1)||($asResults==1)||($_SESSION['user_is_commish']==1))

				  {

					  echo $subleagues[$slid][$pos]['posTxt'];

					  for ($i=$subleagues[$slid][$pos]['asCnt'];$i<$maxPos[$pos];$i++) {echo "     <tr><td colspan=".(3+$showGMVote).">&nbsp;</td></tr>\n";}

				  }

				  else

				  {

					  echo "     <tr class='s1_l'><td colspan=".(3+$showGMVote).">You have not voted for this position</td></tr>\n";

					  for ($i=1;$i<$maxPos[$pos];$i++) {echo "     <tr><td colspan=".(3+$showGMVote).">&nbsp;</td></tr>\n";}

				  }

			  }



			  echo "    </table>\n";

			  echo "   </td>\n";

			  

			  $slCnt++;

			  if ($slCnt<count($subleagues)) {echo "   <td width=40>&nbsp;</td>\n";}

		  }

		  echo "  </tr>\n";

		  echo " </table>\n";

		  echo "</div>\n";	  

	  }

	  else

	  {

		  echo "No votes have been cast";

		  if ($showGM!="") {echo " by human_manager_id=$showGM";}

	  }



	  mysqli_close($db);

  }

  else

  { 

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

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

	  echo "  <tr class='title'><td colspan=3>Voting Ballots</td></tr>\n";

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

	  echo "   <td>&nbsp;</td>\n";

	  foreach ($subleagues as $slid => $val) {echo "   <td class='hsc_l'>".$subleagues[$slid]['name']."</td>\n";}

	  echo "  </tr>\n";

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

	  {

		  if (($pos==10)&&($showDH==0)) {continue;}

		  echo "  <tr>\n";

		  echo "   <td class='s1_l'";

		  if ($pos!=2) {echo " style='border-top:1px dotted #999999;'";}

		  echo ">".get_pos($pos)."</td>\n";

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

		  {

			  echo "   <td class='s2_l'";

			  if ($pos!=2) {echo " style='border-top:1px dotted #999999;'";}

			  echo ">";

			  if (($pos==10)&&($subleagues[$slid]['dh']==0)) {echo "&nbsp;";}

			  elseif (($voted[$pos][$slid]==1)&&($asModEnable!=1)) {echo "Voted";}

			  else

			  {

				  echo "<a href='./allstar.php?page=".$pos."&slid=".$slid."'>";

				  if ($voted[$pos][$slid]==1) {echo "Edit Vote";} else {echo "Vote";}

				  echo "</a>";

			  }

			  echo "</td>\n";

		  }

		  echo "</tr>\n";

	  }

	  echo " </table>\n";

	  echo "</div>\n";



  }



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

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

  

  ## Preload Existing Votes

  switch ($pageView)

  {

  case 'boy': $awID=5; break;

  case 'poy': $awID=4; break;

  case 'roy': $awID=6; break;

  case 'cm': $awID=200; break;

  case 'gm': $awID=300; break;

  }

  switch ($pageView)

  {

  case 'boy':

  case 'poy':

  case 'roy':

  case 'cm':

  case 'gm':		

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

	  ## Get User's Vote

	  $query="SELECT player_id,vote FROM awards_vote WHERE league_id=$lgid AND year=$lgyear AND human_manager_id=$hmid AND award_id=$awID ORDER BY vote;";

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

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

	  if (mysqli_num_rows($result))

	  {

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

		  while ($row=mysqli_fetch_array($result))

		  {

			  $pid=$row['player_id'];

			  echo "  checkPid($pid,document.getElementById('plisting'));\n";

			  echo "  addToList(document.getElementById('draftList'),document.getElementById('plisting'));\n";

		  }

		  echo "</script>\n";

	  }

	  mysqli_close($db);

	  break;		

  }



  page_foot($_SESSION['lgpath']);

  exit;



	



#########################################################################

# gen_as_ballot

#  creates tables for each position and subleague

#########################################################################

function gen_as_ballot($lgid,$sub_league,$position)

{

     	if (($sub_league=="")||($position=="")) {return "ERROR: Incorrect call to gen_as_ballot($lgid,$sub_league,$position)<br/>\n";}

	  

	$hmid=$_SESSION['user_id'];

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

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

	$year=$_SESSION['lgyear'];

     	$lgpath=$_SESSION['lgpath'];

     

	##### Read Settings #####

	$module='All-Star';

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

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

      	if (mysqli_num_rows($result)) 

	{

      		# Get Settings

		$query="SELECT setting,value FROM ootp_sql_admin WHERE scope IN ('ALL',$lgid) AND module='$module'";

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

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

      		if (mysqli_num_rows($result))

		{

      			while ($row=mysqli_fetch_array($result))

			{

				$field=$row['setting'];

		    		$val=$row['value'];

				$val=stripslashes($val);

		    		switch ($field)

				{

				case 'minPA'    : $minPA=$val;     break;

				case 'minFIP'   : $minFIP=$val;    break;

				case 'qOnTotFIP': $qOnTotFIP=$val; break;

       				case 'splitOF'  : $splitOF=$val;   break;

				case 'DHconfig'  : $DHconfig=$val;   break;

				case 'minGS'    : $minGS=$val;     break;

				case 'minIPs'   : $minIPs=$val;    break;

				case 'minIPr'   : $minIPr=$val;    break;

				case 'minSV'    : $minSV=$val;     break;

				case 'maxGSpct' : $maxGSpct=$val;  break;

				}

			}

      		}

	}

	else

    	{

		return;

    	}

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

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

	if (($DHconfig!=1)&&($DHconfig!=2)) {$DHconfig=0;}

	if (($minSV=="")||($minSV<0)) {$minSV=0;}

	     

	##### Get DH Status #####

	$query="SELECT sub_league_id,name,designated_hitter as dh FROM sub_leagues WHERE league_id=$lgid AND sub_league_id=$sub_league ORDER BY sub_league_id;";

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

     	while ($row=mysqli_fetch_array($result))

	{

	  	$slID=$row['sub_league_id'];

		$slName=$row['name'];

	  	$subleagues[$slID]['name']=$slName;

		$slName=ucwords($slName);

	  	$slName=str_replace(".","",$slName);

		$slName=str_replace(" ","_",$slName);

	  	$subleagues[$slID]['imgname']=$slName;

		$subleagues[$slID]['origDH']=$row['dh'];

		switch ($DHconfig)

		{

		case 1: $subleagues[$slID]['dh']=1; break;

		case 2: $subleagues[$slID]['dh']=0; break;

		default: $subleagues[$slID]['dh']=$row['dh']; break;

		}

    	}

     

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

	$tlist="";

	$query="SELECT team_id,abbr FROM teams WHERE league_id=$lgid AND sub_league_id=$sub_league AND allstar_team=0;";

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

	while ($row=mysqli_fetch_array($result))

    	{

		$tid=$row['team_id'];

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

		$tlist.=",$tid";

	}

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



	##### Get User's Vote #####

	$query="SELECT player_id,position FROM awards_vote WHERE league_id=$lgid AND year=$year AND human_manager_id=$hmid AND award_id=9 AND position=$position;";

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

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

	if (mysqli_num_rows($result))

	{

		while ($row=mysqli_fetch_array($result))

		{

			$pid=$row['player_id'];

			$pos=$row['position'];

			$voted[$pid]=$pos;

		}

	}



	##### Find Eligible Players #####

	switch ($position)

	{

	case 11:

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

		$query="SELECT first_name,last_name,organization_id,x.* FROM players as p,(SELECT t2.* FROM (SELECT player_id,team_id";

		foreach ($statArray as $key => $statLbl) {$query.=",".stat_query($statLbl)." as $statLbl";}

		$query.=" FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND year=$year AND team_id IN ($tlist) GROUP BY player_id HAVING (SUM(gs)/SUM(g))>=$minGS) as t2,(SELECT team_id,g FROM team_record WHERE team_id IN ($tlist)) as t WHERE t2.team_id=t.team_id AND (ip>=(".$minIPs."*t.g))) as x WHERE p.player_id=x.player_id AND p.team_id IN ($tlist) ORDER BY last_name,first_name,ip DESC";

		$posKey='players[]';

		$itype='checkbox';

		break;

	case 21:

		$statArray=Array("w","l","s","svPct","era","g","gs","ip","ha","r","er","hra","bb","k","hld","whip","war");

		$query="SELECT first_name,last_name,organization_id,x.* FROM players as p,(SELECT t2.* FROM (SELECT player_id,team_id";

		foreach ($statArray as $key => $statLbl) {$query.=",".stat_query($statLbl)." as $statLbl";}

		$query.=" FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND year=$year AND team_id IN ($tlist) GROUP BY player_id HAVING (SUM(gs)/SUM(g))<=$maxGSpct) as t2,(SELECT team_id,g FROM team_record WHERE team_id IN ($tlist)) as t WHERE t2.team_id=t.team_id AND ((ip>=(".$minIPr."*t.g))";

		if ($minSV>0) {$query.=" OR (s>=(".$minSV."*t.g))";}

		$query.=")) as x WHERE p.player_id=x.player_id AND p.team_id IN ($tlist) ORDER BY last_name,first_name,ip DESC";

		$posKey='players[]';

		$itype='checkbox';

		break;

	case 20:

		$statArray=Array("g","ab","pa","h","r","d","t","hr","rbi","bb","sb","avg","obp","slg","ops","war","wOBA");

		$fldArray=Array("inn","fpct","rng");

		$query="SELECT first_name,last_name,organization_id,x.* FROM players as p,(SELECT y1.*,if(";

		if ($qOnTotFIP==1) {$query.="totalINN";} else {$query.="inn";}

		$query.=">=(4.5*tg),y2.position,10) as position,y2.totalINN";

		foreach ($fldArray as $key => $statLbl) {$query.=",$statLbl";}

		$query.=" FROM (SELECT t1.*,t.g as tg FROM (SELECT player_id,team_id";

		foreach ($statArray as $key => $statLbl) {$query.=",".stat_query($statLbl)." as $statLbl";}

		$query.=" FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND year=$year AND team_id IN ($tlist) GROUP BY player_id) as t1,(SELECT team_id,g FROM team_record WHERE team_id IN ($tlist)) as t WHERE t1.team_id=t.team_id) as y1,(SELECT player_id,position,SUM(inn) as totalINN";

		foreach ($fldArray as $key => $statLbl) {$query.=",$statLbl";}

		$query.=" FROM (";

		$query.="SELECT player_id,position";

		foreach ($fldArray as $key => $statLbl) {$query.=",".stat_query($statLbl)." as $statLbl";}

		$query.=" FROM players_career_fielding_stats WHERE league_id=$lgid AND split_id<=1 AND position>1 AND position<7 AND year=$year GROUP BY player_id,position";

		$query.=" UNION ";

		$query.="SELECT player_id,20 as position";

		foreach ($fldArray as $key => $statLbl) {$query.=",".stat_query($statLbl)." as $statLbl";}

		$query.=" FROM players_career_fielding_stats WHERE league_id=$lgid AND split_id<=1 AND position IN (7,8,9) AND year=$year GROUP BY player_id";

		$query.=" ORDER BY player_id,inn DESC) as y GROUP BY player_id) as y2 WHERE y1.player_id=y2.player_id AND pa>=($minPA*tg)) as x WHERE p.player_id=x.player_id AND p.team_id IN ($tlist) AND x.position=$position ORDER BY last_name,first_name";

		$posKey='players[]';

		$itype='checkbox';

		break;

	default:

		$statArray=Array("g","ab","pa","h","r","d","t","hr","rbi","bb","sb","avg","obp","slg","ops","war","wOBA");

		$fldArray=Array("inn","fpct","rng");

		if ($position==2) {array_push($fldArray,"rtoPct");}

		$query="SELECT first_name,last_name,organization_id,x.* FROM players as p,(SELECT y1.*,if(";

		if ($qOnTotFIP==1) {$query.="totalINN";} else {$query.="inn";}

		$query.=">=(4.5*tg),y2.position,10) as position,y2.totalINN";

		foreach ($fldArray as $key => $statLbl) {$query.=",$statLbl";}

		$query.=" FROM (SELECT t1.*,t.g as tg FROM (SELECT player_id,team_id";

		foreach ($statArray as $key => $statLbl) {$query.=",".stat_query($statLbl)." as $statLbl";}

		$query.=" FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND year=$year AND team_id IN ($tlist) GROUP BY player_id) as t1,(SELECT team_id,g FROM team_record WHERE team_id IN ($tlist)) as t WHERE t1.team_id=t.team_id) as y1 LEFT JOIN (SELECT player_id,position,SUM(inn) as totalINN";

		foreach ($fldArray as $key => $statLbl) {$query.=",$statLbl";}

		$query.=" FROM (SELECT player_id,position";

		foreach ($fldArray as $key => $statLbl) {$query.=",".stat_query($statLbl)." as $statLbl";}

		$query.=" FROM players_career_fielding_stats WHERE league_id=$lgid AND split_id<=1 AND position>1 AND year=$year GROUP BY player_id,position ORDER BY player_id,inn DESC) as y GROUP BY player_id) as y2 ON y1.player_id=y2.player_id WHERE pa>=($minPA*tg)) as x WHERE p.player_id=x.player_id AND p.team_id IN ($tlist) AND x.position=$position ORDER BY last_name,first_name";

		$posKey='players';

		$itype='radio';

		break;

	}



	##### Run Query and Display Ballot #####

	$text="";

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

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

	if (mysqli_num_rows($result))

	{

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

		$text.="    <tr class='headline'><td class='hsc2_l'>Vote</td><td class='hsc2_l'>Player</td><td class='hsc2_l'>Team</td>";

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

		if (($position!=11)&&($position!=21)) 

		{

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

		}

		$text.="</tr>\n";



		$rowCnt=0;

		while ($row=mysqli_fetch_array($result))

		{

			$pid=$row['player_id'];

			$tid=$row['organization_id'];



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

			$text.="    <tr class='$cls'>";

			$text.="<td class='".$cls."_l' sorttable_customkey=\"".$row['last_name'].", ".$row['first_name']."\"><input type='".$itype."' name='".$posKey."' value=$pid";

			if ($voted[$pid]==$position) {$text.=" checked=checked";}

			$text.=" /></td>";

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

			$text.="<td class='".$cls."_l' sorttable_customkey=$tid><a href='./team_summary.php?team_id=$tid&year=$year'>".$teams[$tid]['abbr']."</a></td>";

			foreach ($statArray as $key => $statLbl) {$text.="<td>".stat_format($statLbl,$row[$statLbl])."</td>";}

			if (($position!=11)&&($position!=21)) 

			{

				foreach ($fldArray as $key => $statLbl) {$text.="<td>".stat_format($statLbl,$row[$statLbl])."</td>";}

			}

			$text.="</tr>\n";

			$rowCnt++;

		}



		$text.="    <tfoot><tr class='headline'><td class='hsc2_l'>Vote</td><td class='hsc2_l'>Player</td><td class='hsc2_l'>Team</td>";

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

		if (($position!=11)&&($position!=21)) 

		{

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

		}

		$text.="</tr></tfoot>\n";

		$text.="   </table>\n";



	}

	else

	{

		$text="No eligible players found.  Please review settings on admin page";

	}



	mysqli_close($db);

	return $text;



 }





?>

