<?php

  include("html_functions.php");



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

  $lgid=$_SESSION['lgid'];

  $lgpath=$_SESSION['lgpath'];

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

  $lgyear=$date->format("Y");

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

  

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

  {

       	  switch ($key)

	  {

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

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

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

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

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

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

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

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

	  case 'pList':

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

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

	 	  {

			  $id=$e[$i];

	       		  if ($view=='teams') {$dispTIDS[$id]=1;$tidList.="$id,";}

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

	 	  }

		  break;

      	  }

  }

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

  if ($collate=="") {$collate='byYear';}

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

  if ($scope=="") 

  {

       	  if ($view=='players') {$scope='career';} else {$scope='season';}

  }

  if ($to<$from)

  {

       	  $tmp=$from;

	  $from=$to;

       	  $to=$tmp;

  }

  if ($to=="") 

  {

       	  if ($collate=='byYear') {$to=$lgyear;} else {$to=100;}

  }

  if ($from=="")

  {

       	  if ($collate=='byYear')

	  {

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

		  $query="SELECT MIN(year) as year FROM team_history WHERE league_id=$lgid;";

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

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

		  if (mysqli_num_rows($result))

	   	  {

			  $row=mysqli_fetch_array($result);

		 	  $from=$row['year'];

		  }

	   	  else {$from=$lgyear;}

		  mysqli_close($db);

	  }

       	  else {$from=0;}

  }

  if (($view=='players')&&(!is_numeric($team_id))) {$team_id='All';}



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

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





  ## Page Header

  $title="Historical 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");

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

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

  nav_toolbar("history","History");

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

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



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

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



  ##### Show Filters #####

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

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

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

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

  ## Show Type Selection

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

  if ($view!="") {echo " (<a href='./carGraphs.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='./carGraphs.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='./carGraphs.php?view=players'\"></td>";

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

  

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

  

  ## Show Collate Selection

  if ($view=='players')

  {

	  echo "     <td><b>X-Axis:</b></td>\n";

       	  echo "     <td><input type='radio' name='collate' value='byYear' id='byYear'";

	  if ($collate=='byYear') {echo " checked='checked'";}

       	  if ($pidList=="") {echo "onclick=\"window.location='./carGraphs.php?view=$view&collate=byYear'\"";}

	  else  {echo "onclick=\"if(document.getElementById('toIn').value<1000){document.getElementById('toIn').value=$lgyear;}\"";}

       	  echo "></td>";

	  echo "     <td><label for='byYear'>Year</label></td>";

       	  echo "     <td><input type='radio' name='collate' value='byAge' id='byAge'";

	  if ($collate=='byAge') {echo " checked='checked'";}

       	  if ($pidList=="") {echo "onclick=\"window.location='./carGraphs.php?view=$view&collate=byAge'\"";}

	  else  {echo "onclick=\"if(document.getElementById('fromIn').value>1000){document.getElementById('fromIn').value=0;}if(document.getElementById('toIn').value>1000){document.getElementById('toIn').value=100;}\"";}

       	  echo "></td>";

	  echo "     <td><label for='byAge'>Player Age</label></td>";



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

  }

  

  if (($view=="teams")||($view=='players'))

  {

       	  ## Show Scope Selection

	  echo "     <td><b>Scope:</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'>Season Totals</label></td>";

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

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

       	  echo "></td>";

	  echo "     <td><label for='career'>";

       	  if ($view=='players') {echo "Career";} else {echo "Cumulative";}

	  echo " Totals</label></td>";



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

       

	  ## Show From/To Entries

	  echo "     <td><b>Display ";

       	  if ($collate=='byAge') {echo "Ages";} else {echo "Years";}

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

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

	  echo "     <td><INPUT type='text' size=4 maxlength=4 name='from' id='fromIn' value='$from'></td>\n";

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

	  echo "     <td><INPUT type='text' size=4 maxlength=4 name='to' id='toIn' value='$to'></td>";



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

 }

  

  ## Show Stat Filter

  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";

	  // Leaderboards Stats

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

	  // Graph Stats - copy to leaderboards graph link filter with any changes made

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

     

	  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,'all','',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 "     <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,position,role,minYr,maxYr FROM players as p,(SELECT player_id,MIN(minYr) as minYr,MAX(maxYr) as maxYr FROM (SELECT player_id,MIN(year) as minYr,MAX(year) as maxYr FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND player_id IN ($plist) GROUP BY player_id UNION SELECT player_id,MIN(year) as minYr,MAX(year) as maxYr FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND player_id IN ($plist) GROUP BY player_id) as t1 GROUP BY player_id) as t2 WHERE p.player_id=t2.player_id ORDER BY last_name,first_name,minYr,maxYr";

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

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

		  if (mysqli_num_rows($result)!=0)

		  {

			  while ($row=mysqli_fetch_array($result))

			  {

				  $pid=$row['player_id'];

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

				  $fi=$row['first_name'];

				  $fi=$fi[0];

				  $position=$row['position'];

				  if ($position==1) {$position=$row['role'];}

				  $position=get_pos($position,1);

				  $career=$row['minYr']."-".$row['maxYr'];

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

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

				  $players[$pid]['career']=$career;

				  echo "       <option value='$pid'>".$players[$pid]['dispname']." (".$players[$pid]['career'].")</option>\n";

			  }

		  }

	  }

	  else {echo "       <option value=0>Select and add players to graph</option>\n";}

	  echo "      </select>\n";

	  echo "     </td>\n";     

	  echo "    </tr>\n";

	  if (is_numeric($team_id))

	  {

		  echo "    <tr>\n";

		  echo "     <td><b>Additional Filters:</b></td>\n";

		  echo "     <td>";

		  echo "Team:";

		  echo "</td>\n";

		  echo "     <td colspan=3>";

		  $query="SELECT name,nickname FROM teams WHERE team_id=$team_id";

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

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

		  $row=mysqli_fetch_array($result);

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

		  echo "<input type='hidden' name='team_id' value=$team_id />";

		  echo "</td>\n";

		  echo "    </tr>\n";

	  }

	  break;

  case 'teams':

     	  ## Show stat filter

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

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

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

	  // Leaderboards Stats

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

	  // Graph Stats - copy to leaderboards graph link filter with any changes made

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

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

	  {

	  	  if (($key=='batting')||($key=='pitching')||($key=='record')) {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";



	  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";

     	  $query="SELECT team_id,name,nickname,abbr,MIN(year) as minYr,MAX(year) as maxYr FROM (SELECT team_id,name,nickname,abbr,year FROM team_history WHERE league_id=$lgid ORDER BY team_id,year DESC) as t1 GROUP BY team_id ORDER BY name,nickname,minYr,maxYr;";

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

	       		  $career=$row['minYr']."-".$row['maxYr'];

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

	       		  echo "       <option value='$team,$abbr-$name ($career)'>$abbr-$name ($career)</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)

		  {

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

		  }

    	  }

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

     	  echo "      </select>\n";

	  echo "     </td>\n";     

	  echo "    </tr>\n";

     	  break;

  default:

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

	  echo "    <tr class='title'><td colspan=5>Quick Links</td></tr>\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.",";

		  }

    	  }

	  $cnt=0;

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

	  {

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

		  $cnt++;

    	  }

	  ## Show Links

	  echo "    <tr class='headline'><td class='hsc2_l' colspan=2>Leader Graphs</td>";

	  echo "<td class='hsc2' colspan=3 style='text-align:center;width=500px'>Top 10</td>";

     	  echo "</tr>\n";

	  $statArray=array('batting'=>'batting','h'=>'H','hr'=>'HR','r'=>'R','rbi'=>'RBI','bb'=>'BB','sb'=>'SB','pitching'=>'pitching','w'=>'W','l'=>'L','s'=>'SV','pk'=>'K');

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

	  {

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

		  {

	       		  $table=$dispName;

			  echo "    <tr><td colspan=5><b>".ucwords($table)."</b></td></tr>\n";

	       		  continue;

		  }

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

			  $pList="";

	  	  unset($topPlayers);

		  ## Stat Leaders

		  echo "    <tr>\n";

		  echo "     <td colspan=2>$dispName Leaders</td>\n";

	  	  $link="./carGraphs.php?view=players&scope=career&stat=$statPass";

		  $query="SELECT p.player_id,sum($statName) as $statName FROM players as p,players_career_".$table."_stats as pcb WHERE p.retired=0 AND p.player_id=pcb.player_id AND pcb.league_id=$lgid AND split_id=1 GROUP BY player_id ORDER BY $statName DESC LIMIT 10;";

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

		  if (mysqli_num_rows($result))

	 	  {

			  $link.="&pList=";

	       		  while ($row=mysqli_fetch_array($result))

			  {

		    		  $pid=$row['player_id'];

				  $link.="$pid|";

		    		  if ((!isset($topPlayers[$pid]))&&(count($topPlayers)<3))

				  {

			 		  $topPlayers[$pid]=1;

					  $pList.=",$pid";

		   		  }

			  }

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

			  echo "     <td><a href='$link'>Active</a></td>\n";

	 	  }

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

	  	  $link="./carGraphs.php?view=players&scope=career&collate=byAge&stat=$statPass";

		  $query="SELECT player_id,sum($statName) as $statName FROM players_career_".$table."_stats WHERE league_id=$lgid AND split_id=1 GROUP BY player_id ORDER BY $statName DESC LIMIT 10;";

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

	  	  if (mysqli_num_rows($result))

		  {

	       		  $link.="&pList=";

			  while ($row=mysqli_fetch_array($result))

	      		  {

				  $pid=$row['player_id'];

		    		  $link.="$pid|";

				  if ((!isset($topPlayers[$pid]))&&(count($topPlayers)<10))

		   		  {

					  $topPlayers[$pid]=1;

			 		  $pList.=",$pid";

				  }

	      		  }

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

	       		  echo "     <td><a href='$link'>Career</a></td>\n";

		  }

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

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

	  	  $link="./carGraphs.php?view=players&scope=career&collate=byAge&stat=$statPass&pList=";

		  foreach ($topPlayers as $pid => $val) {$link.="$pid|";}

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

		  echo "     <td><a href='$link' title='Top 7 Career + Top 3 Active'>Combination</a></td>\n";

	  	  echo "    </tr>\n";

	  }

     	  break;

  }

  

  ## Close Filter table

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

  echo "   </table>\n";

  echo "  </div>\n";



  

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

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

  {

	  mysqli_close($db);



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

       	  page_foot($lgpath);

	  exit;

  }

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



	  

  ##### Generate Query and Get 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;

	  }



	  ## Generate Query

	  $query="SELECT pcs.player_id";

	  if ($collate=='byYear') {$query.=",year";} else {$query.=",(pcs.year-YEAR(date_of_birth)-(RIGHT(date_of_birth,5)>'07-01')) as year";}

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

	  switch ($stat)

	  {

  	  case 'ab':

	  case 'h':

  	  case 'd':

	  case 't':

  	  case 'hr':

	  case 'rbi':

  	  case 'r':

	  case 'sb':

  	  case 'cs':

	  case 'bb':

  	  case 'k':

	  case 'sf':

  	  case 'sh':

	  case 'ibb':

  	  case 'hp':

	  case 'gdp':

	  case 'pa':

	  case 'outs':

	  case 'ebh':

	  case 'tb':

	  case 'tob':

	  case 'tto':

	  case 'pitches_seen':

	  case 'avg':

  	  case 'obp':

	  case 'slg':

  	  case 'ops':

	  case 'war':

		  $query.=" FROM players_career_batting_stats as pcs";

		  break;

  	  default:

		  $query.=" FROM players_career_pitching_stats as pcs";

		  break;

	  }

	  if ($collate=='byAge') {$query.=",players as p WHERE pcs.player_id=p.player_id AND";}

    	  else {$query.=" WHERE";}

	  $query.=" pcs.league_id=$lgid AND split_id=1 AND pcs.player_id IN ($pidList)";

	  if ($zeroStats==1) {$query.=" AND year>=$from";}

	  if (is_numeric($team_id)) {$query.=" AND pcs.team_id=$team_id";}

     	  $query.=" GROUP BY player_id,pcs.year";

	  $query.=" ORDER BY player_id,year;";

   

	  break;



   case 'teams':

     ##### Statistical Trend #####

     ## Generate Legend Text

     $query="SELECT team_id,name,nickname,abbr FROM (SELECT team_id,name,nickname,abbr,year FROM team_history WHERE team_id IN ($tidList) AND year>=$from AND year<=$to ORDER BY team_id,year DESC) as t1 GROUP BY team_id;";

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

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

     while ($row=mysqli_fetch_array($result))

     {

	     $tid=$row['team_id'];

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

     }



     ## Get stat query array

     switch ($stat)

     {

     case 'winpct': $statQArray=Array('w','l'); break;

     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;

     }



     ## Generate Query

     $query="SELECT ths.team_id,year";

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



     switch ($stat)

     {

     case 'w':

     case 'l':

     case 'pos':

     case 'winpct':

     case 'gb':

     case 'gmovr500':

	     $query.=" FROM team_history_record as ths";

	     break;

     case 'ab':

     case 'h':

     case 'd':

     case 't':

     case 'hr':

     case 'rbi':

     case 'r':

     case 'sb':

     case 'cs':

     case 'bb':

     case 'k':

     case 'sf':

     case 'sh':

     case 'ibb':

     case 'hp':

     case 'gdp':

     case 'pa':

     case 'outs':

     case 'ebh':

     case 'tb':

     case 'tob':

     case 'tto':

     case 'pitches_seen':

     case 'avg':

     case 'obp':

     case 'slg':

     case 'ops':

     case 'war':

	     $query.=" FROM team_history_batting_stats as ths";

	     break;

     default:

	     $query.=" FROM team_history_pitching_stats as ths";

	     break;

     }

     $query.=" WHERE ths.league_id=$lgid AND ths.team_id IN ($tidList)";

     if ($zeroStats==1) {$query.=" AND year>=$from";}

     $query.=" GROUP BY team_id,year";

     $query.=" ORDER BY team_id,year;";



     break;

  }



  ##### Get Data #####

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

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

  if (mysqli_num_rows($result))

  {

	  $minYr=$to;

	  $maxYr=$from;

	  while ($row=mysqli_fetch_array($result))

	  {

		  switch ($view)

		  {

		  case 'players': $pid=$row['player_id']; break;

		  case 'teams': $pid=$row['team_id']; break;

		  }



		  $yr=$row['year'];



		  if ($yr>$to) {continue;}



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

		  {

			  if ($scope=='season') {$statTotal[$pid][$statLbl]=$row[$statLbl];}

			  else {$statTotal[$pid][$statLbl]=$statTotal[$pid][$statLbl]+$row[$statLbl];}

		  }



		  switch ($stat)

		  {

		  case 'winpct':

			  if ($statTotal[$pid]['w']+$statTotal[$pid]['l']==0) {$statTotal[$pid][$stat]=0;}

			  else {$statTotal[$pid][$stat]=$statTotal[$pid]['w']/($statTotal[$pid]['w']+$statTotal[$pid]['l']);}

			  break;

		  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;

		  }



		  if ($yr<$from) {continue;}



		  if ($yr<=$minYr) {$minYr=$yr-1;}

		  if ($yr>=$maxYr) {$maxYr=$yr+1;}

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

	  }

  }

  else

  {

	  mysqli_close($db);



	  echo "<div class='textbox'>No data found</div>\n";

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

	  page_foot($lgpath);

	  exit;

  }





  ##### 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";

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

  {

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

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

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

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

	  {

		  echo "<td>";

		  if (isset($data[$pid][$i])) {echo stat_format($stat,$data[$pid][$i]);}

		  echo "</td>";

	  }

	  echo "</tr>\n";

  }

  echo "   </table>\n";

  echo "  </div>\n";



  ##### Display Chart

  $nTicks=10;

  $tickInterval=max(1,floor(($maxYr-$minYr)/$nTicks));

  $lastTick=($maxYr+(($maxYr-$minYr+2)%$tickInterval));



  $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 "                    tickInterval:$tickInterval,\n";

  echo "                    min:$minYr,\n";

  echo "                    max:$lastTick\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']);





?>

