<?php

  include("html_functions.php");



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

  $lgid=$_SESSION['lgid'];

  $lgpath=$_SESSION['lgpath'];

  $lgdate=$_SESSION['lgdate'];

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

  $lgyear=$_SESSION['lgyear'];

  $lgdateDay=$date->format("z");



  $topXLimit=5;



  ## Get Sim Length

  $simLen=get_sim_length($_SESSION['adminpath'],$lgid);



  ## Process GET's

  if ((($lgyear%400)==0) || ((($lgyear%100)!=0) && (($lgyear%4)==0)))

  {

       	  $monthDays=Array("1"=>31,"2"=>29,"3"=>31,"4"=>30,"5"=>31,"6"=>30,"7"=>31,"8"=>31,"9"=>30,"10"=>31,"11"=>30,"12"=>31);

  }

  else

  {

       	  $monthDays=Array("1"=>31,"2"=>28,"3"=>31,"4"=>30,"5"=>31,"6"=>30,"7"=>31,"8"=>31,"9"=>30,"10"=>31,"11"=>30,"12"=>31);

  }

  

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

  {

       	  switch ($key)

	  {

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

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

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

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

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

	  case 'from': $frDay=$val; break;

    	  case 'to': $toDay=$val; break;

	  case 'pList':

	  	  $e=explode("|",$val);

		  for ($i=0;$i<count($e);$i++)

	 	  {

			  $id=$e[$i];

	       		  if ($view=='teams') 

			  {

		    		  if (strpos($id,"^"))

				  {

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



					  #Get Teams in Division/League

					  $dExp=explode("^",$id);

			 		  $sLeagueID=$dExp[0];

					  $divID=$dExp[1];

			 		  $query="SELECT team_id FROM team_relations WHERE league_id=$lgid";

					  if ($sLeagueID!="") {$query.=" AND sub_league_id=$sLeagueID";}

			 		  if ($divID!="") {$query.=" AND division_id=$divID";}

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

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

					  if (mysqli_num_rows($result))

					  {

						  while ($row=mysqli_fetch_array($result))

			     			  {

							  $tid=$row['team_id'];

				   			  $dispTIDS[$tid]=1;

							  $tidList.="$tid,";

			     			  }

					  }

					  mysqli_close($db);

				  }

				  else

		   		  {

					  #Single Team

					  $dispTIDS[$id]=1;

					  $tidList.="$id,";

		   		  }

			  }

	      		  elseif ($view=='players') {$dispPIDS[$id]=1;$pidList.="$id,";}

		  }

	  	  break;

	  }

  }

  if (!isset($_GET['stat'])) {$stat="";}

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

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

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



  if ($frDay=="") {$frDay="1/1";$minDay=1;}

  else

  {

	  $e=explode("/",$frDay);

       	  $mo=$e[0];

	  if ($mo[0]==0) {$mo=substr($mo,1);}

       	  if ($mo<1) {$mo=1;}

	  if ($mo>12) {$mo=12;}

       	  $dy=$e[1];

	  if ($dy[0]==0) {$dy=substr($dy,1);}

       	  if ($dy<1) {$dy=1;}

	  if ($dy>$monthDays[$mo]) {$dy=$monthDays[$mo];}

       	  $frDay=$mo."/".$dy;

	  unset($tmpdate);

       	  $tmpdate=new Date($frDay."/".$lgyear);

	  $minDay=$tmpdate->format("z");

  }

  if ($toDay=="") {$toDay=$date->format("m/d");$maxDay=1;}

  else

  {

	  $e=explode("/",$toDay);

       	  $mo=$e[0];

	  if ($mo[0]==0) {$mo=substr($mo,1);}

       	  if ($mo<1) {$mo=1;}

	  if ($mo>12) {$mo=12;}

       	  $dy=$e[1];

	  if ($dy[0]==0) {$dy=substr($dy,1);}

       	  if ($dy<1) {$dy=1;}

	  if ($dy>$monthDays[$mo]) {$dy=$monthDays[$mo];}

       	  $toDay=$mo."/".$dy;

	  unset($tmpdate);

       	  $tmpdate=new Date($toDay."/".$lgyear);

	  $maxDay=$tmpdate->format("z")+1;

  }

  if ($minDay==$maxDay) {$minDay-=2;}

  if ($minDay>$maxDay)

  {

       	  $tmp=$frDay;

	  $frDay=$toDay;

       	  $toDay=$tmp;

	  $tmp=$minDay;

       	  $minDay=$maxDay;

	  $maxDay=$minDay;

  }



  if ((($ndays=="")||($ndays<2))||($scope=='lastSim')) {$ndays=$simLen;}

  if ($ndays>$lgdateDay) {$ndays=$lgdateDay;}

	  

  # Title Bar

  $title='Graphs';



  page_head($title,$_SESSION['lgpath'],"","","graph.js|text_functions.js|player_lookup.js|./jquery/excanvas.js|./jquery/jquery.min.js|./jquery/jquery.jqplot.min.js|./jquery/plugins/jqplot.categoryAxisRenderer.min.js|./jquery/plugins/jqplot.pointLabels.min.js|./jquery/plugins/jqplot.canvasOverlay.min.js|./jquery/plugins/jqplot.highlighter.min.js|./jquery/plugins/jqplot.cursor.min.js|./jquery/plugins/jqplot.dateAxisRenderer.min.js");

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

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

  nav_toolbar("season","Season");

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

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



  ##### Get Sim Length #####	  

  $simLen=get_sim_length($_SESSION['adminpath'],$lgid);



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

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



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

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

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

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

  echo "    <tr><form action='./graphs.php' method='get'>\n";

  ## Show Type Selection

  echo "     <td><b>View:</b>";

  if ($view!="") {echo " (<a href='./graphs.php'>Quick Links</a>)";}

  echo "</td>\n";

  echo "     <td><input type='radio' name='view' value='teams' id='teams'";

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

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

  echo "     <td><label for='teams'>Teams</label></td>";

  echo "     <td><input type='radio' name='view' value='players' id='players'";

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

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

  echo "     <td><label for='players'>Players</label></td>";

  

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

  

  ## Show Scope Selection

  if ($view!="")

  {

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

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

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

       	  echo "></td>";

	  echo "     <td><label for='season'>Entire Season</label></td>";

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

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

       	  echo "></td>";

	  echo "     <td><table><tr><td><label for='lastX'>Last</label></td><td><INPUT type='text' size=3 maxlength=3 name='ndays' value='$ndays' onchange=\"document.getElementById('lastX').checked=true;\"></td><td>Days</td></tr></table></td>";



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



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

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

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

       	  echo "></td>";

	  echo "     <td><label for='lastSim'>Last Sim</label></td>";

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

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

       	  echo "></td>";

	  echo "     <td><table><tr><td><label for='dRange'>Date Range</label> (MM/DD)</td><td>From</td><td><INPUT type='text' size=5 maxlength=5 name='from' value='$frDay' onchange=\"document.getElementById('dRange').checked=true;\"></td><td>To</td><td><INPUT type='text' size=5 maxlength=5 name='to' value='$toDay' onchange=\"document.getElementById('dRange').checked=true;\"></td></tr></table></td>";



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

  }



  switch ($view)

  {

  case 'players':

     ## Show stat filter

     echo "     <td valign='top'><b>Stat:</b></td>\n";

     echo "     <td colspan=4 valign='top'>\n";

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

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

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

      {

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

	 else

	 {

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

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

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

     	 }

      }

     echo "      </select>\n";

     echo "     </td>\n";

     ## Get Teams

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

      }



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



     ## Zero Stats Option

     echo "     <td><b>Start at Zero</b></td>\n";

     echo "     <td><input type='checkbox' name='zeroStats' id='zeroStats' value=1";

     if ($zeroStats==1) {echo " checked='yes'";}

     echo "></td>\n";

     echo "     <td colspan=3><label for='zeroStats'>Disregard history prior to dataset</label></td>\n";



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



     ## Show player filter

     echo "     <td colspan=2 valign='top'><b>Available Players:</b></td>\n";

     echo "     <td valign='top'>&nbsp;</td>\n";

     echo "     <td colspan=2 valign='top'><b>Included Players:</b></td>\n";

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

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

     echo "      <input type='textbox' name='srchStr' value='Enter search string' style='width:250px;font-style:italic;color:#999999;'";

     echo " onfocus=\"if(this.value==='Enter search string') {this.value='';this.style.fontStyle='normal';this.style.color='#000000';}\"";

     echo " onblur=\"if(this.value==='') {this.value='Enter search string';this.style.fontStyle='italic';this.style.color='#999999';}\"";

     echo " onkeyup=\"getPlayers($lgid,this.value,'$lgyear','',document.getElementById('player_list'));\"";

     echo " />\n";

     echo "     </td>\n";

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

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

     echo "     <td colspan=2 valign='top'>\n";

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

     echo "      <select name='player_list' multiple='multiple' size=10 id='player_list' style='width:300px;font-style:italic;color:#999999;'>\n";

     echo "       <option value='-1' disabled='disabled'>Search to add players</option>\n";

     echo "      </select>\n";

     echo "     </td>\n";

     echo "      </select>\n";

     echo "     </td>\n";

     echo "     <td><input type='button' onclick=\"addElem(document.getElementById('player_list'),document.getElementById('id_list'),'Select and add players to graph');\" value='Add' />\n";

     echo "         <br/>\n";

     echo "         <input type='button' onclick=\"removeFromList(document.getElementById('id_list'),'Select and add players to graph');\" value='Remove' /></td>\n";

     echo "     <td colspan=2 valign='top'>\n";

     echo "      <select name='id_list' multiple='multiple' size=10 id='id_list'>\n";

     if (isset($dispPIDS))

     {

	     $plist="";

	     foreach ($dispPIDS as $pid => $val) {$plist.=",$pid";}

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



	     $query="SELECT p.player_id,first_name,last_name,if(position=1,role,position) as position,organization_id FROM players as p,(SELECT player_id FROM (SELECT player_id FROM players_career_pitching_stats WHERE league_id=$lgid AND year=$lgyear AND player_id IN ($plist) GROUP BY player_id UNION SELECT player_id FROM players_career_batting_stats WHERE league_id=$lgid AND year=$lgyear AND player_id IN ($plist) GROUP BY player_id) as t GROUP BY player_id) as x WHERE p.player_id=x.player_id ORDER BY last_name,first_name;";

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

	     if (mysqli_num_rows($result)!=0)

       	     {

		     while ($row=mysqli_fetch_array($result))

	    	     {

			     $player=$row['player_id'];

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

			     $fi=$row['first_name'];

		  	     $fi=$fi[0];

			     $tid=$row['organization_id'];

		  	     if ($tid==0) {$tabbr='FA';}

			     else {$tabbr=$teams[$tid]['abbr'];}

		  	     $position=get_pos($row['position'],1);

			     $players[$player]['dispname']=$position." ".$name;

		  	     $players[$player]['legend']=$position." ".$fi.". ".$row['last_name'];

			     $players[$player]['tabbr']=$tabbr;

		  	     echo "       <option value='$player'>$position $name ($tabbr)</option>\n";

		     }

       	     }

     }

     if (count($dispPIDS)==0) {echo "       <option value=0>Select and add players to graph</option>\n";}

     echo "      </select>\n";

     echo "     </td>\n";     

     break;

  case 'teams':

     	  ## Show stat filter

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

     	  echo "     <td valign='top' colspan=3>\n";

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

     	  $statArray=array('record'=>'Record','gmovr500'=>'Games over .500','winpct'=>'Win %','pOdds'=>'Playoff Odds','batting'=>'Batting','ab'=>'AB','h'=>'H','d'=>'2B','t'=>'3B','hr'=>'HR','rbi'=>'RBI','r'=>'R','sb'=>'SB','cs'=>'CS','bb'=>'BB','k'=>'K','sf'=>'SF','sh'=>'SH','ibb'=>'IBB','hp'=>'HBP','gdp'=>'GIDP','pa'=>'PA','avg'=>'AVG','obp'=>'OBP','slg'=>'SLG','ops'=>'OPS','pitching'=>'Pitching','ip'=>'IP','qs'=>'QS','pk'=>'K','pbb'=>'BB','ha'=>'HA','hra'=>'HR','pr'=>'R','er'=>'ER','hld'=>'HLD','svo'=>'SVO','bs'=>'BS','da'=>'2BA','ta'=>'3BA','bk'=>'BK','wp'=>'WP','php'=>'HP','bf'=>'BF','era'=>'ERA','whip'=>'WHIP','kper9'=>'K/9IP','bbper9'=>'BB/9IP','hper9'=>'H/9IP','kperbb'=>'K/BB');

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

    	  {

		  if (($key=='record')||($key=='batting')||($key=='pitching')) {echo "       <optgroup label='$val'>";continue;}

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

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

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

	  }

     	  echo "      </select>\n";

	  echo "     </td>\n";



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

     

	  ## Zero Stats Option

	  echo "     <td><b>Start at Zero:</b></td>\n";

     	  echo "     <td><input type='checkbox' name='zeroStats' id='zeroStats' value=1";

	  if ($zeroStats==1) {echo " checked='yes'";}

     	  echo "></td>\n";

	  echo "     <td colspan=3><label for='zeroStats'>Disregard history prior to dataset</label></td>\n";

     

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

     

	  ## Show team filter

	  echo "     <td colspan=2 valign='top'><b>Available Teams:</b></td>\n";

     	  echo "     <td valign='top'>&nbsp;</td>\n";

	  echo "     <td colspan=2 valign='top'><b>Included Teams:</b></td>\n";

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

	  echo "     <td colspan=2 valign='top'>\n";

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

	  echo "      <select name='team_list' multiple='multiple' size=10 id='team_list'>\n";

     	  echo "      <optgroup label='Divisions'>\n";

	  $query="SELECT sl.sub_league_id,sl.name as slname,division_id,d.name as divname FROM sub_leagues as sl,divisions as d WHERE sl.league_id=d.league_id AND sl.sub_league_id=d.sub_league_id AND sl.league_id=$lgid ORDER BY sub_league_id,division_id;";

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

	  if (mysqli_num_rows($result)!=0)

    	  {

		  while ($row=mysqli_fetch_array($result))

	 	  {

			  $slid=$row['sub_league_id'];

	       		  $did=$row['division_id'];

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

	       		  $divisions[$did]['name']=$row['divname'];

			  if ($slid!=$prevSLID)

	      		  {

				  echo "       <option value='$slid^,All ".$subleagues[$slid]['name']." Teams'>All ".$subleagues[$slid]['name']." Teams</option>\n";

	       		  }

			  echo "       <option value='$slid^$did,".$subleagues[$slid]['name']." ".$divisions[$did]['name']."'>".$subleagues[$slid]['name']." ".$divisions[$did]['name']."</option>\n";

	       		  $prevSLID=$slid;

		  }

    	  }

	  echo "      <optgroup label='Teams'>\n";

     	  $query="SELECT team_id,name,nickname,abbr FROM teams WHERE league_id=$lgid AND allstar_team=0 ORDER BY name,nickname;";

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

     	  if (mysqli_num_rows($result)!=0)

	  {

	  	  while ($row=mysqli_fetch_array($result))

		  {

	       		  $team=$row['team_id'];

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

	       		  $abbr=$row['abbr'];

			  $teams[$team]['abbr']=$abbr;

	       		  $teams[$team]['dispname']=$name;

			  $teams[$team]['legend']=$abbr;

	       		  echo "       <option value='$team,$name ($abbr)'>$name ($abbr)</option>\n";

		  }

    	  }

	  echo "      </select>\n";

     	  echo "     </td>\n";

	  echo "     <td><input type='button' onclick=\"addElem(document.getElementById('team_list'),document.getElementById('id_list'),'Select and add teams to graph');\" value='Add' />\n";

     	  echo "         <br/>\n";

	  echo "         <input type='button' onclick=\"removeFromList(document.getElementById('id_list'),'Select and add teams to graph');\" value='Remove' /></td>\n";

     	  echo "     <td colspan=2 valign='top'>\n";

	  echo "      <select name='id_list' multiple='multiple' size=10 id='id_list'>\n";

     	  if (isset($dispTIDS))

	  {

	  	  foreach ($dispTIDS as $team => $val)

		  {

			  if (!isset($teams[$team]['dispname'])) {unset($dispTIDS[$team]); continue;}

	       		  echo "       <option value='$team'>".$teams[$team]['dispname']." (".$teams[$team]['abbr'].")</option>\n";

		  }

    	  }

	  if (count($dispTIDS)==0) {echo "       <option value=0>Select and add teams to graph</option>\n";}

	     	  echo "      </select>\n";

	  echo "     </td>\n";    

      	  break; 

  default:

     ##### Show canned report links #####

     echo "    <tr class='title'><td colspan=5>Quick Links</td></tr>\n";

     echo "    <tr><td colspan=5 style='padding:0px;'>";

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

     ## Get Subleague Abbreviations and Teams

     $query="SELECT sl.sub_league_id,sl.abbr,team_id FROM sub_leagues as sl,teams as t WHERE sl.league_id=t.league_id AND sl.sub_league_id=t.sub_league_id AND sl.league_id=$lgid AND allstar_team=0 ORDER BY sub_league_id;";

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

     if (mysqli_num_rows($result)!=0)

      {

        while ($row=mysqli_fetch_array($result))

         {

  	   $slid=$row['sub_league_id'];

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

	   $tid=$row['team_id'];

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

	 }

      }

     $SLcnt=0;

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

      {

        $subleagues[$slid]['teams']=trim($subleagues[$slid]['teams'],",");

        $SLcnt++;

      }

     ## Show Links

     //echo "      <tr class='headline'><td class='hsc2_l'>Graph</td><td class='hsc2_l' colspan=$SLcnt>League</td></tr>\n";

     $statArray=array('batting'=>'batting','h'=>'H','d'=>'2B','t'=>'3B','hr'=>'HR','r'=>'R','rbi'=>'RBI','bb'=>'BB','sb'=>'SB','avg'=>'AVG','obp'=>'OBP','slg'=>'SLG','ops'=>'OPS','pitching'=>'pitching','w'=>'W','l'=>'L','s'=>'SV','ip'=>'IP','pk'=>'K','hld'=>'HLD','era'=>'ERA','whip'=>'WHIP');

     $cnt=1;

     foreach ($statArray as $statName => $dispName)

      {

        if (($statName=='batting')||($statName=='pitching'))

         {

           $table=$dispName;

	   echo "    <tr class='headline'><td colspan=".($SLcnt+1)." class='hsc2_l'><b>".ucwords($table)."</b></td></tr>\n";

	   $ndays=$simLen;

	   if ($statName=='pitching') {$ndays=max(30,$simLen);}

	   continue;

	 }

	if ($statName=='pk') {$statPass='pk';$statName='k';} else {$statPass=$statName;}

        $pList="";

	## Stat Race

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

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

        echo "       <td>$dispName Race</td>\n";

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

         {

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

	   $link="./graphs.php?view=players&scope=lastX&ndays=$ndays&stat=$statPass";

	   $teamList=$subleagues[$slid]['teams'];

	   $query="SELECT player_id,";

	   switch ($statName)

	    {

	      case 'avg' : $query.="SUM(h)/SUM(ab) as avg,tr.g";break;

	      case 'obp' : $query.="(SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf)) as obp,tr.g";break;

	      case 'slg' : $query.="(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab) as slg,tr.g";break;

	      case 'ops' : $query.="(SUM(h)+SUM(bb)+SUM(hp))/(SUM(ab)+SUM(bb)+SUM(hp)+SUM(sf))+(SUM(h)+SUM(d)+2*SUM(t)+3*SUM(hr))/SUM(ab) as ops,tr.g";break;

              case 'ip'  : $query.="(SUM(ip)+SUM(ipf)/3) as ip"; break;

              case 'era' : $query.="9*SUM(ER)/(SUM(ip)+SUM(ipf)/3) as era,tr.g"; break;

              case 'whip': $query.="(SUM(ha)+SUM(bb))/(SUM(ip)+SUM(ipf)/3) as whip,tr.g"; break;

	      default: $query.="SUM($statName) as $statName"; break;

	    }

	   $query.=" FROM players_career_".$table."_stats as pcb";

	   switch ($statName)

	    {

	      case 'avg':

	      case 'obp':

	      case 'slg':

	      case 'ops':

	      case 'era':

	      case 'whip':

	        $query.=",team_record as tr WHERE pcb.team_id=tr.team_id AND";

	        break;

	      default   : $query.=" WHERE";break;

	    }

	   $query.=" pcb.league_id=$lgid AND split_id=1 AND pcb.year=$lgyear AND pcb.team_id IN ($teamList) GROUP BY player_id";

	   switch ($statName)

	    {

	      case 'avg':

	      case 'obp':

	      case 'slg':

	      case 'ops':

	        $query.=" HAVING SUM(pcb.pa)>=(tr.g*3.1)";

	        break;

	      case 'era':

	      case 'whip':

	        $query.=" HAVING (SUM(pcb.ip)+SUM(ipf)/3)>=tr.g";

	        break;

	      default: break;

	   }

	   $query.=" ORDER BY $statName";

	   switch ($statName)

	    {

	      case 'era':

	      case 'whip':

		    break;

	      default: $query.=" DESC"; break;

	   }

	   $query.=" LIMIT $topXLimit;";

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

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

           if (mysqli_num_rows($result))

	    {

	      $link.="&pList=";

	      while ($row=mysqli_fetch_array($result))

	       {

	         $link.=$row['player_id']."|";

	       }

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

   	      echo "<td><a href='$link'>$abbr</a></td>";

	    }

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

	 }

   	echo "\n";

	echo "      </tr>\n";

	$cnt++;

      }

     ## Division Races

     echo "    <tr class='headline'><td colspan=".($SLcnt+1)." class='hsc2_l'><b>Division Races</b></td></tr>\n";

     $query="SELECT tr.team_id,sl.abbr,d.name,sl.sub_league_id,d.division_id FROM team_relations as tr,sub_leagues as sl,divisions as d WHERE tr.sub_league_id=sl.sub_league_id AND tr.sub_league_id=d.sub_league_id AND tr.division_id=d.division_id AND tr.league_id=$lgid AND sl.league_id=$lgid AND d.league_id=$lgid ORDER BY sl.sub_league_id,d.division_id,team_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))

	 {

           $tid=$row['team_id'];

	   $slid=$row['sub_league_id'];

	   $divID=$row['division_id'];

	   $divID=$slid."^".$divID;

	   $divisions[$divID]['name']=$row['abbr']." ".$row['name'];

	   $divisions[$divID]['teams']=$divisions[$divID]['teams']."|$tid";

	 }

      }

     $cnt=1;

     foreach ($divisions as $did => $val)

      {

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

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

        $link="./graphs.php?view=teams&scope=lastSim&stat=gmovr500";

	$teamList=trim($divisions[$did]['teams'],"|");

	$link.="&pList=$teamList";

     	echo "       <td colspan=".($SLcnt+1)."><a href='$link'>".$divisions[$did]['name']."</a></td>\n";

   	echo "\n";

	echo "      </tr>\n";

	$cnt++;

      }

     $query="SELECT num_wild_cards FROM league_playoffs WHERE league_id=$lgid;";

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

     $row=mysqli_fetch_array($result);

     if ($row['num_wild_cards']>0)

      {

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

         {

           $query="SELECT team_id FROM team_record WHERE team_id IN (".str_replace("|",",",$subleagues[$slid]['teams']).") AND pos!=1;";

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

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

	   if (mysqli_num_rows($result))

  	    {

              while ($row=mysqli_fetch_array($result))

	       {

	         $tid=$row['team_id'];

		 $subleagues[$slid]['wcteams']=$subleagues[$slid]['wcteams']."|$tid";

   	       }

	    }

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

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

	   $link="./graphs.php?view=teams&scope=lastSim&stat=gmovr500";

   	   $teamList=trim($subleagues[$slid]['wcteams'],"|");

	   $link.="&pList=$teamList";

   	   echo "       <td colspan=".($SLcnt+1)."><a href='$link'>".$subleagues[$slid]['abbr']." Wild Card</a> (excludes division leaders)</td>\n";

	   echo "\n";

	   echo "      </tr>\n";

	   $cnt++;

	 }

      }

     echo "     </table>\n";

     echo "    </td>\n";

     break;

  }

  

  ## Close Filter table

  echo "    </tr>\n";

  if ($view!="") {echo "    <tr><td colspan=5><input type='submit' onclick=\"moveList(document.getElementById('id_list'),document.getElementById('pListIn'));\" value='Go' /></td></tr>\n";}

  echo "    </form>\n";

  echo "   </table>\n";

  echo "  </div>\n";

  

  ##### Check for settings #####

  if (($view=="") || ($stat=="") || (($view=='teams')&&($tidList=="")) || (($view=='players')&&($pidList=="")))

  {

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

       	  page_foot($lgpath);

	  exit;

  }

  elseif ($_GET['showq']==1) {echo "$view::$stat::$pidList::$tidList<br/>\n";}



  $frDay=str_replace("/","-",$frDay);

  $toDay=str_replace("/","-",$toDay);



  ##### Generate Data #####

  switch ($view)

  {

  case 'players':

	  ## Get stat query array

	  switch ($stat)

	  {

	  case 'avg': $statQArray=Array('h','ab'); break;

	  case 'obp': $statQArray=Array('h','bb','hp','sf','ab'); break;

	  case 'slg': $statQArray=Array('h','d','t','hr','ab'); break;

	  case 'ops': $statQArray=Array('h','d','t','hr','bb','hp','sf','ab'); break;

	  case 'era': $statQArray=Array('er','ip'); break;

	  case 'whip': $statQArray=Array('ha','bb','ip'); break;

	  case 'kper9': $statQArray=Array('k','ip'); break;

	  case 'bbper9': $statQArray=Array('bb','ip'); break;

	  case 'hper9': $statQArray=Array('ha','ip'); break;

	  case 'kperbb': $statQArray=Array('k','bb'); break;

	  default: $statQArray=Array($stat); break;

	  }



	  if (($zeroStats!=1)&&($scope!='season'))  ## Get data prior to data set

	  {

		  $query="SELECT player_id";

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

		  $query.=" FROM games,players_game_";

		  switch ($stat)

		  {

		  case 'ab':

		  case 'h':

		  case 'd':

		  case 't':

		  case 'hr':

		  case 'rbi':

		  case 'r':

		  case 'sb':

		  case 'cs':

		  case 'bb':

		  case 'k':

		  case 'sf':

		  case 'sh':

		  case 'ibb':

		  case 'hp':

		  case 'gdp':

		  case 'pa':

		  case 'avg':

		  case 'obp':

		  case 'slg':

		  case 'ops':

			  $query.="batting";

			  break;

		  default: $query.="pitching_stats"; break;

		  }

		  $query.=" as pgs WHERE pgs.game_id=games.game_id AND player_id IN ($pidList) and game_type=0";

		  if ($scope=="lastSim") {$query.=" AND DATEDIFF('".$lgdate."',games.date)>=".$simLen;}

		  elseif ($scope=="lastX") {$query.=" AND DATEDIFF('".$lgdate."',games.date)>=".$ndays;}

		  elseif ($scope=="dRange") {$query.=" AND games.date<'$lgyear-$frDay'";}

		  $query.=" GROUP BY player_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))

			  {

				  $pid=$row['player_id'];

				  foreach ($statQArray as $key => $statLbl) {$statTotal[$pid][$statLbl]=$row[$statLbl];}

			  }

		  }

	  }



	  ## Get Data

	  $query="SELECT player_id,games.date as game_date";

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

	  $query.=" FROM games,players_game_";

	  switch ($stat)

	  {

	  case 'ab':

	  case 'h':

	  case 'd':

	  case 't':

	  case 'hr':

	  case 'rbi':

	  case 'r':

	  case 'sb':

	  case 'cs':

	  case 'bb':

	  case 'k':

	  case 'sf':

	  case 'sh':

	  case 'ibb':

	  case 'hp':

	  case 'gdp':

	  case 'pa':

	  case 'avg':

	  case 'obp':

	  case 'slg':

	  case 'ops':

		  $query.="batting";

		  break;

	  default: $query.="pitching_stats"; break;

	  }

	  $query.=" as pgs WHERE pgs.game_id=games.game_id AND player_id IN ($pidList) and game_type=0";

	  if ($scope=="lastSim") {$query.=" AND DATEDIFF('".$lgdate."',games.date)<".$simLen;}

	  elseif ($scope=="lastX") {$query.=" AND DATEDIFF('".$lgdate."',games.date)<".$ndays;}

	  elseif ($scope=="dRange") {$query.=" AND games.date>='$lgyear-$frDay' AND games.date<='$lgyear-$toDay'";}

	  $query.=" GROUP BY player_id,game_date ORDER BY game_date";

	  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'];

			  $gmdate=$row['game_date'];



			  foreach ($statQArray as $key => $statLbl) {$statTotal[$pid][$statLbl]=$statTotal[$pid][$statLbl]+$row[$statLbl];}



			  switch ($stat)

			  {

			  case 'avg':

				  if ($statTotal[$pid]['ab']==0) {$statTotal[$pid][$stat]=0;}

				  else {$statTotal[$pid][$stat]=$statTotal[$pid]['h']/$statTotal[$pid]['ab'];}

				  break;

			  case 'obp':

				  if ($statTotal[$pid]['ab']+$statTotal[$pid]['bb']+$statTotal[$pid]['hp']+$statTotal[$pid]['sf']==0) {$statTotal[$pid][$stat]=0;}

				  else {$statTotal[$pid][$stat]=($statTotal[$pid]['h']+$statTotal[$pid]['bb']+$statTotal[$pid]['hp'])/($statTotal[$pid]['ab']+$statTotal[$pid]['bb']+$statTotal[$pid]['hp']+$statTotal[$pid]['sf']);}

				  break;

			  case 'slg':

				  if ($statTotal[$pid]['ab']==0) {$statTotal[$pid][$stat]=0;}

				  else {$statTotal[$pid][$stat]=($statTotal[$pid]['h']+$statTotal[$pid]['d']+2*$statTotal[$pid]['t']+3*$statTotal[$pid]['hr'])/$statTotal[$pid]['ab'];}

				  break;

			  case 'ops':

				  if ($statTotal[$pid]['ab']+$statTotal[$pid]['bb']+$statTotal[$pid]['hp']+$statTotal[$pid]['sf']==0) {$obp=0;}

				  else {$obp=($statTotal[$pid]['h']+$statTotal[$pid]['bb']+$statTotal[$pid]['hp'])/($statTotal[$pid]['ab']+$statTotal[$pid]['bb']+$statTotal[$pid]['hp']+$statTotal[$pid]['sf']);}

				  if ($statTotal[$pid]['ab']==0) {$slg=0;}

				  else {$slg=($statTotal[$pid]['h']+$statTotal[$pid]['d']+2*$statTotal[$pid]['t']+3*$statTotal[$pid]['hr'])/$statTotal[$pid]['ab'];}

				  $statTotal[$pid][$stat]=$obp+$slg;

				  break;

			  case 'era':

				  if ($statTotal[$pid]['ip']==0) {$statTotal[$pid][$stat]=0;}

				  else {$statTotal[$pid][$stat]=(9*$statTotal[$pid]['er'])/$statTotal[$pid]['ip'];}

				  break;

			  case 'whip':

				  if ($statTotal[$pid]['ip']==0) {$statTotal[$pid][$stat]=0;}

				  else {$statTotal[$pid][$stat]=($statTotal[$pid]['ha']+$statTotal[$pid]['bb'])/$statTotal[$pid]['ip'];}

				  break;

			  case 'kper9':

				  if ($statTotal[$pid]['ip']==0) {$statTotal[$pid][$stat]=0;}

				  else {$statTotal[$pid][$stat]=(9*$statTotal[$pid]['k'])/$statTotal[$pid]['ip'];}

				  break;

			  case 'bbper9':

				  if ($statTotal[$pid]['ip']==0) {$statTotal[$pid][$stat]=0;}

				  else {$statTotal[$pid][$stat]=(9*$statTotal[$pid]['bb'])/$statTotal[$pid]['ip'];}

				  break;

			  case 'hper9':

				  if ($statTotal[$pid]['ip']==0) {$statTotal[$pid][$stat]=0;}

				  else {$statTotal[$pid][$stat]=(9*$statTotal[$pid]['ha'])/$statTotal[$pid]['ip'];}

				  break;

			  case 'kperbb':

				  if ($statTotal[$pid]['bb']==0) {$statTotal[$pid][$stat]=0;}

				  else {$statTotal[$pid][$stat]=$statTotal[$pid]['k']/$statTotal[$pid]['bb'];}

				  break;

			  }



			  $data[$pid][$gmdate]=$statTotal[$pid][$stat];

			  $dateArray[$gmdate]=1;

		  }

	  }









	  break;

  case 'teams':

	  switch ($stat)

	  {

	  case 'gmovr500':

	  case 'winpct':

		  if (($zeroStats!=1)&&($scope!='season'))  ## Get data prior to data set

		  {

			  $query="SELECT home_team,away_team,runs0,runs1 FROM games WHERE game_type=0 AND played=1 AND (home_team IN ($tidList) OR away_team IN ($tidList))";

			  if ($scope=="lastSim") {$query.=" AND DATEDIFF('".$lgdate."',games.date)>=".$simLen;}

			  elseif ($scope=="lastX") {$query.=" AND DATEDIFF('".$lgdate."',games.date)>=".$ndays;}

			  elseif ($scope=="dRange") {$query.=" AND games.date<'$lgyear-$frDay'";}



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

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

			  if (mysqli_num_rows($result))

			  {

				  while ($row=mysqli_fetch_array($result))

				  {

					  $aid=$row['away_team'];

					  $hid=$row['home_team'];

	

					  $aruns=$row['runs0'];

					  $hruns=$row['runs1'];



					  if ($hruns>$aruns)

					  {

						  $teams[$hid]['w']=$teams[$hid]['w']+1;

						  $teams[$aid]['l']=$teams[$aid]['l']+1;

	

						  $teams[$hid]['gmovr500']=$teams[$hid]['gmovr500']+1;

						  $teams[$aid]['gmovr500']=$teams[$aid]['gmovr500']-1;

					  }

					  else

					  {

						  $teams[$hid]['l']=$teams[$hid]['l']+1;

						  $teams[$aid]['w']=$teams[$aid]['w']+1;

	  

						  $teams[$hid]['gmovr500']=$teams[$hid]['gmovr500']-1;

						  $teams[$aid]['gmovr500']=$teams[$aid]['gmovr500']+1;

					  }

					  

					  $teams[$hid]['winpct']=$teams[$hid]['w']/($teams[$hid]['w']+$teams[$hid]['l']);

					  $teams[$aid]['winpct']=$teams[$aid]['w']/($teams[$aid]['w']+$teams[$aid]['l']);

				  }

			  }

		  }



		  $query="SELECT games.date as game_date,home_team,away_team,runs0,runs1 FROM games WHERE game_type=0 AND played=1 AND (home_team IN ($tidList) OR away_team IN ($tidList))";

		  if ($scope=="lastSim") {$query.=" AND DATEDIFF('".$lgdate."',games.date)<".$simLen;}

		  elseif ($scope=="lastX") {$query.=" AND DATEDIFF('".$lgdate."',games.date)<".$ndays;}

		  elseif ($scope=="dRange") {$query.=" AND games.date>='$lgyear-$frDay' AND games.date<='$lgyear-$toDay'";}

		  $query.=" ORDER BY game_date";

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

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

		  if (mysqli_num_rows($result))

       		  {

			  while ($row=mysqli_fetch_array($result))

			  {

				  $aid=$row['away_team'];

				  $hid=$row['home_team'];



				  $gmdate=$row['game_date'];



				  $aruns=$row['runs0'];

				  $hruns=$row['runs1'];



				  if ($hruns>$aruns)

				  {

					  $teams[$hid]['w']=$teams[$hid]['w']+1;

					  $teams[$aid]['l']=$teams[$aid]['l']+1;



					  $teams[$hid]['gmovr500']=$teams[$hid]['gmovr500']+1;

					  $teams[$aid]['gmovr500']=$teams[$aid]['gmovr500']-1;

				  }

				  else

				  {

					  $teams[$hid]['l']=$teams[$hid]['l']+1;

					  $teams[$aid]['w']=$teams[$aid]['w']+1;

					  

					  $teams[$hid]['gmovr500']=$teams[$hid]['gmovr500']-1;

					  $teams[$aid]['gmovr500']=$teams[$aid]['gmovr500']+1;

				  }

					  

				  $teams[$hid]['winpct']=$teams[$hid]['w']/($teams[$hid]['w']+$teams[$hid]['l']);

				  $teams[$aid]['winpct']=$teams[$aid]['w']/($teams[$aid]['w']+$teams[$aid]['l']);



				  $data[$hid][$gmdate]=$teams[$hid][$stat];

				  $data[$aid][$gmdate]=$teams[$aid][$stat];

				  $dateArray[$gmdate]=1;

			  }



			  $e=explode(",",$tidList);

			  foreach ($data as $tid => $val) {if (!in_array($tid,$e)) {unset($data[$tid]);} }

		  }

		  break;

	  case 'pOdds':

		  $query="SELECT team_id,league_date,TotPO FROM ootp_sql_podds WHERE league_id=$lgid AND team_id IN ($tidList)";

		  if ($scope=="lastSim") {$query.=" AND DATEDIFF('".$lgdate."',league_date)<".$simLen;}

		  elseif ($scope=="lastX") {$query.=" AND DATEDIFF('".$lgdate."',league_date)<".$ndays;}

		  elseif ($scope=="dRange") {$query.=" AND league_date>='$lgyear-$frDay' AND league_date<='$lgyear-$toDay'";}

		  elseif ($scope=='season')

		  {

			  $query.=" AND league_date>=(";

			  $query.="SELECT IF(start_date<'$lgdate',start_date,CONCAT(YEAR(start_date)-1,'-',MONTH(start_date),'-',DAY(start_date))) as start_date FROM leagues WHERE league_id=$lgid";

			  $query.=")";

		  }

		  $query.=" ORDER BY league_date";

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

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

		  if (mysqli_num_rows($result))

       		  {

			  while ($row=mysqli_fetch_array($result))

			  {

				  $tid=$row['team_id'];

				  $league_date=$row['league_date'];

				  $odds=$row['TotPO'];



				  $data[$tid][$league_date]=$odds;

				  $dateArray[$league_date]=1;

			  }

		  }

		  break;

	  default:

		  ## Get stat query array

		  switch ($stat)

		  {

		  case 'avg': $statQArray=Array('h','ab'); break;

		  case 'obp': $statQArray=Array('h','bb','hp','sf','ab'); break;

		  case 'slg': $statQArray=Array('h','d','t','hr','ab'); break;

		  case 'ops': $statQArray=Array('h','d','t','hr','bb','hp','sf','ab'); break;

		  case 'era': $statQArray=Array('er','ip'); break;

		  case 'whip': $statQArray=Array('ha','bb','ip'); break;

		  case 'kper9': $statQArray=Array('k','ip'); break;

		  case 'bbper9': $statQArray=Array('bb','ip'); break;

		  case 'hper9': $statQArray=Array('ha','ip'); break;

		  case 'kperbb': $statQArray=Array('k','bb'); break;

		  default: $statQArray=Array($stat); break;

		  }



		  if (($zeroStats!=1)&&($scope!='season'))  ## Get data prior to data set

		  {

			  $query="SELECT team_id";

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

			  $query.=" FROM games,players_game_";

			  switch ($stat)

			  {

			  case 'ab':

			  case 'h':

			  case 'd':

			  case 't':

			  case 'hr':

			  case 'rbi':

			  case 'r':

			  case 'sb':

			  case 'cs':

			  case 'bb':

			  case 'k':

			  case 'sf':

			  case 'sh':

			  case 'ibb':

			  case 'hp':

			  case 'gdp':

			  case 'pa':

			  case 'avg':

			  case 'obp':

			  case 'slg':

			  case 'ops':

				  $query.="batting";

				  break;

			  default: $query.="pitching_stats"; break;

			  }

			  $query.=" as pgs WHERE pgs.game_id=games.game_id AND pgs.team_id IN ($tidList) and game_type=0";

			  if ($scope=="lastSim") {$query.=" AND DATEDIFF('".$lgdate."',games.date)>=".$simLen;}

			  elseif ($scope=="lastX") {$query.=" AND DATEDIFF('".$lgdate."',games.date)>=".$ndays;}

			  elseif ($scope=="dRange") {$query.=" AND games.date<'$lgyear-$frDay'";}

			  $query.=" GROUP BY team_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))

				  {

					  $tid=$row['team_id'];

					  foreach ($statQArray as $key => $statLbl) {$statTotal[$tid][$statLbl]=$row[$statLbl];}

				  }

			  }

		  }



		  $query="SELECT team_id,games.date as game_date";

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

		  $query.=" FROM games,players_game_";

		  switch ($stat)

		  {

		  case 'ab':

      		  case 'h':

		  case 'd':

      		  case 't':

		  case 'hr':

      		  case 'rbi':

		  case 'r':

      		  case 'sb':

		  case 'cs':

      		  case 'bb':

		  case 'k':

      		  case 'sf':

		  case 'sh':

      		  case 'ibb':

		  case 'hp':

      		  case 'gdp':

		  case 'pa':

      		  case 'avg':

		  case 'obp':

      		  case 'slg':

		  case 'ops':

	    		  $query.="batting";

			  break;

      		  default: $query.="pitching_stats"; break;

		  }

		  $query.=" as pgs WHERE pgs.game_id=games.game_id AND pgs.team_id IN ($tidList) and game_type=0";

		  if ($scope=="lastSim") {$query.=" AND DATEDIFF('".$lgdate."',games.date)<".$simLen;}

		  elseif ($scope=="lastX") {$query.=" AND DATEDIFF('".$lgdate."',games.date)<".$ndays;}

		  elseif ($scope=="dRange") {$query.=" AND games.date>='$lgyear-$frDay' AND games.date<='$lgyear-$toDay'";}

		  $query.=" GROUP BY team_id,game_date ORDER BY game_date";

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

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

		  if (mysqli_num_rows($result))

       		  {

			  while ($row=mysqli_fetch_array($result))

			  {

				  $tid=$row['team_id'];

				  $gmdate=$row['game_date'];



				  foreach ($statQArray as $key => $statLbl) {$statTotal[$tid][$statLbl]=$statTotal[$tid][$statLbl]+$row[$statLbl];}

		

				  switch ($stat)

				  {

				  case 'avg':

					  if ($statTotal[$tid]['ab']==0) {$statTotal[$tid][$stat]=0;}

					  else {$statTotal[$tid][$stat]=$statTotal[$tid]['h']/$statTotal[$tid]['ab'];}

					  break;

				  case 'obp':

					  if ($statTotal[$tid]['ab']+$statTotal[$tid]['bb']+$statTotal[$tid]['hp']+$statTotal[$tid]['sf']==0) {$statTotal[$tid][$stat]=0;}

					  else {$statTotal[$tid][$stat]=($statTotal[$tid]['h']+$statTotal[$tid]['bb']+$statTotal[$tid]['hp'])/($statTotal[$tid]['ab']+$statTotal[$tid]['bb']+$statTotal[$tid]['hp']+$statTotal[$tid]['sf']);}

					  break;

				  case 'slg':

					  if ($statTotal[$tid]['ab']==0) {$statTotal[$tid][$stat]=0;}

					  else {$statTotal[$tid][$stat]=($statTotal[$tid]['h']+$statTotal[$tid]['d']+2*$statTotal[$tid]['t']+3*$statTotal[$tid]['hr'])/$statTotal[$tid]['ab'];}

					  break;

				  case 'ops':

					  if ($statTotal[$tid]['ab']+$statTotal[$tid]['bb']+$statTotal[$tid]['hp']+$statTotal[$tid]['sf']==0) {$obp=0;}

					  else {$obp=($statTotal[$tid]['h']+$statTotal[$tid]['bb']+$statTotal[$tid]['hp'])/($statTotal[$tid]['ab']+$statTotal[$tid]['bb']+$statTotal[$tid]['hp']+$statTotal[$tid]['sf']);}

					  if ($statTotal[$tid]['ab']==0) {$slg=0;}

					  else {$slg=($statTotal[$tid]['h']+$statTotal[$tid]['d']+2*$statTotal[$tid]['t']+3*$statTotal[$tid]['hr'])/$statTotal[$tid]['ab'];}

					  $statTotal[$tid][$stat]=$obp+$slg;

					  break;

				  case 'era':

					  if ($statTotal[$tid]['ip']==0) {$statTotal[$tid][$stat]=0;}

					  else {$statTotal[$tid][$stat]=(9*$statTotal[$tid]['er'])/$statTotal[$tid]['ip'];}

					  break;

				  case 'whip':

					  if ($statTotal[$tid]['ip']==0) {$statTotal[$tid][$stat]=0;}

					  else {$statTotal[$tid][$stat]=($statTotal[$tid]['ha']+$statTotal[$tid]['bb'])/$statTotal[$tid]['ip'];}

					  break;

				  case 'kper9':

					  if ($statTotal[$tid]['ip']==0) {$statTotal[$tid][$stat]=0;}

					  else {$statTotal[$tid][$stat]=(9*$statTotal[$tid]['k'])/$statTotal[$tid]['ip'];}

					  break;

				  case 'bbper9':

					  if ($statTotal[$tid]['ip']==0) {$statTotal[$tid][$stat]=0;}

					  else {$statTotal[$tid][$stat]=(9*$statTotal[$tid]['bb'])/$statTotal[$tid]['ip'];}

					  break;

				  case 'hper9':

					  if ($statTotal[$tid]['ip']==0) {$statTotal[$tid][$stat]=0;}

					  else {$statTotal[$tid][$stat]=(9*$statTotal[$tid]['ha'])/$statTotal[$tid]['ip'];}

					  break;

				  case 'kperbb':

					  if ($statTotal[$tid]['bb']==0) {$statTotal[$tid][$stat]=0;}

					  else {$statTotal[$tid][$stat]=$statTotal[$tid]['k']/$statTotal[$tid]['bb'];}

					  break;

				  }



				  $data[$tid][$gmdate]=$statTotal[$tid][$stat];

				  $dateArray[$gmdate]=1;

			  }

		  }

		  break;

	  }

  }



  if (!isset($data))

  {

	  echo "  <div class='textbox' style='border:0px;'>No data found for the time frame given.</div>\n";



	  mysqli_close($db);

	

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

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

	  page_foot($_SESSION['lgpath']);

	  exit;

  }



  ksort($data);

  ksort($dateArray);



  ##### Show Display Toggle

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

  echo "<div class='textbox' style='border:0;'>";

  echo "<a href='javascript:void(0);' onclick=\"if(dataVis==0) {dataVis=1;document.getElementById('datatable').style.display='block';document.getElementById('chartdiv').style.display='none';this.innerHTML='Show Graph';} else {dataVis=0;document.getElementById('datatable').style.display='none';document.getElementById('chartdiv').style.display='block';this.innerHTML='Show Data';}\">Show Data</a>";

  echo "</div>\n";



  ##### Display Data

  echo "  <div class='textbox' id='datatable' style='display:none;'>\n";

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

  echo "    <tr class='title2'><td colspan=".(1+count($data)).">".stat_text($stat)."</td></tr>\n";

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

  echo "<td></td>";

  foreach ($data as $pid => $val)

  {

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

	  switch ($view)

	  {

	  case 'players':

		  $legText=$players[$pid]['legend'];

		  echo "<a href='./player.php?player_id=$pid'>";

		  echo $legText;

		  echo "</a>";

		  break;

	  case 'teams':

		  $legText=$teams[$pid]['abbr'];

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

		  echo $legText;

		  echo "</a>";

		  break;



	  }

	  echo "</td>";

  }

  echo "</tr>\n";

  $rowCnt=0;

  foreach ($dateArray as $gdate => $val)

  {

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

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

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

	  foreach ($data as $pid => $val)

	  {

		  echo "<td>";

		  if (isset($data[$pid][$gdate])) {echo $data[$pid][$gdate];}

		  echo "</td>";

	  }

	  echo "</tr>\n";

	  $rowCnt++;

  }

  echo "   </table>\n";

  echo "  </div>\n";



  ##### Display Chart

  $markerArray=Array('diamond', 'circle', 'square', 'x', 'plus', 'filledDiamond', 'filledCircle', 'filledSquare');

  $mCnt=count($markerArray);

  echo "  <div id='chartdiv' style='clear:both;height:400px;width:800px;margin-left:auto;margin-right:auto;'></div>\n";

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

  echo "   <!--\n";

  echo "    $(document).ready(function(){\n";

  foreach ($data as $did => $val)

  {

	  echo "     var line$did = [";

	  $rowCnt=0;

	  foreach ($data[$did] as $x => $y)

	  {

		  if ($rowCnt>0) {echo ", ";}

		  switch ($view)

		  {

		  case 'players': $legText=$players[$did]['dispname']; break;

		  case 'teams': $legText=$teams[$did]['abbr']; break;

		  }

		  echo "['$x',$y, '$legText']";

		  $rowCnt++;

	  }

	  echo "];\n";

  }

  echo "     var plot1=$.jqplot('chartdiv', [";

  $rowCnt=0;

  foreach ($data as $did => $val)

  {

	  if ($rowCnt>0) {echo ", ";}

	  echo "line$did";

	  $rowCnt++;

  }

  echo "], {\n";

  echo "       title:'".stat_text($stat)."',\n";

  echo "       axes:{\n";

  echo "             xaxis:{\n";

  echo "                    renderer:$.jqplot.DateAxisRenderer,\n";

  echo "                    tickOptions: {formatString:'%b %#d, %Y', angle: -30}\n";

  echo "             }\n";

  echo "       },\n";

  echo "       series: [\n";

  $rowCnt=0;

  foreach ($data as $did => $val) 

  {

	  if ($rowCnt>0) {echo "           ,\n";}

	  switch ($view)

	  {

	  case 'players': $legText=$players[$did]['dispname']; break;

	  case 'teams': $legText=$teams[$did]['abbr']; break;

	  }

	  $idx=$rowCnt%$mCnt;

	  echo "              {label: \"$legText\", showLabel: true, markerOptions: {style:\"".$markerArray[$idx]."\" }}\n";

	  $rowCnt++;

  }

  echo "              ],\n";

  echo "       highlighter: {\n";

  echo "                     formatString: \"%s<br/>%s\",\n";

  echo "                     show: true,\n";

  echo "                     showLbl: true,\n";

  echo "                     tooltipAxes: 'both',\n";

  echo "                     bringSeriesToFront: true\n";

  echo "       },\n";

  echo "       cursor: {show: true, zoom: true, tooltipLocation:'sw'},\n";

  echo "       legend: { show:true, location: 'e', placement: 'outsideGrid' }\n";

  switch ($stat)

  {

  case 'winpct'  : $hline=1; $hloc=0.5; break;

  case 'gmovr500': $hline=1; $hloc=0;   break;

  case 'pOdds'   : $hline=1; $hloc=50;  break;

  }

  if ($hline==1)

  {

	  echo "       ,canvasOverlay: {\n";

	  echo "                         show: true,\n";

	  echo "                         objects: [\n";

	  echo "                             {dashedHorizontalLine: {\n";

	  echo "                                 name: 'budgetLine',\n";

	  echo "                                 y: $hloc,\n";

	  echo "                                 lineWidth: 2,\n";

	  echo "                                 color: 'rgb(153, 0, 0)',\n";

	  echo "                                 shadow: false\n";

	  echo "                              }}\n";

	  echo "                         ]\n";

	  echo "             }\n";

  }

  echo "     });\n";

  echo "    });\n";

  echo "   -->\n";

  echo "  </script>\n";



  mysqli_close($db);



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

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

  page_foot($_SESSION['lgpath']);





?>

