<?php

  include("html_functions.php");



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

  $lgid=$_SESSION['lgid'];

  $lgyear=$_SESSION['lgyear'];

  $slid=$_GET['sub_league_id'];

  $who=$_GET['view'];

  if ($who=="") {$who='batting';}



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

  $query="SELECT sub_league_id,name,abbr FROM sub_leagues WHERE league_id=$lgid;";

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

  while ($row=mysqli_fetch_array($result))

  {

	  $sub_league_id=$row['sub_league_id'];

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

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

  }

  if ($slid!="")

  {

	  $title=$subleagues[$slid]['name']." ";

	  if ($who=="fielding_stats") {$title.="Fielding ";}

	  else {$title.=ucwords($who);}

	  $title.=" Trends";

  }

  else {$title='League Trends';}



  page_head($title,$_SESSION['lgpath'],"","","./jquery/excanvas.js|./jquery/jquery.min.js|./jquery/jquery.jqplot.min.js|./jquery/plugins/jqplot.highlighter.min.js|./jquery/plugins/jqplot.cursor.min.js|./jquery/plugins/jqplot.enhancedLegendRenderer.min.js");

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

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

  nav_toolbar("history","History");

  nav_toolbar("leagues","",$lgid,$slid,"",$yr,"view^bpf");

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

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



  ## Inclue Runs/G Chart

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

  $query="SELECT ts.sub_league_id,ts.year,SUM(r)/SUM(tr.g) as rperg FROM team_history_batting_stats as ts,team_history_record as tr WHERE ts.league_id=$lgid AND ts.year=tr.year AND ts.team_id=tr.team_id GROUP BY sub_league_id,year ORDER BY sub_league_id,year";

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

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

  $prevSLid=-1;

  $rowCnt=0;

  $xmin=$lgyear;

  while ($row=mysqli_fetch_array($result))

  {

	  $sub_league_id=$row['sub_league_id'];

	  if ($prevSLid!=$sub_league_id)

	  {

		  if (isset($line[$prevSLid])) {$line[$prevSLid].="]";}

		  $line[$sub_league_id]="[";

		  $rowCnt=0;

	  }



	  $yr=$row['year'];

	  $rpg=$row['rperg'];

	  if ($rowCnt>0) {$line[$sub_league_id].=",";}

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

	  $line[$sub_league_id].="[".$yr.", ".$rpg."]";

	  $rowCnt++;

	  $prevSLid=$sub_league_id;

  }

  $line[$prevSLid].="]";

  $xmax=$yr+1;

  mysqli_close($db);



  $cWidth=max(800,(150+20*($xmax-$xmin)));

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



  if ($cWidth>900)

  {

	  echo "  <div id='controldiv' title='Double-click to reset zoom' style='height:100px;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 ($line as $key => $data) {echo "     var line$key=$data;\n";}

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

  $rowCnt=0;

  foreach ($line as $key => $data)

  {

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

	  echo "line$key";

	  $rowCnt++;

  }

  echo "], {\n";

  echo "       title:'Runs Per Game',\n";

  echo "       axes: {\n";

  echo "         xaxis: {min: $xmin, max: $xmax, tickInterval:".max(1,floor(($xmax-$xmin)/10))."}\n";

  echo "         },\n";

  echo "       series: [\n";

  $rowCnt=0;

  foreach ($line as $key => $data) 

  {

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

	  echo "              {label: '".$subleagues[$key]['abbr']."', showLabel: true}\n";

	  $rowCnt++;

  }

  echo "              ],\n";

  echo "       highlighter: {show: true},\n";

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

  echo "       legend: {renderer: $.jqplot.EnhancedLegendRenderer, show:true, location: 'n', placement: 'outsideGrid', rendererOptions: { numberRows: 1 } }\n";

  echo "     });\n";



  if ($cWidth>900)

  {

	  echo "     var controllerPlot=$.jqplot('controldiv', [";

	  $rowCnt=0;

	  foreach ($line as $key => $data)

	  {

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

		  echo "line$key";

		  $rowCnt++;

	  }

	  echo "], {\n";

	  echo "       title:'Full Timeline (click & drag to zoom)',\n";

	  echo "       axes: {\n";

	  echo "         xaxis: {min: $xmin, max: $xmax, tickInterval:".max(1,floor(($xmax-$xmin)/10))."}\n";

	  echo "         },\n";

	  echo "       series: [\n";

	  $rowCnt=0;

	  foreach ($line as $key => $data) 

	  {

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

			  echo "              {label: '".$subleagues[$key]['abbr']."', showLabel: true}\n";

		  $rowCnt++;

	  }

	  echo "              ],\n";

	  echo "       cursor: {show: true, zoom: true, showTooltip: false, constrainZoomTo: 'x'}\n";

	  echo "     });\n";



	  echo "       $.jqplot.Cursor.zoomProxy(targetPlot, controllerPlot);\n";

	  echo "       $.jqplot._noToImageButton = true;\n";

  }



  echo "    });\n";

  echo "   -->\n";

  echo "  </script>\n";



  ## Close if unselected

  if (($slid=="")||($who==""))

  {

	  echo "<p>Please choose a sub-league and view.</p>\n";

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

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

	  page_foot($_SESSION['lgpath']);

	  exit;

  }



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

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



  ## Get League Team Stats

  switch ($who)

  {

  case "batting":

  case "pitching":

  case "fielding_stats":

	  switch ($who)

	  {

	  case "batting":

		  $statArray=Array('rperg','r','g','pa','ab','h','d','t','hr','rbi','bb','k','sb','cs','avg','obp','slg','ops');

		  break;

	  case "pitching":

		  $statArray=Array("rperg","w","l","winpct","r","g","cg","sho","s","era","ip","ha","hra","bb","k","whip","oavg","babip");

		  break;

	  case "fielding_stats":

		  $statArray=Array("g","po","a","dp","tp","tc","e","fpct","inn","rng","pb","sba","rto","rtoPct");

		  break;

	  }



	  echo "<div class='textbox' style='width:100%;'>   <!-- open $who stats -->\n";

	  echo " <table border=0 cellpadding=4 cellspacing=0 width='100%' style='margin-left:auto;margin-right:auto;'>   <!-- open $who stats -->\n";

	  if ($who=='fielding_stats') {echo "  <tr class='title2'><td>Fielding Stats</td></tr>\n";}

	  else {echo "  <tr class='title2'><td>".ucwords($who)." Stats</td></tr>\n";}

	  echo "  <tr><td style='padding:0px;'>\n";

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

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

	  echo "<td class='hsc2_l'>Year</td>";

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

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

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

	  $query="SELECT ts.year,COUNT(DISTINCT ts.team_id) as tms";

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

	  {

		  switch ($statLbl)

		  {

		  case 'rperg':

			  $query.=",if(SUM(tr.g)=0,0,SUM(ts.r)/SUM(tr.g)) as $statLbl";

			  break;

		  case 'g':

		  case 'w':

		  case 'l':

		  case 'winpct':

			  $query.=",".stat_query($statLbl,'tr')." as $statLbl";

			  break;

		  default:

			  $query.=",".stat_query($statLbl,'ts')." as $statLbl";

			  break;

		  }

	  }

	  $query.=" FROM team_history_".$who."_stats as ts,team_history_record as tr WHERE ts.league_id=$lgid AND ts.year=tr.year AND ";

	  $query.=" ts.team_id=tr.team_id AND ts.sub_league_id=$slid GROUP BY year ORDER BY year DESC";

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

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

	  $rowCnt=0;

	  while ($row=mysqli_fetch_array($result))

	  {

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



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

		  echo "<td class='".$cls."_l'><a href='./league_summary.php?sub_league_id=$slid&year=$yr'>".$row['year']."</a></td>";

		  echo "<td>".$row['tms']."</td>";

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

		  echo "</tr>\n";

		  $rowCnt++;

	  }



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

	  echo "<td class='hsc2_l'>Year</td>";

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

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

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



	  echo "   </table>\n";

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

	  echo " </table>   <!-- close $who stats -->\n";

	  echo "</div>   <!-- close $who stats -->\n";

	  break;



  case "financial":

	  ## Get Team Financial Stats

	  $statArray=Array('attendance','avgtix','player_expenses','staff_expenses','budget','tot_revenue','tot_expenses','profit');

	  echo "<div class='textbox' style='width:100%;'>   <!-- open financial stats -->\n";

	  echo " <table border=0 cellpadding=4 cellspacing=0 width='100%' style='margin-left:auto;margin-right:auto;'>   <!-- open financial stats -->\n";

	  echo "  <tr class='title2'><td>Financial Stats</td></tr>\n";

	  echo "  <tr><td style='padding:0px;'>\n";

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

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

	  echo "<td class='hsc2_l'>Year</td>";

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

	  echo "<td class='hsc2'>Tot Att</td>";

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

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

	  $query="SELECT ts.year,COUNT(DISTINCT ts.team_id) as tms";

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

	  $query.=" FROM team_history_financials as ts WHERE league_id=$lgid AND sub_league_id=$slid GROUP BY year ORDER BY year DESC";

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

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

	  $rowCnt=0;

	  while ($row=mysqli_fetch_array($result))

	  {

		  $yr=$row['year'];

		  $yrTms=$row['tms'];



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



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

		  echo "<td class='".$cls."_l'><a href='./league_summary.php?sub_league_id=$slid&year=$yr'>".$row['year']."</a></td>";

		  echo "<td>".$row['tms']."</td>";

		  echo "<td sorttable_customkey='".$row['attendance']."'>".stat_format('attendance',$row['attendance'])."</td>";

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

		  echo "</tr>\n";

		  $rowCnt++;

	  }

	

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

	  echo "<td class='hsc2_l'>Year</td>";

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

	  echo "<td class='hsc2'>Tot Att</td>";

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

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



	  echo "   </table>\n";

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

	  echo " </table>   <!-- close financial stats -->\n";

	  echo "</div>   <!-- close financial stats -->\n";

	  break;

  }





  mysqli_close($db);



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

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



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

  echo " <!--\n";

  echo "   document.getElementById('year').disabled=1;\n";

  echo " -->\n";

  echo "</script>\n";



  page_foot($_SESSION['lgpath']);





?>

