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

  ################## PAGE INITIALIZATION #########################
  $lgid=$_SESSION['lgid'];
  $lgpath=$_SESSION['lgpath'];
  $date=new DateTime($_SESSION['lgdate']);
  $lgyear=$_SESSION['lgyear'];

  if (($_SESSION['user_team_id']>0)&&(!isset($_GET['team_id'])))
  {
	  if ($_SESSION['user_league_id']==$lgid) {$team_id=$_SESSION['user_team_id'];}
	  else
	  {
		  include($_SESSION['adminpath']."/dbopen.php");
		  $query="SELECT team_id FROM teams WHERE parent_team_id=".$_SESSION['user_team_id']." AND league_id=$lgid";
		  $result=mysqli_query($db,$query);
		  if (mysqli_num_rows($result))
		  {
			  $row=mysqli_fetch_array($result);
			  $team_id=$row['team_id'];
		  }
		  mysqli_close($db);
	  }
  }
  elseif (isset($_GET['team_id'])) {$team_id=$_GET['team_id'];}
  if ($team_id=="") {$team_id=-1;}
  $tyear=$_GET['year'];
	  
  ##### Get Team Names #####
  include($_SESSION['adminpath']."/dbopen.php");
  $query="SELECT team_id,name,nickname,league_id,sub_league_id,division_id FROM teams WHERE league_id=$lgid";
  if ($team_id>0) {$query.=" AND team_id=$team_id";}
  $query.=" AND allstar_team=0 ORDER BY name,nickname LIMIT 1;";
  $result=mysqli_query($db,$query);
  while ($row=mysqli_fetch_array($result))
  {
	  $team_id=$row['team_id'];
	  $tname=$row['name']." ".$row['nickname'];
  }
  mysqli_close($db);
  
  ##### Get Title #####
  $title=$tname." History - Index";
  page_head($title,$_SESSION['lgpath'],"","","./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.barRenderer.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,$team_id);
  nav_toolbar("history","History");
  nav_toolbar("teams","Teams","","",$team_id,$tyear);

  ##### Show Page Content #####
  echo " </div>   <!-- END topbar DIV -->\n";

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

  echo gen_index($team_id);

  ################## END OF PAGE #########################
  echo " </div>   <!-- END contentpane DIV -->\n";
  page_foot($_SESSION['lgpath']);

  exit;


##### Page Generation Functions #####

##############################################################################################
# gen_index - Team Index Page
##############################################################################################
function gen_index($tid="")
 {
   ##### Exit if no team_id #####
   if ($tid=="") {exit;}
   include($_SESSION['adminpath']."/dbopen.php");

   ##### Check for tables #####
   $query="SHOW TABLES LIKE 'team_history%';";
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result)<5) {return "Please load the team_history SQL tables first";}

   ##### Get basic parameters #####
   $date=new DateTime($_SESSION['lgdate']);
   $year=$_SESSION['lgyear'];
   $lgpath=$_SESSION['lgpath'];
   $lgid=$_GET['lgid'];
   if ($lgid=="") {$lgid=$_SESSION['lgid'];}
   if ($lgid=="") {$lgid=100;}
   $text="";
   
   ##### Get Playoff Odds Configuration #####
   ##### Get Playoff Odds Configuration #####
   $query="SHOW TABLES LIKE 'ootp_sql_admin';";
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result)) 
   {
	   # Get Settings
	   $query="SELECT setting,value FROM ootp_sql_admin WHERE scope IN ('ALL',$lgid) AND module IN ('admin','Last Sim') AND setting IN ('pythMeth','pythExp')";
	   $result=mysqli_query($db,$query);
 	   if (mysqli_num_rows($result))
	   {
 		   while ($row=mysqli_fetch_array($result))
		   {
 			   $setting=$row['setting'];
			   $val=$row['value'];

			   switch ($setting)
 			   {
			   case 'pythMeth'     : $pythMeth=$val;     break;
			   case 'pythExp'      : $pythExp=$val;      break;
 			   }
 		   }
	   }
   }
   switch ($pythMeth)
   {
   case 'Pythagorean Win Pct (Pythagenpat)': $pythMeth='pythPat';break;
   case 'Actual Win Pct': $pythMeth='record'; break;
   default: $pythMeth='pythExp';break;
   }
   if ($pythMeth=="") {$pythMeth='pythExp';}
   if ($pythExp=="") {$pythExp=1.82;}

   ##### Get Run Differential #####
   $query="SELECT thb.year, thb.r AS rf, thp.r AS ra,if(thp.gs=0,thp.g,thp.gs) as g,thb.ab as ab,thb.h as h,(thp.ip*3+thp.ipf)/3 as ip,thp.er as er FROM team_history_batting_stats AS thb, team_history_pitching_stats AS thp WHERE thb.year=thp.year AND thb.team_id=thp.team_id AND thb.team_id=$tid UNION SELECT '$year' as year, tbs.r AS rf, tps.r AS ra,tps.gs as g,tbs.ab as ab,tbs.h as h,(tps.ip*3+tps.ipf)/3 as ip,tps.er as er FROM team_batting_stats AS tbs, team_pitching_stats AS tps WHERE tbs.team_id=tps.team_id AND tbs.team_id=$tid ORDER BY year;";
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result))
    {
      while ($row=mysqli_fetch_array($result))
       {
         $yr=$row['year'];
	 $rf=$row['rf'];
	 $ra=$row['ra'];
	 $g=$row['g'];
    
	 if ($g==0) {$pythPct=0.5;}
	  else 
	  {
	    switch ($pythMeth)
             {
               case 'pythPat':
                 $pythExp=pow(($rf+$ra)/$g,0.287);
	         $pythPct=pow($rf,$pythExp)/(pow($rf,$pythExp)+pow($ra,$pythExp));
	         break;
              default:
	         $pythPct=pow($rf,$pythExp)/(pow($rf,$pythExp)+pow($ra,$pythExp));
	         break;
	     }
	  }
	 $years[$yr]['pythPct']=$pythPct;
	 $pythW=round($g*$pythPct,0);
	 $pythL=$g-$pythW;
	 $years[$yr]['pythW']=$pythW;
	 $years[$yr]['pythL']=$pythL;

	 $TpythW+=$pythW;
	 $TpythL+=$pythL;

	 $ab=$row['ab'];
	 $h=$row['h'];
	 $ip=$row['ip'];
	 $er=$row['er'];

	 $Tab+=$ab;
	 $Th+=$h;
	 $Tip+=$ip;
	 $Ter+=$er;

	 if ($ab==0) {$avg=0;} else {$avg=$h/$ab;}
         if ($ip==0) {$era=0;} else {$era=(9*$er)/$ip;}
	 $avg=sprintf("%.3f",$avg);
         if ($avg<1) {$avg=strstr($avg,".");}
	 $era=sprintf("%.2f",$era);

	 $years[$yr]['avg']=$avg;
	 $years[$yr]['era']=$era;
       }
    }

   ##### Get Team Record #####
   $query="SELECT thr.year,thr.league_id,thr.sub_league_id,thr.division_id,g,w,l,pos,gb,made_playoffs,won_playoffs,name,nickname FROM team_history_record as thr,team_history as th WHERE thr.team_id=th.team_id AND thr.year=th.year AND thr.team_id=$tid UNION SELECT '$year' as year,t.league_id,t.sub_league_id,t.division_id,g,w,l,pos,gb,NULL,NULL,name,nickname FROM team_record as tr,teams as t WHERE tr.team_id=t.team_id AND tr.team_id=$tid ORDER BY year;";
   if ($_GET['showq']==1) {echo $query;}
   $result=mysqli_query($db,$query);
   while ($row=mysqli_fetch_array($result))
    {
      $yr=$row['year'];
      $g=$row['g'];
      $l=$row['l'];
      $w=$row['w'];
      $pos=$row['pos'];
      $gb=$row['gb'];
      $poff=$row['made_playoffs'];
      $wsWin=$row['won_playoffs'];
      $name=$row['name']." ".$row['nickname'];

      if ($g==0) {$wpct=0;} else {$wpct=$w/$g;}
      $wpct=sprintf("%.3f",$wpct);
      if ($wpct<1) {$wpct=strstr($wpct,".");}

      $Tyr+=1;
      $Tg+=$g;
      $Tw+=$w;
      $Tl+=$l;
      $Tpos+=$pos;
      $Tgb+=$gb;
      $Tpoff+=$poff;
      $TwsWin+=$wsWin;

      if ($poff==0) {$poff="";} else {$poff="X";}
      if ($wsWin==0) {$wsWin="";} else {$wsWin="X";}
	      
      $years[$yr]['w']=$w;
      $years[$yr]['l']=$l;
      $years[$yr]['wpct']=$wpct;
      $years[$yr]['gb']=$gb;
      $years[$yr]['pos']=$pos;
      $years[$yr]['poff']=$poff;
      $years[$yr]['wsWin']=$wsWin;
      $years[$yr]['name']=$name;
      $years[$yr]['league_id']=$row['league_id'];
      $years[$yr]['sub_league_id']=$row['sub_league_id'];
      $years[$yr]['division_id']=$row['division_id'];
	  
	  $league_id=$row['league_id'];
	  $leagues[$league_id]['fnd']=1;
    }
	$leagueList="";
	$lgCnt=0;
	foreach ($leagues as $league_id => $val)
	{
		if ($lgCnt>0) {$leagueList.=",";}
		$leagueList.=$league_id;
		$lgCnt++;
	}
	
	##### Get League & Sub League Infor #####
	$leagueList=trim($leagueList,",");
	$query="SELECT league_id,name,abbr FROM leagues WHERE league_id IN ($leagueList)";
	if ($_GET['showq']==1) {echo $query;}
	$result=mysqli_query($db,$query);
	if (mysqli_num_rows($result))
	{
		while ($row=mysqli_fetch_array($result))
		{
			$league_id=$row['league_id'];
			$leagues[$league_id]['name']=$row['name'];
			$leagues[$league_id]['abbr']=$row['abbr'];
		}
	}
	$query="SELECT league_id,sub_league_id,name,abbr FROM sub_leagues WHERE league_id IN ($leagueList)";
	if ($_GET['showq']==1) {echo $query;}
	$result=mysqli_query($db,$query);
	if (mysqli_num_rows($result))
	{
		while ($row=mysqli_fetch_array($result))
		{
			$league_id=$row['league_id'];
			$sub_league_id=$row['sub_league_id'];
			$subleagues[$league_id][$sub_league_id]['name']=$row['name'];
			$subleagues[$league_id][$sub_league_id]['abbr']=$row['abbr'];
		}
	}
   

   ##### Get Team Financials #####
   $query="SELECT year,attendance,player_expenses,player_expenses+staff_expenses+stadium_expenses as expenses,gate_revenue+media_revenue+merchandising_revenue+season_ticket_revenue+playoff_revenue as revenue FROM team_history_financials WHERE team_id=$tid UNION SELECT '$year' as year,attendance,player_expenses,player_expenses+staff_expenses+stadium_expenses as expenses,gate_revenue+media_revenue+merchandising_revenue+season_ticket_revenue+playoff_revenue as revenue FROM team_financials WHERE team_id=$tid ORDER BY year;";
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result))
    {
      while ($row=mysqli_fetch_array($result))
       {
         $yr=$row['year'];
	 $att=$row['attendance'];
	 $payroll=$row['player_expenses'];
	 $expenses=$row['expenses'];
	 $revenue=$row['revenue'];
	 $net=$revenue-$expenses;

	 $years[$yr]['attendance']=$att;
	 $years[$yr]['payroll']=$expenses;
	 $years[$yr]['revenue']=$revenue;
	 
	 $Tatt+=$att;
	 $Tnet+=$net;
       }
    }

   ##### Display Results #####
   $text.="<div class='textbox'>\n";
   $text.=" <table cellpadding=0 cellspacing=0 border=0 width='935px'>\n";
   $text.="  <tr class='title'><td style='padding:2px;'>Team Results</td></tr>\n";
   $text.="  <tr><td>\n";
   $text.="   <table cellpadding=2 cellspacing=0 border=0 class='sortable' width='100%'>\n";
   $text.="    <thead><tr class='headline'><td class='hsc2_l'>Year</td>";
   $text.="<td class='hsc2_l'>Lg</td>";
   $text.="<td class='hsc2'>W</td><td class='hsc2'>L</td><td class='hsc2'>WPct</td><td class='hsc2'>Finish</td><td class='hsc2'>GB</td><td class='hsc2'>Exp Rec</td><td class='hsc2'>Diff</td><td class='hsc2'>Avg</td><td class='hsc2'>ERA</td><td class='hsc2'>Playoffs</td><td class='hsc2'>Champion</td><td class='hsc2'>Attendance</td><td class='hsc2'>Expenses</td><td class='hsc2'>Revenue</td>";
   $text.="</tr></thead>\n";

   $nYrs=count($years);
   $cnt=0;
   ksort($years);
   foreach ($years as $yr => $val)
    {
      $g=$years[$yr]['w']+$years[$yr]['l'];
      if (($yr==0)||($g==0)) {continue;}
      $cls='s'.($cnt%2+1);
      $gb=$years[$yr]['gb'];
      if ($gb==0) {$gb="-";}
      $pos=$years[$yr]['pos'];
      $pythDiff=$years[$yr]['w']-$years[$yr]['pythW'];
      $TpythDiff+=$pythDiff;
      $name=$years[$yr]['name'];

      $text.="    <tr class='$cls'>";
      $text.="<td class='".$cls."_l'><a href='./team_summary.php?&team_id=$tid&year=$yr'>$yr $name</a></td>";

		$league_id=$years[$yr]['league_id'];
		$sub_league_id=$years[$yr]['sub_league_id'];
		$text.="<td class='".$cls."_l'>";
		if (isset($leagues[$league_id]['abbr']))
		{
			$text.="<a href='./league_summary.php?league_id=".$league_id."&sub_league_id=".$sub_league_id."&year=$yr'>";
			if (count($leagues)>1) {$text.=$leagues[$league_id]['abbr'];}
			if ((count($leagues)>1)&&(count($subleagues[$league_id])>1)) {$text.=" ";}
			if (count($subleagues[$league_id])>1) {$text.=$subleagues[$league_id][$sub_league_id]['abbr'];}
			$text.="</a>";
		}
		else
		{
			$text.="&nbsp;";
		}
		$text.="</td>";

 	  $text.="<td>".$years[$yr]['w']."</td>";
      $text.="<td>".$years[$yr]['l']."</td>";
      $text.="<td>".$years[$yr]['wpct']."</td>";
      $text.="<td>".ordinal_suffix($pos,1)."</td>";
      $text.="<td>".$gb."</td>";
      $text.="<td>".$years[$yr]['pythW']."-".$years[$yr]['pythL']."</td>";
      $text.="<td>".$pythDiff."</td>";
      $text.="<td>".$years[$yr]['avg']."</td>";
      $text.="<td>".$years[$yr]['era']."</td>";
      $text.="<td>".$years[$yr]['poff']."</td>";
      $text.="<td>".$years[$yr]['wsWin']."</td>";
      $text.="<td>".number_format($years[$yr]['attendance'])."</td>";
      $text.="<td>$".number_format($years[$yr]['payroll'])."</td>";
      $text.="<td>$".number_format($years[$yr]['revenue'])."</td>";
      $text.="</tr>\n";
      $cnt++;
    }

   ## Team Totals
   if ($Tg==0) {$wpct=0;}
   else {$wpct=$Tw/$Tg;}
   $wpct=sprintf("%.3f",$wpct);
   if ($wpct<1) {$wpct=strstr($wpct,".");}

   if ($Tab==0) {$avg=0;} else {$avg=$Th/$Tab;}
   if ($Tip==0) {$era=0;} else {$era=(9*$Ter)/$Tip;}
   $avg=sprintf("%.3f",$avg);
   if ($avg<1) {$avg=strstr($avg,".");}
   $era=sprintf("%.2f",$era);
	   
   $text.="    <tfoot><tr class='headline'>";
   $text.="<td class='hsc2_l' colspan=2>Totals</td>";
   $text.="<td class='hsc2'>$Tw</td>";
   $text.="<td class='hsc2'>$Tl</td>";
   $text.="<td class='hsc2'>$wpct</td>";
   $text.="<td class='hsc2'>&nbsp;</td>";
   $text.="<td class='hsc2'>&nbsp;</td>";
   $text.="<td class='hsc2'>".$TpythW."-".$TpythL."</td>";
   $text.="<td class='hsc2'>$TpythDiff</td>";
   $text.="<td class='hsc2'>$avg</td>";
   $text.="<td class='hsc2'>$era</td>";
   $text.="<td class='hsc2'>$Tpoff</td>";
   $text.="<td class='hsc2'>$TwsWin</td>";
   $text.="<td class='hsc2'>".number_format($Tatt)."</td>";
   $text.="<td class='hsc2'>Net:</td>";
   $text.="<td class='hsc2'>$".number_format($Tnet)."</td>";
   $text.="</tr></tfoot>\n";

   $text.="   </table>\n";
   $text.="  </td></tr>\n";
   $text.=" </table>\n";
   $text.="</div>   <!-- END of Team Index -->\n";

   ##### Display Runs Score/Runs Allowed Ranks #####
   $query="SELECT t1.team_id,t1.year,t1.r,COUNT(t2.r) as rRank FROM team_history_batting_stats as t1,team_history_batting_stats as t2 WHERE (t1.r<=t2.r OR (t1.team_id=t2.team_id AND t1.r=t2.r)) AND t1.year=t2.year AND t1.team_id=$tid AND t1.league_id=t2.league_id AND t1.sub_league_id=t2.sub_league_id GROUP BY t1.team_id,t1.year,t1.r ORDER BY team_id,year,rRank";
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result))
   {
	   while ($row=mysqli_fetch_array($result))
	   {
		   $yr=$row['year'];
		   $r=$row['r'];
		   $rnk=$row['rRank'];

		   $data[$yr]['r']=$r;
		   $data[$yr]['rRank']=$rnk;
	   }
   }
   $query="SELECT t1.team_id,t1.year,t1.r,COUNT(t2.r) as rRank FROM team_history_pitching_stats as t1,team_history_pitching_stats as t2 WHERE (t1.r>=t2.r OR (t1.team_id=t2.team_id AND t1.r=t2.r)) AND t1.year=t2.year AND t1.team_id=$tid AND t1.league_id=t2.league_id AND t1.sub_league_id=t2.sub_league_id GROUP BY t1.team_id,t1.year,t1.r ORDER BY team_id,year,rRank";
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result))
   {
	   while ($row=mysqli_fetch_array($result))
	   {
		   $yr=$row['year'];
		   $r=$row['r'];
		   $rnk=$row['rRank'];

		   $data[$yr]['ra']=$r;
		   $data[$yr]['raRank']=$rnk;
	   }
   }

   if (isset($data))
   {
	   $text.="  <div id='chartdiv' style='margin-top:20px;clear:both;height:400px;width:800px;margin-left:auto;margin-right:auto;'></div>\n";
	   $text.="  <div id='controldiv' title='Double-click to reset zoom' style='margin-top:20px;clear:both;height:100px;width:800px;margin-left:auto;margin-right:auto;'></div>\n";

	   $text.="  <script class='code' type='text/javascript'>\n";
	   $text.="   <!--\n";
	   $text.="    $(document).ready(function(){\n";
	   $text.="       var rLine = [";
	   $rowCnt=0;
	   foreach ($data as $x => $val)
	   {
		   $y=$data[$x]['rRank'];
		   $z=$data[$x]['r'];
		   if ($rowCnt>0) {$text.=", ";}
		   $text.="[$x, $z]";
		   $rowCnt++;
	   }
	   $text.="];\n";
	   $text.="       var raLine = [";
	   $rowCnt=0;
	   foreach ($data as $x => $val)
	   {
		   $y=$data[$x]['raRank'];
		   $z=$data[$x]['ra'];
		   if ($rowCnt>0) {$text.=", ";}
		   $text.="[$x, $z]";
		   $rowCnt++;
	   }
	   $text.="];\n";
	   $text.="       var rDiffLine = [";
	   $rowCnt=0;
	   foreach ($data as $x => $val)
	   {
		   $y=$data[$x]['ra'];
		   $z=$data[$x]['r'];
		   if ($rowCnt>0) {$text.=", ";}
		   $text.="[$x, ".($z-$y)."]";
		   $rowCnt++;
	   }
	   $text.="];\n";
	   $text.="       var finLine = [";
	   $rowCnt=0;
	   $xmin=$year;
	   $xmax=0;
	   foreach ($years as $x => $val)
	   {
		   if (!isset($data[$x])) {continue;}
	
		   if ($x<=$xmin) {$xmin=$x-1;}
		   if ($x>=$xmax) {$xmax=$x+1;}
	
		   $y=$years[$x]['pos'];
		   if ($rowCnt>0) {$text.=", ";}
		   $text.="[$x,$y]";
		   $rowCnt++;
	   }
	   $text.="];\n";

	   $query="SELECT MAX(nTeams) as nTeams FROM (SELECT sub_league_id,year,MAX(pos) as nTeams FROM `team_history_record` WHERE league_id=$lgid AND year>$xmin AND year<$xmax GROUP BY sub_league_id,year) as t";
	   $result=mysqli_query($db,$query);
	   if (mysqli_num_rows($result))
	   {
		   $row=mysqli_fetch_array($result);
		   $tMax=$row['nTeams'];
	   }


	   $text.="       var plot1=$.jqplot('chartdiv', [finLine, rLine, raLine, rDiffLine],{\n";
	   $text.="         title:'Team Ranks',\n";
	   $text.="         axesDefaults:  {\n";
	   $text.="            tickRenderer: $.jqplot.CanvasAxisTickRenderer,\n";
	   $text.="            rendererOptions: {alignTicks: true}\n";
	   $text.="         },\n";
	   $text.="         axes: {\n";
	   $text.="            xaxis: {min: $xmin, max: $xmax,\n";
	   $text.="                    tickOptions: {angle: -30, formatString: '%.0f'}\n";
   	   $text.="            },\n";
	   $text.="            yaxis: {forceTickAt0: true, min:".($tMax+((($tMax%2)==1)?(1):(2))).", max:0, tickInterval: ".(($tMax>10)?(-2):(-1)).", useSeriesColor:true},\n";
	   $text.="            y2axis: {forceTickAt0: true, useSeriesColor:true},\n";
	   $text.="            y3axis: {forceTickAt0: true, useSeriesColor:true}\n";
	   $text.="         },\n";
	   $text.="         series: [\n";
	   $text.="            {label: 'Standings Finish', showLabel: true},\n";
	   $text.="            {label: 'Runs Scored', showLabel: true,\n";
	   $text.="                     yaxis: 'y2axis',\n";
	   $text.="                     highlightMouseOver:true\n";
	   $text.="                     },\n";
	   $text.="            {label: 'Runs Allowed', showLabel: true,\n";
	   $text.="                     yaxis: 'y2axis',\n";
	   $text.="                     highlightMouseOver:true\n";
	   $text.="                     },\n";
	   $text.="            {label: 'Run Differential', showLabel: true,\n";
	   $text.="                     yaxis: 'y3axis',\n";
	   $text.="                     highlightMouseOver:true\n";
	   $text.="                     }\n";
	   $text.="         ],\n";
	   $text.="         highlighter: {show: true},\n";
	   $text.="         cursor: {show: true, zoom: true, showTooltip: false, constrainZoomTo: 'x'},\n";
	   $text.="         legend: {\n";
	   $text.="            renderer: $.jqplot.EnhancedLegendRenderer,\n";
	   $text.="            show:true,\n";
	   $text.="            location: 'n',\n";
	   $text.="            placement: 'outsideGrid',\n";
	   $text.="            rendererOptions: {\n";
	   $text.="               numberRows: 1\n";
	   $text.="               }\n";
	   $text.="            }\n";
	   $text.="       });\n";

	   $text.="       var plot2=$.jqplot('controldiv', [finLine],{\n";
	   $text.="         title:'Standings Finish (click & drag to zoom)',\n";
	   $text.="         axesDefaults:  {\n";
	   $text.="            tickRenderer: $.jqplot.CanvasAxisTickRenderer\n";
	   $text.="         },\n";
	   $text.="         axes: {\n";
	   $text.="            xaxis: {min: $xmin, max: $xmax,\n";
	   $text.="                    tickOptions: {angle: -30, formatString: '%.0f'}\n";
   	   $text.="            },\n";
	   $text.="            yaxis: {forceTickAt0: true, min:".($tMax+((($tMax%2)==1)?(1):(2))).", max:0, tickInterval: ".(($tMax>6)?(-2):(-1))."}\n";
	   $text.="         },\n";
	   $text.="         series: [\n";
	   $text.="            {label: 'Pos in Standings',\n";
	   $text.="             showLabel: true,\n";
	   $text.="             highlightMouseOver:true\n";
	   $text.="            },\n";
	   $text.="         ],\n";
	   $text.="         highlighter: {show: true},\n";
	   $text.="         cursor: {show: true, zoom: true, showTooltip: false, constrainZoomTo: 'x'}\n";
	   $text.="       });\n";

	   $text.="       $.jqplot.Cursor.zoomProxy(plot1, plot2);\n";
 	   $text.="       $.jqplot._noToImageButton = true;\n";
 
	   $text.="    });\n";
	   $text.="   -->\n";
	   $text.="  </script>\n";
   }

   mysqli_close($db);

   return $text;
 }
?>
