Location: PHPKode > projects > Skat Statistics > skatstat-1.7.1/skatstat/inc/smfunc.php
<?
require_once( "ctable.php" );
require_once( "smconfig.php" );
require_once( "auxiliary.php" );
require_once( "session.php" );
include_once( "spielliste.php" );
include_once( "lang_de.php" );
require_once('authentication.php');



// error handling
set_error_handler("error_handler");

/************************************************************************
 / db functions
 /***********************************************************************/
function conn()
{
   global $CONF;

   $conn = $CONF['dbConn'] ;
   $host = $CONF['dbHost'];
   $user = $CONF['dbUser'];
   $pass = $CONF['dbPass'];
   $db   = $CONF['dbDB'] ;

   #echo "commnecing connection to local db<br>";

   if( ! ( $CONF['dbConn']=mysql_connect($host, $user, $pass) ) )
   {
      printf("error connecting to DB<br>");
      printf("make sure, that user and password is valid<br>");
      printf("and that the MySQL server is running.<br>");
      #   printf("error connecting to DB by user = $user and pwd=$pass");
      exit;
   }
   $db=mysql_select_db($db,$CONF['dbConn'])
   or die("Unable to connect to local database");

   return $db;
}

function processSQL( $sql )
{

   global $CONF;
   global $SKAT_SESSION;
   if( $CONF['dbConn'] == '' || ! mysql_ping( $CONF['dbConn'] ) )
   {
      conn();
   }
   $result =  mysql_query($sql);

   if( mysql_errno() )
   {
      handle_db_error( $sql );
   }
   return $result;
}

function processSQLReturnId( $sql )
{
   processSQL( $sql );
   return mysql_insert_id();
}

# Funktion löscht alle Daten einer Spielliste aus der Datenbank
function DeleteScoreSheetData( $Id )
{
   global $CONF;
   global $SKAT_SESSION;

   debug( "Delete ScoreSheet $Id" );

   $sql = "DELETE FROM ".$CONF['tbl_column']." WHERE SpiellisteId=$Id ";
   processSQL( $sql );

   $sql = "DELETE FROM ".$CONF['tbl_game']." WHERE SpiellisteId=$Id";
   processSQL( $sql );

   $sql = "DELETE FROM ".$CONF['tbl_scoresheet']." WHERE Id=$Id AND GroupId=" .$SKAT_SESSION[groupid];
   processSQL( $sql );

   return getSuccess( "Daten wurden erfolgreich geloescht!" );
}

# Funktion legt eine neue Spielliste an oder aktualisiert die Daten
# Rückgabewert ist die SpiellisteId
function InsertScoreSheetData( $SpiellisteId, $Tisch, $Datum, $Serie, $Category,
$NumSpieler, $NumSpiele, $GroupId )
{
   global $CONF;
   global $SKAT_SESSION;
   $set = ""
   .$CONF['col_table'].  "=$Tisch,"
   .$CONF['col_date'].   "=\"$Datum\","
   .$CONF['col_series']. "=$Serie,"
   .$CONF['col_catid'].  "=$Category,
  NumSpieler=$NumSpieler, 
  NumSpiele=$NumSpiele, 
  GroupId=$GroupId";

   if( $SpiellisteId )
   {
      debug( "Id present: $SpiellisteId" );
      $Update       = true;
      $slsql        = "UPDATE ".$CONF['tbl_scoresheet']. " SET " ;
      $slcond       = " WHERE Id=$SpiellisteId";
      processSQL( $slsql.$set.$slcond );
      for( $i = 0; $i < $NumSpiele; $i++ )
      {
         debug( "Process Game $i ");
         ProcessGameData( $SpiellisteId, $i, false );
      }
   }
   else
   {
      $slsql        = "INSERT INTO ".$CONF['tbl_scoresheet']. " SET " ;
      $SpiellisteId = processSQLReturnId( $slsql.$set );
      debug( "after processSQLReturnId: SpiellisteId: $SpiellisteId" );

      //
      // Update LastUpdate in Category Table
      $sql = "UPDATE " . $CONF['tbl_cat'] . " SET LastUpdate=". time() .", LastSpielliste=$SpiellisteId WHERE Id=$Category AND GroupId=".  $SKAT_SESSION[groupid];
      processSQL( $sql );

      # Spalten und Spieldaten einfügen, sind zwar leer, aber sie existieren
      # schon.
      for( $i = 0; $i < $NumSpiele; $i++ )
      {
         debug( "Process Game $i ");
         ProcessGameData( $SpiellisteId, $i, true );
      }
   }

   for( $i = 0; $i < $NumSpieler; $i++ )
   {
      debug( "Process Colum $i ");
      ProcessColumnData( $SpiellisteId, $i );
   }
   return $SpiellisteId;
}

function ProcessScoreSheetData( $SpiellisteId )
{
   global $CONF;
   global $SKAT_SESSION;

   $Tisch = GetPost("Tisch");
   $Datum = GetPost("Datum");
   $Serie = GetPost("Serie");
   $Category   = GetPost("Category");
   $NumSpieler = GetPost("NumSpieler");
   $NumSpiele  = GetPost("NumSpiele");

   debug( "NumSpieler: ". $NumSpieler );
   debug( "NumSpiele : ". $NumSpiele  );

   return InsertScoreSheetData( $SpiellisteId, $Tisch, $Datum,
   $Serie, $Category, $NumSpieler, $NumSpiele, $SKAT_SESSION[groupid] );

}

# Funktion fügt die Spaltendaten in die Datenbank ein. Entweder ein Update oder
# ein Insert, je nachdem es den Eintrag schon gibt.
function InsertColumnData( $SpiellisteId, $Platz, $SpielerId=0, $Gewonnen=0,
$Verloren=0, $Spielpunkte=0, $Extrapunkte=0, $Fremdpunkte=0, $Summe=0)
{
   global $CONF;
   global $SKAT_SESSION;
   $set =
   $CONF['col_SpielerId']. "=$SpielerId, "
   .$CONF['col_SpiellisteId']. "=$SpiellisteId, "
   .$CONF['col_Platznummer']. "=$Platz, "
   .$CONF['col_Gewonnen']. "=$Gewonnen, "
   .$CONF['col_Verloren']. "=$Verloren, "
   .$CONF['col_Spielpunkte']. "=$Spielpunkte, "
   .$CONF['col_Extrapunkte']. "=$Extrapunkte, "
   .$CONF['col_Fremdpunkte']. "=$Fremdpunkte, "
   .$CONF['col_Summe']. "=$Summe";

   $spsql = "REPLACE INTO " . $CONF['tbl_column'] . " SET " ;

   debug( "InsertColumnData: " . $spsql . $set );

   return processSQL( $spsql.$set ) ;
}

# Funktion fügt ein Spiel in die Datenbank ein. Entweder ein Update order ein
# Insert, je nachdem ob es das Spiel schon gibt.
function InsertGameData( $SpiellisteId, $Nr , $AlleinspielerId  =0,
$Ueberreizt      =0 , $Eingepasst      =0 ,
$Grundwert       =0 , $Spitzen          =0, $Hand         =0    ,
$Schneider       =0 , $SchneiderAngesagt=0 , $Schwarz    =0      ,
$SchwarzAngesagt =0 , $Offen            =0, $Spielwert  =0      )
{
   global $CONF;
   global $SKAT_SESSION;

   debug( "InsertGameData: Eingepasst: ". $Eingepasst );

   $set = $CONF['tbl_number']. "=$Nr,  "
   .$CONF['col_AlleinspielerId']. "=$AlleinspielerId, "
   .$CONF['col_SpiellisteId']. "=$SpiellisteId,  "
   .$CONF['col_Ueberreizt']. "=$Ueberreizt, "
   .$CONF['col_Eingepasst']. "=$Eingepasst,  "
   .$CONF['col_Grundwert']. "=$Grundwert, "
   .$CONF['col_Spitzen']. "=$Spitzen,  "
   .$CONF['col_Hand']. "=$Hand, "
   .$CONF['col_Schneider']. "=$Schneider, "
   .$CONF['col_Schneider_angesagt']."=$SchneiderAngesagt, "
   .$CONF['col_Schwarz']. "=$Schwarz, "
   .$CONF['col_Schwarz_angesagt']. "=$SchwarzAngesagt, "
   .$CONF['col_Offen']. "=$Offen, "
   .$CONF['col_Spielwert'] . "=$Spielwert";

   $gsql = "REPLACE INTO " . $CONF['tbl_game'] . " SET  " ;

   debug( "SQL: " . $gsql . $set );

   return processSQL( $gsql.$set );
}

# Funktion berechnet die Spielpunkte auf Basis der eingebenen Spiele
#
function ProcessColumnData( $SpiellisteId, $i )
{
   global $CONF;
   global $SKAT_SESSION;

   $SpielerId  = GetPost( Name  . $i );
   if( !$SpielerId )
   {
      $COND = "AND t2.SpiellisteId=t1.Id  AND t2.Platznummer=$i ";
      $TAB  = $CONF['tbl_column'] .     " AS t2, ";
   }
   else
   {
      $COND = "";
      $TAB  = "";
   }

   $sql = "SELECT
    MAX(t3.AlleinspielerId) AS AlleinspielerId,
    SUM(t3.Spielwert) AS Spielpunkte, 
    SUM(t3.Spielwert > 0) AS Gewonnen, 
    SUM(t3.Spielwert < 0) AS Verloren
  FROM "
  .$CONF['tbl_scoresheet']. " AS t1,
  $TAB " .
  $CONF['tbl_game'] .     " AS t3
  WHERE     t1.GroupId=".$SKAT_SESSION[groupid]."
  AND       t3.AlleinspielerId=$SpielerId
  AND       t3.SpiellisteId=t1.Id  
  $COND
  AND       t3.SpiellisteId=$SpiellisteId";

  #echo $sql;

  $sqlExec = processSQL( $sql );
  $line = mysql_fetch_array($sqlExec);

  $Platz       = $i;
  if( !$SpielerId )
  {
     $SpielerId   = 0+$line[AlleinspielerId];
  }
  $Gewonnen    = 0+$line[Gewonnen];
  $Verloren    = 0+$line[Verloren];
  $Spielpunkte = 0+$line[Spielpunkte];
  $Extrapunkte = ExtraPoints() * ($line[Gewonnen]-$line[Verloren]);

  $sql = "SELECT
    MIN(t1.NumSpieler) AS NumSpieler,
    SUM(t3.Spielwert < 0) AS Gegner
  FROM "
  .$CONF['tbl_scoresheet']. " AS t1, " .
  $CONF['tbl_game'] .     " AS t3
  WHERE     t1.GroupId=".$SKAT_SESSION[groupid]."
  AND       t3.AlleinspielerId!=$SpielerId
  AND       t3.SpiellisteId=t1.Id  
  AND       t3.SpiellisteId=$SpiellisteId";

  #echo "<br>" . $sql . "<br>";

  debug("ProcessColumnData: " . $sql );

  $sqlExec = processSQL( $sql );
  $line = mysql_fetch_array($sqlExec);

  debug("line[Gegner]: " . $line[Gegner] );
  debug("NumSpieler: " . $line[NumSpieler] );
  debug("Punkte( line[Gegner] ): " . PunkteGegner( $line[NumSpieler] ) );

  $Fremdpunkte = PunkteGegner( $line[NumSpieler] ) *  $line[Gegner];
  $Summe       = $Fremdpunkte + $Extrapunkte + $Spielpunkte;

  return InsertColumnData( $SpiellisteId, $Platz, $SpielerId, $Gewonnen,
  $Verloren, $Spielpunkte, $Extrapunkte, $Fremdpunkte , $Summe  );
}

# Funktion parst die GET Parameter eines Spiels und fügt es in die DB ein.
function ProcessGameData( $SpiellisteId, $i, $init = false )
{
   if( isset( $_POST[ "Wer$i" ] ) || $init )
   {
      $Nr = $i;
      $AlleinspielerId  = 0+GetPost( Name   . GetPost( "Wer$i" ) );
      $Ueberreizt       = 0+GetPost( "Ueberreizt$i" );
      $Eingepasst       = ( 0+GetPost( "Eingepasst$i" ) ) > 0 ? 1 : 0;
      $Grundwert        = 0+GetPost( "Grundwert$i" );
      $Spitzen          = 0+GetPost( "Spitzen$i" );
      $Hand             = 0+GetPost( "Hand$i" );
      $Schneider        = 0+GetPost( "Schneider$i" );
      $SchneiderAngesagt = 0+GetPost( "Schneider_angesagt$i" );
      $Schwarz          = 0+GetPost( "Schwarz$i" );
      $SchwarzAngesagt  = 0+GetPost( "Schwarz_angesagt$i" );
      $Offen            = 0+GetPost( "Offen$i" );
      $Spielwert        = 0+GetPost( "spielwert$i" );

      # Korrektur der Eingabe
      if( ! $Hand )
      {
         $SchneiderAngesagt = 0;
         $SchwarzAngesagt   = 0;
         $Offen             = 0;
      }

      debug("Alleinspieler von Spiel $i ist " . GetPost( "Wer$i" ) );
      debug("Mit Id: $AlleinspielerId" );
      debug("Eingepasst : $Eingepasst" );

      if( 0 == $AlleinspielerId && !$Eingepasst )
      {
         debug( "(default) Spiel ist nicht angelegt!" );
         /** Wenn keiner spielte und das spiel nicht eingepasst wurde,
          ist das Spiel per Definition eingepasst.
          **/
         $Eingepasst   = 2;
      }


      ## Calc game value
      # if( !$Eingepasst && !$Ueberreizt )
      # {
      #   # Null
      # }




      $msg = InsertGameData( $SpiellisteId, $Nr , $AlleinspielerId  ,
      $Ueberreizt       , $Eingepasst       ,
      $Grundwert        , $Spitzen          , $Hand             ,
      $Schneider        , $SchneiderAngesagt , $Schwarz          ,
      $SchwarzAngesagt  , $Offen            , $Spielwert        );
   }
   return $msg;
}

#/ Function receives submitted data and add it to the database
function insertInDB()
{
   global $CONF;
   global $SKAT_SESSION;

   //
   if( $_POST["Delete"] == "delete" )
   {
      $Id = getPost( "SpiellisteId" );
      $msg = DeleteScoreSheetData( $Id );
   }
   else
   {
      $SpiellisteId = ProcessScoreSheetData( getPost( "SpiellisteId" ) );
      debug( "SpiellisteId: $SpiellisteId" );
      $msg = getSuccess("Daten der Spielliste wurden eingetragen.");
   }
   return $msg;
}


#/************************************************************************
#/ session functions
#/***********************************************************************/

function updateSessionVars()
{
   global $CONF;
   global $SKAT_SESSION;
   # Update GroupName and tbd
   $sql = "SELECT name FROM " . $CONF['tbl_grp'] .
  " WHERE id=".$SKAT_SESSION[groupid];

   $result = processSQL( $sql );
   if( $result )
   {
      $row = mysql_fetch_array( $result );
      $SKAT_SESSION[groupname] = $row['name'];
   }
   else
   {
      die( mysql_error() );
   }
}


#/************************************************************************
#/ functions generating whole pages and the navigation
#/***********************************************************************/

function generateHtmlNavi()
{
   global $CONF;
   global $SKAT_SESSION;

#  starttable();
#  startRow();

   echo "<ul id='udm' class='udm'>\n";

   if( ! $SKAT_SESSION[handheld] )
   {
#     startCol();
         echo "<li><a href='.'>" . $SKAT_SESSION[groupname]."</a>";
           echo "<ul class='udm'>\n
                    <li><a href='?Grand=1'>" . HALLOFFAME ."</a></li>";
           echo "   <li><a href='?Faq=1'  >" . HELPFAQ ."</a></li>";
           echo "</ul></li>\n";
#     echo "</ul>";
#     endCol();
#     startCol();
        echo "<li><a href='.'>" .KATEGORIEN ."</a>";
        generateListOfCategoriesHtml();
        echo "</li>";
#     endCol();
   }


   # If user is allowed to write, display Management panel
   if( $SKAT_SESSION[admin] && !$SKAT_SESSION[handheld])
   {
#     startCol();
      echo "<li><a href='.'>SkatManagement</a>";

      echo "<ul class='udm'>
               <li><a href='.'>".SPIELMANAGEMENT ."</a>";
      echo "      <ul>";

      $list = array( 1=>SPIELER, 7=>VEREINE, 2=>KATEGORIEN, 3=>GRANDOUVERT, 4=>SPIELLISTEN );
      while( list($lid, $name) = each( $list ))
      {
         echo "<li><a href='?Mngt=$lid'>".$name."</a></li>";
      }
      echo "      </ul>
               </li>";

      # Admin & Usermanagement
      echo "   <li><a href='.'>".BENUTZERMANAGEMENT . "</a>";
      echo "      <ul>";
      $list =  array( 5=>USERMANAGEMENT, 6=>GRPEIGENSCHAFTEN ) ;
      while( list($lid, $name) = each( $list ) )
      {
         echo "<li><a href='?Mngt=$lid'>".$name."</a></li>";
      }

      echo( "     </ul>" );
      
      echo  "  </li> </ul></li>";
      
#     endCol();
#     startCol();
      
      echo "<li><a href='?handheld=2&amp;Mngt=4'>". SPIELLISTEN ."</a>";
      echo( "</li>" );
#     endCol();
   }
   # Logout
   
#  startCol();
   echo "<li><a href='".BASEHREF."/logout.php'>Logout</a></li>";
   echo "</ul>";
#  endCol();
#  endTable();
}

function generateJSNavi()
{
   global $CONF;
   global $SKAT_SESSION;

   echo "['" . $SKAT_SESSION[groupname] . "', null, null";
   echo ",\n['" . HALLOFFAME ."', '?Grand=1', null]";

   echo ",\n['" . HELPFAQ ."', '?Faq=1', null]";
   echo "]";

   echo ",\n['" .KATEGORIEN . "', null, null";
   generateListOfCategories(true);
   echo "]";


   # If user is allowed to write, display Management panel
   if( $SKAT_SESSION[admin] )
   {
      echo ",\n['SkatManagement', null, null";

      echo ",\n['".SPIELMANAGEMENT."', null, null";

      $list = array( 1=>SPIELER, 7=>VEREINE, 2=>KATEGORIEN, 3=>GRANDOUVERT, 4=>SPIELLISTEN );
      while( list($lid, $name) = each( $list ))
      {
         echo ",\n['".$name."', '?Mngt=$lid', null]";
      }
      echo "]";


      # Admin & Usermanagement
      echo ",\n['".BENUTZERMANAGEMENT."', null, null";

      $list =  array( 5=>USERMANAGEMENT, 6=>GRPEIGENSCHAFTEN ) ;
      while( list($lid, $name) = each( $list ) )
      {
         echo ",\n['".$name."', '?Mngt=$lid', null]";
      }

      echo( "]" );
      echo( "]" );

      echo ",\n['". SPIELLISTEN ."', null, null";
      echo ",\n['". SPIELLISTEN ." Klein', '?handheld=1&Mngt=4', null]";
      echo ",\n['". SPIELLISTEN ." Gro&szlig;', '?handheld=2&Mngt=4', null]";
      echo( "]" );
   }
   # Logout
   echo ",['Logout', '".BASEHREF."/logout.php', null]";
}

function generateNavi()
{
   global $CONF;
   global $SKAT_SESSION;

   starttag( "div", "class", "Title" );
   echo $SKAT_SESSION[groupname];
   endtag( "div" );

   starttag( "div", "class", "NavItem" );
   echo KATEGORIEN;
   endtag( "div" );

   generateListOfCategories() ;

   starttag( "div", "class", "NavItem" );
   echoLink( "?Grand=1", HALLOFFAME );
   endtag( "div" );

   starttag( "div", "class", "NavItem" );
   echoLink( "?Faq=1", HELPFAQ );
   endtag( "div" );

   # If user is allowed to write, display Management panel
   if( $SKAT_SESSION[admin] )
   {
      starttag( "div", "class", "SkatManagement" );

      starttag( "div", "class", "NavItem" );
      echo SPIELMANAGEMENT;
      endtag( "div" );

      $list = array( 1=>SPIELER, 7=>VEREINE, 2=>KATEGORIEN, 3=>GRANDOUVERT, 4=>SPIELLISTEN );
      while( list($lid, $name) = each( $list ))
      {
         starttag( "div", "class", "NavSubItem" );
         echoLink( "?Mngt=$lid", $name );
         endtag( "div" );
      }


      # Admin & Usermanagement
      starttag( "div", "class", "NavItem" );
      echo BENUTZERMANAGEMENT;
      endtag( "div" );

      $list =  array( 5=>USERMANAGEMENT, 6=>GRPEIGENSCHAFTEN ) ;
      while( list($lid, $name) = each( $list ) )
      {
         starttag( "div", "class", "NavSubItem" );
         echoLink( "?Mngt=$lid", $name );
         endtag( "div" );
      }

      endtag( "div" );
   }
   # Logout
   /*
    $elem = CreateElement( $domdoc, "div" );
    SetAttribute( $elem, "class", "NavItem" );
    AppendChild( $elem,
    generateLink( $domdoc, "logout.php", "Logout" ) );
    $h->AddNode( $elem );
    displayPage( $domdoc, $h->GetNode() );
    */
}


function generateFirstPage()
{
   include( "fragen.php" );
}

function generateHallOfFame()
{
   global $CONF;
   global $SKAT_SESSION;
   //  startContainer( "Skatseite" );
   createTitle( "Hall of Fame" );
   starttag( "div", "class", "SubTitle" );
   echo( "Ewigen Besten Liste" );
   endtag("div");

   $sql = "SELECT t1.Id AS CatId, t1.CatName, t3.Type FROM " .
   $CONF['tbl_cat'] . " AS t1, ".
   $CONF['tbl_cattype'] . " AS t3
  WHERE t1.GroupId=".$SKAT_SESSION[groupid]."
  AND t3.Id=t1.TypeId 
  ORDER BY t1.TypeId DESC, t1.Description DESC";
   $sqlExec = processSQL( $sql );

   $hs = array();
   while( $line = mysql_fetch_array( $sqlExec ) )
   {
      if( $line["Type"] != $LastType )
      {
         if( $LastType )
         {
            endtag( "table" );
         }
         $LastType = $line["Type"];
         starttag( "table" , "class", "HallOfFame" );
         starttag( "caption" );
         echo $LastType;
         endtag( "caption" );
         if( $LastType == "Jahreswertung" )
         {
            $header = array( KATEGORIEN, "Gewinner", "Punkte/Liste" , "Erf.-Quote", ANZAHL );
            $index = array( 3, 4, 8,9  );
         }
         else
         {
            $header = array( KATEGORIEN, "Gewinner", "Gesamtpunkte", "gew", "verl", "Erf.-Quote", "Serien" );
            $index = array( 3, 5, 6, 7, 8, 9  );
         }
         starttag("tr");
         foreach( $header as $content )
         {
            starttag( "th" );
            echo $content;
            endtag( "th" );
         }
         endtag( "tr" );
      }
      $CategoryId = $line[ "CatId" ];

      $sql = sqlBestOfCategory( $CategoryId, 1 );
      $cat = mysql_fetch_array( processSQL( $sql ) );
      starttag( "tr" );
      starttag( "td" );
      echoLink( "?CatId=".$cat["CatId"], $cat["CatName"] );
      endtag( "td" );

      foreach( $index as $cnt )
      {
         starttag( "td" );
         echo $cat[$cnt];
         endtag( "td" );
      }
      endtag( "tr" );
   }
   endtag( "table" );

   starttag( "div", "class", "SubTitle" );
   echo( GRANDOUVERT );
   endtag( "div" );
   generateListOfGrandOuverts();
   // endContainer();
}



#/************************************************************************
#/ functions generating whole pages and the navigation
#/***********************************************************************/

function ListOfCategories()
{
   global $CONF;
   global $SKAT_SESSION;
   $sql = "SELECT t1.Id, t1.CatName, t3.* FROM " .
   $CONF['tbl_cat'] . " AS t1, " .
   $CONF['tbl_cattype'] . " AS t3
  WHERE t1.GroupId=".$SKAT_SESSION[groupid]."
  AND t3.Id=t1.TypeId 
  ORDER BY t3.Id DESC, t1.Description DESC";

   return processSQL( $sql );
}

function generateListOfCategories( $JS = false )
{
   if( $sqlExec = ListOfCategories()  )
   {
      while ( $line = mysql_fetch_array($sqlExec) )
      {
         if( $JS )
         {
            echo( ",\n['$line[1]'" );
            echo( ",'?CatId=".$line[0]."'" );
            echo( ",null]" );
         }
         else
         {
            starttag( "div", "class", "NavSubItem" );
            echoLink( "?CatId=".$line[0], $line[1] );
            endtag( "div" );
         }
      }
   }
   return 0;
}

function generateListOfCategoriesHtml()
{
   if( $sqlExec = ListOfCategories()  )
   {
      echo "<ul class='udm'>";
      while ( $line = mysql_fetch_array($sqlExec) )
      {
         starttag( "li" );
         echoLink( "?CatId=".$line[0], $line[1] );
         endtag( "li" );
      }
      echo "</ul>";
   }
   return 0;
}

function generateCategoryPage( $CategoryId )
{
   generateStatisticPage( $CategoryId );
}

function generatePlayerStatisticPage( $CategoryId, $SpielerId )
{
   global $CONF;
   global $SKAT_SESSION;


   # determin players with too less number of games
   $SpInfo  = getPlayerInformation( $SpielerId );
   $CatInfo = getCategoryInformation( $CategoryId );

   //  startContainer( "Skatseite" );
   createTitle( SPIELERPROFIL . " "
   . $SpInfo['Name' ] . " - "
   . createLink( "?CatId=$CategoryId", $CatInfo['CatName'] ) );

   startContainer( "Verteilungen" );

   generateSpielwertAnalyse( $CategoryId, $SpielerId );

   startTable( "SpielStat" );
   startRow();
   startCol();
   generateGewonnenVerlorenVerteilung( $CategoryId, $SpielerId );
   endCol();
   startCol();
   generateScoreSheetHighscore( $CategoryId, $SpielerId,  0 );
   endCol();
   startCol();
   generateScoreSheetHighscore( $CategoryId, $SpielerId,  1 );
   endCol();
   endRow();
   endTable();

   startTable("Highscore");
   createCaption(SPIELWERTVERTEILUNG);
   startRow();
   startCol();
   generateSpielwertVerteilung( $CategoryId, $SpielerId );
   endCol();
   endRow();
   endTable();

   startTable("Highscore");
   createCaption(SPIELLISTEVERTEILUNG);
   startRow();
   startCol();
   generateSpiellistenVerteilung( $CategoryId, $SpielerId );
   endCol();
   endRow();
   endTable();

   if( $CatInfo["Type"] == "Jahreswertung" )
   {
      generatePerformanceGraph( $CategoryId, $SpielerId );
   }


   endContainer();
   //  endContainer();
}

function generateStatisticPage( $CategoryId )
{
   global $CONF;
   global $SKAT_SESSION;


   # determin players with too less number of games
   $CatInfo = getCategoryInformation( $CategoryId );

   //  startContainer( "Skatseite" );
   createTitle( $CatInfo['CatName' ] . " - " . $CatInfo['Description' ] );
   if( 0 < $CatInfo['NumSpiellisten'] )
   {
      generateOverallHighscore( $CategoryId, $CatInfo );


      if( false && getPost( 'Fieberkurve' ) )
      {
         startTable("Highscore");
         createCaption(FIEBERKURVE);
         startRow();
         starttag("td", "id", "Fieberkurve" );
         starttag( "img", "rel", "inc/dist.php?GraphType=Fieber",
      "alt", "Fieberkurve") ;
         endtag("td");
         endRow();
         endTable();
      }

      startContainer( "SpieleContainer" );
      #
      # if yearly stat    -> Quarterly
      # if champtionship  -> no quarterly

      startTable( "SpielStat" );

      if( $CatInfo[ 'Type' ] == "Jahreswertung" )
      {
         startRow();
         for( $i = 1; $i < 5; $i++ )
         {
            startTag( "td", "asyn", BASEHREF."/?". htmlentities( $CONF[QU]."=".$i."&CatId=$CategoryId" ) );
            #generateQuarterlyHighscore( $CategoryId, $i );
            endTag("td");
         }
         endRow();
      }
      startRow();
      startTag( "td", "asyn", BASEHREF."/?". htmlentities( $CONF[EQ]."=".$CONF[EQGrand]."&CatId=$CategoryId" ) );
      #generateErfolgsquotenStatGrand( $CategoryId );
      endTag("td");
      #startCol();
      startTag( "td", "asyn", BASEHREF."/?". htmlentities( $CONF[EQ]."=".$CONF[EQFarbe]."&CatId=$CategoryId" ) );
      #generateErfolgsquotenStatFarbe( $CategoryId );
      endCol();
      #startCol();
      startTag( "td", "asyn", BASEHREF."/?". htmlentities( $CONF[EQ]."=".$CONF[EQNull]."&CatId=$CategoryId" ) );
      #generateErfolgsquotenStatNull( $CategoryId );
      endCol();
      #startCol();
      startTag( "td", "asyn", BASEHREF."/?". htmlentities( $CONF[HS]."=".$CONF[HSHand]."&CatId=$CategoryId" ) );
      #generateHandspielStat( $CategoryId );
      endCol();
      endRow();

      startRow();

      startTag( "td", "asyn", BASEHREF."/?". htmlentities( $CONF[HS]."=".$CONF[HSGrand]."&CatId=$CategoryId" ) );
      #generateGrandHighScore( $CategoryId );
      endCol();

      startTag( "td", "asyn", BASEHREF."/?". htmlentities( $CONF[HS]."=".$CONF[HSFarbe]."&CatId=$CategoryId" ) );
      #generateFarbHighScore( $CategoryId );
      endCol();

      startTag( "td", "asyn", BASEHREF."/?". htmlentities( $CONF[HS]."=".$CONF[HSNull]."&CatId=$CategoryId" ) );
      #generateNullHighScore( $CategoryId);
      endCol();

      #startCol();
      startTag( "td", "asyn", BASEHREF."/?". htmlentities( $CONF[HS]."=".$CONF[HSSpiel]."&CatId=$CategoryId" ) );
      #generateScoreSheetHighscore( $CategoryId, "", 0 );
      endCol();
      endRow();

      startRow();

      #startCol();
      startTag( "td", "asyn", BASEHREF."/?". htmlentities( $CONF[LS]."=".$CONF[LSGrand]."&CatId=$CategoryId" ) );
      #generateGrandLowScore( $CategoryId);
      endCol();

      #startCol();
      startTag( "td", "asyn", BASEHREF."/?". htmlentities( $CONF[LS]."=".$CONF[LSFarbe]."&CatId=$CategoryId" ) );
      #    generateFarbLowScore( $CategoryId  );
      endCol();

      #startCol();
      startTag( "td", "asyn", BASEHREF."/?". htmlentities( $CONF[LS]."=".$CONF[LSNull]."&CatId=$CategoryId" ) );
      #    generateNullLowScore( $CategoryId );
      endCol();
      #startCol();
      startTag( "td", "asyn", BASEHREF."/?". htmlentities( $CONF[LS]."=".$CONF[LSSpiel]."&CatId=$CategoryId" ) );
      #    generateScoreSheetHighscore( $CategoryId, "", 1 );
      endCol();

      endRow();
      endTable();

      startContainer( "SpieleContainer" );
      generateGewonnenVerlorenVerteilung( $CategoryId );

      generatePunktezusammensetzung( $CategoryId  );

      startTable("Highscore");
      createCaption(SPIELWERTVERTEILUNG);
      startRow();
      startCol();
      generateSpielwertVerteilung( $CategoryId );
      endCol();
      endRow();
      endTable();

      startTable("Highscore");
      createCaption(SPIELLISTEVERTEILUNG);
      startRow();
      startCol();
      generateSpiellistenVerteilung( $CategoryId, $SpielerId );
      endCol();
      endRow();
      endTable();


      endContainer();
      endContainer();
   }
   else
   {
      echo NODATAAVAILABLE;
   }
   //  endContainer();
}

function generateListenPage( $CategoryId, $SpielerId = "" )
{
   generateListOfScoreSheets( $CategoryId, $SpielerId );
}

function generateListOfScoreSheets( $CategoryId, $SpielerId = "" )
{
   global $CONF;
   global $SKAT_SESSION;

   $prefix = "SELECT
  GROUP_CONCAT(t4.Name, \"(\",t2.Summe,\")\" ORDER BY t2.Platznummer SEPARATOR \", \") AS Spieler, 
  t1.Id AS SpiellisteId, t1.Datum, t4.Name, t2.Summe, 
  t0.Description AS Beschreibung,
  t3.Type, t1.Tisch AS Tisch, t1.Serie AS Serie,
  MONTH(t1.Datum) AS Monat,
  WEEK(t1.Datum,7)  AS Woche,
  YEAR(t1.Datum)  AS Jahr
  FROM " . 
   $CONF['tbl_cat'].  " AS t0, " .
   $CONF['tbl_scoresheet'].  " AS t1, " .
   $CONF['tbl_column'] .     " AS t2, " .
   $CONF['tbl_cattype'] . " AS t3, " .
   $CONF['tbl_player'] .    " AS t4
  WHERE   t1.CatId=$CategoryId  
  AND t0.GroupId=".$SKAT_SESSION[groupid]." 
  AND t2.SpiellisteId=t1.Id  
  AND t0.Id=t1.CatId  
  AND t4.Id=t2.SpielerId 
  AND t0.TypeId=t3.Id ";

   $subquery  = "( SELECT t1.Id FROM " .
   $CONF['tbl_scoresheet'].  " AS t1, " .
   $CONF['tbl_column'] .     " AS t2, " .
   $CONF['tbl_player'] .    " AS t4
  WHERE   t1.CatId=$CategoryId  
  AND t2.SpiellisteId=t1.Id  
  AND t4.Id=t2.SpielerId AND t2.SpielerId=$SpielerId) ";

   $condition = " AND t1.Id IN $subquery ";
   $postfix = " GROUP BY t1.Id ORDER BY t1.Datum DESC, t1.Serie ASC, t1.Tisch ASC";

   if( $SpielerId )
   {
      $sql = $prefix . $condition . $postfix;
   }
   else
   {
      $sql = $prefix . $postfix;
   }

   //  startContainer( "Skatseite" );

   $sqlExec = processSQL( $sql );
   if( $sqlExec )
   {
      if( mysql_num_rows( $sqlExec ) )
      {
         $line   = mysql_fetch_array( $sqlExec );

         $lastId = -1;
         $title = "Spiellisten: " . createLink( "?CatId=$CategoryId", $line["Beschreibung"] );
         if( $SpielerId )
         {
            $row = getPlayerInformation( $SpielerId );
            $title .= " mit Beteiligung von " .
            createLink( "?CatId=$CategoryId&amp;SpId=$SpielerId", $row["Name"] );
         }
         createTitle( $title );
         startTable( "ListSpiellisten" );

         if( $line['Type'] == "Jahreswertung" )
         {
            $Lfd = 1;
            $LastYear = -1;
            $LastWeek = -1;
            startRow();
            createHCol( "Jahr" );
            createHCol( "Woche" );
            createHCol( "Datum" );
            createHCol( "Spielliste" );
            endRow();
            do {
               startRow();
               if( $LastYear != $line["Jahr"] )
               {
                  createCol( $line["Jahr"] );
                  $LastYear = $line["Jahr"];
               }
               else
               {
                  createCol( "" );
               }
               if( $LastWeek != $line["Woche"] )
               {
                  createCol( $line["Woche"] );
                  $LastWeek = $line["Woche"];
               }
               else
               {
                  createCol( "" );
               }
               createCol( $line["Datum"] );

               if( $SKAT_SESSION[admin] )
               {
                  createCol(
                  createLink( "?Mngt=4&amp;SpiellisteId=".$line["SpiellisteId"], $line["Spieler"] )  );
                  createCol(
                  createLink( "?Mngt=4&amp;SpiellisteId=".$line["SpiellisteId"], "edit" )  );
               }
               else
               {
                  createCol(
                "<a href=\"javascript:showHtml('', '?SpiellisteId=".$line["SpiellisteId"]."')\">".$line["Spieler"]."</a> " 
                );
               }
               endRow();
            } while( $line = mysql_fetch_array( $sqlExec ) );
         }
         else
         {
            $lastSerie = -1;
            do {
               startRow();
               if( $lastSerie != $line["Serie"] )
               {
                  $lastSerie = $line["Serie"];
                  createCol( "Serie: " . $lastSerie );
               }
               else
               {
                  createCol( "" );
               }
               createCol( "Tisch: ". $line["Tisch"] );
               createCol(
               createLink( "?SpiellisteId=".$line["SpiellisteId"], $line["Spieler"] )  );
               if( $SKAT_SESSION[admin] )
               {
                  createCol(
                  createLink( "?Mngt=4&amp;SpiellisteId=".$line["SpiellisteId"], "edit" )  );
               }
               endRow();
            } while( $line = mysql_fetch_array( $sqlExec ) );
         }
         endTable();
      }
   }
   else
   {
      echo errormsg( mysql_errno(), mysql_error(), $sql );
   }
   //  endContainer();
}

function generatePerformanceGraph( $CategoryId, $SpielerId )
{
   startTable("Highscore");
   createCaption("Spielerperformance");
   startRow();
   startCol();
   starttag( "img", "rel", "inc/graphen.php?GraphType=Perf&CatId=$CategoryId&SpielerId[]=$SpielerId", "alt", "Spielperformance" );
   endCol();
   endRow();
   endTable();
}

#/************************************************************************
#/ highscore functions
#/***********************************************************************/

# generates a highscore according to the sql statement, with a sequence number
# in the first column
#
function generateHighscore(  $sql, $title, $header, $class,
$NotValidNames = "" , $AdditionalInfo = "", $LastScore = "",
$Comparison = false )
{
   global $CONF;
   global $SKAT_SESSION;
   $table = 0;
   if( $sqlExec = processSQL( $sql ) )
   {
      if( $NumPlayer = mysql_num_rows( $sqlExec ) )
      {
         $rows = 1 + mysql_num_rows( $sqlExec );
         $cols = count( $header ) + 1;

         if( $Comparison )
         {
            starttag( "form", "action", "javascript:get(this,'".BASEHREF."/inc/graphen.php?GraphType=Fieber' );", "name", "myform" );
            #starttag( "form", "name", "myform" );
            #starttag( "form", "action", "javascript:zoom('".FIEBERKURVE."', 'inc/dist.php?GraphType=Fieber')", "method", "post" );
         }

         startTable( $class );
         createCaption( $title );

         $r = 0;
         $c = 0;

         startRow();
         if( $Comparison )
         {
            starttag( "th", "onclick", "Checkall( 'SpielerId' )" );
            echo "click";
            endtag( "th" );
         }

         $flag = 0;
         while( list(, $head) = each( $header )  )
         {
            if( $flag == 0 )
            {
               if( $LastScore )
               {
                  createHCol( $head, "", 2 );
               }
               else
               {
                  createHCol( $head, "" );
               }
               $flag = 1;
            }
            else
            {
               createHCol( $head );
            }
         }
         endRow();
         $r   = 1;
         $Lfd = 1;
         $val = 10941491;
         # Body rows
         while ( $line = mysql_fetch_array($sqlExec) )
         {
            # last highscore value
            $oldval = $val;
            $val    = $line[3];
            # Lfd number
            $c = 0;
            $lp = 0;
            # Get CategoryId
            $CatId    = $line[$lp++];
            # Get PlayerId
            $PlayerId = explode( ", ", $line[$lp++] );

            startRow();
            if( $Comparison )
            {
               starttag( "td");

               $checked = "checked";
               starttag( "input", "type", "checkbox", "value", $line['SpielerId'],
            "name", "SpielerId", $checked, $checked );

               endtag( "td");
            }
            if( $val != $oldval )
            {
               createCol( $Lfd );
            }
            else
            {
               createCol( "" );
            }

            $changeclass = "ScoreSame";
            if( $LastScore )
            {
               if( isset( $LastScore[ $PlayerId[0] ] ) )
               {
                  # Veraenderung
                  if( $Lfd < $LastScore[ $PlayerId[0] ] )
                  {
                     $content     = "&uArr;";
                     $changeclass = "ScoreUp";
                  }
                  elseif( $Lfd > $LastScore[ $PlayerId[0] ] )
                  {
                     $content     = "&dArr;";
                     $changeclass = "ScoreDown";
                  }
                  else
                  {
                     $content     = "&hArr;";
                     $changeclass = "ScoreSame";
                  }
               }
               else
               {
                  $content     = "&hArr;";
                  $changeclass = "ScoreSame";
               }
               createCol( $content, $changeclass );
            }

            $flag = 0;
            while( ( isset( $line[$lp] ) ) || ( $lp < count($header) ) )
            {
               $cell = explode( ", ", $line[$lp] );
               if( !$flag )
               {
                  # Zerlegt die zweite Spalte (bei einer Aggregation in ihre
                  # Bestandteile und verlinkt die Einzelbausteine entweder zu
                  # Spielern oder zu ScoreSheets

                  $content = "";
                  while( ( list(, $pcell ) = each( $cell ) )
                  && ( list(, $pId ) = each( $PlayerId ) ) )
                  {
                     $flag = 1;
                     if( mysql_field_name( $sqlExec, ($lp-1)  ) == "AggrSpiellisteId" )
                     {
                        if( !$SKAT_SESSION[admin] )
                        {

                           //$content .= "<a href=\"?SpiellisteId=$pId\" class=\"lbOn\">$pcell</a>";
                           $content .= "<a href=\"javascript:showHtml('', '?SpiellisteId=$pId')\">$pcell</a> ";
                        }
                        else
                        {
                           $content .= createLink( "?SpiellisteId=$pId", $pcell . " " );
                        }
                     }
                     else
                     {
                        $content .= createLink( "?CatId=$CatId&amp;SpId=$pId", $pcell. " ");
                     }
                  }
                  createCol( $content );
               }
               else
               {
                  $content = "";
                  foreach( $cell as $pcell )
                  {
                     if( mysql_field_name( $sqlExec, $lp  ) == "SpiellisteId" )
                     {
                        $content .= createLink( "?SpiellisteId=$pcell", "Id: " .$pcell );
                     }
                     else
                     {
                        $content .= $pcell ;
                     }
                  }
                  createCol( $content );
               }
               $lp++;
            }
            $Lfd++;
            endRow();
         }
         if( $NotValidNames )
         {
            startRow();
            createCol( "Ausser Konkurrenz: " . $NotValidNames, "TableFootnote", $cols + 1 );
            endRow();
         }
         if( $AdditionalInfo )
         {
            startRow();
            $content = "Gesamtzahl ";
            $content .= createLink( "?Listen=". $AdditionalInfo[0], "Spiellisten" );
            $content .= ": "
            . $AdditionalInfo['Gesamtzahl'].", Teilnahmequalifikation: "
            . 100*$AdditionalInfo['Quali'] . "%";

            createCol( $content, "TableFootnote", $cols + 1 );
            endRow();
            startRow();
            createCol( "Last update: " .
            date( "D M j G:i:s T Y", $AdditionalInfo['LastUpdate'] ), "TableFootnote", $cols + 1 );
            endRow();
         }
         if( $Comparison )
         {
            startRow();
            starttag( "td", "class", "TableFootnote", "colspan", $cols+1 );
            starttag( "input", "type", "radio", "name", "FieberType", "value", "1" );

            echo " Platzierung ";
            starttag( "input", "type", "radio", "name", "FieberType",
          "checked", "checked", "value", "2" );
            echo " Punkte, ";
            echo "ueber die letzten ";
            starttag( "select", "name", "LastNumListen" );
            foreach( array( 0.1, 0.25, 0.50, 0.75, 1.0 ) as $per )
            {
               $val = max(1, (1-$per) * $AdditionalInfo['NumSpieltage']);
               starttag( "option", "value",  $val );
               echo ( 100 * $per )."%";
               endtag( "option" );
            }
            endtag( "select" );
            echo "Spieltage ";
            #starttag( "input", "type", "submit", "value", "Fieberkurve", "onclick", "javascript:get(this.parentNode);" );
            starttag( "input", "type", "submit", "value", "Fieberkurve" );

            starttag( "input", "type", "hidden", "name", "NumValidPlayer", "value", $NumPlayer );
            starttag( "input", "type", "hidden", "name", "CatId", "value", $CatId);
            starttag( "input", "type", "hidden", "name", "Fieberkurve", "value", 1);
            endtag( "td");
            endRow();
         }
         endTable();
         if( $Comparison )
         {
            endtag( "form" );
         }
      }
   }
   else
   {
      echo errormsg( mysql_errno(), mysql_error(), $sql );
   }
}

function generateOverallHighscore( $CategoryId, $CatInfo )
{
   global $CONF;
   global $SKAT_SESSION;

   if( $CatInfo['Type'] == 'Jahreswertung' )
   {
      #    $praefix = sqlBestOfCategory( $CategoryId );
      $praefix = "SELECT t1.CatId, t2.SpielerId, t4.Name,
    ROUND(AVG(t2.Summe),2) AS PPL,  
    SUM(t2.Summe)  AS Gesamtpunkte, 
    AVG(t2.Gewonnen),
    AVG(t2.Verloren),
    ROUND(100 * SUM(t2.Gewonnen) / (SUM(t2.Gewonnen)+SUM(t2.Verloren)),2) 
    as 'Spieler u. gewonnen',  
    COUNT(*)  AS Anzahl  FROM " . 
      $CONF['tbl_cat'].  " AS t0, " .
      $CONF['tbl_scoresheet'].  " AS t1, " .
      $CONF['tbl_column'] .     " AS t2, " .
      $CONF['tbl_player'] .    " AS t4
    WHERE   t1.CatId=$CategoryId  
    AND t2.SpiellisteId=t1.Id  
    AND t4.Id=t2.SpielerId 
    AND t2.SpielerId IN " .  sqlQualified( $CategoryId) .  "
    AND t0.GroupId=".$SKAT_SESSION[groupid]." 
    AND t0.Id=t1.CatId ";

      #AND t4.Id=t2.SpielerId $NotValidSql
      $postfix = " GROUP BY  t2.SpielerId  ORDER BY PPL DESC ";
      $header = array( PLATZ, NAME  , PUNKTEPROLISTE, GESAMTPUNKTE,
      GEWONNEN, VERLOREN, ERFOLGSQUOTE, ANZAHL);
   }
   else
   {
      $praefix = "SELECT t1.CatId, t2.SpielerId, t4.Name, SUM(t2.Summe)  AS Gesamtpunkte,
    SUM(t2.Gewonnen) AS Gewonnen, SUM(t2.Verloren) AS Verloren, 
    ROUND(100 * SUM(t2.Gewonnen) / (SUM(t2.Gewonnen)+SUM(t2.Verloren)),2) 
    as 'Spieler u. gewonnen',  
    COUNT(*)  AS Anzahl  FROM " . 
      $CONF['tbl_cat'].  " AS t0, " .
      $CONF['tbl_scoresheet'].  " AS t1, " .
      $CONF['tbl_column'] .     " AS t2, " .
      $CONF['tbl_player'] .    " AS t4
    WHERE   t1.CatId=$CategoryId  
    AND t2.SpiellisteId=t1.Id  
    AND t4.Id=t2.SpielerId 
    AND t2.SpielerId IN " .  sqlQualified( $CategoryId) .  "
    AND t0.GroupId=".$SKAT_SESSION[groupid]." 
    AND t0.Id=t1.CatId ";

      $postfix = " GROUP BY  t4.Id  ORDER BY Gesamtpunkte DESC ";
      $header = array( PLATZ, NAME  , GESAMTPUNKTE, SGEWONNEN, SVERLOREN,
      ERFOLGSQUOTE, ANZAHL);
   }

   # subquery returns week of last inserted spielliste
   $week = "(SELECT WEEK(t1.Datum,7)  FROM " .
   $CONF['tbl_scoresheet'].  " AS t1 , ".
   $CONF['tbl_cat'].  " AS t0
  WHERE  t1.CatId=$CategoryId AND t1.Id=t0.LastSpielliste  
  AND t0.Id=t1.CatId )";

   # only spiellisten of weeks before latest week
   $condition = " AND WEEK(t1.Datum,7) < $week ";

   $otherlist = generateLastScore($praefix . $condition . $postfix, 1 );

   $title = "Tabelle";

   $Comparison = false;
   if( $CatInfo['Type'] == 'Jahreswertung' )
   {
      $Comparison = true;
   }
   generateHighscore(  $praefix . $postfix, $title,
   $header, "OverallHighscore", listDisqualified( $CategoryId ), $CatInfo, $otherlist, $Comparison );
}

function generateQuarterlyHighscore( $CategoryId, $quarter )
{
   global $CONF;
   global $SKAT_SESSION;

   # subquery
   $subquery = "(SELECT t1.Id  FROM " .
   $CONF['tbl_scoresheet'].  " AS t1
  WHERE  t1.CatId=$CategoryId AND QUARTER(t1.Datum)=$quarter ) ";

   # subquery returns week of last inserted spielliste
   $week = "(SELECT WEEK(t1.Datum,7)  FROM " .
   $CONF['tbl_scoresheet'].  " AS t1 , ".
   $CONF['tbl_cat'].  " AS t0
  WHERE  t1.CatId=$CategoryId AND t1.Id=t0.LastSpielliste  
  AND t0.Id=t1.CatId )";

   $praefix = "SELECT t1.CatId, t2.SpielerId, t4.Name, ROUND(AVG(t2.Summe),2) AS PPL,
  COUNT(*)  AS Anzahl  FROM " . 
   $CONF['tbl_cat'].  " AS t0, " .
   $CONF['tbl_scoresheet'].  " AS t1, " .
   $CONF['tbl_column'] .     " AS t2, " .
   $CONF['tbl_player'] .    " AS t4
  WHERE QUARTER(t1.Datum)=$quarter 
  AND t1.CatId=$CategoryId  
  AND t2.SpiellisteId=t1.Id  
    AND t2.SpielerId IN " .  sqlQualified( $CategoryId) .  "
  AND t0.Id=t1.CatId 
  AND t0.GroupId=".$SKAT_SESSION[groupid]." 
  AND t4.Id=t2.SpielerId ";

   $postfix = " GROUP BY  t4.Id  ORDER BY PPL DESC ";

   $condition = " AND WEEK(t1.Datum,7) < $week
  AND t0.LastSpielliste IN $subquery ";

   $header = array( PLATZ, NAME  , PUNKTEPROLISTE, ANZAHL);

   $otherlist = generateLastScore($praefix . $condition . $postfix, 1 );

   generateHighscore(  $praefix . $postfix, "$quarter. Quartal", $header,
  "Highscore", "", "", $otherlist );
}
#
# Spielwertverteilung
function generateSpielwertAnalyse( $CategoryId, $PlayerId = 0 )
{
   global $CONF;
   global $SKAT_SESSION;

   $PlayerCondition = "";
   if( $PlayerId  )
   {
      $PlayerCondition = "AND t3.AlleinspielerId=$PlayerId ";
   }
   #
   # tbd
   $sql = "SELECT t3.Grundwert AS Grundwert,
  100*SUM(t3.Spitzen>0)/COUNT(*)     AS MitSpitzen, 
  AVG(IF(t3.Spitzen>0,t3.Spitzen,NULL)) AS AvgMitSpitzen,
  100*SUM(t3.Spitzen<0)/COUNT(*)     AS OhneSpitzen,
  AVG(IF(t3.Spitzen<0,-t3.Spitzen,NULL)) AS AvgOhneSpitzen,
  100*SUM(t3.Hand)/COUNT(*)      AS Hand, 
  100*SUM(t3.Schneider)/COUNT(*)     AS Schneider, 
  100*SUM(t3.Schneider_angesagt)/COUNT(*)    AS SchneiderAngesagt, 
  100*SUM(t3.Schwarz)/COUNT(*)     AS Schwarz, 
  100*SUM(t3.Schwarz_angesagt)/COUNT(*)    AS SchwarzAngesagt,
  100*SUM(t3.Offen)/COUNT(*)     AS Offen, 
  100*SUM(t3.Spielwert>0)/COUNT(*)  AS Gewonnen , 

  100* SUM( t3.Spielwert > 0  AND (
    MOD(t3.Number, t1.NumSpieler ) = 
    MOD(t1.NumSpieler + t2.Platznummer - 1 , t1.NumSpieler )
  ) ) /
  SUM(
    MOD(t3.Number, t1.NumSpieler ) = 
    MOD(t1.NumSpieler + t2.Platznummer - 1 , t1.NumSpieler )
  ) AS VHGewonnen , 

  SUM(
    MOD(t3.Number, t1.NumSpieler ) = 
    MOD(t1.NumSpieler + t2.Platznummer - 1 , t1.NumSpieler )
  ) AS AnzVHGewonnen , 

  100 * SUM( t3.Spielwert > 0 AND 
  MOD(t3.Number, t1.NumSpieler ) = 
  MOD(t1.NumSpieler + t2.Platznummer - 2 , t1.NumSpieler )
) /
SUM(
  MOD(t3.Number, t1.NumSpieler ) = 
  MOD(t1.NumSpieler + t2.Platznummer - 2 , t1.NumSpieler )
) AS MHGewonnen , 

SUM(
  MOD(t3.Number, t1.NumSpieler ) = 
  MOD(t1.NumSpieler + t2.Platznummer - 2 , t1.NumSpieler )
) AS AnzMHGewonnen , 

100*SUM( t3.Spielwert > 0 AND 
MOD(t3.Number, t1.NumSpieler ) = 
MOD(t1.NumSpieler + t2.Platznummer - 3 , t1.NumSpieler )
       )  /
       SUM(
         MOD(t3.Number, t1.NumSpieler ) = 
         MOD(t1.NumSpieler + t2.Platznummer - 3 , t1.NumSpieler )
       ) AS HHGewonnen , 

       SUM(
         MOD(t3.Number, t1.NumSpieler ) = 
         MOD(t1.NumSpieler + t2.Platznummer - 3 , t1.NumSpieler )
       ) AS AnzHHGewonnen , 

       COUNT(*) AS Anzahl FROM ".
   $CONF['tbl_scoresheet']. " AS t1, " .
   $CONF['tbl_column'] .     " AS t2, " .
   $CONF['tbl_game'] .     " AS t3, " .
   $CONF['tbl_gamecat'] .  " AS t4
       WHERE     t1.CatId=$CategoryId  
       AND       t1.GroupId=".$SKAT_SESSION[groupid]."
       AND       t3.SpiellisteId=t1.Id  
       AND       t2.SpielerId=t3.AlleinspielerId
       AND       t2.SpiellisteId=t1.Id
       $PlayerCondition
       AND ( t3.Eingepasst IS NULL OR t3.Eingepasst=0 ) 
       AND t4.Grundwert=t3.Grundwert 
       GROUP BY  t3.Grundwert  
       ORDER BY  t4.Type, t4.Grundwert ASC";

       $sqlExec = processSQL( $sql );
       $return = 0;
       if( $sqlExec )
       {
          startTable( "Highscore" );
          createCaption( SPIELWERTANALYSE . " [%]" );
          if( $rows = mysql_num_rows( $sqlExec ) )
          {
             $cols = mysql_num_fields( $sqlExec );

             $dist = array();
             $sum  = 0;
             while ( $line = mysql_fetch_array($sqlExec) )
             {
                array_push( $dist, $line );
                $sum += $line[ "Anzahl" ];
             }
             # Bottom Row
             # Annotation Row
             #

             #
             startRow();
             $heading = array( GRUNDWERT, MITSPITZEN, OHNESPITZEN, HAND,
             SCHNEIDER, SCHNEIDERANGESAGT, SCHWARZ, SCHWARZANGESAGT,
             OFFEN, ERFOLGSQUOTE, VHGEWONNEN, MHGEWONNEN, HHGEWONNEN, ANZAHL );
             $c = 0;
             while( $h = array_shift( $heading ) )
             {
                createHCol( $h );
             }
             endRow();

             $r = 1;
             while( $cnt = array_shift( $dist ) )
             {
                startRow();
                if( $cnt[ 0 ] == 9 )
                {
                   startCol();
                   echo "<span class='Karo'>&diams;</span>";
                   endCol();
                }
                elseif( $cnt[ 0 ] == 10 )
                {
                   startCol();
                   echo "<span class='Herz'>&hearts;</span>";
                   endCol();
                }
                elseif( $cnt[ 0 ] == 11 )
                {
                   startCol();
                   echo "<span class='Pik'>&spades;</span>";
                   endCol();
                }
                elseif( $cnt[ 0 ] == 12 )
                {
                   startCol();
                   echo "<span class='Pik'>&clubs;</span>";
                   endCol();
                }
                else
                {
                   createCol(  $cnt[ 0 ] );
                }

                if( $cnt[ "Grundwert" ] > 12 && $cnt[ "Grundwert" ] != 24 )
                {
                   createCol(  " ", "", 8 );
                }
                else
                {
                   foreach( array( "MitSpitzen", "OhneSpitzen" ) as $pcol )
                   {
                      starttag("td");
                      echo(  sprintf( "%.1f", $cnt[ $pcol ] ) );
                      echo( " (".sprintf( "%.1f", $cnt[ "Avg".$pcol ] ) .")" );
                      endtag("td");
                   }
                   foreach( array( "Hand", "Schneider", "SchneiderAngesagt",
               "Schwarz", "SchwarzAngesagt", "Offen" ) as $pcol )
                   {
                      starttag("td");
                      echo(  sprintf( "%.1f", $cnt[ $pcol ] ) );
                      endtag("td");
                   }
                }
                starttag("td");
                echo(  sprintf( "%.1f", $cnt[ "Gewonnen" ] ) );
                endtag("td");
                foreach( array( "VHGewonnen", "MHGewonnen", "HHGewonnen" )               as $pcol )
                {
                   starttag("td");
                   echo(  sprintf( "%.1f", $cnt[ $pcol ] ) );
                   echo( " (" . $cnt[ "Anz".$pcol ] . ")");
                   endtag("td");
                }

                createCol( $cnt[ "Anzahl" ] );

                $r++;
                endRow();
             }
          }
          startRow();
          createCol( createLink( "?Listen=$CategoryId&amp;SpId=$PlayerId", "Spiellisten" ) . " " . DERSPIELWERTANALYSE, "TableFootnote", $cols );
          endRow();
          endTable();
       }
       else
       {
          echo errormsg( mysql_errno() )."<br>";
          echo mysql_error()."<br>";
          echo $sql;
       }
}
#
# Statistik ueber Erfolgsquoten
function generateErfolgsquotenStat( $CategoryId, $GW, $Title  )
{
   global $CONF;
   global $SKAT_SESSION;

   $Grundwert = "";
   foreach( $GW as $item )
   {
      $Grundwert .= " t3.Grundwert=$item OR ";
   }
   $Grundwert = preg_replace("/OR $/", "", $Grundwert);

   $sql = "SELECT t1.CatId, t3.AlleinspielerId,
  t4.Name, 
  ROUND(100 * ( (0+SUM(t3.Spielwert>0)) / (SUM(t3.Spielwert>0)+SUM(t3.Spielwert<0)) ),2) AS Erfolgsquote
  FROM "
  .$CONF['tbl_scoresheet']. " AS t1, " .
  $CONF['tbl_game'] .     " AS t3, " .
  $CONF['tbl_player'] .     " AS t4
  WHERE     t1.CatId=$CategoryId  
  AND       t1.GroupId=".$SKAT_SESSION[groupid]."
  AND       t3.SpiellisteId=t1.Id  
  AND ( t3.Eingepasst IS NULL OR t3.Eingepasst=0 ) 
  AND ($Grundwert)
    AND t4.Id IN " .  sqlQualified( $CategoryId) .  "
  AND t4.Id=t3.AlleinspielerId 
  GROUP BY  t3.AlleinspielerId  
  ORDER BY  Erfolgsquote DESC";

  $Header = array(PLATZ, NAME  , ERFOLGSQUOTE );

  generateHighscore($sql, $Title, $Header, "Highscore" );
}

function generateHandspielStat( $CategoryId, $Title = HIGHSCOREHAND )
{
   global $CONF;
   global $SKAT_SESSION;

   $sql = "SELECT t1.CatId, t3.AlleinspielerId,
  t4.Name, 
  ROUND(100 * ( SUM(t3.Spielwert>0 AND ( t3.Grundwert=35 OR t3.Grundwert=59 OR t3.Hand=1 )) / (SUM(t3.Spielwert>0)+SUM(t3.Spielwert<0)) ),2) AS Handspielquote
  FROM "
  .$CONF['tbl_scoresheet']. " AS t1, " .
  $CONF['tbl_game'] .     " AS t3, " .
  $CONF['tbl_player'] .     " AS t4
  WHERE     t1.CatId=$CategoryId  
  AND       t1.GroupId=".$SKAT_SESSION[groupid]."
  AND       t3.SpiellisteId=t1.Id  
  AND ( t3.Eingepasst IS NULL OR t3.Eingepasst=0 ) 
    AND t4.Id IN " .  sqlQualified( $CategoryId) .  "
  AND t4.Id=t3.AlleinspielerId 
  GROUP BY  t3.AlleinspielerId  
  HAVING Handspielquote>0
  ORDER BY  Handspielquote DESC";

  $Header = array(PLATZ, NAME, HANDGEWONNEN );

  generateHighscore($sql, $Title, $Header, "Highscore" );
}

function generateCatHighscore()
{
   global $CONF;
   global $SKAT_SESSION;


   $Header = array(PLATZ, NAME  , ANZAHL );

   generateHighscore($sql, $Title, $Header, "Highscore" );
}

function generateLastScore( $sql, $idx )
{
   $result = processSQL( $sql );
   $return = array();
   $pos    = 1;
   if( $result )
   {
      while( $line = mysql_fetch_array( $result ) )
      {
         $return[ $line[ $idx ] ] = $pos++;
      }
   }
   return $return;
}

function generateXScore(  $CategoryId, $Crit, $Type, $Heading, $Title )
{
   global $CONF;
   global $SKAT_SESSION;
   list($sql1, $sql2) = getSQL( $CategoryId, $Crit, $Type );
   $header = array( PLATZ, NAME  , $Heading );
   $otherlist = generateLastScore($sql2, 1 );
   generateHighscore(  $sql1, $Title, $header, "Highscore", "","", $otherlist );
}

function generateNullHighScore( $CategoryId )
{
   generateXScore( $CategoryId,"High", "Null", "% " . SGEWONNEN . " " . NULLSPIELE,
   NULLHS);
}

function generateNullLowScore( $CategoryId )
{
   generateXScore( $CategoryId,"Low", "Null", "% ". SVERLOREN. " " . NULLSPIELE,
   NULLLS);
}

function generateGrandHighScore( $CategoryId)
{
   generateXScore( $CategoryId,"High", "Grand", "% ".SGEWONNEN . " " . GRANDSPIELE,
   GRANDHS);
}

function generateGrandLowScore( $CategoryId)
{
   generateXScore( $CategoryId,"Low", "Grand", "% ". SVERLOREN. " " . GRANDSPIELE,
   GRANDLS);
}

function generateFarbHighScore( $CategoryId)
{
   generateXScore( $CategoryId,"High", "Farbe", "% ". SGEWONNEN. " " . FARBSPIELE,
   FARBHS);
}

function generateFarbLowScore( $CategoryId)
{
   generateXScore( $CategoryId,"Low", "Farbe", "% " . SVERLOREN . " " . FARBSPIELE,
   FARBLS);
}

function generateScoreSheetHighscore( $CategoryId, $SpielerId="", $Asc = 1)
{
   global $CONF;
   global $SKAT_SESSION;

   //GROUP_CONCAT(t2.SpielerId SEPARATOR \", \"),
   $praefix = "SELECT t1.CatId,
  GROUP_CONCAT(t1.Id SEPARATOR \", \") AS AggrSpiellisteId, 
  GROUP_CONCAT(t4.Name SEPARATOR \", \"), t2.Summe FROM ".
   $CONF['tbl_cat'].  " AS t0, " .
   $CONF['tbl_scoresheet'].  " AS t1, " .
   $CONF['tbl_column'] .     " AS t2, " .
   $CONF['tbl_player'] .    " AS t4
  WHERE 
  t1.CatId=$CategoryId  
  AND t2.SpiellisteId=t1.Id  
  AND t0.Id=t1.CatId 
  AND t0.GroupId=".$SKAT_SESSION[groupid]." 
  AND t2.SpielerId IN " .  sqlQualified( $CategoryId) .  "
  AND t4.Id=t2.SpielerId ";
   if( $SpielerId )
   {
      $praefix .= " AND t2.SpielerId=$SpielerId ";
   }

   $postfix  = " GROUP BY t2.Summe ORDER BY t2.Summe ";
   if( $Asc )
   {
      $postfix .= " ASC ";
      $Title    = SPIELLISTEN . " Lowscore";
   }
   else
   {
      $postfix .= " DESC ";
      $Title    = SPIELLISTEN . " Highscore";
   }
   $CatInfo = getCategoryInformation($CategoryId);
   # Could be changed by configuration
   $postfix .= " LIMIT 10";

   $header = array( PLATZ, NAME  , PUNKTE );
   generateHighscore( $praefix . $postfix, $Title, $header,
  "Highscore", "", "", "" );
}

/**
 * Matrix der gewonnen und verlorenen Spiele, tabelle
 *
 * @param unknown_type $CategoryId
 * @param unknown_type $SpielerId
 */
function generateGewonnenVerlorenVerteilung( $CategoryId, $SpielerId = 0 )
{
   #
   $return  = 0;
   global $CONF;
   global $SKAT_SESSION;
   if( $SpielerId != 0 )
   {
      $PlayerCondition = "AND t2.SpielerId=$SpielerId";
   }
   $sql = "SELECT  t2.Gewonnen, t2.Verloren FROM "
   . $CONF['tbl_cat'] . " AS t0, "
   . $CONF['tbl_scoresheet'] . " AS t1, "
   . $CONF['tbl_column']     . " AS t2
  WHERE t1.CatId=$CategoryId  
  AND   t0.Id=$CategoryId 
  AND   t1.GroupId=".$SKAT_SESSION[groupid]."
  AND t2.SpiellisteId=t1.Id "
  . $PlayerCondition;

  $sqlExec = processSQL( $sql );

  if( $sqlExec )
  {
     $maxV = 0;
     $maxG = 0;
     if( mysql_num_rows( $sqlExec ) )
     {
        while( $line = mysql_fetch_array( $sqlExec ) )
        {
           if( $line[0] > $maxG )
           {
              $maxG = $line[0];
           }
           if( $line[1] > $maxV )
           {
              $maxV = $line[1];
           }
           $Pkt[ $line[0] ][ $line[ 1 ] ] += 1;
        }

        $basiscolor = "3333";

        $table = new CTable( 3+$maxV, 3+$maxG, "Gewonnenverloren", 0 );
        $table->SetTitle( VERTEILUNGGEWONNENVERLOREN);
        for( $r = 0; $r < $maxV + 1; $r++ )
        {
           $table->SetContent( $r, 1,  $maxV-$r );
           $table->SetAttribute( $r, 1, "class", "axis" );
           for( $c = 2; $c < $maxG + 3; $c++ )
           {
              $value = $Pkt[ $c-2  ][ $maxV - $r ];
              $table->SetContent( $r, $c, $value );
              if( $value )
              {
                 $farbe = 255 + 30 * log( $value/100 );
                 $farbe = $farbe < 0 ?  0 : $farbe;
                 $farbe = $farbe > 255 ?  255 : $farbe;
                 $Color = "#" . sprintf( "%02x", $farbe) . $basiscolor;
                 $table->SetAttribute( $r, $c, "style", "background-color:$Color" );
              }
           }
        }
        for( $c = 2; $c < $maxG + 3; $c++ )
        {
           $table->SetContent( $maxV+1, $c, $c-2 );
           $table->SetAttribute( $maxV+1, $c, "class", "axis" );
        }

        $table->SetColspan( -1, 2, $maxG + 1);
        $table->SetContent( -1, 2, "# gewonnen pro Liste" );
        $table->SetAttribute( -1, 2, "class", "xannotation" );

        $table->SetRowspan( 0, 0, $maxV + 1 );
        $table->SetContent( 0, 0, "# verloren pro Liste" );
        $table->SetAttribute( 0, 0, "class", "yannotation" );

        $table->Display();
     }
     else
     {
        echo errormsg( mysql_errno() )."<br>";
        echo mysql_error()."<br>";
        echo $sql;
     }
  }
  else
  {
     echo errormsg( mysql_errno() )."<br>";
     echo mysql_error()."<br>";
     echo $sql;
  }
}

# Function generiert eine Matrix, woher ein Spieler seine Punkte
# erhaelt. Dazu werden alle Punktedifferenzen zu jedem Mitspieler aufaddiert
# und entsprechend der Gesamtsumme gewichtet.
# A bekommt =       A-B + A-C + A-D
# B bekommt = B-A       + B-C + B-D
# C bekommt = C-A + C-B       + C-D
# D bekommt = D-A + D-B + D-C
# Die Einzeldifferenzen koennen gewichtet werden, indem man durch die Summe
# teilt
# Die Zusammensetzung der Punkte werden in der Rangliste der gebenen
# dargestellt. Erst kommen die bessern, dann man selbst und dann die
# schlechteren.
function generatePunktezusammensetzung( $CategoryId, $PlayerId = 0 )
{
   global $CONF;
   global $SKAT_SESSION;
   $sql = "SELECT t1.Id AS ListId, t2.SpielerId AS PlayerId, t2.Summe AS Summe
  FROM " . 
   $CONF['tbl_cat'].  " AS t0, " .
   $CONF['tbl_scoresheet'].  " AS t1, " .
   $CONF['tbl_column'] .     " AS t2
  WHERE 
  t1.CatId=$CategoryId  
  AND t2.SpielerId IN " .  sqlQualified( $CategoryId ) .  "
  AND t2.SpiellisteId=t1.Id ";
   if( $PlayerId )
   {
      $sql .= " AND t2.SpielerId=$PlayerId ";
   }
   $sql .= "AND t0.Id=t1.CatId
  AND t0.GroupId=".$SKAT_SESSION[groupid]."
  ORDER BY ListID ASC ";

   $result = processSQL($sql);
   if( $result )
   {
      $oldlistid = -1;
      $successors = array();
      $punkte = array();
      while($row = mysql_fetch_array($result))
      {
         # Anzahl der Listen in der PlayerId mitgespielt hat
         $punkte[ $row["PlayerId"] ][ "Listen" ] += 1;

         if( $row['ListId'] != $oldlistid )
         {
            $oldlistid = $row['ListId'];
            $successors = array();

         }
         else
         {
            foreach( $successors as $item )
            {
               #A - B
               $ab =  $item['Summe'] - $row['Summe'];

               # Anzahl der Listen in der ItemPlayId mit RowPlayId gespielt hat
               $punkte[ $item['PlayerId'] ][ $row['PlayerId'] ][ "Listen" ] += 1;
               # Punkte die der ItemPlayId von RowPlayId bekommen hat
               $punkte[ $item['PlayerId'] ][ $row['PlayerId'] ][ "Punkte"] += $ab;
               # GesamtPunkte von ItemPlayId
               $punkte[ $item['PlayerId'] ][ 'Summe' ]          += $ab;

               #B - A
               $punkte[ $row['PlayerId'] ][ $item['PlayerId'] ][ "Listen" ] += 1;
               $punkte[ $row['PlayerId'] ][ $item['PlayerId'] ][ "Punkte"]  -= $ab;
               $punkte[ $row['PlayerId'] ][ 'Summe' ]           -= $ab;

            }
         }
         array_push( $successors, $row );
      }

      #   echo "Punkte PlayerID 7 Summe: " . $punkte[ 7 ]['Summe'];
      #   echo "<br>";
      #   echo "Punkte PlayerID 7 => 23: " . $punkte[ 7 ][ 23 ];
      #   echo "<br>";
      #   echo "Punkte PlayerID 23 => 7: " . $punkte[ 23 ][ 7 ];
      #   echo "<br>";

      # folgendes SQL Anweisung findet nur die Rangliste der Spieler heraus
      $praefix = sqlBestOfCategory( $CategoryId );
      $result = processSQL($praefix);
      if( $result )
      {
         $platzierung = array();
         $platz = 1;
         while($row = mysql_fetch_array($result))
         {
            $platzierung[ $platz++ ] = $row[2];
            $IdName[ $row[2] ] = $row[ 3 ];
         }

         startTable("PunkteMatrix");
         startTag("caption");
         echo "Punkte- und Spiellistenzusammensetzung";
         endTag("caption");
         # Reihung der Kandidaten nach der Rangliste
         startRow(); startTag("th");
         endTag("th");
         for( $p = 1; $p < $platz; $p++ )
         {
            $geber = $platzierung[ $p ];
            startTag("th");
            echo $IdName[ $geber ]."<br> ";
            echo $punkte[ $geber ]["Summe"];
            endTag("th");
         }
         endRow();
         for( $p = 1; $p < $platz; $p++ )
         {
            $geber = $platzierung[ $p ];
            startRow();
            startTag("th");
            echo $IdName[ $geber ];
            endTag("th");
            for( $k = 1; $k < $platz; $k++ )
            {
               startCol();
               $nehmer = $platzierung[ $k ];
               if( ( $p != $k ) && $punkte[$geber][$nehmer]["Punkte"] != 0)
               {
                  #            echo  $punkte[ $geber ][ $k ] ."<br>";
                  #echo  $punkte[ $geber ][ 'Summe' ] ."<br>";
                  #echo round(100 * $punkte[ $geber ][ $nehmer ] / $punkte[ $geber ][ 'Summe' ]);
                  if( $punkte[ $geber ][ $nehmer ][ "Punkte"] < 0 )
                  {
                     echo "<span style=\"color:red;\">";
                  }
                  else
                  {
                     echo "<span style=\"color:green;\">";
                  }
                  #echo $punkte[ $geber ][ $nehmer ][ "Punkte"];

                  echo " A(";
                  echo $punkte[ $geber ][ $nehmer ][ "Listen"] . ", " ;
                  echo round(100 * $punkte[ $geber ][ $nehmer ][ "Listen"] / $punkte[ $geber ][ "Listen" ]);
                  echo "%)";
                  echo "<br>";
                  echo " P(";

                  echo $punkte[ $geber ][ $nehmer ][ "Punkte"].", ";

                  echo round(100 * $punkte[ $geber ][ $nehmer ][ "Punkte"] / abs($punkte[ $geber ][ 'Summe' ]));
                  echo "%)";
                  echo "</span>";
               }
               else
               {
                  #echo $IdName[ $geber ];
                  #echo "-";
               }
               endCol();
            }
            endRow();
         }
         startRow();
         starttag("td", "class", "TableFootnote", "colspan", count($IdName) + 1 );
         echo "A: Anzahl wie oft mit diesem Spieler gespielt wurde, absolut und
        in %<br>";
         echo "P: Punkte, die er von diesem Spieler bekommt, ihm gibt, absolut
        und in %";
         endtag("td");
         endRow();
         endTable();
      }
      else
      {
         echo errormsg( mysql_errno(), mysql_error(), $sql );
      }
   }
   else
   {
      echo errormsg( mysql_errno(), mysql_error(), $sql );
   }
}


# SQL Funktionen fuer Graphen
function generateWeeklyPerformanceSQL( $CategoryId, $PlayerId )
{
   return generateFieberSQL( $CategoryId, $PlayerId );
   global $CONF;
   global $SKAT_SESSION;
   $praefix = "SELECT WEEK(t1.Datum,7) AS Woche, ROUND(AVG(t2.Summe),2)
  FROM " . 
   $CONF['tbl_cat'].  " AS t0, " .
   $CONF['tbl_scoresheet'].  " AS t1, " .
   $CONF['tbl_column'] .     " AS t2, " .
   $CONF['tbl_player'] .    " AS t4
  WHERE 
  t1.CatId=$CategoryId  
  AND t2.SpiellisteId=t1.Id  
  AND t2.SpielerId=$PlayerId 
  AND t0.Id=t1.CatId 
  AND t0.GroupId=".$SKAT_SESSION[groupid]."
  GROUP BY  Woche ORDER BY Woche ASC ";

   return $praefix;
}

# Spielwertverteilung
function generateSpielwertVerteilung( $CategoryId, $PlayerId = false )
{
   starttag( "img", "rel", "inc/graphen.php?GraphType=Spielwert&CatId=$CategoryId&SpielerId[]=$PlayerId", "alt", "Spielwertverteilung" );
   return 0;
}

function generateSpielwertVerteilungSQL( $CategoryId, $PlayerId = false )
{
   global $CONF;
   global $SKAT_SESSION;

   $PlayerCondition = "";
   if( $PlayerId  )
   {
      $PlayerCondition = " AND t3.AlleinspielerId=$PlayerId ";
   }
   #
   # tbd
   $sql = "SELECT t3.Spielwert, t2.Name, COUNT(*) AS Anzahl  FROM ".
   $CONF['tbl_scoresheet']. " AS t1, " .
   $CONF['tbl_player']. " AS t2, " .
   $CONF['tbl_game'] .     " AS t3
  WHERE     t1.CatId=$CategoryId  
  AND       t1.GroupId=".$SKAT_SESSION[groupid]."
  AND       t3.SpiellisteId=t1.Id  
  $PlayerCondition
  AND t3.AlleinspielerId IN " .  sqlQualified( $CategoryId ) .  "
  AND t3.AlleinspielerId=t2.Id
  AND ( t3.Eingepasst IS NULL OR t3.Eingepasst=0 ) 
  GROUP BY  t3.Spielwert, t3.AlleinspielerId
  ORDER BY t3.Spielwert ASC";

  return $sql;
}
#
# Spielwertverteilung
function generateSpiellistenVerteilung( $CategoryId, $PlayerId = false )
{
   starttag( "img", "rel", "inc/graphen.php?GraphType=Spielliste&CatId=$CategoryId&SpielerId[]=$PlayerId", "alt", "Spiellistenverteilung" );
   return 0;
}

function generateSpiellistenVerteilungSQL( $CategoryId, $PlayerId = false )
{
   global $CONF;
   global $SKAT_SESSION;

   $PlayerCondition = "";
   if( $PlayerId  )
   {
      $PlayerCondition = "AND t2.SpielerId=$PlayerId ";
   }
   #
   # tbd
   $sql = "SELECT t2.Summe, COUNT(*) AS Anzahl FROM ".
   $CONF['tbl_scoresheet']. " AS t1, " .
   $CONF['tbl_column'].     " AS t2
  WHERE     t1.CatId=$CategoryId  
  AND       t1.GroupId=".$SKAT_SESSION[groupid]."
  AND       t2.SpiellisteId=t1.Id $PlayerCondition
  GROUP BY  t2.Summe
  ORDER BY t2.Summe ASC";

   return $sql;
}

function generateSpiellistenVerteilungSQLEx( $CategoryId, $PlayerId = false )
{
   global $CONF;
   global $SKAT_SESSION;

   $PlayerCondition = "";
   if( $PlayerId  )
   {
      $PlayerCondition = "AND t2.SpielerId=$PlayerId ";
   }
   #
   # tbd
   $sql = "SELECT MIN(t2.Summe), MAX(t2.Summe) FROM ".
   $CONF['tbl_scoresheet']. " AS t1, " .
   $CONF['tbl_column'].     " AS t2
  WHERE     t1.CatId=$CategoryId  
  AND       t1.GroupId=".$SKAT_SESSION[groupid]."
  AND       t2.SpiellisteId=t1.Id $PlayerCondition
  GROUP BY  t1.CatId
  ORDER BY t2.Summe ASC";

   return $sql;
}

function generateFieberSQL( $CategoryId )
{
   global $CONF;
   global $SKAT_SESSION;

   $sql = "SELECT t1.Id AS SpiellisteId,
  t1.Datum AS Datum, 
  t2.Summe AS Punkte, 
  t2.SpielerId AS SpielerId, 
  t4.Name AS SpielerName FROM ".
   $CONF['tbl_scoresheet']. " AS t1, " .
   $CONF['tbl_column'] .    " AS t2, " .
   $CONF['tbl_player']. " AS t4
  WHERE     t1.CatId=$CategoryId  
  AND       t1.GroupId=".$SKAT_SESSION[groupid]."
  AND       t2.SpiellisteId=t1.Id  
  AND SpielerId IN " .  sqlQualified( $CategoryId ) .  "
  AND       t4.Id=t2.SpielerId  
  ORDER BY t1.Datum, t1.Id, t2.Platznummer ASC";


   return $sql;
}

function generateListOfGrandOuverts( $link = "", $Id = "" )
{
   global $CONF;
   global $SKAT_SESSION;
   static $Pfad, $Alt;

   if( !$Pfad )
   {
      $sql = "select * from " .$CONF['tbl_cards'];
      $result = processSQL($sql);
      while($row = mysql_fetch_array($result))
      {
         $Pfad[ $row['Id'] ] = $row['Pfad'];
         $Alt[ $row['Id'] ] = $row['Name'];
      }
   }

   $sql = "select *,
  t2.Name As SpName, 
  t1.Id As GId , t4.Pfad 
  from "
  .$CONF['tbl_grand'] . " as t1, "
  .$CONF['tbl_player'] . " as t2, "
  .$CONF['tbl_position'] . " as t3, "
  .$CONF['tbl_cards'] . " as t4
  Where t1.AlleinspielerId=t2.Id 
  and t1.PositionId=t3.Id
  AND t1.GroupId=".$SKAT_SESSION[groupid]."
  AND t2.GroupId=".$SKAT_SESSION[groupid]."
  and t4.Id=t1.Karte1 ORDER BY t1.Datum DESC"; 

  $result = processSQL($sql);
  starttag("table", "class", "ListGrandOuverts");
  if( $NumRows = mysql_num_rows($result) )
  {
     while($rows = mysql_fetch_array($result))
     {
        $c = 0;
        #$table->AppendRow();
        starttag("tr");
        starttag("td", "colspan", 10);
        if( $link )
        {
           echo "<a href='?Mngt=3&amp;Id=".$rows['GId']."'>".$rows['Datum']."</a>";
        }
        else
        {
           echo $rows['Datum'];
        }
        echo " " . $rows['SpName'];
        echo " gewinnt in " . $rows['Position'] ;
        endtag("td");
        endtag("tr");

        starttag("tr");
        for( $i = 1; $i < 11; $i++ )
        {
           starttag("td");
           starttag("img", "rel", $CONF["IMGROOT"]."/".$Pfad[ $rows[ "Karte$i"]]);
           endtag("td");
        }

        if( $Id == $rows['GId'] )
        {
           $Datum = $rows[ 'Datum' ];
           $AId   = $rows[ 'AlleinspielerId' ];
           $PosId = $rows[ 'PositionId' ];
           for( $i = 1; $i <= 10; $i++ )
           {
              $Karten[ $rows["Karte$i"] ] = true;
           }
        }
        endtag("tr");
     }//end while
  }
  endtag("table");
  return array($Datum, $AId, $PosId, $Karten, $NumRows );
}

// Function liefert die sql fuer eine Highscore
//function getSQLHighscore( $Type, $Category, $NotValid )
//{
//  return getSQL( "High", $Type, $Category, $NotValid );
//}

//function getSQLLowscore( $Type, $Category )
//{
//  return getSQL( $Category, "Low", $Type );
//}

function getSQL( $Category, $Crit, $Type  )
{
   global $CONF;
   global $SKAT_SESSION;
   if( $Type == "Grand" )
   {
      // Grand = 24
      $game = "t3.Grundwert=24";
   }
   elseif( $Type == "Null" )
   {
      // Null = 23, 35, 46, 59
      $game = "( t3.Grundwert=23 OR t3.Grundwert>24 ) ";
   }
   elseif( $Type == "Farbe" )
   {
      // Farbe = 9, 10, 11, 12
      $game = "t3.Grundwert<13";
   }
   else
   {
      // error
   }
   if( $Crit == "Low" )
   {
      $op = "<";
   }
   else
   {
      $op = ">";
   }

   $praefix = "SELECT t1.CatId, t4.Id, t4.Name,
    ROUND(100 * SUM( t3.Spielwert $op 0 AND $game ) / COUNT(*),2) AS Criteria FROM ".
   $CONF['tbl_cat'].  " AS t0, " .
   $CONF['tbl_scoresheet']. " AS t1, " .
   $CONF['tbl_game'] .     " AS t3, " .
   $CONF['tbl_player'] .   " AS t4
  WHERE     t1.CatId=$Category  
  AND t0.Id=t1.CatId 
  AND t0.GroupId=".$SKAT_SESSION[groupid]." 
  AND t4.Id IN " .  sqlQualified( $Category) .  "
  AND       t4.Id=t3.AlleinspielerId  
  AND       t3.SpiellisteId=t1.Id";  

   $postfix = " GROUP BY  t4.Id  HAVING  Criteria>0 ORDER BY Criteria DESC";

   $subquery = "(SELECT t1.Id FROM ".
   $CONF['tbl_cat'].  " AS t0, " .
   $CONF['tbl_scoresheet']. " AS t1, " .
   $CONF['tbl_game'] .     " AS t3
  WHERE     t1.CatId=$Category  
  AND t0.Id=t1.CatId 
  AND       t3.SpiellisteId=t1.Id 
  AND t0.GroupId=".$SKAT_SESSION[groupid]." 
  AND t3.Spielwert $op 0 AND $game GROUP BY t1.Id)";

   # subquery returns week of last inserted spielliste
   $week = "(SELECT WEEK(t1.Datum,7)  FROM " .
   $CONF['tbl_scoresheet'].  " AS t1 , ".
   $CONF['tbl_cat'].  " AS t0
  WHERE  t1.CatId=$Category AND t1.Id=t0.LastSpielliste  
  AND t0.GroupId=".$SKAT_SESSION[groupid]." 
  AND t0.Id=t1.CatId )";

   $condition = " AND WEEK(t1.Datum,7) < $week
  AND t0.LastSpielliste IN $subquery ";

   return array($praefix . $postfix, $praefix . $condition . $postfix );
}


###################################################################
# Information functions
###################################################################

function processCategory( $CategoryId )
{
   global $CONF;
   global $SKAT_SESSION;
   $sql = "SELECT *, Count(DISTINCT t1.Id) AS Gesamtzahl,
  Count(DISTINCT t1.Datum) AS NumSpieltage,
  Count(DISTINCT t1.Id) AS NumSpiellisten,
  Count(DISTINCT t2.SpielerId) AS NumSpieler FROM " 
  . $CONF["tbl_cat"] . " AS t0, "
  . $CONF["tbl_scoresheet"] . " AS t1, "
  . $CONF["tbl_column"] . " AS t2, "
  . $CONF['tbl_cattype'] . " AS t3 "
  . "WHERE t0.Id=$CategoryId
  AND   t1.CatId=t0.Id 
  AND t0.TypeId=t3.Id 
  AND t2.SpiellisteId=t1.Id 
  AND t0.GroupId=".$SKAT_SESSION[groupid]."
  GROUP BY t0.Id";

  return  processSQL( $sql );
}

function getCategoryInformation( $CategoryId )
{
   return mysql_fetch_array( processCategory( $CategoryId ) );
}

function getScoreSheetInfo( $SpiellisteId )
{
   global $CONF;
   global $SKAT_SESSION;

   $sql = "SELECT t1.Id, t1.Datum, t1.Tisch, t1.Serie, t4.Name,
    t0.CatName AS CatName , t0.Id AS CatId, t4.Id AS PlayerId,
    t1.NumSpiele AS NumSpiele, t1.NumSpieler AS NumSpieler FROM " . 
   $CONF['tbl_cat'].  " AS t0, " .
   $CONF['tbl_scoresheet'].  " AS t1, " .
   $CONF['tbl_column'] .     " AS t2, " .
   $CONF['tbl_player'] .    " AS t4
    WHERE   t1.Id=$SpiellisteId  
    AND t0.Id=t1.CatId  
    AND t2.SpiellisteId=t1.Id  
    AND t0.GroupId=".$SKAT_SESSION[groupid]." 
    AND t4.Id=t2.SpielerId 
    ORDER BY t2.Platznummer ";
   return processSQL( $sql );
}

function getPlayerInformation( $PlayerId )
{
   global $CONF;
   global $SKAT_SESSION;
   $sql = "SELECT * FROM "
   . $CONF["tbl_player"] . " AS t0 "
   . "WHERE t0.Id=$PlayerId
  AND t0.GroupId=".$SKAT_SESSION[groupid];

   $result = processSQL( $sql );
   return mysql_fetch_array( $result );
}


function sqlGewonnenVerlorenVerteilung( $CategoryId, $SpielerId )
{
   global $CONF;
   global $SKAT_SESSION;
   if( $SpielerId != 0 )
   {
      $PlayerCondition = "AND t2.SpielerId=$SpielerId";
   }
   return "SELECT  t2.Gewonnen as gewonnen, t2.Verloren as verloren,
  CONCAT( t2.Gewonnen, t2.Verloren ) AS CON, COUNT(*) as anzahl FROM " 
  . $CONF['tbl_cat'] . " AS t0, "
  . $CONF['tbl_scoresheet'] . " AS t1, "
  . $CONF['tbl_column']     . " AS t2
  WHERE t1.CatId=$CategoryId  
  AND   t0.Id=$CategoryId 
  AND   t1.GroupId=".$SKAT_SESSION[groupid]."
  AND t2.SpiellisteId=t1.Id "
  . $PlayerCondition . " GROUP BY CON";
}

function sqlQualified( $CatId, $Qualified = true )
{
   global $CONF;
   global $SKAT_SESSION;
   # query determines the number of necessary lists
   $subsql = "(SELECT COUNT(*) * t0.Quali FROM "
   . $CONF['tbl_scoresheet'].  " AS t1, "
   . $CONF['tbl_cat'].         " AS t0 "
   . " WHERE t1.CatId=$CatId
    AND t0.Id=$CatId 
    AND t0.GroupId=".$SKAT_SESSION[groupid]." GROUP BY t0.Id)";

   if( $Qualified )
   {
      $cond = ">=";
   }
   else
   {
      $cond = "<";
   }

   $sql = "(SELECT id FROM (SELECT t4.Id AS id, COUNT(*) AS Anzahl
    FROM "
    . $CONF['tbl_cat'].      " AS t0, "
    . $CONF['tbl_scoresheet']." AS t1, "
    . $CONF['tbl_column'].    " AS t2, "
    . $CONF['tbl_cattype'].   " AS t3, "
    . $CONF['tbl_player'] .  " AS t4
    WHERE t0.Id=$CatId 
    AND t1.CatId=$CatId 
    AND t0.GroupId=".$SKAT_SESSION[groupid]." 
    AND t0.TypeId=t3.Id 
    AND t4.Id=t2.SpielerId 
    AND t2.SpiellisteId=t1.Id 
    GROUP BY t4.Id 
    HAVING Anzahl".$cond."$subsql
    ORDER BY Anzahl DESC) AS tab1)";

    return $sql;
}

function sqlDisqualified( $CatId )
{
   global $CONF;
   global $SKAT_SESSION;
   $subsql = "(SELECT COUNT(*) FROM "
   . $CONF['tbl_scoresheet'].  " AS t1, "
   . $CONF['tbl_cat'].         " AS t0 "
   . " WHERE t1.CatId=$CatId
    AND t0.Id=$CatId 
    AND t0.GroupId=".$SKAT_SESSION[groupid]." GROUP BY t0.Id)";

   $sql = "SELECT t4.Name, COUNT(*) AS Anzahl, ROUND(100*COUNT(*)/$subsql,2)
    FROM "
   . $CONF['tbl_cat'].      " AS t0, "
   . $CONF['tbl_scoresheet']." AS t1, "
   . $CONF['tbl_column'].    " AS t2, "
   . $CONF['tbl_cattype'].   " AS t3, "
   . $CONF['tbl_player'] .  " AS t4
    WHERE t0.Id=$CatId 
    AND t1.CatId=$CatId 
    AND t0.GroupId=".$SKAT_SESSION[groupid]." 
    AND t0.TypeId=t3.Id 
    AND t4.Id=t2.SpielerId 
    AND t2.SpiellisteId=t1.Id AND t2.SpielerId IN "
    .sqlQualified( $CatId, false ) . "
    GROUP BY t4.Id 
    ORDER BY Anzahl DESC";

    return $sql;
}

function listDisqualified( $CatId )
{
   global $CONF;
   global $SKAT_SESSION;
   $sqlExec = processSQL( sqlDisqualified( $CatId ) );

   $list = "";

   while( $line = mysql_fetch_array( $sqlExec ) )
   {
      $list .= $line[0] . "(" . $line[1] . ", " . $line[2] . "%) ";
   }
   return $list;
}


function generateListDQ( $CatId )
{
   global $CONF;
   global $SKAT_SESSION;
   $sql = "SELECT COUNT(*) AS 'Anzahl', t0.Quali FROM "
   . $CONF['tbl_scoresheet'].  " AS t1, "
   . $CONF['tbl_cat'].         " AS t0 "
   . " WHERE t1.CatId=$CatId
  AND t0.Id=$CatId 
  AND t0.GroupId=".$SKAT_SESSION[groupid]." GROUP BY t0.Id";

   $line = mysql_fetch_array( processSQL( $sql ) );
   if( $line )
   {
      $totalnum = $line[ 0 ];
      $quali    = $line[ 1 ];
      $minnum   = $totalnum * $quali;

      $sql = "SELECT t4.Id, t4.Name,
    COUNT(*) AS 'Anzahl', 
    ROUND(100*COUNT(*) / $totalnum,2) AS 'PerCentage', 
    t3.Type,
    t0.Description,
    t0.Quali FROM "
      . $CONF['tbl_cat'].      " AS t0, "
      . $CONF['tbl_scoresheet']." AS t1, "
      . $CONF['tbl_column'].    " AS t2, "
      . $CONF['tbl_cattype'].   " AS t3, "
      . $CONF['tbl_player'] .  " AS t4
    WHERE t0.Id=$CatId 
    AND t1.CatId=$CatId 
    AND t0.GroupId=".$SKAT_SESSION[groupid]." 
    AND t0.TypeId=t3.Id 
    AND t4.Id=t2.SpielerId 
    AND t2.SpiellisteId=t1.Id 
    GROUP BY t4.Id 
    HAVING Anzahl<$minnum
    ORDER BY Anzahl DESC";

      $result = processSQL( $sql );
      $return = array();
      while( $line = mysql_fetch_array( $result ) )
      {
         array_push( $return, $line );
      }
   }
   else
   {
      $return = 0;
   }
   return $return;
}

function processDQ( $list )
{
   $DQNames = "";
   $DQSQL   = "";
   foreach( $list as $dq )
   {
      $DQSQL   .= " AND t4.Id !=" . $dq[0];
      $DQNames .= " " . $dq[1] . "(".$dq[2].", " . $dq[3] ."%)";
   }
   return array(  $DQSQL , $DQNames );
}


function listGroupProperties()
{
   global $CONF;
   global $SKAT_SESSION;
   $header = array( NAME  , "Beschreibung" );
   $fields = array( "Name", "Info" );
   $displayname = $fields;

   $msg = processSimpleData( $CONF['tbl_grp'], $fields, "Id" );
   echo $msg;

   $sql = "SELECT * FROM " .
   $CONF['tbl_grp'] . " WHERE Id=".$SKAT_SESSION[groupid] .
  " AND Id=".$SKAT_SESSION[groupid];

   $title = "Gruppen Eigenschaften";
   simpleDataManagement( $title, $sql, $header, $displayname, $fields, "Id","");
}



/**
 add / update the contact's data
 */
function list_all_cat()
{
   global $CONF;
   global $SKAT_SESSION;
   $header = array( NAME  , "Beschreibung", "Type", "Quali" );
   $displayname = array( "CatName", "Description", "Type", "Quali" );
   $fields = array( "CatName", "Description", "TypeId", "Quali" );

   echo processSimpleData( $CONF['tbl_cat'], $fields, "Id" );


   $sql = "SELECT CatName, Description,
  Quali, t2.Id AS TypeId, t2.Type AS Type, t1.Id as Id FROM " . 
   $CONF['tbl_cat'] . " AS t1 , ".
   $CONF['tbl_cattype'] . " AS t2
  WHERE t1.GroupId=".$SKAT_SESSION[groupid]."
  AND t2.Id=t1.TypeId 
  ORDER BY TypeId DESC, t1.Description DESC";

   $title = "Kategorie Management";
   $fsql[ "TypeId" ]   = "SELECT * from " . $CONF['tbl_cattype'];

   simpleDataManagement( $title, $sql, $header, $displayname, $fields, "Id", $fsql );
   require("hcat.php");
}

function list_cat()
{
   global $CONF;
   global $SKAT_SESSION;
   $y = 0; //counter
   # $sql = "select *, ". $CONF['tbl_cat'].".Id AS CId, ". $CONF['tbl_cattype']
   #   . ".Type as Typename from "
   #   . $CONF['tbl_cat'] . ", " . $CONF['tbl_cattype']
   #   . " WHere " . $CONF['tbl_cattype'] . ".Id = ".$CONF['tbl_cat'].".TypeId";

   $sql = "SELECT *, t1.Id AS CId, t2.Type as Typename FROM " .
   $CONF['tbl_cat'] . " AS t1 , ".
   $CONF['tbl_cattype'] . " AS t2
  WHERE t1.GroupId=".$SKAT_SESSION[groupid]."
  AND t2.Id=t1.TypeId 
  ORDER BY t1.Description DESC";

   $result = processSQL($sql);
   $Mngt = (int)getGet('Mngt');
   if( !$Mngt )
   {
      $Mngt = (int)getPost('Mngt');
   }
   starttag( "div", "class", "Title" );
   echo "Kategoriemanagement";
   endtag( "div" );
   starttag( "form", "name", "method", "post", "action", $_SERVER['PHP_SELF'] );
   starttag( "div" );
   starttag( "input", "name", "CId", "type", "hidden", "value", getGet('CId') );
   starttag( "input", "name", "Mngt", "type", "hidden", "value", $Mngt );
   endtag( "div" );
   starttag( "table", "class", "KategorieTable" );
   $val  = "Add";
   if( $result )
   {
      //show a list of kIds with name as a link to the prepopulated form with
      //their data in it
      while($rows = mysql_fetch_array($result))
      {
         //build strings to make life easier
         $Id     = $rows['CId'];

         if( $Id == getGet('CId') )
         {
            $Name   = $rows['CatName'];
            $Description = $rows['Description'];
            $Quali = $rows['Quali'];
            $Datum = $rows['Datum'];
            $TypId = $rows['TypeId'];
            $val  = "Edit";
         }

         //echo out the row
         starttag("tr");
         starttag("td");
         echoLink($_SERVER['PHP_SELF']."?Mngt=$Mngt&amp;CId=$Id", $rows['CatName'] );
         endtag("td");
         foreach( array( $rows['Description'],$rows['Typename'], $rows['Quali'] )
         as $item )
         {
            starttag("td");
            echo $item;
            endtag("td");
         }

         endtag("tr");
         $y++;  //increment the counter
      }//end while
   }
   starttag("tr");
   foreach( array( NAME  , "Beschreibung", "Type", "Mindestspielanteil", "Loeschen" ) as $item )
   {
      starttag("th");
      echo $item;
      endtag("th");
   }
   endtag("tr");
   starttag("tr");
   starttag("td");
   starttag("input", "name", "CName" );
   starttag( "input", "name", "CName", "type", "text", "value", $Name );
   endtag("td");
   starttag("td");
   starttag( "input", "name", "Description", "type", "text", "value", $Description );
   endtag("td");
   starttag("td") ;
   option_type( $TypId );
   endtag("td");
   starttag("td");
   starttag( "input", "name", "Qualification", "type", "text", "value", $Quali );
   endtag("td");
   starttag("td");
   starttag( "input", "name", "Delete", "type", "checkbox" );
   endtag("td");
   endtag("tr");
   starttag("tr");
   starttag("td", "colspan", 2);
   starttag("input", "name", "submit", "type", "submit", "value", $val);
   endtag("tr");
   endtag("table");
   endtag("form");
}

function process_form_cat()
{
   global $CONF;
   global $SKAT_SESSION;
   # Category Data
   $cname  = getPost('CName');
   $cdesc  = getPost('Description');
   $cquali = getPost('Qualification');
   $cId    = getPost('CId');
   $TypeId = getPost('Type');
   $Delete = getPost('Delete');

   if( $Delete )
   {
      $sql = "delete " .$CONF['tbl_cat'].", "
      .$CONF['tbl_column'].", "
      .$CONF['tbl_scoresheet'].", "
      .$CONF['tbl_game'].
    " from "
    .$CONF['tbl_cat']." AS t0, "
    .$CONF['tbl_column'].", "
    .$CONF['tbl_scoresheet'].", "
    .$CONF['tbl_game'].
    " where t0.Id=$cId  
    AND ". $CONF['tbl_scoresheet'].".CatId=$cId 
    AND ". $CONF['tbl_column'].".SpiellisteId="
    . $CONF['tbl_scoresheet'].".Id
    AND ". $CONF['tbl_game'].".SpiellisteId="
    . $CONF['tbl_scoresheet'].".Id";

    $sql2 = " delete  FROM " .$CONF['tbl_cat']. " AS t0
    where t0.Id=$cId 
    AND t0.GroupId=". $SKAT_SESSION[groupid];
   }
   elseif ( $cname && $cdesc && $cId )
   {
      $sql = "update " . $CONF['tbl_cat']."
    set CatName ='$cname', Description='$cdesc', 
    Quali=$cquali, TypeId=$TypeId 
    where Id=$cId AND GroupId=".$SKAT_SESSION[groupid];
      $msg = "Record successfully updated";
   }
   elseif ( $cname && $cdesc )
   {
      $path = preg_replace( '/\s+/', '', $cname );

      $sql = "insert into " . $CONF['tbl_cat'].
    " (CatName, Description, Path, TypeId, GroupId) 
    VALUES('$cname','$cdesc', '$path', $TypeId,".$SKAT_SESSION[groupid].")";
      $msg = "Record successfully added";
   }
   else
   {
      #nothing happens
   }

   $msg = "";
   if( $sql )
   {
      $result = processSQL($sql);
      if( ! $result )
      {
         $msg = errormsg( mysql_errno() );
      }//end if
   }
   if( $sql2 )
   {
      $result = processSQL($sql2);
      if( ! $result )
      {
         $msg = errormsg( mysql_errno() );
      }//end if
   }
   return $msg;
}


function list_all_go()
{
   $msg = process_form_go();
   list_go();
   getWarning( $msg );
}

function list_go()
{
   global $CONF;
   global $SKAT_SESSION;

   $Mngt = (int)getGet('Mngt');
   if( !$Mngt )
   {
      $Mngt = (int)getPost('Mngt');
   }

   if( getGet('Id') )
   {
      $val  = "Edit";
   }
   else
   {
      $val  = "Add";
   }
   starttag("div", "class", "Title");
   echo "Grand Ouvert Management";
   endtag("div" );
   starttag("form", "name", "form", "method", "post", "action", $_SERVER['PHP_SELF']);
   starttag("div" );
   starttag("input", "type", "hidden", "value", getGet('Id'), "name", "Id");
   starttag("input", "type", "hidden", "value", $Mngt, "name", "Mngt");
   endtag("div" );

   list( $Datum, $AId, $PosId, $Karten, $NumRows)
   = generateListOfGrandOuverts( 1, getGet('Id') );
   if( ! $NumRows )
   {
      $val = "Add";
   }
   if( ! $Datum )
   {
      $Datum = "yyyy-mm-dd";
   }
   starttag("br");
   starttag("hr");
   starttag("table", "class", "EditGrandOuverts");
   starttag("tr");
   starttag("td");
   echo "Datum";
   endtag("td");
   starttag("td");
   starttag("input", "size", 10, "name", "Datum", "type", "text", "value", $Datum );
   endtag("td");
   starttag("td");
   echo "Spieler";
   endtag("td");
   starttag("td");
   option_users( "Spieler", $AId );
   endtag("td");
   starttag("td");
   echo "Position";
   endtag("td");
   starttag("td");
   option_position( $PosId );
   endtag("td");
   if( $val == "Edit" )
   {
      starttag("td");
      echo "Loeschen";
      endtag("td");
      starttag("td");
      starttag("input", "name", "Delete", "type", "checkbox", "value", "delete");
      endtag("td");
   }
   starttag("td", "align", "center", "colspan", 2);
   starttag("input", "name", "submit", "type", "submit", "value", $val);
   endtag("td");
   endtag("tr");
   endtag("table");
   starttag("table", "class", "EditGrandOuverts" );
   starttag("tr");
   starttag("td");
   box_blatt( $Karten );
   endtag("td");
   endtag("tr");
   endtag("table");
   endtag("form");
}

function process_form_go()
{
   global $CONF;
   global $SKAT_SESSION;
   # User Data
   $Name  =    getPost('Spieler');
   $Datum  =   getPost('Datum');
   $Id     =   getPost('Id');
   $Position = getPost('Position');
   $Karte  =   getPost('Karte');

   if ( $Id = (int)$_POST['Id'] )
   {
      if( $_POST['Delete'] == "delete" )
      {
         $sql  = "DELETE FROM " . $CONF['tbl_grand']." WHERE ";
         $sql .= "Id=".$Id." AND GroupId=".$SKAT_SESSION[groupid];
         $msg = "Record successfully deleted";
      }
      else
      {
         $sql   = "update ";
         $cond  = " where Id=$Id AND GroupId=".$SKAT_SESSION[groupid];
         $msg = "Record successfully updated";
      }
   }
   else if( $Name && $Datum )
   {
      $sql  = "INSERT INTO ";
      $cond = "";
      $msg = "Record successfully added";
   }
   else
   {
      $msg = "Nothing to do ...";
   }

   $AuswahlError = 0;
   # Add common SQL part
   if( ! $_POST['Delete'] && $sql )
   {
      $sql .= $CONF['tbl_grand'] . " SET ";
      $sql .= "Datum='" . $Datum . "' ";
      $sql .= ", AlleinspielerId=" . $Name . " ";
      $sql .= ", PositionId=" . $Position . " ";
      $sql .= ", GroupId=" . $SKAT_SESSION[groupid] . " ";
      for( $i = 1; $i < 11; $i++ )
      {
         $sql .= ", Karte$i=" . $Karte[$i - 1];
         if( ! $Karte[$i - 1] )
         {
            $AuswahlError = 1;
            break;
         }
      }
      $sql .= $cond;
   }

   if( ! $AuswahlError && $sql )
   {
      $result = processSQL($sql);
      if ( mysql_errno() )
      {
         $msg = errormsg( mysql_error() );
      }//end if
   }
   elseif( $AuswahlError )
   {
      $msg = "Bitte waehlen Sie fuer einen Grand Ouver alle 10 Karten aus.";
   }
   else
   {
      $msg = "";
   }
   return $msg;
}

/*************************************************************************
 add / update the contact's data
 *************************************************************************/

function  box_blatt( $Karten )
{
   global $CONF;
   global $SKAT_SESSION;
   $sql = "SELECT * from " . $CONF['tbl_cards']." ORDER BY Wert DESC";
   $result = processSQL($sql);
   $c = 1;
   startTable( "Blatt" );
   while($rows = mysql_fetch_array($result))
   {
      if( $c % 8 == 1 )
      {
         startRow();
      }
      startCol();

      $fieldname = "Karte[]";
      ImgKarte( $rows["Id"], $c-1, $fieldname );
      starttag("br");


      if( $Karten[$rows["Id"]] )
      {
         $checked =  "checked";
      }
      else
      {
         $checked =  "";
      }
      starttag("input", "type", 'checkbox', "name", $fieldname, "value",
      $rows["Id"], $checked, $checked );
      endtag("td");

      if( $c % 8 == 0 )
      {
         endRow();
      }
      $c++;
   }
   endTable( "Blatt" );
}

################################################################
# Functions to build option fields
################################################################
function  option_users( $FieldName = "Spieler", $preselectedId = "", $tabindex=0 )
{
   global $CONF;
   global $SKAT_SESSION;
   $sql = "SELECT * from ".$CONF['tbl_player']." WHERE GroupId=".$SKAT_SESSION[groupid] . " ORDER BY Name";
   generateOption( $FieldName, $sql, $preselectedId, 0, $tabindex );
}

function  option_position( $Id )
{
   global $CONF;
   global $SKAT_SESSION;
   $sql = "SELECT * from ".$CONF['tbl_position'];
   generateOption( "Position", $sql, $Id );
}

function  option_categories( $preselectedId = "")
{
   global $CONF;
   global $SKAT_SESSION;
   $sql = "SELECT Id, CatName FROM " . $CONF['tbl_cat'] . " AS t0 WHERE
  t0.GroupId=" .$SKAT_SESSION[groupid]." ORDER BY CatName DESC" ;
   generateOption( "Category", $sql, $preselectedId );
}

function  option_type( $Id )
{
   global $CONF;
   global $SKAT_SESSION;
   $sql = "SELECT * from " . $CONF['tbl_cattype'];
   generateOption( "Type", $sql, $Id );
}

function generateOption( $name, $sql, $selection, $limit = 0, $tabindex = 0 )
{
   $result = processSQL($sql);
   echo "<select tabindex='$tabindex' ". $status ." name='$name'>\n";
   while($rows = mysql_fetch_array($result))
   {
      if( !$limit  || ( $limit &&  $selection == $rows[ 0 ] ) )
      {
         echo "<option ";
         if( $selection == $rows[ 0 ] )
         {
            echo " selected ";
         }
         echo " value=\"" . $rows[ 0 ]."\"";
         echo "> " . $rows[ 1 ];
         echo "</option>";
      }
   }
   echo "</select>";
   if( $name == "Category" && 1 > mysql_num_rows( $result ) )
   {
      echo "<big><i>Erstellen Sie zuerst eine Kategorie!</i></big>";
   }
   elseif( preg_match( "/^Name\d+/", $name ) && 3 > mysql_num_rows( $result ) )
   {
      echo "<big><i>Fuegen Sie zuerst min. 3 Spieler hinzu!</i></big>";
   }
   elseif( preg_match( "/^VereinId/", $name ) && 1 > mysql_num_rows( $result ) )
   {
      echo "<big><i>Erstellen Sie zuerst einen Verein!</i></big>";
   }
}

################################################################
# Functions for player/club etc management
################################################################
function list_all_player()
{
   global $CONF;
   global $SKAT_SESSION;
   $header      = array( NAME  , "Verein");
   $displayname = array( NAME  , "Verein");
   $fields      = array( NAME  , "VereinId");

   $msg = processSimpleData( $CONF['tbl_player'], $fields, "Id" );
   echo $msg;

   $sql = "SELECT t0.Id, t0.Name, t1.Name AS Verein FROM ". $CONF['tbl_player'] . " AS t0, "
   . $CONF['tbl_club'] . " AS t1 ".
  " WHERE t0.GroupId=".$SKAT_SESSION[groupid].
  " AND t1.GroupId=t0.GroupId " .
  " AND t1.Id=t0.VereinId " .
  " ORDER BY Name"; 

   $title = "Spieler Management";
   $fsql[ "VereinId" ]   = "SELECT * from ". $CONF['tbl_club'].
  " WHERE GroupId=".$SKAT_SESSION[groupid] ;
   simpleDataManagement( $title, $sql, $header, $displayname, $fields, "Id", $fsql );
   require("hplayer.php");
}

function list_all_clubs()
{
   global $CONF;
   global $SKAT_SESSION;
   $header = array( NAME  , "Beschreibung");
   $displayname = $header;

   $msg = processSimpleData( $CONF['tbl_club'], $header, "Id" );
   echo $msg;

   $sql = "SELECT * FROM ". $CONF['tbl_club'] .
  " WHERE GroupId=".$SKAT_SESSION[groupid].
  " ORDER BY Name"; 
   $title = "Vereins Management";
   simpleDataManagement( $title, $sql, $header, $displayname, $header, "Id", $fsql );
   require("hclubs.php");
}

function list_all_user()
{
   global $CONF;
   global $SKAT_SESSION;
   $header      = array( "UserId", "EMail", "Vorname", "Nachname", "Type");
   $displayname = array( "uid", "email", "fname", "lname", "NType");
   $fields      = array( "uid", "email", "fname", "lname", "pwd", "type");
   $change      = array( "UserId", "EMail", "Vorname", "Nachname", "Passwort", "Type");

   processAllUser( $CONF['tbl_user'], $fields, "id" );

   $sql = "SELECT *, t2.Id AS type, t2.Type as NType FROM "
   . $CONF['tbl_user'] . " AS t1,"
   . $CONF['tbl_uac'] . " AS t2
  WHERE t1.GroupId=".$SKAT_SESSION[groupid].
  " AND t2.Id=t1.type 
  ORDER BY uid"; 
   $title = "User Management";
   $identifier = "id";
   $fsql[ "type" ]   = "SELECT * from ". $CONF['tbl_uac'];

   $Mngt = (int)getGet('Mngt');
   if( !$Mngt )
   {
      $Mngt = (int)getPost('Mngt');
   }
   startContainer( "SkatVerwaltung" );
   starttag( "div", "class", "Title" );
   echo $title;
   endtag( "div", "class", "Title" );
   starttag( "form", "name", "form", "method", "post", "action", $_SERVER['PHP_SELF']);
   starttag( "div" );
   starttag( "input", "type", "hidden", "value", getGet('Id'), "name", "Id" );
   starttag( "input", "type", "hidden", "value", $Mngt, "name", "Mngt" );
   endtag( "div" );
   starttag( "table", "class", "SpielerTable" );
   starttag("tr");
   $c = 0;
   # header row
   foreach( $header as $field )
   {
      starttag("th");
      echo $field;
      endtag("th");
   }
   endtag("tr");
   $val  = "Add";
   $result = processSQL($sql);
   if( mysql_num_rows($result) )
   {
      while( $rows = mysql_fetch_array($result) )
      {
         # Get identifier for FORM
         $Id     = $rows[$identifier];

         # If identifier == value received, store data for modification
         if( $Id == getGet('Id') )
         {
            while( list(,$field)=each($fields) )
            {
               $$field  = $rows[$field];
            }
            $val  = "Edit";
         }

         //echo out the row
         starttag("tr");
         $y = 0;
         foreach( $displayname as $field )
         {
            # First colum is always a link
            if( 0 == $y )
            {
               $y++;
               starttag("td");
               echoLink( $_SERVER['PHP_SELF']."?Mngt=$Mngt&amp;Id=$Id",
               $rows[$field] );
               endtag("td");
            }
            else
            {
               starttag("td");
               echo $rows[$field];
               endtag("td");
            }
         }
         endtag("tr");
      }//end while
   }
   endtag("table");
   starttag("hr");
   starttag("table", "class", "SpielerTable");
   reset($fields);
   reset($header);
   while(( list(,$field ) = each( $fields ) ) &&
   ( list(,$head)   = each( $change ) ) )
   {
      starttag("tr");
      starttag("td");
      echo $head;
      endtag("td");
      starttag("td");
      if( $fsql[ $field ] )
      {
         if( ( $field == "type" ) && ( $SKAT_SESSION[userid] == getGet('Id') ) )
         {
            generateOption( $field, $fsql[ $field ], $$field, 1 );
         }
         else
         {
            generateOption( $field, $fsql[ $field ], $$field, 0 );
         }
      }
      else
      {
         if( $field == "pwd" )
         {
            starttag( "input", "type", "password", "value", $$field, "name", $field );
         }
         else
         {
            if( $field == "uid" && $SKAT_SESSION[userid] ==getGet("Id") )
            {
               $readonly = "readonly";
            }
            else
            {
               $readonly = "";
            }
            starttag( "input", $readonly, $readonly, "type", "text", "value", $$field, "name", $field );

         }
      }
      endtag("td");
      endtag("tr");
   }
   if( $val == "Edit" && $SKAT_SESSION[userid] != getGet('Id') )
   {
      starttag("tr");
      starttag("td");
      echo "Loeschen";
      endtag("td");
      starttag("td");
      starttag( "input", "type", "checkbox", "value", "delete", "name", "Delete" );
      endtag("td");
      endtag("tr");
   }
   starttag("tr");
   starttag("td", "colspan", 2);
   starttag( "input", "type", "hidden", "value", $val, "name", "Mode" );
   starttag( "input", "type", "submit", "value", $val, "name", "submit" );
   endtag("td");
   endtag("tr");

   endtag("table");
   endtag("form");
   endContainer();
   require( "husermanagement.php" );
}


/*************************************************************************
 add / update simple interface
 *************************************************************************/

function simpleDataManagement( $title, $sql,
$header, $displayname, $fields, $identifier, $fsql )
{
   global $CONF;
   global $SKAT_SESSION;

   $Mngt = (int)getGet('Mngt');
   if( !$Mngt )
   {
      $Mngt = (int)getPost('Mngt');
   }
   if( 6 == $Mngt )
   {
      $subId = $SKAT_SESSION[groupid];
   }
   else
   {
      $subId = getGet('Id');
   }
   starttag("div", "class", "SkatVerwaltung");
   starttag("div", "class", "Title");
   echo $title;
   endtag("div");
   starttag("form", "method", "post", "action", $_SERVER['PHP_SELF'], "name", "form");
   starttag("div");
   starttag("input", "type", "hidden", "value", $subId, "name", "Id");
   starttag("input", "type", "hidden", "value", $Mngt, "name", "Mngt");
   endtag("div");

   starttag("table", "class", "SpielerTable");
   starttag("tr");
   # header row
   foreach( $header as $field )
   {
      starttag("th");
      echo $field;
      endtag("th");
   }
   endtag("tr");
   $val  = "Add";
   $result = processSQL($sql);
   if( mysql_num_rows($result) )
   {
      while( $rows = mysql_fetch_array($result) )
      {
         # Get identifier for FORM
         $Id     = $rows[$identifier];

         # If identifier == value received, store data for modification
         if( $Id == $subId )
         {
            while( list(,$field)=each($fields) )
            {
               $$field  = $rows[$field];
            }
            $val  = "Edit";
         }

         //echo out the row
         starttag("tr");
         $y = 0;
         foreach( $displayname as $field )
         {
            # First colum is always a link
            if( 0 == $y )
            {
               $y++;
               starttag("td");
               echoLink($_SERVER['PHP_SELF']."?Mngt=$Mngt&amp;Id=$Id", $rows[$field]);
               endtag("td");
            }
            else
            {
               starttag("td");
               echo $rows[$field];
               endtag("td");
            }
         }
         endtag("tr");
      }//end while
   }
   endtag("table");
   starttag("hr");
   starttag("table", "class", "SpielerTable");

   reset($fields);
   reset($header);
   while(( list(,$field ) = each( $fields ) ) &&
   ( list(,$head)   = each( $header ) ) )
   {
      starttag("tr");
      starttag("td");
      echo $head;
      endtag("td");
      starttag("td");
      if( $fsql[ $field ] )
      {
         generateOption( $field, $fsql[ $field ], $$field );
      }
      else
      {
         starttag("input", "name", $field, "type", "text", "value", $$field );
      }
      endtag("td");
      endtag("tr");
   }
   if( $val == "Edit" && $Mngt != 6 )
   {
      #<!-- Possibility to delete user/cat -->
      starttag("tr");
      starttag("td");
      echo "Loeschen";
      endtag("td");
      starttag("td");
      starttag("input", "name", "Delete", "type", "checkbox", "value", "delete" );
      endtag("td");
      endtag("tr");
   }
   starttag("tr");
   starttag("td", "colspan", 2);
   starttag("input", "name", "Mode", "type", "hidden", "value", $val );
   starttag("input", "name", "submit", "type", "submit", "value", $val );
   endtag("td");
   endtag("tr");
   endtag("table");
   endtag("form");
   endtag("div");
}

function processSimpleData( $table, $fields, $identifier )
{
   global $CONF;
   global $SKAT_SESSION;
   # User Data
   foreach( $fields as $field )
   {
      $$field  = $_POST[$field];
   }
   $Id     = (int)$_POST['Id'];
   $Mode   = $_POST['Mode'];
   $msg = "";

   # Data already in
   # Check if all other fields are empty
   if( $_POST['Delete'] == "delete" )
   {
      # data should be deleted
      # admin was warned before due to message and held content
      # distinguish according to the table submitted
      if( $table == $CONF['tbl_player'] )
      {
         # If there exist Spiellisten with player to be deleted,
         # the player will not be deleted!!
         $sql = "SELECT * FROM ".$CONF['tbl_column']." WHERE SpielerId=".$Id;
         if( 0 < mysql_num_rows( processSQL( $sql ) ) )
         {
            $sql = "";
            $msg = "player cannot be delete, because there are Spiellisten with his participation";
         }
         else
         {
            $sql = "DELETE FROM $table WHERE $identifier=$Id AND GroupId=" .$SKAT_SESSION[groupid];
            $msg = "deleted player successful";
         }
      }
      elseif( $table == $CONF['tbl_cat'] )
      {
         $sql = "delete " .$CONF['tbl_cat'].", "
         .$CONF['tbl_column'].", "
         .$CONF['tbl_scoresheet'].", "
         .$CONF['tbl_game'].
      " from "
      .$CONF['tbl_cat'].", "
      .$CONF['tbl_column'].", "
      .$CONF['tbl_scoresheet'].", "
      .$CONF['tbl_game'].
      " where ".$CONF['tbl_cat'].".Id=$Id  
      AND ". $CONF['tbl_scoresheet'].".CatId=$Id 
      AND ". $CONF['tbl_column'].".SpiellisteId="
      . $CONF['tbl_scoresheet'].".Id
      AND ". $CONF['tbl_game'].".SpiellisteId="
      . $CONF['tbl_scoresheet'].".Id
      AND ".$CONF['tbl_cat'].".GroupId=". $SKAT_SESSION[groupid];

      $sql2 = " delete  FROM " .$CONF['tbl_cat']. "
      where " . $CONF['tbl_cat'] . ".Id=$Id 
      AND " . $CONF['tbl_cat'] . ".GroupId=". $SKAT_SESSION[groupid];
      $msg = "deleted category successful";
      }
      elseif( $table == $CONF['tbl_club'] )
      {
         # If there exist Spieler with Club to be deleted,
         # the Club will not be deleted!!
         $sql = "SELECT * FROM ".$CONF['tbl_player']." WHERE VereinId=".$Id;
         if( 0 < mysql_num_rows( processSQL( $sql ) ) )
         {
            $sql = "";
            $msg = "club cannot be delete, because there are Player belonging to that club";
         }
         else
         {
            $sql = "DELETE FROM $table WHERE $identifier=$Id AND GroupId="
            .$SKAT_SESSION[groupid];
            $msg = "deleted club successful";
         }
      }
   }
   else
   {
      if( $Mode )
      {
         if( $Id )
         {
            $sql = "UPDATE ". $table . " SET ";
            $cond = " WHERE $identifier=$Id";
            $msg  = "Record successfully updated";
         }
         else
         {
            $sql  = "INSERT INTO ". $table ." SET ";
            $cond = "";
            $msg  = "Record successfully added";
         }

         $y = 0;
         if( $$fields[0] )
         {
            foreach( $fields as $field )
            {
               if( $y++ > 0 )
               {
                  $sql .= ",";
               }
               $sql .= $field."='".$$field."' ";
            }
            if( $table != $CONF['tbl_grp'] )
            {
               $sql .= ", GroupId='".$SKAT_SESSION[groupid]."' ";
            }
            $sql .= $cond;
         }
         else
         {
            $sql = "";
            $sql2 = "";
            $msg = getWarning( "Record cannot be updated/inserted, because you did not fill in the required <b>".$fields[0]."</b> field." );
         }
      }
      else
      {
      }
   }

   if( $sql )
   {
      $result = processSQL($sql);
      if( ! $result )
      {
         $msg = errormsg( mysql_errno() );
      }
      if( $sql2 )
      {
         $result = processSQL($sql2);
         if( ! $result )
         {
            $msg = errormsg( mysql_errno() );
         }//end if
      }
   }
   return $msg;
}

# Field name "Id" to identify already existing data is implicit!!!
function processAllUser( $table, $fields, $identifier )
{
   global $CONF;
   global $SKAT_SESSION;
   # User Data
   foreach( $fields as $field )
   {
      $$field  = $_POST[$field];
   }
   $Id     = (int)$_POST['Id'];
   $Mode   = $_POST['Mode'];

   # Data already in
   # Check if all other fields are empty
   if( $_POST['Delete'] == "delete" )
   {
      $sql = "DELETE FROM $table WHERE $identifier=$Id AND GroupId=".
      $SKAT_SESSION[groupid];
      $msg = "Deleted user successfully";
   }
   else
   {
      if( $Mode )
      {
         if( $uid )
         {
            if( $Id )
            {
               $sql = "UPDATE ". $table . " SET ";
               $cond = " WHERE $identifier=$Id";
               $msg  = "Record successfully updated";
            }
            else
            {
               # Check if doublicate user names
               $sqlcheck = "SELECT * FROM ". $table . " WHERE
          uid=\"". $uid ."\"";

               $result = processSQL($sqlcheck);
               if( 0 < mysql_num_rows( $result ) )
               {
                  # username is already in user, choose another one
                  $UserNameInUser = 1;
               }

               $sql  = "INSERT INTO ". $table ." SET ";
               $cond = "";
               $msg  = "Record successfully added";
            }

            if( $UserNameInUser )
            {
               $msg = "The username is already in use, please choose another one.";
            }
            else
            {
               $y = 0;
               foreach( $fields as $field )
               {
                  if( $y++ > 0 )
                  {
                     $sql .= ",";
                  }
                  $sql .= $field."='".$$field."' ";
               }
               $sql .= ", GroupId='".$SKAT_SESSION[groupid]."' ";
               $sql .= $cond;
            }
         }
         else
         {
            $sql = 0;
            $msg = "Record cannot be updated/inserted, because you did not fill in the required <b>UserId</b> field.";
         }
      }
   }

   if( $sql )
   {
      $result = processSQL($sql);
      if( ! $result )
      {
         $msg = "There was a problem in the mysql statement.";
      }
   }
   confirm($msg);
}


function  ImgKarte( $Id, $c, $fieldname )
{
   global $CONF;
   global $SKAT_SESSION;
   static $Blatt = 0;

   if( ! is_array(  $Blatt ) )
   {
      $Blatt = array( array() );
      $sql = "select * from " . $CONF['tbl_cards'];
      $result = processSQL( $sql );
      if (mysql_num_rows($result))
      {
         while($rows = mysql_fetch_array($result))
         {
            $Blatt[ $rows["Id"] ][ "Pfad" ] = $CONF['IMGROOT']."/". $rows[ "Pfad" ];
            $Blatt[ $rows["Id"] ][ "Name" ] = $rows[ "Name" ];
         }
      }
   }
   echo "<img class='Spielkarte' ";
   echo "rel='" . $Blatt[ $Id ][ "Pfad" ] . "' ";
   echo "alt='" . $Blatt[ $Id ][ "Name" ] . "' ";
   echo "onClick='toggle(\"$fieldname\",$c)' ";
   echo ">";
}

function sqlBestOfCategory($CategoryId, $limit = 100000 )
{
   global $CONF;
   global $SKAT_SESSION;
   $sql = "SELECT t1.CatId, t0.CatName, t2.SpielerId, t4.Name,
    ROUND(AVG(t2.Summe),2) AS PPL,  
    SUM(t2.Summe)  AS Gesamtpunkte, 
    SUM(t2.Gewonnen) AS gew,
    SUM(t2.Verloren) AS verl,
    ROUND(100 * SUM(t2.Gewonnen) / (SUM(t2.Gewonnen)+SUM(t2.Verloren)),2) 
    as 'Spieler u. gewonnen',  
    SUM( t1.CatId=$CategoryId ) AS SumListen, 
    COUNT(*)  AS Anzahl  FROM " . 
   $CONF['tbl_cat'].  " AS t0, " .
   $CONF['tbl_scoresheet'].  " AS t1, " .
   $CONF['tbl_column'] .     " AS t2, " .
   $CONF['tbl_player'] .    " AS t4
    WHERE   t1.CatId=$CategoryId  
    AND t2.SpiellisteId=t1.Id  
    AND t4.Id=t2.SpielerId 
    AND t2.SpielerId IN " .  sqlQualified( $CategoryId) .  "
    AND t0.GroupId=".$SKAT_SESSION[groupid]." 
    AND t0.Id=t1.CatId 
    GROUP BY  t4.Id  ORDER BY PPL DESC LIMIT $limit";
   return $sql;
}

function generateErfolgsquotenStatGrand( $CategoryId )
{
   generateErfolgsquotenStat( $CategoryId, array(24), ERFOLGSQUOTEGRAND );
}

function generateErfolgsquotenStatFarbe( $CategoryId )
{
   generateErfolgsquotenStat( $CategoryId, array(9,10,11,12), ERFOLGSQUOTEFARBSPIEL );
}

function generateErfolgsquotenStatNull( $CategoryId )
{
   generateErfolgsquotenStat( $CategoryId, array(23,46,35,49), ERFOLGSQUOTENULLSPIEL );
}


?>
Return current item: Skat Statistics