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

  ################## PAGE INITIALIZATION #########################
  $lgid=$_SESSION['lgid'];
  $lgpath=$_SESSION['lgpath'];
  $date=new DateTime($_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='Awards';
  $query="SHOW TABLES LIKE 'ootp_sql_admin';";
  $result=mysqli_query($db,$query);
  if (mysqli_num_rows($result)) 
  {
	  # Get Settings
	  $query="SELECT * 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))
		  {
			  $scope=$row['scope'];
			  $module=$row['module'];
			  $setting=$row['setting'];
			  $identifier=$row['identifier'];
			  $value=$row['value'];

			  $settings[$scope][$module][$identifier][$setting]=$value;
		  }
	  }
  }
  if ($settings[$lgid]['Awards'][-1]['splitOF']=="") {$settings[$lgid]['Awards'][-1]['splitOF']=0;}
  $awList=Array ("5"=>"boy","4"=>"poy","6"=>"roy");
  if ($settings[$lgid]['Awards'][-1]['ggEnable']==1) {array_push($awList,"gg");}
  if ($settings[$lgid]['Awards'][-1]['cmEnable']==1) {array_push($awList,"cm");}
  $votes['boy']=$settings[$lgid]['Awards'][-1]['boyVotes'];
  $votes['poy']=$settings[$lgid]['Awards'][-1]['poyVotes'];
  $votes['roy']=$settings[$lgid]['Awards'][-1]['royVotes'];
  $votes['cm']=$settings[$lgid]['Awards'][-1]['cmVotes'];
  $votes['gm']=$settings[$lgid]['Awards'][-1]['gmVotes'];

  # Get leagues
  $query="SELECT sub_league_id,name 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'];
       	  $SLcnt++;
  }

  # Get Award Info
  $query="SELECT mvp_award_name,pitcher_award_name,rookie_award_name,defense_award_name FROM leagues WHERE league_id=$lgid;";
  if ($_GET['showq']==1) {echo "$query<br/>\n";}
  $result=mysqli_query($db,$query);
  $row=mysqli_fetch_array($result);
  $awardName['boy']=$row['mvp_award_name'];
  $awardName['poy']=$row['pitcher_award_name'];
  $awardName['roy']=$row['rookie_award_name'];
  $awardName['gg']=$row['defense_award_name'];
  $awardName['cm']=$settings[$lgid]['Awards'][-1]['cmAwardName'];
  $awardName['gm']="General Manager of the Year Award";
	
  $awardsAbbr[4]='poy';
  $awardsAbbr[5]='boy';
  $awardsAbbr[6]='roy';
  $awardsAbbr[7]='gg';
  $awardsAbbr[200]='cm';
  $awardsAbbr[300]='gm';

  # 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 award_id,sub_league_id,player_id FROM awards_vote WHERE league_id=$lgid AND year=$lgyear AND award_id IN (4,5,6,7,200,300) AND human_manager_id=$hmid GROUP BY award_id,sub_league_id;";
		  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'];
				  $awAbbr=$awardsAbbr[$awID];
  				  $voted[$awAbbr][$sub_league_id]=1;			
			  }
  		  }
	  }
  }
 
  mysqli_close($db);

  # Title Bar
  if (($pageView=='boy')||($pageView=='poy')||($pageView=='roy')||($pageView=='gg')||($pageView=='cm')) {$title=$subleagues[$slid]['name']." - ".$awardName[$pageView];}
  elseif ($pageView=='gm') {$title=$awardName['gm'];}
  else {$title="End of Season Awards Voting";}

  switch ($pageView)
  {
  case 'boy':
  case 'poy':
  case 'roy':
  case 'gg':
  case 'cm':
  case 'gm':
	  page_head($title,$_SESSION['lgpath'],"","","./awValidate.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");
	  break;
  case 'gg':
      page_head($title,$_SESSION['lgpath'],"","","./awValidate.js");
      break;
  default:
	  page_head($title,$_SESSION['lgpath']);
	  break;
  }
  echo " <div id='topbar'>\n";
  main_titlebar($lgid,$_SESSION['lgpath'],$title);
  nav_toolbar("awards","Awards Voting");
  echo " </div>   <!-- END topbar DIV -->\n";
  echo " <div id='contentpane'>\n";
  
  ## Exit Conditions
  if (($settings[$lgid]['Awards'][-1]['awVotingOn']!=1)&&($pageView!='results'))
  {
	  echo "  <p>Awards 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 #########################
  switch ($pageView)
  {
  case 'boy':
  case 'poy':
  case 'roy':
  case 'cm':
  case 'gm':
	  if ($slid=="") {$slid=0;}

	  echo "<div class='textbox'>\n";
	  $whoText='player';
	  if ($pageView=='gm') {$whoText='manager';}
	  if ($votes[$pageView]==1) {$btxt="vote for 1 $whoText";}
	  else {$btxt="vote for ".$votes[$pageView]." ".$whoText."s, in order";}
	  echo "<table cellpadding=2 cellspacing=0 border=0><tr class='title'><td>Ballot ($btxt)</td></tr><tr><td>\n";
	  echo "<form method='post' action='awSubmit.php' name='draft' onsubmit=\"return checkCount(document.getElementById('draftList'), ".$votes[$pageView].",'$whoText'";
	  if (($pageView=='gm')&&($settings[$lgid]['Awards'][-1]['gmSelfVote']!=1)) {echo ",$hmid";}
	  echo ");\">\n";
	  echo " <input type='hidden' name='hmid' value=$hmid />\n";
	  echo " <input type='hidden' name='slid' value=$slid />\n";
	  echo " <input type='hidden' name='award' value='".$pageView."' />\n";
	  echo " <input type='hidden' name='dList' id='dList' />\n";
	  if ($_GET['showq']==1) {echo " <input type='hidden' name='debug' value=1 />\n";}

	  echo " <table style='clear:left;'>\n";
	  echo "  <tr>\n";
	  echo "   <td rowspan=5>\n";
	  echo "    <select id='draftList' name='draftList' multiple='multiple' size=10 width='85%'>\n";
	  echo "     <option value=0>Select ".$whoText."s below</option>\n";
	  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 "  </tr>\n";
	  echo "  <tr>\n";
	  echo "   <td><input type='button' onclick=\"moveUp(document.getElementById('draftList'));\" value='Up'></input></td>\n";
	  echo "  </tr>\n";
	  echo "  <tr>\n";
	  echo "   <td><input type='button' onclick=\"moveDown(document.getElementById('draftList'));\" value='Down'></input></td>\n";
	  echo "  </tr>\n";
	  echo "  <tr>\n";
	  echo "   <td><input type='button' onclick=\"removeFromList(document.getElementById('draftList'),'$whoText');\" value='Remove'></input></td>\n";
	  echo "  </tr>\n";
	  echo "  <tr>\n";
	  echo "   <td><input type='button' onclick=\"addToList(document.getElementById('draftList'),document.getElementById('plisting'));\" value='Add to List'></input></td>\n";
	  echo "  </tr>\n";
	  echo "  <tr>\n";
	  echo "   <td colspan=2><input type='submit' onclick=\"moveList(document.getElementById('draftList'), document.getElementById('dList'));\" value='Submit Vote'></input></td>\n";
	  echo "  </tr>\n";
      echo "    </form>\n";
	  echo " </table>\n";
	  echo "</td></tr></table>\n";
	  echo "</div>\n";

	  echo "<div style='float:right;padding:10px 0 0 0;'>\n";
	  echo " <img src='$lgpath/images/".$subleagues[$slid]['name'].".png' style='float:right;' />\n";
	  echo "</div>\n";

      echo "<form id='plisting'>\n";
	  echo "<div class='textbox noborder' style='width:98%;'>\n";
	  echo gen_eos_ballot($lgid,$slid,$pageView);
	  echo "</div>\n";
      echo "</form>\n";
	  break;
  case 'gg':
	  echo "<div class='textbox'>\n";

	  echo "<form method='post' action='awSubmit.php' id='plisting' name='draft' onsubmit=\"return formValidation(this,".$settings[$lgid]['Awards'][-1]['splitOF'].");\">\n";
	  echo " <input type='hidden' name='hmid' value=$hmid />\n";
	  echo " <input type='hidden' name='slid' value=$slid />\n";
	  echo " <input type='hidden' name='award' value='gg' />\n";
	  echo " <input type='hidden' name='dList' id='dList' />\n";

	  echo " <table cellpadding=0 cellspacing=0 border=0>\n";
	  echo "  <tr><td>\n";
	  echo gen_eos_ballot($lgid,$slid,'gg');
	  echo "   </td>\n";
	  echo "   <td rowspan=2 valign='top'><img src='$lgpath/images/".$subleagues[$slid]['name'].".png' style='float:right;' /></td></tr>\n";
	  echo "  <tr><td><input type='submit' onclick=\"moveGGList(document.getElementById('plisting'),document.getElementById('dList'),".$settings[$lgid]['Awards'][-1]['splitOF'].");\" value='Submit Vote' /></td></tr>\n";
	  echo " </table>\n";
	  echo "</form>\n";
	  echo "</div>\n";
	  break;
  case '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 (($settings[$lgid]['Awards'][-1]['awResults']==0)&&($_SESSION['user_is_commish']!=1))
	  {
		  $query="SELECT human_manager_id,award_id,sub_league_id FROM awards_vote WHERE league_id=$lgid AND year=$lgyear AND award_id IN (4,5,6,7,200,300) AND human_manager_id=$hmid GROUP BY human_manager_id,award_id,sub_league_id";
		  $result=mysqli_query($db,$query);
		  if (mysqli_num_rows($result))
		  {
			  while ($row=mysqli_fetch_array($result))
			  {
				  $awID=$row['award_id'];
				  $slid=$row['sub_league_id'];
				  $voted[$hmid][$awID][$slid]=1;
			  }
		  }			
	  }

	  ## Get Subleagues
	  $query="SELECT sub_league_id,name 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'];
		  $SLcnt++;
	  }
	  
	  foreach ($subleagues as $slid => $val)
	  {
		  echo "<div class='textbox'>\n";
		  echo " <table cellpadding=0 cellspacing=0 border=0>\n";
		  echo "  <tr class='title2'><td style='padding:2px;'>".$subleagues[$slid]['name']."</td></tr>\n";
		  echo "  <tr><td>\n";
		  echo "   <table cellpadding=2 cellspacing=0 border=0 width='650px'>\n";
		  echo "    <tr class='headline'><td class='hsc2_l'>Player</td><td class='hsc2'>1st</td><td class='hsc2'>2nd</td><td class='hsc2'>3rd</td><td class='hsc2'>4th</td><td class='hsc2'>5th</td><td class='hsc2'>6th</td><td class='hsc2'>7th</td><td class='hsc2'>8th</td><td class='hsc2'>9th</td><td class='hsc2'>10th</td><td class='hsc2'>Score</td>";
		  if ($showGMVote==1) {echo "<td class='hsc2'>Your Vote</td>";}
		  echo "</tr>\n";

		  foreach ($awList as $awID => $award)
		  {
			  if ($award=='gg') {$awID=7;}
  			  if ($award=='cm') {$awID=200;}
	  
			  echo "    <tr class='title'><td colspan=".(12+$showGMVote).">".$awardName[$award]."</td></tr>\n";
			  $cnt=0;

			  $query="SELECT p.player_id,x.position,first_name,last_name,organization_id,first,second,third,fourth,fifth,sixth,seventh,eighth,ninth,tenth,score,who FROM players as p,(SELECT player_id,position,SUM(first) as first,SUM(second) as second,SUM(third) as third,SUM(fourth) as fourth,SUM(fifth) as fifth,SUM(sixth) as sixth,SUM(seventh) as seventh,SUM(eighth) as eighth,SUM(ninth) as ninth,SUM(tenth) as tenth,SUM(score) as score,MAX(who) as who FROM (SELECT player_id,position,if(vote=1,1,0) as first,if(vote=2,1,0) as second,if(vote=3,1,0) as third,if(vote=4,1,0) as fourth,if(vote=5,1,0) as fifth,if(vote=6,1,0) as sixth,if(vote=7,1,0) as seventh,if(vote=8,1,0) as eighth,if(vote=9,1,0) as ninth,if(vote=10,1,0) as tenth,".get_vote_query($votes[$award])." as score,if(human_manager_id=$hmid,vote,0) as who FROM awards_vote WHERE league_id=$lgid AND year=$lgyear AND sub_league_id=$slid AND award_id=$awID";
			  if (($gmID!="")&&($_SESSION['user_is_commish'])) {$query.=" AND human_manager_id=$gmID";}
			  $query.=") as t GROUP BY player_id) as x WHERE p.player_id=x.player_id ORDER BY position,score DESC";
			  if ($_GET['showq']==1) {echo "$query<br/>\n";}
			  $result=mysqli_query($db,$query);
			  if (($voted[$hmid][$awID][$slid]!=1)&&($settings[$lgid]['Awards'][-1]['awResults']==0)&&($_SESSION['user_is_commish']!=1)) {echo "    <tr class='s2'><td class='".$cls."_l' colspan=".(12+$showGMVote)." style='text-align:center;'>You have not voted for this award</td>";}
			  elseif (mysqli_num_rows($result))
			  {
				  $lastPos=-1;
				  while ($row=mysqli_fetch_array($result))
				  {
					  $pid=$row['player_id'];
					  $position=$row['position'];
					  $name=$row['first_name']." ".$row['last_name'];

					  if (($award=='gg')&&($lastPos!=$position))
					  {
						  $cnt=0;
						  echo "    <tr class='headline'><td class='hsc2_l' colspan=".(12+$showGMVote).">".get_pos($position)."</td>";
					  }

					  $cls='s'.($cnt%2+1);
					  echo "    <tr class='$cls'>";
					  echo "<td class='".$cls."_l'><a href='./player.php?player_id=$pid'>$name</a></td>";
					  if ($row['first']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['first']."</td>";}
					  if ($row['second']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['second']."</td>";}
					  if ($row['third']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['third']."</td>";}
					  if ($row['fourth']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['fourth']."</td>";}
					  if ($row['fifth']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['fifth']."</td>";}
					  if ($row['sixth']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['sixth']."</td>";}
					  if ($row['seventh']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['seventh']."</td>";}
					  if ($row['eighth']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['eighth']."</td>";}
					  if ($row['ninth']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['ninth']."</td>";}
					  if ($row['tenth']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['tenth']."</td>";}
					  echo "<td>".$row['score']."</td>";
					  if ($showGMVote==1)
					  {
						  if ($row['who']==0) {echo "<td>&nbsp;</td>";}
						  elseif ($votes[$award]==1) {echo "<td>X</td>";}
						  else {echo "<td>".$row['who']."</td>";}
					  }
					  echo "</tr>\n";

					  $lastPos=$position;
					  $cnt++;
				  }
			  }
			  else {echo "    <tr class='s2'><td class='".$cls."_l' colspan=".(12+$showGMVote)." style='text-align:center;'>No votes recorded</td>";}
		  }
		  echo "   </table>\n";
		  echo "  </td></tr>\n";
		  echo " </table>\n";
		  echo "</div>\n";
	  }

	  if ($settings[$lgid]['Awards'][-1]['gmEnable']==1)
	  {
		  echo "<div class='textbox'>\n";
		  echo " <table cellpadding=0 cellspacing=0 border=0>\n";
		  echo "  <tr class='title2'><td style='padding:2px;'>League-Wide</td></tr>\n";
		  echo "  <tr><td>\n";
		  echo "   <table cellpadding=2 cellspacing=0 border=0 width='650px'>\n";
		  echo "    <tr class='headline'><td class='hsc2_l'>Manager</td><td class='hsc2'>1st</td><td class='hsc2'>2nd</td><td class='hsc2'>3rd</td><td class='hsc2'>4th</td><td class='hsc2'>5th</td><td class='hsc2'>6th</td><td class='hsc2'>7th</td><td class='hsc2'>8th</td><td class='hsc2'>9th</td><td class='hsc2'>10th</td><td class='hsc2'>Score</td>";
		  if ($showGMVote==1) {echo "<td class='hsc2'>Your Vote</td>";}
		  echo "</tr>\n";

		  $award='gm';
		  $awID=300;			
		  $slid=0;
		  echo "    <tr class='title'><td colspan=".(12+$showGMVote).">".$awardName[$award]."</td></tr>\n";
		  $cnt=0;

		  $query="SELECT hm.human_manager_id,first_name,last_name,first,second,third,fourth,fifth,sixth,seventh,eighth,ninth,tenth,score,who FROM human_managers as hm,(SELECT player_id,position,SUM(first) as first,SUM(second) as second,SUM(third) as third,SUM(fourth) as fourth,SUM(fifth) as fifth,SUM(sixth) as sixth,SUM(seventh) as seventh,SUM(eighth) as eighth,SUM(ninth) as ninth,SUM(tenth) as tenth,SUM(score) as score,MAX(who) as who FROM (SELECT player_id,position,if(vote=1,1,0) as first,if(vote=2,1,0) as second,if(vote=3,1,0) as third,if(vote=4,1,0) as fourth,if(vote=5,1,0) as fifth,if(vote=6,1,0) as sixth,if(vote=7,1,0) as seventh,if(vote=8,1,0) as eighth,if(vote=9,1,0) as ninth,if(vote=10,1,0) as tenth,".get_vote_query($votes[$award])." as score,if(human_manager_id=$hmid,vote,0) as who FROM awards_vote WHERE league_id=$lgid AND year=$lgyear AND sub_league_id=$slid AND award_id=$awID";
		  if (($gmID!="")&&($_SESSION['user_is_commish'])) {$query.=" AND human_manager_id=$gmID";}
		  $query.=") as t GROUP BY player_id) as x WHERE hm.human_manager_id=x.player_id ORDER BY position,score DESC";
		  if ($_GET['showq']==1) {echo "$query<br/>\n";}
		  $result=mysqli_query($db,$query);
		  if (($voted[$hmid][$awID][$slid]!=1)&&($settings[$lgid]['Awards'][-1]['awResults']==0)&&($_SESSION['user_is_commish']!=1)) {echo "    <tr class='s2'><td class='".$cls."_l' colspan=".(12+$showGMVote)." style='text-align:center;'>You have not voted for this award</td>";}
		  elseif (mysqli_num_rows($result))
		  {
			  while ($row=mysqli_fetch_array($result))
			  {
				  $pid=$row['human_manager_id'];
				  $name=$row['first_name']." ".$row['last_name'];

				  $cls='s'.($cnt%2+1);
				  echo "    <tr class='$cls'>";
				  echo "<td class='".$cls."_l'><a href='$lgpath/coaches/human_manager_$pid.html'>$name</a></td>";
				  if ($row['first']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['first']."</td>";}
				  if ($row['second']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['second']."</td>";}
				  if ($row['third']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['third']."</td>";}
				  if ($row['fourth']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['fourth']."</td>";}
				  if ($row['fifth']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['fifth']."</td>";}
				  if ($row['sixth']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['sixth']."</td>";}
				  if ($row['seventh']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['seventh']."</td>";}
				  if ($row['eighth']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['eighth']."</td>";}
				  if ($row['ninth']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['ninth']."</td>";}
				  if ($row['tenth']==0) {echo "<td>&nbsp;</td>";} else {echo "<td>".$row['tenth']."</td>";}
				  echo "<td>".$row['score']."</td>";
				  if ($showGMVote==1)
				  {
					  if ($row['who']==0) {echo "<td>&nbsp;</td>";}
					  elseif ($votes[$award]==1) {echo "<td>X</td>";}
					  else {echo "<td>".$row['who']."</td>";}
				  }
				  echo "</tr>\n";

				  $cnt++;
			  }
		  }
		  else {echo "    <tr class='s2'><td class='".$cls."_l' colspan=".(12+$showGMVote)." style='text-align:center;'>No votes recorded</td>";}
		  echo "   </table>\n";
		  echo "  </td></tr>\n";
		  echo " </table>\n";
		  echo "</div>\n";
	  }

	  mysqli_close($db);

	  break;		
  default:
	  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 ($awList as $key => $awAbbr)
	  {
		  echo "  <tr>\n";
		  echo "   <td class='s1_l'";
		  if ($awAbbr!="boy") {echo " style='border-top:1px dotted #999999;'";}
		  echo ">".$awardName[$awAbbr]."</td>\n";
		  foreach ($subleagues as $slid => $val)
		  {
			  echo "   <td class='s2_l'";
			  if ($awAbbr!="boy") {echo " style='border-top:1px dotted #999999;'";}
			  echo ">";
			  if (($voted[$awAbbr][$slid]==1)&&($settings[$lgid]['Awards'][-1]['awModEnable']!=1)) {echo "Voted";}
			  else
			  {
				  echo "<a href='./eos_ballot.php?page=".$awAbbr."&slid=".$slid."'>";
				  if ($voted[$awAbbr][$slid]==1) {echo "Edit Vote";} else {echo "Vote";}
				  echo "</a>";
			  }
			  echo "</td>\n";
		  }
		  echo "</tr>\n";
	  }
	  if ($settings[$lgid]['Awards'][-1]['gmEnable']==1)
	  {
		  $awAbbr='gm';
		  echo "  <tr class='headline'>\n";
		  echo "   <td>&nbsp;</td>\n";
		  echo "   <td class='hsc_l' colspan=2>League-wide</td>\n";
		  echo "  </tr>\n";
		  echo "  <tr>\n";
		  echo "   <td class='s1_l'>".$awardName[$awAbbr]."</td>\n";
		  echo "   <td class='s2_l' colspan=2>";
		  if (($voted[$awAbbr][0]==1)&&($settings[$lgid]['Awards'][-1]['awModEnable']!=1)) {echo "Voted";}
		  else
		  {
			  echo "<a href='./eos_ballot.php?page=".$awAbbr."&slid=0'>";
			  if ($voted[$awAbbr][0]==1) {echo "Edit Vote";} else {echo "Vote";}
			  echo "</a>";
		  }
		  echo "</td>\n";
		  echo "</tr>\n";
	  }

	  echo " </table>\n";
	  echo "</div>\n";
	  break;
  }

  ################## 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 sub_league_id=$slid 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;		
  }
?>

 <script type='text/javascript'>
    $(document).ready(function () {
        var boyTable = $('#boyTable').DataTable( {
            'bPaginate': false,
            'sDom': '<"top">t<"bottom">',
            'order': [[ 6, 'desc' ]],
            'aoColumnDefs': [
                {'bVisible': false, 'aTargets': [2]},
                {'aDataSort': [2], 'aTargets': [3]}
            ]
        } );
        var poyTable = $('#poyTable').DataTable( {
            'bPaginate': false,
            'sDom': '<"top">t<"bottom">',
            'order': [[ 9, 'desc' ]],
            'aoColumnDefs': [
                {'bVisible': false, 'aTargets': [2]},
                {'aDataSort': [2], 'aTargets': [3]}
            ]
        } );
        var gmTable = $('#gmTable').DataTable( {
            'bPaginate': false,
            'sDom': '<"top">t<"bottom">',
            'order': [[ 6, 'desc' ]],
            'aoColumnDefs': [
                {'bVisible': false, 'aTargets': [1]},
                {'aDataSort': [1], 'aTargets': [2]}
            ]
        } );
    } );
 </script>

<?php

  page_foot($_SESSION['lgpath']);
  exit;

	

#########################################################################
# gen_eos_ballot
#  creates tables for each award and subleague
#########################################################################
function gen_eos_ballot($lgid,$sub_league,$award)
{
     	if (($sub_league=="")||($award=="")) {return "ERROR: Incorrect call to gen_eos_ballot($lgid,$sub_league,$award)<br/>\n";}
	  
	$hmid=$_SESSION['user_id'];
	$date=new DateTime($_SESSION['lgdate']);
     	include($_SESSION['adminpath']."/dbopen.php");
	$year=$_SESSION['lgyear'];
     	$lgpath=$_SESSION['lgpath'];
     
	##### Read Settings #####
	$module='Awards';
      	$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 'maxPlyrs'   : $maxPlyrs=$val;    break;
				case 'minPA'      : $minPA=$val;       break;
				case 'minIP'      : $minIP=$val;       break;
				case 'maxServ'    : $maxServ=$val;     break;
				case 'ggEnable'   : $ggEnable=$val;    break;
				case 'splitOF'    : $splitOF=$val;     break;
				case 'minFIP'     : $minFIP=$val;      break;
				case 'cmEnable'   : $cmEnable=$val;    break;
				case 'cmAwardName': $cmAwardName=$val; break;
				case 'cmVotes'    : $cmVotes=$val;     break;
				case 'cmQual'     : $cmQual=$val;      break;
				case 'cmWho'      : $cmWho=$val;       break;
				case 'gmEnable'   : $gmEnable=$val;    break;
				}
			}
      		}
	}
	if ($minPA=="") {$minPA=3.1;}
     	if ($minIP=="") {$minIP=0.3;}
	if ($maxService=="") {$maxService=45;}
     	if ($maxPlyrs=="") {$maxPlyrs=50;}
	if ($minFIP=="") {$minFIP=5;}
     	if ($ggEnable=="") {$ggEnable=0;}
	if ($splitOF=="") {$splitOF=0;}
     	if ($splitOF==1) {$nPos=9;} else {$nPos=7;}
	     
	##### Get Subleagues #####
	$query="SELECT sub_league_id,name 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;
	}
     
	##### Get Rookie Status #####
	if ($award=='roy')
    	{
		$query="SELECT player_id,mlb_service_days,mlb_service_days_this_year FROM players_roster_status";
	  	$query.=" WHERE (mlb_service_days-mlb_service_days_this_year)<=$maxService";
		$query.=" AND mlb_service_days_this_year>0;";
	  	$result=mysqli_query($db,$query);
		while ($row=mysqli_fetch_array($result))
	 	{
			$pid=$row['player_id'];
	       		$rookies[$pid]=1;
		}
    	}
     
	##### Get Batters #####
	if (($award=='boy') || ($award=='roy') || (($award=='cm')&&(($cmWho=='batters')||($cmWho=='all'))) )
    	{
		$query="SELECT p.player_id,p.first_name,p.last_name,p.position,t.team_id,t.abbr,t.sub_league_id,tr.g as tgame,SUM(pa) as pa,SUM(pcb.g) as g,SUM(ab) as ab,SUM(h) as h,SUM(r) as r,SUM(d) as d,SUM(t) as t,SUM(hr) as hr,SUM(rbi) as rbi,SUM(bb) as bb,SUM(sb) as sb,SUM(cs) as cs,(SUM(h)/SUM(ab)) as avg,(SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf)) as obp,(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab) as slg,SUM(war) as war,if(SUM(pa)=0,0,(0.72*SUM(bb)+0.75*SUM(hp)+0.9*(SUM(h)-SUM(d)-SUM(t)-SUM(hr))+0.92*0+1.24*SUM(d)+1.56*SUM(t)+1.95*SUM(hr))/SUM(pa)) as wOBA,(.47*(SUM(h)-SUM(d)-SUM(t)-SUM(hr))+.78*SUM(d)+1.09*SUM(t)+1.4*SUM(hr)+.33*(SUM(bb)+SUM(hp))+.3*SUM(sb)-.52*SUM(cs)-.26*(SUM(ab)-SUM(h)-SUM(gdp))-.72*SUM(gdp)) as lw";
	  	$query.=" FROM players_career_batting_stats as pcb,players as p,(SELECT team_id,g FROM team_record) as tr,teams as t";
		$query.=" WHERE pcb.team_id=tr.team_id";
	  	$query.=" AND pcb.team_id=t.team_id";
		$query.=" AND t.team_id=tr.team_id";
	  	$query.=" AND pcb.player_id=p.player_id";
		$query.=" AND pcb.league_id=$lgid";
	  	$query.=" AND t.sub_league_id=$sub_league";
		$query.=" AND split_id=1";
	  	$query.=" AND p.position!=1";
		$query.=" AND year=$year";
	  	$query.=" GROUP BY player_id,sub_league_id";
		$query.=" ORDER BY t.sub_league_id,lw DESC;";

      $result=mysqli_query($db,$query);
      while ($row=mysqli_fetch_array($result))
       {
         $pid=$row['player_id'];
	 $lw=$row['lw'];
   	 $pa=$row['pa'];
	 $tg=$row['tgame'];
   	 $pt=$pa/$tg;
       
	 $name=$row['first_name']." ".$row['last_name'];
	 $nameSort=$row['last_name'].", ".$row['first_name'];
   	 $pos=get_pos($row['position'],1);
	 $slid=$row['sub_league_id'];
   	 $tid=$row['team_id'];
	 $tabbr=$row['abbr'];
   	 $players[$pid]['name']=$name;
     $players[$pid]['nameSort']=$nameSort;
	 $players[$pid]['pos']=$pos;

	 $batters[$pid]['slid']=$teams[$tid]['slid'];
   	 $g=$row['g'];
	 $ab=$row['ab'];
   	 $h=$row['h'];
	 $d=$row['d'];
   	 $t=$row['t'];
	 $hr=$row['hr'];
   	 $r=$row['r'];
	 $rbi=$row['rbi'];
   	 $bb=$row['bb'];
	 $sb=$row['sb'];
   	 $cs=$row['cs'];
	 $avg=$row['avg'];
   	 $obp=$row['obp'];
	 $slg=$row['slg'];
	 $war=$row['war'];
	 $wOBA=$row['wOBA'];
   	 $players[$pid]['hr']=$hr;
	 $players[$pid]['rbi']=$rbi;

	 $ops=$obp+$slg;
   	 $avg=sprintf("%0.3f",$avg);
	 $obp=sprintf("%0.3f",$obp);
   	 $slg=sprintf("%0.3f",$slg);
	 $ops=sprintf("%0.3f",$ops);
	 $war=sprintf("%0.1f",$war);
	 $wOBA=sprintf("%0.3f",$wOBA);
   	 if ($avg<1) {$avg=substr($avg,1);}
	 if ($obp<1) {$obp=substr($obp,1);}
   	 if ($slg<1) {$slg=substr($slg,1);}
	 if ($ops<1) {$ops=substr($ops,1);}
	 if ($wOBA<1) {$wOBA=substr($wOBA,1);}
   	 $players[$pid]['avg']=$avg;
      
	 $bRow="<td><a href='$lgpath/teams/team_$tid.html'>".$tabbr."</a></td>";
   	 $bRow.="<td>".$g."</td>";
	 $bRow.="<td>".$ab."</td>";
   	 $bRow.="<td>".$r."</td>";
	 $bRow.="<td>".$h."</td>";
   	 $bRow.="<td>".$d."</td>";
	 $bRow.="<td>".$t."</td>";
   	 $bRow.="<td>".$hr."</td>";
	 $bRow.="<td>".$rbi."</td>";
   	 $bRow.="<td>".$bb."</td>";
	 $bRow.="<td>".$sb."</td>";
   	 $bRow.="<td>".$cs."</td>";
	 $bRow.="<td>".$avg."</td>";
   	 $bRow.="<td>".$obp."</td>";
	 $bRow.="<td>".$slg."</td>";
   	 $bRow.="<td>".$ops."</td>";
   	 $bRow.="<td>".$war."</td>";
   	 $bRow.="<td>".$wOBA."</td>";
	 $players[$pid][$slid]['brow']=$bRow;

	 if (($subleagues[$slid]['batCnt']<$maxPlyrs) && ($pt>=$minPA))
  	  {
            $cnt=$subleagues[$slid]['batCnt']+1;
	    $subleagues[$slid]['batCnt']=$cnt;
   	    $subleagues[$slid]['boynames'][$pid]=$nameSort;
	  }

         if (($rookies[$pid]==1) && ($subleagues[$slid]['batRCnt']<($maxPlyrs/2)) && ($pt>=($minPA/3)))
          {
            $cnt=$subleagues[$slid]['batRCnt']+1;
	    $subleagues[$slid]['batRCnt']=$cnt;
   	    $subleagues[$slid]['royBnames'][$pid]=$nameSort;
	  }

	 if ($cmEnable==1)
  	  {
            if ($cmQual=='all')
             {
               if ((($cmWho=='batters') && ($subleagues[$slid]['cmBatRCnt']<$maxPlyrs) && ($pt>=$minPA)) || (($cmWho=='all') && ($subleagues[$slid]['cmBatRCnt']<($maxPlyrs/2)) && ($pt>=$minPA)))
                {
                  $cnt=$subleagues[$slid]['cmBatRCnt']+1;
		  $subleagues[$slid]['cmBatRCnt']=$cnt;
   		  $subleagues[$slid]['cmBnames'][$pid]=$nameSort;
		}
   	     }
	     elseif ($rookies[$pid]==1)
  	     {
               if ((($cmWho=='batters') && ($subleagues[$slid]['cmBatRCnt']<$maxPlyrs) && ($pt>=($minPA/3))) || (($cmWho=='all') && ($subleagues[$slid]['cmBatRCnt']<($maxPlyrs/2)) && ($pt>=($minPA/3))))
                {
                  $cnt=$subleagues[$slid]['cmBatRCnt']+1;
		  $subleagues[$slid]['cmBatRCnt']=$cnt;
   		  $subleagues[$slid]['cmBnames'][$pid]=$nameSort;
		}
   	     }
	  }
       }
    }

   ##### Get Pitchers #####
   if (($award=='poy') || ($award=='roy') || (($award=='cm')&&(($cmWho=='pitchers')||($cmWho=='relievers')||($cmWho=='all'))) )
    {
      $query="SELECT p.player_id,p.first_name,p.last_name,p.role,t.team_id,t.abbr,t.sub_league_id,tr.g as tgame,SUM(pcp.w) as w,SUM(pcp.l) as l,SUM(s) as s,SUM(cg) as cg,SUM(sho) as sho,((SUM(ip)*3+SUM(ipf))/3) as ip,SUM(pcp.g) as g,SUM(gs) as gs,SUM(ha) as ha,SUM(r) as r,SUM(er) as er,SUM(hra) as hra,SUM(bb) as bb,SUM(k) as k,(SUM(er)*9)/((SUM(ip)*3+SUM(ipf))/3) as era,(SUM(ha)+SUM(bb))/((SUM(ip)*3+SUM(ipf))/3) as whip,SUM(war) as war,2*((SUM(ip)*3+SUM(ipf))/3)+4*sum(pcp.w)-4*sum(pcp.l)+3*sum(s)+sum(k)-2*sum(ha)-2*sum(bb) as score";
      $query.=" FROM players_career_pitching_stats as pcp,players as p,(SELECT team_id,g FROM team_record) as tr,teams as t";
      $query.=" WHERE pcp.team_id=tr.team_id";
      $query.=" AND pcp.team_id=t.team_id";
      $query.=" AND t.team_id=tr.team_id";
      $query.=" AND pcp.player_id=p.player_id";
      $query.=" AND pcp.league_id=$lgid";
      $query.=" AND t.sub_league_id=$sub_league";
      $query.=" AND split_id=1";
      $query.=" AND year=$year";
      $query.=" GROUP BY player_id,sub_league_id";
      $query.=" ORDER BY t.sub_league_id,score DESC;";
   
      $result=mysqli_query($db,$query);
      while ($row=mysqli_fetch_array($result))
       {
         $pid=$row['player_id'];

	 $name=$row['first_name']." ".$row['last_name'];
   	 $nameSort=$row['last_name'].", ".$row['first_name'];
	 $slid=$row['sub_league_id'];
   	 $role=get_pos($row['role'],1);
	 $tid=$row['team_id'];
   	 $tabbr=$row['abbr'];
     $players[$pid]['name']=$name;
     $players[$pid]['nameSort']=$nameSort;
   	 $players[$pid]['role']=$role;

	 $ip=$row['ip'];
   	 $tg=$row['tgame'];
	 $pt=$ip/$tg;
   	 $g=$row['g'];
	 $gs=$row['gs'];

	 $bf=$row['bf'];
   	 $w=$row['w'];
	 $l=$row['l'];
   	 $s=$row['s'];
	 $cg=$row['cg'];
   	 $sho=$row['sho'];
	 $ha=$row['ha'];
   	 $bba=$row['bb'];
	 $k=$row['k'];
   	 $d=$row['da'];
	 $t=$row['ta'];
   	 $hr=$row['hra'];
	 $er=$row['er'];
   	 $r=$row['r'];
	 $era=$row['era'];
   	 $whip=$row['whip'];
   	 $war=$row['war'];
	 $era=sprintf("%0.2f",$era);
   	 $whip=sprintf("%0.2f",$whip);
   	 $war=sprintf("%0.1f",$war);
	 if ($whip<1) {$whip=substr($whip,1);}

	 if ((($g-$gs)>$gs) && (($ip/$g)<4.00)) {$role='RP';}
	  else {$role='SP';}

         $ip=sprintf("%0.1f",$ip);

	 $pRow="<td><a href='$lgpath/teams/team_$tid.html'>".$tabbr."</a></td>";
   	 $pRow.="<td>".$w."</td>";
	 $pRow.="<td>".$l."</td>";
   	 $pRow.="<td>".$s."</td>";
	 $pRow.="<td>".$era."</td>";
   	 $pRow.="<td>".$ip."</td>";
	 $pRow.="<td>".$g."</td>";
   	 $pRow.="<td>".$gs."</td>";
	 $pRow.="<td>".$ha."</td>";
   	 $pRow.="<td>".$r."</td>";
	 $pRow.="<td>".$er."</td>";
   	 $pRow.="<td>".$hr."</td>";
	 $pRow.="<td>".$bba."</td>";
   	 $pRow.="<td>".$k."</td>";
	 $pRow.="<td>".$cg."</td>";
   	 $pRow.="<td>".$sho."</td>";
	 $pRow.="<td>".$whip."</td>";
	 $pRow.="<td>".$war."</td>";
   	 $players[$pid][$slid]['prow']=$pRow;

	 $stats="$w-$l $era ERA";
   	 if ($role!="SP") {$stats.=" $s SV";}
	 $players[$pid]['stats']=$stats;

	 if (($subleagues[$slid]['pitCnt']<=$maxPlyrs) && ($pt>$minIP))
  	  {
            $cnt=$subleagues[$slid]['pitCnt']+1;
	    $subleagues[$slid]['pitCnt']=$cnt;
   	    $subleagues[$slid]['poynames'][$pid]=$nameSort;
	  }

	 if (($rookies[$pid]==1) && ($subleagues[$slid]['pitRCnt']<=($maxPlyrs/2)) && ($pt>($minIP/3)))
  	  {
            $cnt=$subleagues[$slid]['pitRCnt']+1;
	    $subleagues[$slid]['pitRCnt']=$cnt;
   	    $subleagues[$slid]['royPnames'][$pid]=$nameSort;
          }

         if ($cmEnable==1)
          {
            if ($cmQual=='all')
             {
               if ((($cmWho=='pitchers') && ($subleagues[$slid]['cmPitCnt']<$maxPlyrs) && ($pt>=$minIP)) || (($cmWho=='relievers') && ($role!="SP") && ($subleagues[$slid]['cmPitCnt']<$maxPlyrs) && ($pt>=($minIP/3))) || (($cmWho=='all') && ($subleagues[$slid]['cmPitCnt']<($maxPlyrs/2)) && ($pt>=$minIP)))
                {
                  $cnt=$subleagues[$slid]['cmPitCnt']+1;
		  $subleagues[$slid]['cmPitCnt']=$cnt;
   		  $subleagues[$slid]['cmPnames'][$pid]=$nameSort;
		}
   	     }
	     elseif ($rookies[$pid]==1)
  	     {
               if ((($cmWho=='pitchers') && ($subleagues[$slid]['cmPitCnt']<$maxPlyrs) && ($pt>=($minIP/3))) || (($cmWho=='relievers') && ($role!="SP") && ($subleagues[$slid]['cmPitCnt']<$maxPlyrs) && ($pt>=($minIP/5))) || (($cmWho=='all') && ($subleagues[$slid]['cmPitCnt']<($maxPlyrs/2)) && ($pt>=($minIP/3))))
                {
                  $cnt=$subleagues[$slid]['cmPitCnt']+1;
		  $subleagues[$slid]['cmPitCnt']=$cnt;
   		  $subleagues[$slid]['cmPnames'][$pid]=$nameSort;
		}
   	     }
	  }
       }
    }

   ##### Sort Players Alphabetically #####
   foreach ($subleagues as $slid => $val)
    {
      if ($award=='boy')
       {
         asort($subleagues[$slid]['boynames']);
         $cnt=0;
         foreach ($subleagues[$slid]['boynames'] as $pid => $val)
          {
            $name=$players[$pid]['name'];
            $nameSort=$players[$pid]['nameSort'];
	    $pos=$players[$pid]['pos'];
   	    $avg=$players[$pid]['avg'];
	    $hr=$players[$pid]['hr'];
   	    $rbi=$players[$pid]['rbi'];
	    $bRow=$players[$pid][$slid]['brow'];

	    $cls="s".($cnt%2+1);
   	    $bRowStart="     <tr class='".$cls."'>";
	    $bRowStart.="<td><input type='checkbox' name='player' value='$pid,$pos $name ($avg/$hr/$rbi)' /></td>";
        $bRowStart.="<td>".$pos."</td>";
        $bRowStart.="<td class='left'>".$nameSort."</td>";
        $bRowStart.="<td class='left'><a href='./player.php?player_id=$pid'>".$name."</a></td>";
	    $tmp=$batters[$slid];
   	    $batters[$slid]=$tmp.$bRowStart.$bRow."</tr>\n";
	    $cnt++;
	  }
       }

      if ($award=='roy')
       {
         asort($subleagues[$slid]['royBnames']);
	 $cnt=0;
   	 foreach ($subleagues[$slid]['royBnames'] as $pid => $val)
          {
            $name=$players[$pid]['name'];
        $nameSort=$players[$pid]['nameSort'];
	    $pos=$players[$pid]['pos'];
   	    $avg=$players[$pid]['avg'];
	    $hr=$players[$pid]['hr'];
   	    $rbi=$players[$pid]['rbi'];
	    $bRow=$players[$pid][$slid]['brow'];

	    $cls="s".($cnt%2+1);
   	    $bRookStart="     <tr class='".$cls."'>";
	    $bRookStart.="<td><input type='checkbox' name='player' value='$pid,$pos $name ($avg/$hr/$rbi)' /></td>";
              $bRookStart.="<td>".$pos."</td>";
              $bRookStart.="<td class='left'>".$nameSort."</td>";
              $bRookStart.="<td class='left'><a href='./player.php?player_id=$pid'>".$name."</a></td>";
	    $tmp=$bRooks[$slid];
   	    $bRooks[$slid]=$tmp.$bRookStart.$bRow."</tr>\n";
	    $cnt++;
	  }
       }

      if ($award=='poy')
       {
         asort($subleagues[$slid]['poynames']);
	 $cnt=0;
   	 foreach ($subleagues[$slid]['poynames'] as $pid => $val)
	  {
        $name=$players[$pid]['name'];
        $nameSort=$players[$pid]['nameSort'];
	    $role=$players[$pid]['role'];
   	    $stats=$players[$pid]['stats'];
	    $pRow=$players[$pid][$slid]['prow'];

	    $cls="s".($cnt%2+1);
   	    $pRowStart="     <tr class='".$cls."'>";
	    $pRowStart.="<td><input type='checkbox' name='player' value='$pid,$role $name ($stats)' /></td>";
   	    $pRowStart.="<td>".$role."</td>";
        $pRowStart.="<td class='left'>".$nameSort."</td>";
        $pRowStart.="<td class='left'><a href='./player.php?player_id=$pid'>".$name."</a></td>";
	    $tmp=$pitchers[$slid];
   	    $pitchers[$slid]=$tmp.$pRowStart.$pRow."</tr>\n";
	    $cnt++;
	  }
       }

      if ($award=='roy')
       {
         asort($subleagues[$slid]['royPnames']);
	 $cnt=0;
   	 foreach ($subleagues[$slid]['royPnames'] as $pid => $val)
          {
            $name=$players[$pid]['name'];
              $nameSort=$players[$pid]['nameSort'];
	    $role=$players[$pid]['role'];
   	    $stats=$players[$pid]['stats'];
	    $pRow=$players[$pid][$slid]['prow'];

	    $cls="s".($cnt%2+1);
   	    $pRookStart="     <tr class='".$cls."'>";
	    $pRookStart.="<td><input type='checkbox' name='player' value='$pid,$role $name ($stats)' /></td>";
           $pRookStart.="<td>".$role."</td>";
        $pRookStart.="<td class='left'>".$nameSort."</td>";
        $pRookStart.="<td class='left'><a href='./player.php?player_id=$pid'>".$name."</a></td>";
	    $tmp=$pRooks[$slid];
   	    $pRooks[$slid]=$tmp.$pRookStart.$pRow."</tr>\n";
	    $cnt++;
	  }
       }

      if (($cmEnable==1)&&($award=='cm'))
       {
         if (($cmWho=='batters')||($cmWho=='all'))
          {
            asort($subleagues[$slid]['cmBnames']);
            $cnt=0;
            foreach ($subleagues[$slid]['cmBnames'] as $pid => $val)
	     {
	       $name=$players[$pid]['name'];
           $nameSort=$players[$pid]['nameSort'];
	       $pos=$players[$pid]['pos'];
      	       $avg=$players[$pid]['avg'];
	       $hr=$players[$pid]['hr'];
      	       $rbi=$players[$pid]['rbi'];
	       $bRow=$players[$pid][$slid]['brow'];

	       $cls="s".($cnt%2+1);
      	       $cmBStart="     <tr class='".$cls."'>";
	       $cmBStart.="<td><input type='checkbox' name='player' value='$pid,$pos $name ($avg/$hr/$rbi)' /></td>";
             $cmBStart.="<td>".$pos."</td>";
             $cmBStart.="<td class='left'>".$nameSort."</td>";
             $cmBStart.="<td class='left'><a href='./player.php?player_id=$pid'>".$name."</a></td>";
	       $tmp=$cmB[$slid];
      	       $cmB[$slid]=$tmp.$cmBStart.$bRow."</tr>\n";
	       $cnt++;
	     }
	  }
         if (($cmWho=='pitchers')||($cmWho=='relievers')||($cmWho=='all'))
          {
            asort($subleagues[$slid]['cmPnames']);
            $cnt=0;
	    foreach ($subleagues[$slid]['cmPnames'] as $pid => $val)
     	     {
	       $name=$players[$pid]['name'];
           $nameSort=$players[$pid]['nameSort'];
	       $role=$players[$pid]['role'];
      	       $stats=$players[$pid]['stats'];
	       $pRow=$players[$pid][$slid]['prow'];

	       $cls="s".($cnt%2+1);
      	       $cmPStart="     <tr class='".$cls."'>";
	       $cmPStart.="<td><input type='checkbox' name='player' value='$pid,$role $name ($stats)' /></td>";
                 $cmPStart.="<td>".$role."</td>";
                 $cmPStart.="<td class='left'>".$nameSort."</td>";
                 $cmPStart.="<td class='left'><a href='./player.php?player_id=$pid'>".$name."</a></td>";
	       $tmp=$cmP[$slid];
      	       $cmP[$slid]=$tmp.$cmPStart.$pRow."</tr>\n";
	       $cnt++;
      	     }
	  }
       }
    }

   ##### Generate Ballot Tables #####
   $boyText="    <table id=\"boyTable\" class='dataTable'>\n";
   $boyText.="     <thead>";
   $boyText.="      <tr class='title2'><th colspan=22>Batters</th></tr>\n";
   $poyText.="      <tr class='headline'>";
   $boyText.="<th class='hsc2_l'>Vote</th>";
   $boyText.="<th class='hsc2'>Pos</th>";
   $boyText.="<th class='hsc2_l'>PlayerSort</th>";
   $boyText.="<th class='hsc2_l'>Player</th>";
   $boyText.="<th class='hsc2'>Tm</th>";
   $boyText.="<th class='hsc2'>G</th>";
   $boyText.="<th class='hsc2'>AB</th>";
   $boyText.="<th class='hsc2'>R</th>";
   $boyText.="<th class='hsc2'>H</th>";
   $boyText.="<th class='hsc2'>2B</th>";
   $boyText.="<th class='hsc2'>3B</th>";
   $boyText.="<th class='hsc2'>HR</th>";
   $boyText.="<th class='hsc2'>RBI</th>";
   $boyText.="<th class='hsc2'>BB</th>";
   $boyText.="<th class='hsc2'>SB</th>";
   $boyText.="<th class='hsc2'>CS</th>";
   $boyText.="<th class='hsc2'>AVG</th>";
   $boyText.="<th class='hsc2'>OBP</th>";
   $boyText.="<th class='hsc2'>SLG</th>";
   $boyText.="<th class='hsc2'>OPS</th>";
   $boyText.="<th class='hsc2'>WAR</th>";
   $boyText.="<th class='hsc2'>wOBA</th>";
   $boyText.="</tr></thead>\n";
   $boyText.="     <tbody>\n";
    
   $poyText="    <table id=\"poyTable\" class='dataTable'>\n";
    $poyText.="     <thead>";
    $poyText.="      <tr class='title2'><th colspan=22>Pitchers</th></tr>\n";
    $poyText.="      <tr class='headline'>";
   $poyText.="<th class='hsc2_l'>Vote</th>";
   $poyText.="<th class='hsc2'>Role</th>";
   $poyText.="<th class='hsc2_l'>PlayerSort</th>";
   $poyText.="<th class='hsc2_l'>Player</th>";
   $poyText.="<th class='hsc2'>Tm</th>";
   $poyText.="<th class='hsc2'>W</th>";
   $poyText.="<th class='hsc2'>L</th>";
   $poyText.="<th class='hsc2'>SV</th>";
   $poyText.="<th class='hsc2'>ERA</th>";
   $poyText.="<th class='hsc2'>IP</th>";
   $poyText.="<th class='hsc2'>G</th>";
   $poyText.="<th class='hsc2'>GS</th>";
   $poyText.="<th class='hsc2'>HA</th>";
   $poyText.="<th class='hsc2'>R</th>";
   $poyText.="<th class='hsc2'>ER</th>";
   $poyText.="<th class='hsc2'>HR</th>";
   $poyText.="<th class='hsc2'>BB</th>";
   $poyText.="<th class='hsc2'>K</th>";
   $poyText.="<th class='hsc2'>CG</th>";
   $poyText.="<th class='hsc2'>SHO</th>";
   $poyText.="<th class='hsc2'>WHIP</th>";
   $poyText.="<th class='hsc2'>WAR</th>";
   $poyText.="</tr></thead>\n";
   $poyText.="     <tbody>\n";
   
   ##### Write Data to Cache #####
   switch ($award)
    {
      case 'boy':
        $retText=$boyText;
        $retText.=$batters[$sub_league];
        $retText.="     </tbody>\n";
        $retText.="   </table>\n";
	mysqli_close($db);
	return $retText;
        break;
      case 'poy':
        $retText=$poyText;
        $retText.=$pitchers[$sub_league];
        $retText.="     </tbody>\n";
        $retText.="   </table>\n";
	mysqli_close($db);
	return $retText;
	break;
      case 'roy':
        $retText.=$boyText;
	$retText.=$bRooks[$sub_league];
    $retText.="     </tbody>\n";
   	$retText.="   </table>\n";

    $retText.=$poyText;
   	$retText.=$pRooks[$sub_league];
    $retText.="     </tbody>\n";
	$retText.="   </table>\n";
	mysqli_close($db);
	return $retText;
	break;
      case 'cm':
	$retText="";
        if ($cmEnable==1)
         {
           if (($cmWho=='batters')||($cmWho=='all'))
	    {
   	      $retText.=$boyText;
	      $retText.=$cmB[$sub_league];
          $retText.="     </tbody>\n";
	      $retText.="   </table>\n";
	    }
   	   if (($cmWho=='pitchers')||($cmWho=='relievers')||($cmWho=='all'))
	    {
	      $retText.=$poyText;
	      $retText.=$cmP[$sub_league];
          $retText.="     </tbody>\n";
	      $retText.="   </table>\n";
	    }
	 }
	mysqli_close($db);
	return $retText;
       break;	
    }

   ##### Get Fielders #####
   if (($ggEnable==1)&&($award=='gg'))
    {
		## 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=7;";
		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;
			}
		}
		
      ## Get Primary Position
      $query="SELECT player_id,position,(SUM(ip)*3+SUM(ipf))/3 as ip FROM players_career_fielding_stats WHERE league_id=$lgid AND year=$year GROUP BY player_id,position ORDER BY player_id,ip DESC;";
      $result=mysqli_query($db,$query);
      $prevPID="";
      while ($row=mysqli_fetch_array($result))
       {
         $pid=$row['player_id'];
         $pos=$row['position'];
         if ((($pos==7) || ($pos==8) || ($pos==9)) && ($splitOF==0))
          {
            $players[$pid]['ofFIP']=$players[$pid]['ofFIP']+$row['ip'];
            if ($row['ip']>$players[$pid]['ofMaxIP'])
             {
               $players[$pid]['ofMaxIP']=$row['ip'];
               $players[$pid]['ofPOS']=$pos;
             }
          }
         if ($prevPID!=$pid)
          {
            $players[$pid]['pos']=$row['position'];
            $players[$pid]['FIP']=$row['ip'];
          }
         $prevPID=$pid;
       }

      ## Get Fielding Stats
      $query="SELECT p.player_id,p.first_name,p.last_name,pcf.position,t.team_id,t.abbr,t.sub_league_id,tr.g as tgame,(SUM(ip)*3+SUM(ipf))/3 as ip,SUM(pcf.g) as g,SUM(gs) as gs,SUM(po) as po,SUM(a) as a,SUM(dp) as dp,SUM(tc) as tc,SUM(e) as e,SUM(pb) as pb,SUM(sba) as sba,SUM(rto) as rto,SUM(zr) as zr";
      $query.=" FROM players_career_fielding_stats as pcf,players as p,(SELECT team_id,g FROM team_record) as tr,teams as t";
      $query.=" WHERE pcf.team_id=tr.team_id";
      $query.=" AND pcf.team_id=t.team_id";
      $query.=" AND t.team_id=tr.team_id";
      $query.=" AND pcf.player_id=p.player_id";
      $query.=" AND pcf.league_id=$lgid";
      $query.=" AND t.sub_league_id=$sub_league";
      $query.=" AND pcf.position IN (1,2,3,4,5,6";
      if ($splitOF==1) {$query.=",7,8,9)";} else {$query.=")";}
      $query.=" AND year=$year";
      $query.=" GROUP BY player_id,pcf.position,sub_league_id";
      if ($splitOF==0)
       {
         $query.=" UNION";
	 $query.=" SELECT p.player_id,p.first_name,p.last_name,20 as position,t.team_id,t.abbr,t.sub_league_id,tr.g as tgame,(SUM(ip)*3+SUM(ipf))/3 as ip,SUM(pcf.g) as g,SUM(gs) as gs,SUM(po) as po,SUM(a) as a,SUM(dp) as dp,SUM(tc) as tc,SUM(e) as e,SUM(pb) as pb,SUM(sba) as sba,SUM(rto) as rto,SUM(zr) as zr";
   	 $query.=" FROM players_career_fielding_stats as pcf,players as p,(SELECT team_id,g FROM team_record) as tr,teams as t";
	 $query.=" WHERE pcf.team_id=tr.team_id";
   	 $query.=" AND pcf.team_id=t.team_id";
	 $query.=" AND t.team_id=tr.team_id";
   	 $query.=" AND pcf.player_id=p.player_id";
	 $query.=" AND pcf.league_id=$lgid";
   	 $query.=" AND pcf.position IN (7,8,9)";
	 $query.=" AND year=$year";
	 $query.=" GROUP BY player_id,sub_league_id";
       }
      $query.=" ORDER BY position,sub_league_id,last_name,first_name;";
      
      $result=mysqli_query($db,$query);
      while ($row=mysqli_fetch_array($result))
       {
         $pid=$row['player_id'];
         $ip=$row['ip'];
         $tg=$row['tgame'];
         $pt=$ip/$tg;
         $tc=$row['tc'];
	 $pos=$row['position'];
	 $maxPOS=$players[$pid]['pos'];

         if (($pos!=$maxPOS)&&($pos!=20)) {continue;}    #Only include max FIP position      
	
	 if ((($maxPOS==7)||($maxPOS==8)||($maxPOS==9))&&($pos!=20)&&($splitOF==0)) {continue;}    #Only include max FIP position      
	
	 if (($tc==0) || (($pt<$minFIP) && ($pos!=1)) || (($pt<1.0) && ($pos==1))) {continue;}

         $name=$row['first_name']." ".$row['last_name'];
         $slid=$row['sub_league_id'];
         $tid=$row['team_id'];
         $tabbr=$row['abbr'];
         $players[$pid]['slid']=$slid;

         $g=$row['g'];
         $gs=$row['gs'];
         $po=$row['po'];
         $a=$row['a'];
         $dp=$row['dp'];
         $e=$row['e'];
         $pb=$row['pb'];
         $sba=$row['sba'];
         $rto=$row['rto'];
         $zr=$row['zr'];
         
         $fpct=($po+$a)/$tc;
         $rng=($po+$a)/($ip/9);
         if ($sba==0) {$csPct=0;}
          else {$csPct=$rto/$sba;}

         $fpct=sprintf("%0.3f",$fpct);
         if ($fpct<1) {$fpct=substr($fpct,1);}
         $rng=sprintf("%0.2f",$rng);
         $csPct=sprintf("%0.1f",100*$csPct);
         
         $ip=sprintf("%0.1f",$ip);
         $zr=sprintf("%0.1f",$zr);
         if ($zr>0) {$zr="+".$zr;}
      
         $fRow="<td><a href='$lgpath/teams/team_$tid.html'>".$tabbr."</a></td>";
         $fRow.="<td>".$g."</td>";
         $fRow.="<td>".$gs."</td>";
         $fRow.="<td>".$po."</td>";
         $fRow.="<td>".$a."</td>";
         $fRow.="<td>".$dp."</td>";
         $fRow.="<td>".$tc."</td>";
         $fRow.="<td>".$e."</td>";
         $fRow.="<td>".$fpct."</td>";
         $fRow.="<td>".$ip."</td>";
         $fRow.="<td>".$rng."</td>";
         $fRow.="<td>".$zr."</td>";
         if ($pos==2)
          {
            $fRow.="<td>".$pb."</td>";
            $fRow.="<td>".$sba."</td>";
            $fRow.="<td>".$rto."</td>";
            $fRow.="<td>".$csPct."</td>";
          }
            
         switch ($pos)
          {
            case 1: $poskey='pitcher';     $itype='radio'; break;
            case 2: $poskey='catcher';     $itype='radio'; break;
            case 3: $poskey='firstbase';   $itype='radio'; break;
            case 4: $poskey='secondbase';  $itype='radio'; break;
            case 5: $poskey='thirdbase';   $itype='radio'; break;
            case 6: $poskey='shortstop';   $itype='radio'; break;
	    case 7:
	      if ($splitOF==1)
	       {
	         $poskey='leftfield';
	         $itype='radio';
	       }
	       else
	       {
	         $poskey='outfield[]';
	         $itype='checkbox';
	       }
	      break;
            case 8:
	      if ($splitOF==1)
	       {
	         $poskey='centerfield';
	         $itype='radio';
	       }
	       else
	       {
	         $poskey='outfield[]';
	         $itype='checkbox';
	       }
	      break;
            case 9:
	      if ($splitOF==1)
	       {
	         $poskey='rightfield';
	         $itype='radio';
	       }
	       else
	       {
	         $poskey='outfield[]';
	         $itype='checkbox';
	       }
	      break;
            case 20: $poskey='outfield[]'; $itype='checkbox'; break;
          }
          
         $cnt=$subleagues[$slid]['ggCnt']+1;
         $cls="s".($cnt%2+1);
         $subleagues[$slid]['ggCnt']=$cnt;
		   if ((($pos==7)||($pos==8)||($pos==9))&&($splitOF==0)) {$pos=20;}
         $fRowStart="     <tr class='".$cls."'>";
         $fRowStart.="<td><input type='".$itype."' name='".$poskey."' value=$pid ";
		   if ($voted[$pid]==$pos) {$fRowStart.="checked='checked' ";}
		 $fRowStart.="/></td>";
         $fRowStart.="<td class='".$cls."_l'><a href='./player.php?player_id=$pid'>".$name."</a></td>";
         $tmp=$fielders[$slid][$pos];
         $fielders[$slid][$pos]=$tmp.$fRowStart.$fRow."</tr>\n";
       }

      for ($i=1;$i<=$nPos;$i++)
       {
         if (($i==7)&&($splitOF==0)) {$pos=20;}
          else {$pos=$i;}
          
         $ggText[$pos]="    <table cellpadding=2 cellspacing=0 border=0 class='sortable' width='100%'>\n";
         $ggText[$pos].="     <thead><tr class='headline'>";
         $ggText[$pos].="<td class='hsc2_l'>Vote</td>";
         $ggText[$pos].="<td class='hsc2_l'>Player</td>";
         $ggText[$pos].="<td class='hsc2'>Tm</td>";
         $ggText[$pos].="<td class='hsc2'>G</td>";
         $ggText[$pos].="<td class='hsc2'>GS</td>";
         $ggText[$pos].="<td class='hsc2'>PO</td>";
         $ggText[$pos].="<td class='hsc2'>A</td>";
         $ggText[$pos].="<td class='hsc2'>DP</td>";
         $ggText[$pos].="<td class='hsc2'>TC</td>";
         $ggText[$pos].="<td class='hsc2'>E</td>";
         $ggText[$pos].="<td class='hsc2'>Pct</td>";
         $ggText[$pos].="<td class='hsc2'>IP</td>";
         $ggText[$pos].="<td class='hsc2'>Range</td>";
         $ggText[$pos].="<td class='hsc2'>ZR</td>";
         if ($pos==2)
          {
            $ggText[$pos].="<td class='hsc2'>PB</td>";
            $ggText[$pos].="<td class='hsc2'>SBA</td>";
            $ggText[$pos].="<td class='hsc2'>RTO</td>";
            $ggText[$pos].="<td class='hsc2'>RTO%</td>";
          }
         $ggText[$pos].="</tr></thead>\n";
       }

      ##### Write Data to Cache #####
      $retGGText="  <table cellpadding=0 cellspacing=0 border=0>\n";
      for ($i=1;$i<=$nPos;$i++)
       {
         if (($i==7)&&($splitOF==0)) {continue;}
         switch ($i)
          {
            case 1: $img='p'; break;
	    case 2: $img='c'; break;
	    case 3: $img='1b'; break;
	    case 4: $img='2b'; break;
	    case 5: $img='3b'; break;
	    case 6: $img='ss'; break;
	    case 7: $img='lf'; break;
	    case 8: $img='cf'; break;
	    case 9: $img='rf'; break;
	  }
         $retGGText.="   <tr><td><img src='./images/$img.png' /></td></tr>\n";
         $retGGText.="   <tr><td>\n";
         $retGGText.=$ggText[$i];
         $retGGText.=$fielders[$sub_league][$i];
         $retGGText.="    </table>\n";
         $retGGText.="   </td></tr><tr><td>&nbsp;</td></tr>\n";
       }
      if ($splitOF==0)
       {
	 $retGGText.="   <tr><td><img src='./images/of.png' /></td></tr>\n";
	 $retGGText.="   <tr><td>\n";
   	 $retGGText.=$ggText[20];
	 $retGGText.=$fielders[$sub_league][20];
	 $retGGText.="    </table>\n";
	 $retGGText.="   </td></tr>\n";
       }
      $retGGText.="  </table>\n";

      mysqli_close($db);
      return $retGGText;
    }

   ##### General Manager Ballot #####
   if (($gmEnable==1)&&($award=='gm'))
    {
      ## Get GM's
      $query="SELECT human_manager_id,first_name,last_name,organization_id FROM human_managers WHERE league_id=$lgid ORDER BY last_name,first_name;";
      $result=mysqli_query($db,$query);
      while ($row=mysqli_fetch_array($result))
       {
         $hmid=$row['human_manager_id'];
	 $name=$row['first_name']." ".$row['last_name'];
           $nameSort=$row['last_name'].", ".$row['first_name'];
	 $tid=$row['organization_id'];
	 $managers[$hmid]['tid']=$tid;
     $managers[$hmid]['name']=$name;
     $managers[$hmid]['nameSort']=$nameSort;
       }

      ## Get team records
      $query="SELECT t.team_id,name,nickname,w,l,pos,pct,gb FROM teams as t,team_record as tr WHERE t.team_id=tr.team_id AND t.league_id=$lgid;";
      $result=mysqli_query($db,$query);
      while ($row=mysqli_fetch_array($result))
       {
         $tid=$row['team_id'];
         $w=$row['w'];
         $l=$row['l'];
	 $gb=$row['gb'];
	 if ($gb==0) {$gb="-";}
 	  else {$gb=sprintf("%.1f",$gb);}
	 if (($w+$l)==0) {$pct=0;}
 	  else {$pct=$w/($w+$l);}
         $pct=sprintf("%.3f",$pct);
         if ($pct<1) {$pct=substr($pct,1);}
         $teams[$tid]['name']=$row['name']." ".$row['nickname'];
         $teams[$tid]['w']=$w;
         $teams[$tid]['l']=$l;
         $teams[$tid]['pos']=ordinal_suffix($row['pos']);
	 $teams[$tid]['gb']=$gb;
	 $teams[$tid]['pct']=$pct;
       }

      ## Get Playoff Odds Configuration
      $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 IN ('admin','Last Sim') AND setting IN ('pythMeth','pythExp')";
	      $result=mysqli_query($db,$query);
   	      if (mysqli_num_rows($result))
	      {
   		      while ($row=mysqli_fetch_array($result))
		      {
   			      $setting=$row['setting'];
			      $val=$row['value'];

			      switch ($setting)
   			      {
			      case 'pythMeth'     : $pythMeth=$val;     break;
   			      case 'pythExp'      : $pythExp=$val;      break;
			      }
   		      }
	      }
      }
      switch ($pythMeth)
      {
      case 'Pythagorean Win Pct (Pythagenpat)': $pythMeth='pythPat';break;
      case 'Actual Win Pct': $pythMeth='record'; break;
      default: $pythMeth='pythExp';break;
      }
      if ($pythMeth=="") {$pythMeth='pythExp';}
      if ($pythExp=="") {$pythExp=1.82;}
     
      ## Get Pyth Records
      $query="SELECT tb.team_id,tb.r as rf,tp.r as ra FROM team_batting_stats as tb,team_pitching_stats as tp WHERE tb.team_id=tp.team_id AND tb.league_id=$lgid;";
      $result=mysqli_query($db,$query);
      while ($row=mysqli_fetch_array($result))
       {
         $tid=$row['team_id'];
         $rf=$row['rf'];
	 $ra=$row['ra'];

	 $teams[$tid]['rf']=$rf;
	 $teams[$tid]['ra']=$ra;

	 $w=$teams[$tid]['w'];
	 $l=$teams[$tid]['l'];
	 $g=$w+$l;

         switch ($pythMeth)
          {
            case 'pythPat':
	       $pythExp=pow(($rf+$ra)/$g,0.287);
	       $pythPct=pow($rf,$pythExp)/(pow($rf,$pythExp)+pow($ra,$pythExp));
   	       break;
 	    case 'pythExp':
	       $pythPct=pow($rf,$pythExp)/(pow($rf,$pythExp)+pow($ra,$pythExp));
	       break;
	    case 'record':
	    default:
	       $pythPct=$teams[$tid]['pct'];
	       break;
          }
   	 $teams[$tid]['pythPct']=$pythPct;
	 $teams[$tid]['pythW']=round($g*$teams[$tid]['pythPct'],0);
   	 $teams[$tid]['pythL']=$g-$teams[$tid]['pythW'];
	 $teams[$tid]['pythDiff']=$w-$teams[$tid]['pythW'];
       }

      ## Generate Ballot
      $gmText="";
      $gmText.="  <table id=\"gmTable\" class='dataTable'>\n";
      $gmText.="   <thead><tr class='headline'><th class='hsc2_l'>Vote</th><th class='hsc2_l'>GMSort</th><th class='hsc2_l'>General Manager</th><th class='hsc2_l'>Team</th><th class='hsc2'>W</th><th class='hsc2'>L</th><th class='hsc2'>Pct</th><th class='hsc2'>Finish</th><th class='hsc2'>GB</th><th class='hsc2'>RF</th><th class='hsc2'>RA</th><th class='hsc2'>PRec</th><th class='hsc2'>PPct</th><th class='hsc2'>Diff</th></tr></thead>\n";
      $cnt=0;
      foreach ($managers as $hmid => $val)
       {
         $cls='s'.($cnt%2+1);
	 $name=$managers[$hmid]['name'];
     $nameSort=$managers[$hmid]['nameSort'];
	 $tid=$managers[$hmid]['tid'];
	 $w=$teams[$tid]['w'];
	 $l=$teams[$tid]['l'];
	 $pct=$teams[$tid]['pct'];
	 $fin=$teams[$tid]['pos'];
	 $gmText.="   <tr class='$cls'>";
	 $gmText.="    <td><input type='checkbox' name='player' value='$hmid,$name ($w-$l, $fin place)' /></td>";
           $gmText.="<td class='left'>".$nameSort."</td>";
	 $gmText.="<td class='left'><a href='$lgpath/coaches/human_manager_$hmid.html'>".$name."</a></td>";
	 $gmText.="<td class='left'><a href='$lgpath/teams/team_$tid.html'>".$teams[$tid]['name']."</a></td>";
	 $gmText.="<td>".$w."</td>";
	 $gmText.="<td>".$l."</td>";
	 $gmText.="<td>".$pct."</td>";
	 $gmText.="<td>".$fin."</td>";
	 $gmText.="<td>".$teams[$tid]['gb']."</td>";
	 $gmText.="<td>".$teams[$tid]['rf']."</td>";
	 $gmText.="<td>".$teams[$tid]['ra']."</td>";
	 $gmText.="<td>".$teams[$tid]['pythW']."-".$teams[$tid]['pythL']."</td>";
	 $pythPct=sprintf("%.3f",$teams[$tid]['pythPct']);
	 if ($pythPct<1) {$pythPct=substr($pythPct,1);}
	 $gmText.="<td>".$pythPct."</td>";
	 $gmText.="<td>".$teams[$tid]['pythDiff']."</td>";
	 $gmText.="</tr>\n";
	 $cnt++;
       }
      $gmText.="  </table>\n";

      mysqli_close($db);
      return $gmText;
    }
 }


?>
