#!/usr/bin/perl
# CollapsedSubs: my_load_error_doc  my_read_CGI_input  ConnectToDB2  DisConnectFromDB  DB_query_prepare  DB_query_execute  format_decimal_places  round_average  SIT_escape_string  SIT_get_count  SIT_get_field_names  SIT_Show_News_Records  SIT_next_UNIQUE_db_ID  SIT_Create_New_Login_Record  do_user_login  get_news_search_form  get_number_of_players_in_division  get_number_of_hosts_in_division  get_number_of_teams_in_division  get_division_totals_content  get_divisions_in_session  get_division_info  get_session_info  get_info_current_session  get_active_sessions  get_active_divisions  get_player_info  get_team_info  select_team_form  create_temp_mvp_report_table  delete_temp_mvp_report_table  get_player_mvp_report  get_player_mvp_average  get_player_8ball_avergage  get_player_9ball_avergage  get_player_statistics_report  get_team_standings_report  show_hostroom_info  RetCal  verify_divsion  Default_Content  Default_Dir  get_News  get_Announcements  login_dir  main_HTML_login_doc  Main_HTML_Doc  Main_PRINTER_Doc
# start user configuration
################################################################################


my $CueSport;
my $Feature_Name = "$CueSport Pool League Statistics"; # soon to be assigned by db server data
my $Feature_Short_Name = "$CueSport Statistics";
my $Feature_Link_Name = "$CueSport Stats";

my %league_op_info;
$league_op_info->{League_ID} = "";
$league_op_info->{League_Name} = "SW Ontario CCS";
$league_op_info->{League_User_Path} = "sw_ontario_ccs";
$league_op_info->{League_DB_Name} = "swonccs";
$league_op_info->{League_DB_Driver} = "mysql";
$league_op_info->{League_DB_Host} = "bunjeecu.startlogicmysql.com";
$league_op_info->{League_DB_User} = "swoccsadmin";
$league_op_info->{League_DB_PSWD} = "swoccsplayer";
$league_op_info->{League_Import_ID} = "swontari";
$league_op_info->{League_Import_PSWD} = "bunjeeroy";

$league_op_info->{FName} = "Roy";
$league_op_info->{LName} = "Mason";
$league_op_info->{Address} = "137 Elgin Street N";
$league_op_info->{City} = "Cambridge";
$league_op_info->{State} = "Ontario";
$league_op_info->{Zip} = "N1R 5H6";
$league_op_info->{Phone_Number} = "519-622-0756";
$league_op_info->{Email} = "masonr\@golden.net";

my $report_header_color = "gold";
my $my_Images_folder = "/league-stats";
my $my_fora_logo = "sw-ontario-ccs-fora-logo.gif";
################################################################################
# end user configuration ---> Begin Main Exec
my $CalCMD = "/usr/bin/cal";
#####          All content delivered by this script is HTML
print "Content-type: text/html \n\n\r\n\r\n\r" unless ($content_type_printed);

#use CGI::Carp qw(fatalsToBrowser);
#comment out the above line when you're done debugging this script

my $selfURL = $ENV{SCRIPT_NAME};
#$selfURL = "/cgi-bin/bca-league-stats.pl";

my (@active_session_array,$session_info, $division_info, $team_info, @divisions_in_session, $global_city_counter);

$|++;	#dont't buffer output

# find out the OS
if ($^O eq 'MSWin32' || $ENV{'OS'} eq 'Windows_NT') {
      # this one for windows
      $windows = 'Yes';
      $slash = '\\';
}
else
{
      $windows = 'No';
      $slash = '/';
}
my @dirs = split("$slash",$ENV{SCRIPT_FILENAME});
shift(@dirs);
pop(@dirs);
my $uploaddir = "$slash" .join("$slash",@dirs) ."$slash";
#print "$uploaddir<BR>";
#load required perl modules or libraries
my $dbh;
my $site_params = "..$slash" ."admin$slash" ."params.pl";
eval {
        #use strict;
        use DBI;
        require $site_params;
};
#check for load errors
if ($@) { &my_load_error_doc($@);  exit(0); }

#load script dependent perl modules
my $online_mod = "$uploaddir$slash" ."lavail.pl";
#eval {
#        require $online_mod;
#};
#check for load errors or
$My_Feature_Online = 1;
if ($@)
{
    push(@error_messages,"We appologize for the inconvenience, but the league stats server is currently offline.<BR><BR>Possible Reasons:<BR> - The software is being updated, or<BR> - $@.");
    Main_HTML_Doc();
    exit(0);
}
elsif ($My_Feature_Online == 0)
{
	push(@error_messages,"We appologize for the inconvenience, but the league stats server is currently offline.<BR><BR>Possible Reasons:<BR> - The data is being updated, or<BR> - The last data import did not complete successfully.");
    Main_HTML_Doc();
    exit(0);
}
else
{
	ConnectToDB();
	my_read_CGI_input();

    if (defined ($data{CueSport}))
    {
        if ($data{CueSport} eq "9ball")
        {
        	$CueSport= "9-Ball";  #$CueSport = $data{CueSport};
        }
        else
        {
        	$data{CueSport}  = "8ball"; $CueSport= "8-Ball";
        }
    }
    else
    {
     	$data{CueSport} = "8ball"; $CueSport= "8-Ball";
    }

    $Feature_Name = "$CueSport Pool League Statistics"; # soon to be assigned by db server data
	$Feature_Short_Name = "$CueSport Statistics";
	$Feature_Link_Name = "$CueSport Stats";

	if ($data{Printable} eq "Yes")  {   Main_PRINTER_Doc();}
	else {  Main_HTML_Doc(); }

	DisConnectFromDB();
}
exit(0);
#End of main perl code

#Begin script integration subs, BDI subs, and general use subs
sub my_load_error_doc(){
    my($item) = shift;
    my $server = ($ENV{HTTP_HOST}) ? $ENV{HTTP_HOST}:'localhost';
    my $REQUEST_URI = $ENV{'SCRIPT_NAME'} ? $ENV{'SCRIPT_NAME'}:$0;
    $item =~ s/\]/\]<br>/g;
    $item =~ s/\(/<br>\(/g;
    $item =~ s/\)/\)<br>/g;
    $item =~ s/\bat\b/<br>at/g;
    my $error =  qq~Error loading required perl modules or libraries.
    <br>Check that the required perl modules or libraries exist and are
    located in the correct directory.
    <br>Reason:<br>$item
    ~;

    print qq~
    <HTML>
    <HEAD>
    <TITLE>Script Error</TITLE>
    </HEAD>

    <BODY BGCOLOR='#FFFFFF'>
    <CENTER>
    <TABLE border='0' cellpadding='0' cellspacing='1' width='98%' BGCOLOR='#990000'><TR><TD>
        <TABLE BORDER=0 WIDTH="100%" CELLSPACING=0 BGCOLOR='#ffffff' cellpadding=3>
              <TR>
                  <TD align="center" BGCOLOR='#990000'>
                      <TABLE><TR><TD>
                              <FONT color='#FFFFFF' face="Verdana,Arial,Helvetica" size=3>
                              <B>CGI Module Error</B></FONT>
                          </TD></TR>
                      </TABLE>
                  </TD>
	          </TR>
	          <TR>
                  <TD bgcolor="#ffeeee">
                      <FONT color='#000000' face="Verdana,Arial,Helvetica" size=3>
                          <P><B>The requested URL</B><BR>http://$server$REQUEST_URI</p>
                          <P><B>returned this error:</B><BR>
                     </FONT>
                     <FONT color='#000000' face="Verdana,Arial,Helvetica" size=2>$error </FONT></P>
                     <P>
                  </TD>
	          </TR>
	          <TR>
                  <TD BGCOLOR='#990000'>
                     <DIV align="center">
                       <FONT color='#ffffff' size=1 face="Verdana,Arial,Helvetica">
                               <B>Spark-IT SITe Myzer for Unix/Linux</B>
                       </FONT>
                   </DIV>
                  </TD>
	          </TR>
        </TABLE>
    </TD></TR></TABLE><BR>
    <P>
    </CENTER>
    </BODY></HTML>
       ~;
    exit(0);
}

sub my_read_CGI_input() {
    my($buffer) = undef;
    my($item);
    return(&SIT_read_CGI_input_multi_part()) if($ENV{'CONTENT_TYPE'} =~ /multi/i);

    if ($ENV{'REQUEST_METHOD'} =~ /POST/i) {
            read(STDIN,$buffer,$ENV{'CONTENT_LENGTH'});
    }
    else {
            $buffer=$ENV{'QUERY_STRING'};
    }
    $buffer = $ARGV[0]  if (not $buffer);

    my @pairs=split(/&/,$buffer);
    my $i = 0;
    foreach $item(@pairs) {
        my ($key,$content)=split (/=/,$item,2);    # Split into key and value.
        $content =~ tr/+/ /; # Convert plus's to spaces
        $content =~ s/%(..)/pack("c",hex($1))/ge;        # Convert %XX from hex numbers to alphanumeric
        # Convert %XX from hex numbers to alphanumeric when using hidden input tags
        $content =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
        $key =~ tr/+/ /; # Convert plus's to spaces
        $key =~ s/%(..)/pack("c",hex($1))/ge;        # Convert %XX from hex numbers to alphanumeric
        # Convert %XX from hex numbers to alphanumeric when using hidden input tags
        $key =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
        $key =~ s/ /_/g;

        # get rid of attempts to insert illegal characters
        $content =~ s/\\//g; # remove black slashes
        $content =~ s/\0//g; # remove nulls
        $content =~ s/[\\\&\;\`\'\"\|\*\~\^\[\]\{\}\$]//gs;
        # get rid of attempts to insert HTML tags
        $content =~ s/>/&gt;/gs;
        $content =~ s/</&lt;/gs;
        $content =~ s/\cM/\n/g;        #convert CR to LF
        $content =~ s/[\r\n]/ /g;
        $content =~ s/TRUNCATE/ /ig;
        $content = substr($content,0,4096);
        $content =~ s/^\s+|\s+$//gs;

        #make sure the email address is legal
        if(($content =~ m/\w\S+\@\w\S+\./) &&($key =~ /Email/i))
        {
                my $mail_to = $content;
                $mail_to =~ /([\w-.]+\@[\w-.]+)/;
                $content = $1;
        }

        if (!defined($data{$key})) {
                $data{$key}=$content;
        }
        else
        {
            if($key !~ /username/ and   $key !~ /password/ and $key !~ /RecordID/)
            {
                     $data{$key} .= ",$content" if($content ne "");
            }
        }

        if ($data{$key} =~ /action/) {
                $data{$key}=$content;
        }

        $CGI_input_names[$i]  = $key;
        $CGI_input_values[$i] = $content;

        $i++;
    }
    return 1;
}

sub ConnectToDB(){

    #%The name of the database driver your using. It can be mysql or any DBI:DBD driver
	my $dbdriver ="mysql";
	#%The URL to the database server, usually localhost, if the database server is on the same machine.
	my $dbserver ="mysql102.neureal.com";
	#%Access to your DBI::SQL Database will require that you supply your database name
	my $dbname ="spark-i_swontccs";
	#%Access to your DBI::SQL Database will require that you supply your database password
	my $dbpass = "bunjeeroy";
	#%Access to your DBI::SQL Database will require that you supply your database username
	my $dbuser ="spark-i_swontroy";

    $dbh = DBI -> connect("DBI:$dbdriver:$dbname:$dbserver", $dbuser, $dbpass);
	unless($dbh){
		push(@error_messages,"<p>Can't connect to  server.<p>Reason: $DBI::errstr");
        Main_HTML_Doc();
        DisConnectFromDB();
        exit();
	}
    @DB_Tables = $dbh->tables();
}

sub ConnectToDB2(){

	$dbh = DBI -> connect("DBI:$league_op_info->{League_DB_Driver}:$league_op_info->{League_DB_Name}:$league_op_info->{League_DB_Server}", "$league_op_info->{League_DB_User}", "$league_op_info->{League_DB_PSWD}");
    unless($dbh){
		push(@error_messages,"<p>Can't connect to  server.<p>Reason: $DBI::errstr");
        Main_HTML_Doc();
        DisConnectFromDB();
        exit();
	}
    @DB_Tables = $dbh->tables();
}

sub DisConnectFromDB(){
	if (defined $sth){ $sth->finish();}
	if(defined $dbh){
		$dbh->disconnect or die "Can't disconnect from database. Reason: $DBI::errstr" and undef $dbh;
	}
}

sub DB_query_prepare(){
    my $sth;
	my $dbquery = shift();
	unless ($sth = $dbh -> prepare($dbquery))
    {
    	push(@error_messages,"Query syntax error. $dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
	    DisConnectFromDB();
        Main_HTML_Doc();
	    exit(0);
    }
    return $sth;
}

sub DB_query_execute(){
	my $sth;
	my $dbquery = shift();
	unless ($sth -> execute())
    {
    	push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
	    DisConnectFromDB();
        Main_HTML_Doc();
	    exit(0);
    }
    return $sth;
}

sub format_decimal_places(){
	my $number = shift;
    my $decimal_places = shift;
    my ($integers, $decimals) = split(/\./,$number);
    my $answer;

    if (length($decimals)<$decimal_places)
    {
        my $temp_zeros;
        for (my $i=length($decimals); $i<$decimal_places; $i++)
        {
        	$temp_zeros .= "0";
        }
        $answer = "$integers\.$decimals$temp_zeros";
    }
    else
    {
    	$answer = "$integers\.$decimals";
    }

    return $answer;
}

sub round_average(){
	my $number = shift;
    my $decimal_places = shift;

    my $decimal_multiplier = $decimal_places+1;
    my $multiplier = 1;
    for (my $i = 0; $i < $decimal_multiplier; $i++)
    {
    	$multiplier = $multiplier * 10;
    }
    my $multiplied_number = int($number * $multiplier);

    my $mn_length = length($multiplied_number);
    my $digit = substr($multiplied_number,$mn_length-1,1);

    if ($digit >= 5)
    {
    	$multiplied_number = $multiplied_number+10;
    }
    my $new_number = int($multiplied_number/10);
    my $answer = ($new_number*10/$multiplier);

    #format answer
    $answer = &format_decimal_places($answer,1);

    return $answer;
}
#End script integration subs, BDI subs, and general use subs


#Begin app specific subs
sub SIT_escape_string {
    my($esc) = @_;
    $esc =~ s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
        $esc =~ s/ /+/g;
    return $esc;
}

sub SIT_get_count {
	my $dbtable = shift;
    my $rows = 0;
    my $dbquery = "SELECT COUNT(*) AS cnt_of_rows  FROM $dbtable";
    unless ($sth = $dbh -> prepare($dbquery))
    {
        push(@error_messages,"Query syntax error. $dbquery. Reason: $DBI::errstr.");
        return 0;
    }
    if (not $sth -> execute())
    {
        push(@error_messages,"Can't execute query:<br> $dbquery.<p><B>Reason:</B><BR>$DBI::errstr.");
        return 0;
    }
    ($rows) = $sth->fetchrow_array;
    $sth -> finish;
    return $rows;
}

sub SIT_get_field_names(){
        my @fields = ();
        my $dbtable = shift;
        if ($dbtable eq "")
        {
        	push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
	        $sth -> finish;
	        DisConnectFromDB();
	        Main_HTML_Doc();
	        exit(0);
        }
        my $sth = $dbh->prepare("DESC $dbtable");
        if (not $sth -> execute())
        {
        	push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
	        $sth -> finish;
	        DisConnectFromDB();
	        Main_HTML_Doc();
	        exit(0);
        }

        my $i = 0;
        my $row;
        while ($row = $sth->fetchrow_hashref())
        {
        	push(@fields,$row->{Field});
        	$i++;
        }
        $sth->finish;
        $DB_field_count = $i;

        return @fields;
}

sub SIT_Show_News_Records() {

    my $dbtable = shift;
    my $search_param = shift;

    my ($offset, $LIMIT, $SELECT, $links, $limit_records, $sort_order,
    $order_by, $html, $dbquery, $sth, $ref, $j, $key, $value, $max_rows,
    $rows, $where, $search_title);


    my $count = &SIT_get_count($dbtable);

    my @DB_field_names = &SIT_get_field_names($dbtable);

    my $fieldsort1 = &SIT_escape_string($data{fieldsort1});
    my $fieldsort2 = &SIT_escape_string($data{fieldsort2});

    my $keywords1 = &SIT_escape_string($data{keywords1});
    my $keywords2 = &SIT_escape_string($data{keywords2});

    my $sort_order = &SIT_escape_string($data{sort_order}) if($data{sort_order} ne "");

    my $params = "&offset=$data{offset}&max_rows=$data{max_rows}&fieldsort1=$fieldsort1&&fieldsort2=$fieldsort2&keywords1=$keywords1&keywords2=$keywords2&sort_order=$sort_order";
    $params .= "&action=" .&SIT_escape_string($data{action}) if($data{action} ne "");

    ##### The first row color (HTML) used for admin search results.
    $row_color1 = "#ffffff";
    #The second row color (HTML) used for admin search results.
    $row_color2 = "#F5F5F5";


    #### prepare query
    $limit_records = $MaxRecordsToShow ? $MaxRecordsToShow:5; ## set to 12 in params
    $limit_records = 7;

    $sort_order = "DESC";

    $max_length_to_show = $max_length_to_show ? $max_length_to_show:20;
    $Sort_Field = "RecordID" unless($Sort_Field);

    if($data{sort_order} ne "")
    {
            $sort_order = $data{sort_order};
    }

    $order_by = " ORDER BY $Sort_Field $sort_order" if($Sort_Field ne "");

    if($data{fieldsort1} ne "")
    {
            my $field = $data{fieldsort1};
            $order_by = " ORDER BY $field $sort_order";
    }

    ## WHERE
    if ((defined $data{fieldsort1}) || (defined $data{keywords1}))
    {
    	if($data{keywords1} eq "")
        {
	        push(@error_messages,"You need to enter a keyword to search with.");
	        DisConnectFromDB();
	        Main_HTML_Doc();
	        exit(0);
	    }

        if($data{fieldsort1} eq "")
        {
	    	push(@error_messages,"You need to select a field to sort the records by.");
            DisConnectFromDB();
	        Main_HTML_Doc();
	        exit(0);
	    }

	    my $keywords1 = "%" .$data{keywords1} ."%";
	    my $keywords1_q = $dbh -> quote($keywords1);
	    if ((defined $data{keywords2}) && ($data{keywords2}  ne ""))
	    {
	        my $keywords2 = "%" .$data{keywords2} ."%";
	        my $keywords2_q = $dbh -> quote($keywords2);
	        $where = " WHERE $data{fieldsort1} LIKE $keywords1_q AND $data{fieldsort2} LIKE $keywords2_q";
	    }
	    else
	    {
	        $where = " WHERE $data{fieldsort1} LIKE $keywords1_q";
	    }
        $search_title = "News Search Results";
    }
    else
    {
        if ($search_param eq "Announcement")
        {
            $search_title = "$league_op_info->{League_Name} Announcements";
            $where = " WHERE Article_Type LIKE 'Announcement'";
        }
        else
        {
            $search_title = "$league_op_info->{League_Name} News";
            $where = " WHERE Article_Type LIKE 'General'";
            $order_by
        }
        $order_by = "ORDER BY Date_Posted DESC";
    }

    my $max_rows = $data{'max_rows'};
    if ($max_rows <= 0){ ### Get result count
        my $dbquery = "SELECT * FROM $dbtable $where";
        my $sth = $dbh -> prepare($dbquery) or print "Query syntax error. $dbquery. Reason: $DBI::errstr.";
        if( not $sth -> execute())
        {
            push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
            $sth -> finish;
            DisConnectFromDB();
            Main_HTML_Doc();
            exit(0);
        }

        $data{'max_rows'} = $max_rows = $sth -> rows;
        $sth -> finish;
    }

    $offset  = $data{offset};
    $offset  = 0 if(($offset <= 0) || ($offset > $max_rows) || ($offset eq ""));
    $LIMIT   = " LIMIT $offset,$limit_records";
    $SELECT  = "SELECT * FROM $dbtable $where $order_by";
    $dbquery = $SELECT.$LIMIT;

    #### Query SOL for rows/records
    my $sth = $dbh -> prepare($dbquery) or print "Query syntax error. $dbquery. Reason: $DBI::errstr.";
    if( not $sth -> execute())
    {
    	push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
        DisConnectFromDB();
        Main_HTML_Doc();
        exit(0);
    }

    my $rows = $sth -> rows;
    if ($max_rows <=0) { $max_rows = $rows; }
    if ($rows <= 0)    { $sth -> finish; return "No records found matching your search parameters.";}
    #### Build page links in memmory if not rendering page for printing

    if($max_rows > $limit_records){
        my $params = "&max_rows=$max_rows";
        while(($key,$value)= each %data ){
            next if($key eq 'offset' || $key eq 'max_rows');
            $params  .= "&$key=" .&SIT_escape_string($data{$key});
        }

        $links = "Pages: ";
        my $num = int ($max_rows / $limit_records);
        my $rem = $max_rows % $limit_records;
        $num++ if($rem > 0);
        my ($lastpage,$lastnumber,$lastlink,$min,$max);

        if($num > 10){
            $min = (($data{offset} - (4 * $limit_records)) < 0) ? 0:($data{offset} - (4 * $limit_records));
            $max = (($data{offset} + (4 * $limit_records)) > $max_rows) ? $max_rows-$limit_records:($data{offset} + (4 * $limit_records));
            if ($data{offset} > 0){
                $links .= "<a href=\"$selfURL?offset=0$params\"> 1</a>...&nbsp;";
            }
            else{
                $links .= "1... &nbsp;";

            }
            $max = 9 * $limit_records if $max < 90;

            $lastpage = ($num-1) * $limit_records;
            $lastnumber = $num;
            $lastlink = "&nbsp;...<a href=\"$selfURL?offset=$lastpage$params\"> $lastnumber</a>&nbsp;";
            $lastlink = "&nbsp;...$lastnumber &nbsp;" if($data{offset} == $lastpage);
            $min = ($lastpage - (9 * $limit_records)) if($min > $lastpage - (9 * $limit_records));
        }
        for($i=0; $i<$num; $i++){
            my $c = $i * $limit_records;
            my $ix = $i +1;
            if($num > 10 ){
                next if $i == 0;
                next if $c == $lastpage;
                if($c == $max){
                    $links .= "<a href=\"$selfURL?offset=$c$params\"> $ix</a>&nbsp;";
                }
                if($c == $min){
                    $links .= "<a href=\"$selfURL?offset=$c$params\"> $ix</a>&nbsp;";
                }
                if($c == $data{offset} && $data{offset} > 0){
                    $links .= " $ix&nbsp;";
                }
                else{
                    if(($c > $min) && ($c <  $max)){
                        $links .= "<a href=\"$selfURL?offset=$c$params\"> $ix</a>&nbsp;";
                    }
                }
            }
            else{
                if($c == $offset){
                    $links .= " $ix&nbsp;";
                }
                else{
                    $links .= "<a href=\"$selfURL?offset=$c$params\"> $ix</a>&nbsp;";
                }
            }
        }
        if($num > 10){
            $links .= $lastlink;
        }
    }
    $my_page_links = qq~<TR><td colspan="3" style="background-color:$second_table_bgcolor;">$links &nbsp;</td></TR>\n~;


    ##### output the record/rows table starting with
    ##### the page links row & list index column hdr

    my $html =qq~
    	<TABLE width="95%">
        	<TR>
	            <TD align="left" style="font-size:10pt;" valign="bottom" width="15%">
	                $news_link
	            </TD>
	            <TD align="center"  style="font-size:14pt;"  valign="middle" width="70%">
	                <B>$search_title</B>
	            </TD>
	            <TD align="right"  style="font-size:10pt;" valign="bottom" width="15%">
	                $announce_link
	            </TD>
            </TR>
            $my_page_links
    ~;
    ##### output the table rows (data)

    my $listIndex = 1;
    while(my $sku_ref = $sth->fetchrow_hashref())
    {
        my $color = $row_color1;
        if ($listIndex % 2) {$color = $row_color2; }
        ##### output in mem a line reference number for this record
        $html .=qq~
        <TR style=" border-style:ridge; border-width:2px; border-color:red; background-color:$report_header_color; color:black; height:30px; ">
            <TD colspan=2 style="font-size:10pt;"><B>&nbsp;$sku_ref->{Headline}</B>
            </TD>
            <TD  style="font-size:8pt;">Date Posted:<BR>$sku_ref->{Date_Posted}
            </TD>
        </TR>
        <TR>
            <TD colspan=3 style="font-size:10pt;" style="background-color:$color">
                $sku_ref->{Subheading}
                <DIV style="font-size:8pt;">
                    $sku_ref->{Content}<BR>-<I>$sku_ref->{Author}</I>
                </DIV>
            </TD>
        </TR>
        ~;
        $listIndex++;
    }
    $sth -> finish;
    ##### output the table page links
    $html .= qq!$my_page_links</TABLE>\n!;

    return $html; #$rows;
}

sub SIT_next_UNIQUE_db_ID(){
	my $db_table_name = shift;
    my $db_table = $dbtable;
    my $this_unique_id_field = $my_unique_id_field;
    $db_table = $db_table_name if ($db_table_name ne "");

    # Use this function to increment repair ticket number,
    # sales order number, fulfillment number, invoice number,
    # login number, signon number, etc
    my $random_Inc = 1; # Default increment value
    if (($db_table =~ m/login/g) || ($db_table eq "catalog_sessions") || ($db_table eq "Sign-Up"))
    {
        # This code for signons and logins only;
        $this_unique_id_field = "Login_ID"  if ($db_table eq "login");
        $this_unique_id_field = "Session_ID" if ($db_table eq "catalog_sessions");
        # It sets random increment value to keep longin #'s
        # non-sequential for security reasons
        $random_Inc = int(rand(127) + 127);
    }
    # Check for data directory: if not exist, create
    my $data_folder = "$ENV{DOCUMENT_ROOT}/../cgi-bin/sit_data";
    unless (-d "$data_folder")
    {
    	unless (mkdir "$data_folder")
        {
        	push(@error_messages,"Can't create data folder:<BR>$data_folder<BR><B>Reason: </B>$!.");
	        $sth -> finish;
	        main_HTML_login_doc();
	        DisConnectFromDB();
	        exit(0);
        }
    }
    my $Unique_number;
    $num_file_name = "$this_unique_id_field.num";

    use Fcntl qw(:DEFAULT :flock);
    # To DO: Change die() calls into standard output print() using unless()
    sysopen(NUMBER, "$data_folder/$num_file_name", O_RDWR | O_CREAT) or die "can't open $num_file_name file: $!";

    $ofh = select(NUMBER); $| = 1; select ($ofh);
    flock(NUMBER, LOCK_EX) or die "can't write-lock $num_file_name file: $!";

    chomp($Unique_number = <NUMBER>) || 0;

    seek(NUMBER, 0, 0) or die "can't rewind $num_file_name file : $!";
    print NUMBER $Unique_number+$random_Inc, "\n"  or die "can't write $num_file_name file: $!";

    truncate(NUMBER, tell(NUMBER))  or die "can't truncate $num_file_name file: $!";
    close(NUMBER) or die "can't close $num_file_name file: $!";

    $Unique_number =~ s/\n//g;
    $Unique_number =~ s/\r//g;
    $Unique_number = int($Unique_number);
    return $Unique_number;
}

sub SIT_Create_New_Login_Record(){
    my $tempDBfields = join(",",&SIT_get_field_names("League_Users"));
    my $temp_field_name;
    my $field_values_list = qq~''~;   #  <<-----####  First value of record field values array is null for auto_increment
    my $log_data = "[$data{Login}]"; #  <<-----####  $data{Target} pre-assigned by next_UNIQUE_db_ID
    my $f_Index = 0;
    foreach $temp_field_name (@DB_field_names)
    {
            if (($f_Index > 0) && (defined $data{$temp_field_name}) && ($data{$temp_field_name} ne ""))
            {
                    $field_values_list .= qq~,\'$data{$temp_field_name}\'~;
                    $log_data .= qq~,[$data{$temp_field_name}]~;
            }
            elsif ($f_Index > 0)
            {
                    $field_values_list .= qq~,\'\'~;
                    $log_data  .= qq~,[]~;
            }
            $f_Index++;
    }

    $dbquery = qq~INSERT INTO $dbtable ($tempDBfields) VALUES ($field_values_list)~;
    &DB_query_execute($dbquery);
    $sth -> finish();


}

sub do_user_login(){
    my $TempUser = $data{ID};
	my $TempPass = $data{Pass};
    my $LOGIN; my $html;
    my $sth;
    my $my_db_query = qq~SELECT * FROM League_Users WHERE User_ID LIKE '$TempUser' LIMIT 1~;
    unless ($sth = $dbh -> prepare($my_db_query))
    {
        push(@error_messages,"Query syntax error. $dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
        $data{cmd} = $data{cmd2};
        return main_HTML_login_doc();
    }
    unless ($sth -> execute())
    {
        push(@error_messages,"Can't execute Sign On:<BR>Reason: $DBI::errstr.");
        $sth -> finish;
        $data{cmd} = $data{cmd2};
        return main_HTML_login_doc();
    }
    my $rows = $sth->rows;
    if ($rows == 1)
	{
    	while ( my $record_hashref = $sth->fetchrow_hashref())
   		{
        	if ($record_hashref->{Web_Pass} eq $TempPass)
	        {
                $data{Login}       = $LOGIN = &SIT_next_UNIQUE_db_ID("League_Users");
                $data{Expired}     = "0";
                $data{Web_ID}      = $data{ID};
                $data{Login_Date}  = $my_Login_Date;
                $data{Last_Access} = $my_Last_Access_TIMESTAMP;
                $data{Last_Action} = "Logged In";
                $data{Remote_IP}   = $ENV{REMOTE_ADDR};
                $data{Remote_Name} = $ENV{REMOTE_HOST};

                print "creating login record..<br>";
                &SIT_Create_New_Login_Record();

                if ($data{type} eq "RepLogin")
	        	{
                    $html = qq~
	                    <BR>
	                    Signing on, please wait $rows...
	                    <DIV style="">
	                        <FORM name="transferForm" method="POST" action="$my_WS_HTTPS_URL/league-user-access.pl">
	                            <INPUT type="hidden" name="login"  value="$LOGIN">
	                            <INPUT type="submit" name="Submit" value="Submit">
	                        </FORM>
	                    </DIV>
	                    <SCRIPT language="JavaScript"><!--

	                    //function start(){
	                        setTimeout("go()", 5000);
	                    //}

	                    function go(){
	                        if (document.transferForm)
	                        {
	                            document.transferForm.submit();
	                        }
	                    }

	                    //--></SCRIPT>

	                ~;

	            }
                elsif ($data{type} eq "OpLogin")
                {
                	$html = qq~
	                    <BR>
	                    Welcom Operator! Signing on, please wait $rows...
	                    <DIV style="">
	                        <FORM name="transferForm" method="POST" action="$my_WS_HTTPS_URL/league-user-access.pl">
	                            <INPUT type="hidden" name="login"  value="$LOGIN">
	                            <INPUT type="submit" name="Submit" value="Submit">
	                        </FORM>
	                    </DIV>
	                    <SCRIPT language="JavaScript"><!--

	                    //function start(){
	                        //setTimeout("go()", 5000);
	                    //}

	                    function go(){
	                        if (document.transferForm)
	                        {
	                            document.transferForm.submit();
	                        }
	                    }

	                    //--></SCRIPT>

	                ~;
                }
	        }
	        else
	        {
	            # User ID found, Password bad
	            $gen_err_title = "<FONT color='#990000'><B>Attempt Failed</B></FONT>";
	            $Password_Error_msg = "<FONT color='#990000'><B>Bad Password.</B></FONT>";
	            $sth->finish;
	            $data{cmd} = $data{cmd2};
	            return main_HTML_login_doc();
	        }
	    }
    }
    else
    {
	    # User ID not found
	    $gen_err_title = "<FONT color='#990000'><B>Attempt Failed</B></FONT>";
	    $ID_Error_msg = "<FONT color='#990000'><B>Bad ID.</B></FONT>";
	    $sth->finish;
	    $data{cmd} = $data{cmd2};
	    return main_HTML_login_doc();
    }
    $sth->finish;


    if ($rows == 1)
    {

    }
    else
    {

    }
    return $html;
}

sub get_news_search_form(){

    foreach(&SIT_get_field_names("League_News")){
        $x = $_;
        $x =~ s/_/ /g;
        $sort1 .= "<option value=\"$_\">$x<\/option>\n";
    }


	my $html=qq~
        <SCRIPT language="JavaScript"><!--

	    var TempBkgColor, AN, MySQL_query;
	    MySQL_query ="$params";
	    AN = "$AN";

	    function verifyMe$AN(){
	        var A = document.SearchForm.keywords1.value;
	        var B = document.SearchForm.fieldsort1.value;
	        if ((A == "") || (B == ""))
	        {
	            alert("Search Parameters?");
	            return;
	        }
	        else
	        {
	            var C = document.SearchForm.keywords2.value;
	            var D = document.SearchForm.fieldsort2.value;
	            if ((C != "") && (D == ""))
	            {
	                alert("Search Parameters?");
	                return;
	            }
                document.SearchForm.submit();
            }
	    }
        //-->
        </SCRIPT>
        <FORM name="SearchForm" action="$selfURL" method="POST">
        <TABLE>
            <TR>
                <TD align="left" valign="top" >
                	<DIV align="center" style="font-size:10pt;"><B>Search<BR>$league_op_info->{League_Name}<BR>League News!<?B></DIV><BR>
                    <DIV style="font-family:Verdana,Arial,Helvetica; font-size:10pt">

                        <input type="hidden"  name="login"     value="$LOGIN">
                        <INPUT type="hidden"  name="AN"        value="$AN">
                        <INPUT type="hidden"  name="cmd"       value="SearchNews">
                        Search for:<BR>
                        <input type="text"    name="keywords1" value="$data{keywords1}" size="20">
                        in: <select name="fieldsort1">
                                <option value="" selected>Search field 1</option>
                                $sort1
                        </select>
                    </DIV>

                    <DIV style="font-family:Verdana,Arial,Helvetica; font-size:10pt">
                    	 <BR>
                         Search for:<BR>
                         <input type="text"  name="keywords2" value="$data{keywords2}" size="20">
                         in: <select name="fieldsort2">
                                 <option value="" selected>Search field 2</option>
                                 $sort1
                         </select>
                    </DIV>

                    <DIV style="font-family:Verdana,Arial,Helvetica; font-size:10pt">
                    	<BR>
                        &nbsp;Desc <input type="radio" name="sort_order" value="desc" checked>
                        &nbsp;&nbsp;Asc<input type="radio" name="sort_order" value="asc">
                        <br><br>
                        <input type="button" value="Search" name="searchBTN" onClick="verifyMe$AN();">
                        <NOSCRIPT><FON color="#ff0000">Reqires JavaScript</FONT></NOSCRIPT>
                    </DIV>
                </TD>
            </TR>
        </TABLE>
        </FORM>
	~;
    return $html;
}

sub get_number_of_players_in_division(){
    #select distinct players
    my $session = shift;
    my $division= shift;

	my $dbquery = qq~SELECT DISTINCT Member_Id
    FROM Team_Rosters
    WHERE Session LIKE '%$session%' AND Division LIKE '%$division%'
    ORDER BY Member_Id
    ~;
    my $sth = &DB_query_prepare($dbquery);
    my @players = ();
	if( not $sth -> execute())
	{
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
	    DisConnectFromDB();
	}
    my $female_players = 0;
    while (my $sku_ref= $sth->fetchrow_hashref())
    {
    	push(@players,$sku_ref->{Member_Id});
        my $player_info = get_player_info($sku_ref->{Member_Id});
        if ($player_info->{Gender} eq "Female")
        {
        	$female_players++;
        }
    }
    my $rows = $sth->rows;
    $sth->finish();
    return $rows, $female_players; #@players;
}

sub get_number_of_hosts_in_division(){
    #select distinct players
    my $session = shift;
    my $division= shift;
    my $hosts_found = 0;
    my @hosts=();
    my @found_cities1=();
    #print "@teams<BR>";

    my $dbquery = qq~SELECT DISTINCT Host_Name
    FROM Teams
    WHERE Session LIKE '$session' AND Division LIKE '$division'
    ORDER BY Host_Name
    ~;
    my $sth1 = &DB_query_prepare($dbquery);

    if( not $sth1 -> execute())
    {
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth1 -> finish;
        DisConnectFromDB();
    }
    while (my $sku_ref1= $sth1->fetchrow_hashref())
    {
        #query this host record
        #get host info?
        my $dbquery2 = qq~SELECT *
	    FROM Host_Rooms
	    WHERE Id = '$sku_ref1->{Host_Name}' LIMIT 1
	    ~;
	    my $sth2 = &DB_query_prepare($dbquery2);

	    if( not $sth2 -> execute())
	    {
	        push(@error_messages,"Can't execute query:<BR>$dbquery2. Reason: $DBI::errstr.");
	        $sth2 -> finish;
	        DisConnectFromDB();
	    }

	    while (my $sku_ref2 = $sth2->fetchrow_hashref())
	    {
            push(@found_cities1, $sku_ref2->{City});
            push(@hosts,$sku_ref2->{Id});
        }
	    $sth2->finish();
    }
    my $rows = $sth1->rows;
    $sth1->finish();


    my @found_cities2;
    foreach my $city1 (@found_cities1)
    {
        my $found = 0;
        foreach my $city2 (@found_cities2)
        {
            if ($city2 eq $city1)
            {
            	$found = 1;
            }
        }
        push(@found_cities2,$city1) if (($found == 0) && ($city1 ne ""));
    }
    $hosts_found =  @hosts;
    $global_city_counter = @found_cities2;

    #print "@hosts<BR>";
    return $hosts_found, @hosts;

}

sub get_number_of_teams_in_division(){
    #select distinct players
    my $session = shift;
    my $division= shift;
	my $dbquery = qq~SELECT DISTINCT Team
    FROM $data{CueSport}_Standings
    WHERE Session LIKE '$session' AND Division LIKE '$division'

    ~;
    my $sth = &DB_query_prepare($dbquery);
    @teams = ();
	if( not $sth -> execute())
	{
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
	    DisConnectFromDB();
	}
    while (my $sku_ref= $sth->fetchrow_hashref())
    {
    	push(@teams,$sku_ref->{Team});
    }
    my $rows = $sth->rows;
    $sth->finish();
    return $rows, @teams;
}

sub get_division_totals_content(){
    #in current session, get distinct divisions
    my @divisions = &get_divisions_in_session($session_info->{Session});
    my $no_of_divisions = @divisions;
    my $total_players=0;
    my $total_females=0;
    my $total_hosts=0;
    my $total_teams=0;
    my $total_cities;

    my $html = qq~
        <DIV style="font-size:12pt;"><B>$session_info->{Session} $CueSport Dynamics</B></DIV>
    	<TABLE width="100%" border="0" bgcolor="$second_table_bgcolor">
	        <TR  style='background-color:$report_header_color'>
	            <TD align="center" style="font-size:10pt;">
	                <B>&nbsp;Divisions ($no_of_divisions)</B>
	            </TD>
                <TD align="center" style="font-size:10pt;">
                	<B>&nbsp;# of<BR>Cities</B>
	            </TD>
	            <TD align="center" style="font-size:10pt;">
                	<B>&nbsp;# of<BR>Hosts</B>
	            </TD>
	            <TD align="center" style="font-size:10pt;">
                	<B>&nbsp;# of<BR>Teams</B>
	            </TD>
                <TD align="center" style="font-size:10pt;">
                	<B>&nbsp;# of<BR>Players</B>
	            </TD>
                <TD align="center" style="font-size:10pt;">
                	<B>&nbsp;# of<BR>Ladies</B>
	            </TD>
	        </TR>
    ~;

    my $i=0;
    foreach my $my_division_info (@divisions)
    {
         #do each query
	     my ($players_in_division, $females_in_division) = &get_number_of_players_in_division($session_info->{Session},$my_division_info->{Division_Name});

         if ($players_in_division > 0)
         {
         	$total_players = $total_players + $players_in_division;
	        $total_females = $total_females + $females_in_division;

	        my $teams_in_division = &get_number_of_teams_in_division($session_info->{Session},$my_division_info->{Division_Name});
	        $total_teams = $total_teams + $teams_in_division;

	        my $hosts_in_division = &get_number_of_hosts_in_division($session_info->{Session},$my_division_info->{Division_Name});
            $total_hosts = $total_hosts + $hosts_in_division;

            my $cities = $global_city_counter;
            $total_cities = $total_cities + $cities;

	        my $total_lady_players;
	        my $td_color = $row_color1;
	        if ($i % 2) {$td_color = $row_color2; }
	        $html .= qq~
	            <TR style='background-color:$td_color;'>
	                <TD align="left" style="font-size:10pt;">
	                    &nbsp;$my_division_info->{Division_Name}
	                </TD>
	                <TD align="right" style="font-size:10pt;">
	                    $cities &nbsp;&nbsp;
	                </TD>
	                <TD align="right" style="font-size:10pt;">
	                    <A href="$selfURL?CueSport=$data{CueSport}&cmd=ShowHosts&Session=$session_info->{ID}&Division=$my_division_info->{Division_ID}" title="View Host List">$hosts_in_division</A> &nbsp;&nbsp;
	                </TD>
	                <TD align="right" style="font-size:10pt;">
                    	$teams_in_division &nbsp;&nbsp;
	                    <!--<A href="$selfURL?cmd=ShowTeams&Session=$session_info->{ID}&Division=$my_division_info->{Division_ID}" title="View Team Roster">$teams_in_division</A> &nbsp;&nbsp;-->
	                </TD>
	                <TD align="right" style="font-size:10pt;">
	                    $players_in_division &nbsp;&nbsp;
	                </TD>
	                <TD align="right" style="font-size:10pt;">
	                    $females_in_division &nbsp;&nbsp;
	                </TD>
	            </TR>
	        ~;
         }
	        $i++;

    }

    $html .= qq~
            <TR style='background-color:$second_table_bgcolor;'>
	            <TD align="right" style="font-size:10pt;"><B>League Totals:</B>
	            </TD>
                <TD align="right" style="font-size:10pt;">
                	<!--$total_cities &nbsp;&nbsp;-->
	            </TD>
	            <TD align="right" style="font-size:10pt;">
                	$total_hosts &nbsp;&nbsp;
	            </TD>
	            <TD align="right" style="font-size:10pt;">
                	$total_teams &nbsp;&nbsp;
	            </TD>
                <TD align="right" style="font-size:10pt;">
                	$total_players &nbsp;&nbsp;
	            </TD>
                <TD align="right" style="font-size:10pt;">
                	$total_females &nbsp;&nbsp;
	            </TD>
	        </TR>
    	</TABLE>
    ~;

    return $html;
}

sub get_divisions_in_session() {

	my $session = shift;
	my $dbquery = qq~SELECT DISTINCT Division FROM $data{CueSport}_Standings WHERE Session LIKE '%$session%' ORDER BY Division ~;
    my $sth = &DB_query_prepare($dbquery);
    my @divisions=();

	if( not $sth -> execute())
	{
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
	    DisConnectFromDB();
	}
    while (my $sku_ref= $sth->fetchrow_hashref())
    {
    	push(@divisions,$sku_ref->{Division});
    }
    $sth->finish();

    my @active_divisions_hash_array = ();
    foreach my $division (@divisions)
    {
        my $dbquery = qq~SELECT * FROM $data{CueSport}_Divisions WHERE Division_Name LIKE '%$division%' LIMIT 1 ~;
        my $sth = &DB_query_prepare($dbquery);
        if( not $sth -> execute())
        {
            push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
            $sth -> finish;
            DisConnectFromDB();
        }
        while (my $sku_ref= $sth->fetchrow_hashref())
        {
            push(@active_divisions_hash_array,$sku_ref);
        }

        $sth->finish();
    }
    return @active_divisions_hash_array;
}

sub get_division_info(){
	my $division_id = shift();
	my %my_division_info;
	my $dbquery = qq~
    SELECT * FROM $data{CueSport}_Divisions WHERE Division_ID = "$division_id" LIMIT 1
    ~;
    #print "Division Query: $dbquery<BR>";
    my $sth = &DB_query_prepare($dbquery);
	if (not $sth -> execute())
	{
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
	    DisConnectFromDB();
	}
    if (my $sku_ref = $sth->fetchrow_hashref())
	{
    	$my_division_info = $sku_ref;
	}
    $sth->finish();
    return $my_division_info;
}

sub get_session_info(){
    my $session_id = shift();
	my %my_session_info;
	my $dbquery = qq~
    SELECT * FROM $data{CueSport}_Sessions WHERE ID ="$session_id" LIMIT 1
    ~;


    #print "Session Query: $dbquery<BR>";
    my $sth = &DB_query_prepare($dbquery);
	unless ($sth -> execute())
	{
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
	    DisConnectFromDB();
	}
    if (my $sku_ref = $sth->fetchrow_hashref())
	{
    	$my_session_info = $sku_ref;
	}

    $sth->finish();
    return $my_session_info;
}

sub get_info_current_session(){
	my %my_session_info;
	my $dbquery = qq~
    SELECT DISTINCT ID
    FROM $data{CueSport}_Sessions
    WHERE ID > 0 AND Hide_Session LIKE "%FALSE%"
    ORDER BY ID DESC LIMIT 1
    ~;
    #print "Session Query: $dbquery<BR>";
    my $sth = &DB_query_prepare($dbquery);
	unless ($sth -> execute())
	{
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
	    DisConnectFromDB();
	}
    if (my $sku_ref = $sth->fetchrow_hashref())
	{
        $session_info = &get_session_info($sku_ref->{ID});
	}

    $sth->finish();
    return $my_session_info;
}

sub get_active_sessions(){

	@active_session_array = ();
    # start build HTML form
    my $session_form = qq~
    	<B>Session:</B><BR>
        <SELECT name="Session">
        <OPTION value="">Choose:</OPTION>
        ~;

	my $LIMIT = 3;
    $LIMIT = 2 if ($data{CueSport} eq "9ball");
    #WHERE Hide_Session LIKE 'False'
	my $dbquery = qq~SELECT * FROM $data{CueSport}_Sessions ORDER BY ID DESC LIMIT $LIMIT~;
    my $sth = &DB_query_prepare($dbquery);
	if( not $sth -> execute())
	{
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
	    DisConnectFromDB();
	}

    my $rows_found_here = $sth->rows();

    while(my $sku_ref=$sth->fetchrow_hashref())
	{
        my $session_hashref;

	    push(@my_sessions,$sku_ref->{Session});

	    $session_hashref->{Session} = $sku_ref->{Session};
	    $session_hashref->{ID} = $sku_ref->{ID};
	    push(@active_session_array,$sku_ref);
	    $session_form .= qq~
	    <OPTION value="$sku_ref->{ID}">$sku_ref->{Session}</OPTION>
	    ~;

	}
    $sth->finish();
    #my $waste = shift(@active_session_array);
    # finish build HTML form
    $session_form .= qq~
    </SELECT>
    ~;
    return $session_form;
}

sub get_active_divisions(){
	#delete this sub?
    @active_division_array = ();
    # start build HTML form
    my $division_form = qq~
    	<B>Division:</B><BR>
        <SELECT name="Division">
        <OPTION value="">Choose:</OPTION>
        ~;

	my $dbquery = qq~SELECT * FROM $data{CueSport}_Divisions WHERE Hide_Division LIKE '%FALSE%' ORDER BY Division_Name ~;
    my $sth = &DB_query_prepare($dbquery);
	if( not $sth -> execute())
	{
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
	    DisConnectFromDB();
	}
    while(my $sku_ref=$sth->fetchrow_hashref())
	{
        if ($sku_ref->{Hide_Division} == 0)
        {
           push(@all_my_active_divisions,$sku_ref->{Division_ID});
           push(@active_division_array,$sku_ref);
	       $division_form .= qq~
	       <OPTION value="$sku_ref->{Division_ID}">$sku_ref->{Division_Name}</OPTION>
	       ~;
        }

	}
    $sth->finish();

    # finish build HTML form
    $division_form .= qq~
    </SELECT>
    ~;
    return $division_form, ;
}

sub get_player_info(){
	my $player = shift();
    my %my_player_info;
	my $dbquery = qq~
    SELECT * FROM Players WHERE Member_ID LIKE "$player" LIMIT 1
    ~;
    my $sth = &DB_query_prepare($dbquery);
	unless ($sth -> execute())
	{
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
	    DisConnectFromDB();
	}
    while (my $sku_ref = $sth->fetchrow_hashref())
	{
    	$my_player_info = $sku_ref;
	}
    $sth->finish();
    return $my_player_info;
}

sub get_team_info(){
	my $team = shift();
    my %my_team_info;
	my $dbquery = qq~
    SELECT * FROM Teams WHERE ID LIKE "$team" LIMIT 1
    ~;
    my $sth = &DB_query_prepare($dbquery);
	unless ($sth -> execute())
	{
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
	    DisConnectFromDB();
	}
    while (my $sku_ref = $sth->fetchrow_hashref())
	{
    	$my_team_info = $sku_ref;
	}
    $sth->finish();
    return $my_team_info;
}

sub select_team_form(){

    my $html = qq~
    <DIV align="center" style='font-size:16pt; color:#0000FF'>
    	<B>$division_info->{Division_Name}<BR>
        $session_info->{Session}</B>
        <!--<BR><BR><FONT style='font-size:14pt; color:#990000;'>Reports temporarily unavailable.</FONT>-->
    </DIV>
    ~;

    #return $html;

    my $dbquery = qq~
    SELECT DISTINCT $data{CueSport}_Standings.Team, Teams.Team_Names
    FROM $data{CueSport}_Standings INNER JOIN Teams ON ($data{CueSport}_Standings.Team = Teams.ID)
    WHERE $data{CueSport}_Standings.Division LIKE "%$division_info->{Division_Name}%" AND $data{CueSport}_Standings.Session LIKE "%$session_info->{Session}%"
    ORDER BY Teams.Team_Names
    ~;

    my $sth = &DB_query_prepare($dbquery);
	if( not $sth -> execute())
	{
        $html = qq~</TABLE>~;
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
	    DisConnectFromDB();
	}

    my $rows_found =  $sth->rows;

    my @team_options;
    my @team_links;
    my $i = 0;
    while(my $sku_ref1 = $sth->fetchrow_hashref())
	{
        my $team_info = &get_team_info($sku_ref1->{Team});
        my $color = $row_color1;
        if ($i % 2) {$color = $row_color2; }

        push(@team_options,qq~<OPTION value='$team_info->{ID}'>$team_info->{Team_Names} | $team_info->{Coined_Name}</OPTION>~);
        push(@team_links,qq~<TR style='background-color:$color;'><TD align='left' width='50%'><A href='$selfURL?CueSport=$data{CueSport}&cmd=GetStatsRpt&Session=$data{Session}&Division=$data{Division}&Team_ID=$team_info->{ID}'>$team_info->{Team_Names}</A></TD><TD align='left' width='50%'>$team_info->{Coined_Name}</TD></TR>~);
        $i++;
    }
    $sth->finish;



    $html .= qq~
    <DIV align="center">
	    <H3>Please select a team for player statistics:</H3>
        <TABLE width="65%">
	        <TR background-color=$report_header_color>
	            <TD width="50%">
	                <DIV align=center style=" border-style:ridge; border-width:2px; border-color:red; background-color:$report_header_color; color:black; height:25px;">
	                    Team
	                </DIV>
	            </TD>
	            <TD width="50%">
	                <DIV align=center style=" border-style:ridge; border-width:2px; border-color:red; background-color:$report_header_color; color:black; height:25px;">
	                    Coined Name
	                </DIV>
	            </TD>
	        </TR>
	        <TR>
	            <TD width="50%">
	                <img src='$my_Images_folder/spacer.gif' width='200px' height='1' border='0'>
	            </TD>
	            <TD width="50%">
	                <img src='$my_Images_folder/spacer.gif' width='200px' height='1' border='0'>
	            </TD>
	        </TR>
        	@team_links
        </TABLE>
    </DIV>
    ~;
    return $html;
}

sub create_temp_mvp_report_table(){
	my $tbl_no = &SIT_next_UNIQUE_db_ID("TempMvp");
    my $tempMvpTbl = "TempMvp_$tbl_no";

    my $table_def = qq~
    	(RecordID INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
        Player VARCHAR(40),
        Avg DECIMAL(3,2),
	    Weeks INT(11))
    ~;
    my $dbquery = qq~CREATE TABLE $tempMvpTbl $table_def~;
    my $sth = &DB_query_prepare($dbquery);
    unless ($sth -> execute())
    {
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
        DisConnectFromDB();
    }
    $sth -> finish;
    #print "Temp MVP table '$tempMvpTbl' created. Processing report...<BR>";
    return "$tempMvpTbl";
}


sub delete_temp_mvp_report_table(){
	my $table = shift;
    my $dbquery = qq~DROP TABLE $table~;
    my $sth = &DB_query_prepare($dbquery);
    unless ($sth -> execute())
    {
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
        DisConnectFromDB();
    }
    $sth -> finish;
    #print "Temp MVP table deleted.<BR>";
}

sub get_player_mvp_report(){
	my $html = "<H3 align=center>$division_info->{Division_Name} $session_info->{Session}<BR>MVP Report</H3>";
    my $temp_rpt_tbl = create_temp_mvp_report_table();

    if ($data{CueSport} eq "9ball")
    {
        #push(@error_messages,"Can't display report: 9-Ball Player MVP Report.<BR>Reason: Database interface temporarily off-line.");
        #return;
    }

    my @teamsRetreived=();

    #get distinct teams in session
    $teams_dbquery = qq~
    SELECT DISTINCT $data{CueSport}_Standings.Team, Teams.Team_Names
    FROM $data{CueSport}_Standings INNER JOIN Teams ON ($data{CueSport}_Standings.Team = Teams.ID)
    WHERE $data{CueSport}_Standings.Division = "$division_info->{Division_Name}" AND
    $data{CueSport}_Standings.Session = "$session_info->{Session}"
    ORDER BY Teams.ID DESC
    ~;

    #print "$teams_dbquery<BR>";

    my $teams_sth = &DB_query_prepare($teams_dbquery);
    unless ($teams_sth -> execute())
    {
        push(@error_messages,"Can't execute query:<BR>$teams_dbquery. Reason: $DBI::errstr.");
        $teams_sth -> finish;
        DisConnectFromDB();
    }
    # for each unique team in Division and Session, select distinct Member_Id
    my ($player_mvp_avg, $countOfWeeks);
    my $i = 0;$pt=0;
    my @myMvpPlayers = ();

    while(my $teams_sku_ref = $teams_sth->fetchrow_hashref())
    {
    	push(@teamsRetreived,$teams_sku_ref->{Team});

    }
    $teams_sth->finish();

    #print "@teamsRetreived<BR>";

    foreach my $Team (@teamsRetreived)# while(my $teams_sku_ref = $teams_sth->fetchrow_hashref())
    {
    	my $team_info = &get_team_info($Team); #($teams_sku_ref->{Team});
        unless ($team_info->{Team_Names} eq "")
        {
            #print "$team_info->{Team_Names} - ";
            #foreach distinct team, get distinct players
            my $players_dbquery = qq~
	        SELECT DISTINCT Team_Rosters.Member_Id
	        FROM Team_Rosters  INNER JOIN Players ON (Players.Member_ID = Team_Rosters.Member_Id)
	        WHERE Team_Rosters.Team = $Team AND
            Team_Rosters.Division = "$division_info->{Division_Name}" AND
            Team_Rosters.Session = "$session_info->{Session}"
            ORDER BY Players.Member_ID DESC
	        ~;

            #print "$players_dbquery<BR>";

	        my $players_sth = &DB_query_prepare($players_dbquery);
	        unless ($players_sth -> execute())
	        {
	            push(@error_messages,"Can't execute query:<BR>$players_dbquery. Reason: $DBI::errstr.");
	            $players_sth -> finish;
	            DisConnectFromDB();
	        }
            my $pFoundByRows = $players_sth->rows;
            #print "players found by rows: $pFoundByRows = ";
            my $p = 0;
            while (my $players_sku_ref = $players_sth->fetchrow_hashref())
	        {
            	push(@playersRetreived,$players_sku_ref->{Member_Id});
                $p++;
        	}
            $players_sth -> finish;
            #print "$p<BR>"; $pt=$pt+$p;
		}
    }

    #print "@playersRetreived<BR>";

    foreach my $PlayerID (@playersRetreived)
    {
        my $player_info = &get_player_info($PlayerID);
        if ($player_info->{Inactive} eq "FALSE")
        {
            ($player_mvp_avg, $countOfWeeks) = &get_player_mvp_average($PlayerID,$division_info->{Number_of_Rounds});
            #my $player_mvp_avg2 = ($player_total_points / $count_of_rounds) if ($count_of_rounds != 0);
            #push(@myMvpPlayers,"$players_sku_ref->{Member_Id}:$player_info->{First_Name} $player_info->{Last_Name} | $player_mvp_avg | $countOfWeeks<BR>" );

            my $insert_query = qq~INSERT INTO $temp_rpt_tbl (Player,Avg,Weeks) VALUES ("$player_info->{First_Name} $player_info->{Last_Name}",$player_mvp_avg,$countOfWeeks)~;
            my $insert_sth = &DB_query_prepare($insert_query);
            unless ($insert_sth -> execute())
            {
                push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
                $insert_sth -> finish;
                DisConnectFromDB();
            }
            $insert_sth->finish();
        }
        #push (@my_mvp_teams,"$teams_sku_ref->{Team},$team_info->{Team_Names}, found $my_players_found players<BR>");
    }
    #$teams_sth -> finish;
    #foreach distinct player, &get_player_avergage($mvp_sth->{Member_Id},)

    my $mvp_dbquery = qq~SELECT *
    FROM $temp_rpt_tbl
    ORDER BY Avg DESC LIMIT 76
    ~;
    my $mvp_sth = &DB_query_prepare($mvp_dbquery);
	if( not $mvp_sth -> execute())
	{
	   push(@error_messages,"Can't execute query:<BR>$mvp_dbquery. Reason: $DBI::errstr.");
	   $mvp_sth->finish;
	   DisConnectFromDB();
	}
    push(@myMvpPlayers,"<TABLE width=250 align=center><TR><TD width=200><B>Player</B><HR></TD><TD width=50><B>Avg</B><HR></TD><TD><B>Weeks</B><HR></TD></TR>");
    while (my $mvp_sku_ref = $mvp_sth->fetchrow_hashref())
	{
        my $temp_avg;
        if ($data{CueSport} eq "9ball")
        {
        	$temp_avg = &round_average($mvp_sku_ref->{Avg},1);
        }
        elsif ($data{CueSport} eq "8ball")
        {
        	$temp_avg = $mvp_sku_ref->{Avg};
        }
        push(@myMvpPlayers,qq~<TR><TD>$mvp_sku_ref->{Player} </TD><TD align=right> $temp_avg </TD><TD align=center> $mvp_sku_ref->{Weeks}</TD></TR>~);
    }
    $mvp_sth->finish();
    my $my_players_found = scalar(@myMvpPlayers)-1;
    #Return top 76 player names, weeks played, avg, ordered by avg
    push(@myMvpPlayers,"</TABLE>");
    $html .="<BR>@myMvpPlayers";
    &delete_temp_mvp_report_table($temp_rpt_tbl);

    return $html;
}

sub get_player_mvp_average(){
	my $player_id = shift;
    my $number_of_rounds = shift;
    my $player_average;

    my $dbquery = qq~
	SELECT  $data{CueSport}_Score_Sheet.Player, $data{CueSport}_Score_Sheet.Points, $data{CueSport}_Score_Sheet.Wins, $data{CueSport}_Divisions.Number_Of_Rounds
	FROM ($data{CueSport}_Standings INNER JOIN $data{CueSport}_Score_Sheet ON ($data{CueSport}_Standings.League_Id = $data{CueSport}_Score_Sheet.League_Id) AND ($data{CueSport}_Standings.League_Id = $data{CueSport}_Score_Sheet.League_Id)) INNER JOIN $data{CueSport}_Divisions ON $data{CueSport}_Standings.Division = $data{CueSport}_Divisions.Division_Name
  	WHERE Player = $player_id AND
    $data{CueSport}_Standings.Division = "$division_info->{Division_Name}" AND
    $data{CueSport}_Standings.Session = "$session_info->{Session}"
	~;

	my $stats_sth = &DB_query_prepare($dbquery);
	if( not $stats_sth -> execute())
	{
	   push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
	   $stats_sth->finish;
	   DisConnectFromDB();
	}

	my $rows_found = $stats_sth->rows;

    my $player_total_points = 0;
    my $player_average3 = 0;
    my $count_of_rounds = 0;
    my $player_average = 0;

	my $i = 0;
    my @weeks_data;
	while (my $sku_ref3 = $stats_sth->fetchrow_hashref())
	{
	   $player_total_points = $player_total_points + $sku_ref3->{Points};
       $player_total_wins = $player_total_wins + $sku_ref3->{Wins};
       if ($data{CueSport} eq "9ball")
       {
	       	$player_average3 = $player_average3 + ($sku_ref3->{Wins}/$number_of_rounds);
            $count_of_rounds = $count_of_rounds + $number_of_rounds;
       }
       elsif ($data{CueSport} eq "8ball")
       {
            $player_average3 = $player_average3 + ($sku_ref3->{Points}/$sku_ref3->{Number_Of_Rounds});
            $count_of_rounds = $count_of_rounds + $sku_ref3->{Number_Of_Rounds};
       }
       my $score = ($sku_ref3->{Points}/$sku_ref3->{Number_Of_Rounds});

       $player_average = ($player_total_points / $sku_ref3->{Number_Of_Rounds}) if ($count_of_rounds != 0);
       #push(@weeks_data,qq~ $sku_ref3->{Date} : $sku_ref3->{Points} / $sku_ref3->{Number_Of_Rounds} = $score \n~);
	   $i++;
	}
    $count_of_weeks_found = $stats_sth->rows;
    $stats_sth->finish();

    $player_average3 = $player_average3/$count_of_weeks_found unless (($count_of_weeks_found == 0) || ($count_of_weeks_found eq ""));
    if ($data{CueSport} eq "9ball")
    {
    	$player_average_points = &round_average($player_average3,2);
    }
    elsif ($data{CueSport} eq "8ball")
    {
        $player_average_points = &round_average($player_average3,2);
    }

    return $player_average_points,$count_of_weeks_found;
}

sub get_player_8ball_avergage(){
	my $player_id = shift;
    my $number_of_rounds = shift;
    my $count_of_weeks = shift;
    my $player_average;

    $count_of_weeks = 15; # move this param to param file

    #$count_of_weeks = $count_of_weeks + 1 if ($count_of_weeks < 15);

    my $dbquery = qq~
	SELECT  $data{CueSport}_Score_Sheet.Date, $data{CueSport}_Score_Sheet.Player, $data{CueSport}_Score_Sheet.Points
	FROM $data{CueSport}_Standings INNER JOIN $data{CueSport}_Score_Sheet ON ($data{CueSport}_Standings.League_Id = $data{CueSport}_Score_Sheet.League_Id) AND ($data{CueSport}_Standings.League_Id = $data{CueSport}_Score_Sheet.League_Id)
  	WHERE Player = $player_id
	ORDER BY $data{CueSport}_Score_Sheet.Game_Id DESC LIMIT $count_of_weeks
	~;


	my $stats_sth = &DB_query_prepare($dbquery);
	if( not $stats_sth -> execute())
	{
	   push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
	   $stats_sth->finish;
	   DisConnectFromDB();
	}

	my $rows_found = $stats_sth->rows;

    my $player_total_points = 0;
    my $player_average3 = 0;
    my $count_of_rounds = 0;
    my $player_average = 0;

	my $i = 0;
    @weeks_data = ();
    push(@weeks_data,qq~<SELECT name="scores"><OPTION>History:</OPTION>~);
	while (my $sku_ref3 = $stats_sth->fetchrow_hashref())
	{
	   $player_total_points = $player_total_points + $sku_ref3->{Points};
       $player_average3 = $player_average3 + ($sku_ref3->{Points}/$number_of_rounds);
       my $score = ($sku_ref3->{Points}/$number_of_rounds);
	   $count_of_rounds = $count_of_rounds + $number_of_rounds;
       $player_average = ($player_total_points / $number_of_rounds) if ($count_of_rounds != 0);
       push(@weeks_data,qq~<OPTION>$sku_ref3->{Date} : $sku_ref3->{Points} / $number_of_rounds = $score</OPTION>\n~);
	   $i++;
	}
    push(@weeks_data,qq~</SELECT>~);
    $count_of_weeks_found = $stats_sth->rows;
    $stats_sth->finish();

    $player_average3 = $player_average3/$count_of_weeks_found unless (($count_of_weeks_found == 0) || ($count_of_weeks_found eq ""));
    $player_average_points = &round_average($player_average3,1);

    return "$player_average_points";
}

sub get_player_9ball_avergage(){
	my $player_id = shift;
    my $number_of_rounds = shift;
    my $count_of_weeks = shift;

    $count_of_weeks = 15; # move this handicap param to param file for avg this many weeks

    #$count_of_weeks = $count_of_weeks + 1 if ($count_of_weeks < 15);

    my $dbquery = qq~
	SELECT  $data{CueSport}_Score_Sheet.Date, $data{CueSport}_Score_Sheet.Player, $data{CueSport}_Score_Sheet.Wins
	FROM $data{CueSport}_Standings INNER JOIN $data{CueSport}_Score_Sheet ON ($data{CueSport}_Standings.League_Id = $data{CueSport}_Score_Sheet.League_Id) AND ($data{CueSport}_Standings.League_Id = $data{CueSport}_Score_Sheet.League_Id)
  	WHERE Player = $player_id
	ORDER BY $data{CueSport}_Score_Sheet.Game_Id DESC LIMIT $count_of_weeks
	~;

	my $stats_sth = &DB_query_prepare($dbquery);
	if( not $stats_sth -> execute())
	{
	   push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
	   $stats_sth->finish;
	   DisConnectFromDB();
	}

	my $rows_found = $stats_sth->rows;

    my $player_total_wins = 0;
    my $player_average3 = 0;
    my $count_of_rounds = 0;
    my $player_average = 0;

	my $i = 0;
    @weeks_data = ();
    #push(@weeks_data,qq~<SELECT name="scores"><OPTION>History:</OPTION>~);
	while (my $sku_ref3 = $stats_sth->fetchrow_hashref())
	{
	   $player_total_wins = $player_total_wins + $sku_ref3->{Wins};
       $player_average3 = $player_average3 + ($sku_ref3->{Wins}/$number_of_rounds);
       #my $score = ($sku_ref3->{Wins}/$number_of_rounds);
	   $count_of_rounds = $count_of_rounds + $number_of_rounds;
       #$player_average = ($player_total_points / $number_of_rounds) if ($count_of_rounds != 0);
       #push(@weeks_data,qq~<OPTION>$sku_ref3->{Date} : $sku_ref3->{Points} / $number_of_rounds = $score</OPTION>\n~);
	   $i++;
	}
    #push(@weeks_data,qq~</SELECT>~);
    $count_of_weeks_found = $stats_sth->rows;
    $stats_sth->finish();

    $player_average3 = $player_average3/$count_of_weeks_found unless (($count_of_weeks_found == 0) || ($count_of_weeks_found eq ""));
    $player_average_points = &round_average($player_average3,1);

    return "$player_average_points";
}


sub get_player_statistics_report(){

	if ((not defined $data{Team_ID}) or ($data{Team_ID} eq ""))
    {
    	return select_team_form();
    }

    if ($data{CueSport} eq "9ball")
    {
        #push(@error_messages,"Can't display report: 9-Ball Player Stats.<BR>Reason: Database interface temporarily off-line.");
        #return;
    }

    $team_info = &get_team_info($data{Team_ID});

    my $rpt_header;
    if ($data{CueSport} eq "8ball")
    {
    	$rpt_header=qq~
            <TD width="22%" align='center'><B>Team Member</B>
            </TD>
            <TD width="13%" align='center' style='background-color:$my_highlight_bkgColor'><B>Wks</B>
            </TD>
            <TD width="13%" align='center'><B>Pts</B>
            </TD>
            <TD width="13%" align='center' style='background-color:$my_highlight_bkgColor'><B>W's</B>
            </TD>
            <TD width="13%" align='center'><B>L's</B>
            </TD>
            <TD width="13%" align='center' style='background-color:$my_highlight_bkgColor'><B>B/R</B>
            </TD>
            <TD width="13%" align='center'><B>Avg</B>
            </TD>
        ~;
    }
    elsif ($data{CueSport} eq "9ball")
    {
        $rpt_header=qq~
        	<TD width="22%" align='center'><B>Team Member</B>
            </TD>
            <TD width="13%" align='center' style='background-color:$my_highlight_bkgColor'><B>Wks</B>
            </TD>
            <TD width="13%" align='center' style='background-color:$my_highlight_bkgColor'><B>W's</B>
            </TD>
            <TD width="13%" align='center'><B>L's</B>
            </TD>
            <TD width="13%" align='center' style='background-color:$my_highlight_bkgColor'><B>B/R</B>
            </TD>
            <TD width="13%" align='center'><B>9-Ball</B>
            </TD>
            <TD width="13%" align='center'><B>Avg</B>
            </TD>
    	~;
    }
    #return $html;
    my $html .= qq~
    <TABLE width="95%" border="0">
        <TR>
	        <TD >
            	<DIV align="center" style='font-size:16pt; color:#0000FF'>
                	<B>$division_info->{Division_Name}<BR>$session_info->{Session}</B>
                </DIV>
            	<DIV align="center" style='font-size:14pt;'>
                	$CueSport<BR>
                    <B>Player Statistics</B>
                </DIV>
	        </TD>
	    </TR>
	</TABLE>
    <DIV style="font-size:12pt; font-weight:bold; background-color:#dddddd;"></DIV>
    <TABLE width="95%" border="0" cellpadding=6 cellspacing=2 bgcolor='$second_table_bgcolor'>
        <TR>
            <TD width="22%" align='center'><img src='$my_Images_folder/spacer.gif' width='150px' height='1' border='0'></TD>
            <TD width="13%" align='center'><img src='$my_Images_folder/spacer.gif' width='50px' height='1' border='0'></TD>
            <TD width="13%" align='center'><img src='$my_Images_folder/spacer.gif' width='50px' height='1' border='0'></TD>
            <TD width="13%" align='center'><img src='$my_Images_folder/spacer.gif' width='50px' height='1' border='0'></TD>
            <TD width="13%" align='center'><img src='$my_Images_folder/spacer.gif' width='50px' height='1' border='0'></TD>
            <TD width="13%" align='center'><img src='$my_Images_folder/spacer.gif' width='50px' height='1' border='0'></TD>
            <TD width="13%" align='center'><img src='$my_Images_folder/spacer.gif' width='50px' height='1' border='0'></TD>
        </TR>
        <TR style="font-size:12pt; font-weight:bold;">
        	<TD colspan=7  style=" border-style:ridge; border-width:2px; border-color:red; background-color:$report_header_color; color:black; height:25px; width:100%;">
            	<DIV align=left >
             		&nbsp;$team_info->{Team_Names} - $team_info->{Coined_Name}
                </DIV>
            </TD>
        </TR>
        <TR>
            <TD width="22%" align='center'><img src='$my_Images_folder/spacer.gif' width='150px' height='1' border='0'></TD>
            <TD width="13%" align='center'><img src='$my_Images_folder/spacer.gif' width='50px' height='1' border='0'></TD>
            <TD width="13%" align='center'><img src='$my_Images_folder/spacer.gif' width='50px' height='1' border='0'></TD>
            <TD width="13%" align='center'><img src='$my_Images_folder/spacer.gif' width='50px' height='1' border='0'></TD>
            <TD width="13%" align='center'><img src='$my_Images_folder/spacer.gif' width='50px' height='1' border='0'></TD>
            <TD width="13%" align='center'><img src='$my_Images_folder/spacer.gif' width='50px' height='1' border='0'></TD>
            <TD width="13%" align='center'><img src='$my_Images_folder/spacer.gif' width='50px' height='1' border='0'></TD>
        </TR>
        <TR style="font-size:10pt; background-color:$row_color2;">
            $rpt_header
        </TR>
    ~;

    my $dbquery1 = qq~SELECT Team_Rosters.Captain, Team_Rosters.Member_Id, Players.First_Name, Players.Last_Name
    FROM Team_Rosters INNER JOIN Players ON (Players.Member_ID = Team_Rosters.Member_Id)
    WHERE Team_Rosters.Team = $team_info->{ID} AND Team_Rosters.Division LIKE '$division_info->{Division_Name}' AND Team_Rosters.Session LIKE '$session_info->{Session}'
    ORDER BY Players.First_Name, Players.Last_Name
    ~;

    my $teams_sth = &DB_query_prepare($dbquery1);
    unless ($teams_sth -> execute())
    {
        push(@error_messages,"Can't execute query:<BR>$dbquery1. Reason: $DBI::errstr.");
        $teams_sth -> finish;
        DisConnectFromDB();
    }
    # for each unique team in Division and Session, select player's Member_ID
    my $i = 0;
    while (my $teams_sku_ref = $teams_sth->fetchrow_hashref())
    {

        my $player_info = &get_player_info($teams_sku_ref->{Member_Id});
        #if ($player_info->{Inactive} eq "False")
        #{
             #for each player, follow these steps to get player stats / average
            # 1) get distinct league Ids from Standings where Session, Division, & team
            # 2) using each distinct league id, query for player stats (where League Ids match...?)

            my $dbquery2 = qq~
            SELECT DISTINCT League_Id
            FROM $data{CueSport}_Standings
            WHERE Division LIKE '$division_info->{Division_Name}'
            AND Session LIKE '$session_info->{Session}'
            AND Team = $team_info->{ID}

            ~; #ORDER BY Date DESC LIMIT 15
            my $league_sth = &DB_query_prepare($dbquery2);
	        if( not $league_sth->execute())
	        {
	            $html = qq~</TABLE>~;
	            push(@error_messages,"Can't execute query:<BR>$dbquery2. Reason: $DBI::errstr.");
	            $league_sth->finish;
	            DisConnectFromDB();
	        }

	        my $rows_found =  $league_sth->rows;

	        my @distinct_league_ids;
	        while(my $sku_ref = $league_sth->fetchrow_hashref())
	        {
	            push(@distinct_league_ids,$sku_ref->{League_Id});
	        }
	        $league_sth->finish;

            my $player_total_points=0;
            my $count_of_weeks=0;
            my $count_of_wins=0;
            my $count_of_rounds=0;
            my $count_of_break_n_runs=0;
            my $player_average=0;
            my $count_of_9ball_loses=0;
            my $where_league_id;

            my $ik=1;
            foreach my $league_id (@distinct_league_ids)
            {
                if ($ik == scalar(@distinct_league_ids))
                {
                	$where_league_id .= qq~League_Id = $league_id ~;
                }
                else
                {
                    $where_league_id .= qq~League_Id = $league_id OR ~;
                }
                $ik++;
            }

            my $dbquery3 = qq~
            SELECT  Date, Player, Points, Wins, Break_N_Run
            FROM $data{CueSport}_Score_Sheet
            WHERE Player = $teams_sku_ref->{Member_Id}
            AND ($where_league_id)
            ORDER BY Game_Id DESC LIMIT 15
            ~;

            my $stats_sth = &DB_query_prepare($dbquery3);
            if( not $stats_sth -> execute())
            {
               push(@error_messages,"Can't execute query:<BR>$dbquery3. Reason: $DBI::errstr.");
               $stats_sth->finish;
               DisConnectFromDB();
            }

            my $rows_found = $stats_sth->rows;

            while (my $sku_ref3 = $stats_sth->fetchrow_hashref())
            {
				$player_total_points = $player_total_points + $sku_ref3->{Points}; #for counting 9-balls
	            $count_of_weeks++;
	            if ($sku_ref3->{Wins} > 0)
	            {
	                $count_of_wins = $count_of_wins + $sku_ref3->{Wins};

	            }
                $count_of_9ball_loses = $count_of_9ball_loses + ($division_info->{Number_of_Rounds} * 3) - $sku_ref3->{Wins};
                #print "$division_info->{Number_of_Rounds}<BR>";
	            $count_of_rounds = $count_of_rounds + $division_info->{Number_of_Rounds};
	            $count_of_break_n_runs = $count_of_break_n_runs + $sku_ref3->{Break_N_Run};
            }
            $stats_sth->finish();

            my $count_of_loses = $count_of_rounds - $count_of_wins;
            #my $total_losses = "$count_of_rounds - $count_of_wins = $count_of_loses<BR>"; # $count_of_rounds -$count_of_loses;

            my $player = "$player_info->{First_Name} $player_info->{Last_Name}";
            if ($teams_sku_ref->{Captain} eq "True")
            {
                 $player = "<Font color='#990000'><B>$player_info->{First_Name} $player_info->{Last_Name}</B><!--<BR>$player_info->{Home_Phone}--></FONT>";
            }

            my $color = $row_color1;
        	if ($i % 2) {$color = $row_color2; }

            if ($data{CueSport} eq "8ball")
            {
            	$player_average = &get_player_8ball_avergage($teams_sku_ref->{Member_Id},$division_info->{Number_of_Rounds},$count_of_weeks);
                $html .= qq~
	                <TR style="font-size:10pt; background-color:$color;">
	                    <TD width="22%">
	                        <!-- <A href="$selfURL?cmd=GetPlayerStats&Session=$session_info->{ID}&Division=$division_info->{Division_ID}&Team_Id=$team_info->{ID}&Member_ID=$player_info->{Member_ID}">$player_info->{First_Name} $player_info->{Last_Name}</A> -->
	                         $player
	                    </TD>
	                    <TD width="13%" align='right' style='background-color:$my_highlight_bkgColor'>$count_of_weeks
	                    </TD>
	                    <TD width="13%" align='right'>$player_total_points
	                    </TD>
	                    <TD width="13%" align='right' style='background-color:$my_highlight_bkgColor'>$count_of_wins
	                    </TD>
	                    <TD width="13%" align='right'>$count_of_loses
	                    </TD>
	                    <TD width="13%" align='right' style='background-color:$my_highlight_bkgColor'>$count_of_break_n_runs
	                    </TD>
	                    <TD width="13%" align='right' >&nbsp; $player_average <!--<BR> @weeks_data<BR>
	                    $player_average2-->
	                    </TD>
	                </TR>
	            ~;
            }
            elsif ($data{CueSport} eq "9ball")
            {
            	$player_average = &get_player_9ball_avergage($teams_sku_ref->{Member_Id},$division_info->{Number_of_Rounds},$count_of_weeks);
                $html .= qq~
	                <TR style="font-size:10pt; background-color:$color;">
	                    <TD width="22%">
	                        <!-- <A href="$selfURL?cmd=GetPlayerStats&Session=$session_info->{ID}&Division=$division_info->{Division_ID}&Team_Id=$team_info->{ID}&Member_ID=$player_info->{Member_ID}">$player_info->{First_Name} $player_info->{Last_Name}</A> -->
	                         $player
	                    </TD>
	                    <TD width="13%" align='right' style='background-color:$my_highlight_bkgColor'>$count_of_weeks
	                    </TD>
	                    <TD width="13%" align='right' style='background-color:$my_highlight_bkgColor'>$count_of_wins
	                    </TD>
	                    <TD width="13%" align='right'>$count_of_9ball_loses
	                    </TD>
	                    <TD width="13%" align='right' style='background-color:$my_highlight_bkgColor'>$count_of_break_n_runs
	                    </TD>
                        <TD width="13%" align='right'>$player_total_points
	                    </TD>
	                    <TD width="13%" align='right' >&nbsp; $player_average <!--<BR> @weeks_data<BR>
	                    $player_average2-->
	                    </TD>
	                </TR>
	            ~;
            }
            else
            {
             	$player_average = "X";
            }
        #}
        $i++;
    }
    $html .= qq~
     </TABLE><BR>
     <!-- <FONT style="font-size:9pt;">Query: $dbquery</FONT> -->
    ~;
    $teams_sth->finish;

    return $html;
}


sub get_team_standings_report(){

    my $column_spacer_width = "25px";
    my $printable_link, $wkcount;
    if ($data{Printable} eq "Yes")
    {
        $column_spacer_width = "20px";
    }

    if (($session_info->{Weeks} eq "") || ($session_info->{Weeks} == 0))
    {
    	$wkcount = 15;
    }
    else
    {
    	$wkcount = $session_info->{Weeks};
    }

    for (my $i = 1; $i <= $wkcount; $i++)
    {
        my $td_color = $row_color1;
        if ($i % 2) {$td_color = $my_highlight_bkgColor; }
        @week_header_array[$i] = qq~<TD align='center' style='background-color:$td_color;'><img src='$my_Images_folder/spacer.gif' width='$column_spacer_width' height='1' border='0'><BR>
            $i
        </TD>~;
    }

    my $html = qq~
    <TABLE width="98%" border="0">
        <TR>
	        <TD>
            	<DIV align="center" style='font-size:16pt; color:#0000FF'>
                	<B>$session_info->{Session}</B><BR>
                    $division_info->{Division_Name}
                </DIV>
            	<DIV align="center" style='font-size:14pt;'>
                	$CueSport<BR>
                    <B>Team Standings</B>
                </DIV>
	        </TD>
	    </TR>
	</TABLE>
    <TABLE width="98%" border="1" bgcolor="$second_table_bgcolor">
    	<TR style=" border-style:ridge; border-width:2px; border-color:red; background-color:$report_header_color; color:black; height:55px; ">
            <TD valign='bottom' width="25%"><B>&nbsp;Team</B><BR>&nbsp;Coined Name
            </TD>

            <TD valign='bottom' align='center' width="65%"><B>Weekly Scores</B>
	            <TABLE width="100%" border="1">
	                <TR>
	                    @week_header_array
	                </TR>
	            </TABLE>
            </TD>

            <TD valign='bottom' width="10%"><B>&nbsp;Points&nbsp;</B>
            </TD>
        </TR>

    ~;

    my $dbquery = qq~
    SELECT DISTINCT $data{CueSport}_Standings.Team, Teams.Team_Names
    FROM $data{CueSport}_Standings INNER JOIN Teams ON ($data{CueSport}_Standings.Team = Teams.ID)
    WHERE $data{CueSport}_Standings.Division LIKE "$division_info->{Division_Name}" AND $data{CueSport}_Standings.Session LIKE "%$session_info->{Session}%"
    ORDER BY Teams.Team_Names
    ~;

    my $sth = &DB_query_prepare($dbquery);
    if( not $sth -> execute())
    {
        $html .= qq~</TABLE>~;
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
        DisConnectFromDB();
        return $html;
    }
    my $i = 0;

    while(my $sku_ref = $sth->fetchrow_hashref())
    {

    	my $team_info = &get_team_info($sku_ref->{Team});
        unless ($team_info->{Team_Names} eq "")
        {

	            my $color = $row_color1;
	            if ($i % 2) {$color = $row_color2; }

	            my $order_by = "Date ASC";
	            $order_by = "Week ASC" if ($session_info->{ID} > 14);

	            my $dbquery = qq~
	            SELECT Division, Session, Date, Week, Team, Points
	            FROM $data{CueSport}_Standings
	            WHERE Division LIKE "$division_info->{Division_Name}"
	            AND Session LIKE "$session_info->{Session}"
	            AND Team LIKE "$sku_ref->{Team}"
	            ORDER BY $order_by LIMIT $wkcount
	            ~;

	            my $sth = &DB_query_prepare($dbquery);
	            if( not $sth -> execute())
	            {
	                $html = qq~</TABLE>~;
	                push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
	                $sth -> finish;
	                DisConnectFromDB();
	            }
	            my @weeks_table_array = ();
	            for (my $k = 1; $k <= $wkcount; $k++)
	            {
	                my $td_color = $row_color1;
	                if ($i % 2) {$td_color = $row_color2; }
	                if ($k % 2) {$td_color = $my_highlight_bkgColor; }
	                @weeks_table_array[$k-1] = qq~<TD align='right' style='background-color:$td_color;'>
	                <img src='$my_Images_folder/spacer.gif' width='$column_spacer_width' height='1' border='0'><BR>&nbsp;</TD>~;
	            }

	            my $weeks_table = "<Table width='100%' height='100%' align='left' border='0'><TR> ";
	            my $team_points=0; $count_of_weeks=1;
	            while(my $sku_ref1 = $sth->fetchrow_hashref())
	            {
	                my $td_color = $row_color1;

	                my $date_HTML;
	                if ($data{Printable} ne "Yes")
	                {
	                    $date_HTML = qq~
	                    <FONT style='font-size:6pt;' face='Ariel, Helvetica, sans-serif'><BR>$sku_ref1->{Date}</FONT>
	                    ~;
	                }

	                if ($session_info->{ID} > 14)
	                {
	                    if ($i % 2) {$td_color = $row_color2; }
	                    if (($sku_ref1->{Week}) % 2) {$td_color = $my_highlight_bkgColor; }
	                    @weeks_table_array[$sku_ref1->{Week}-1] = qq~<TD align='right' style='background-color:$td_color;'>
	                    <img src='$my_Images_folder/spacer.gif' width='$column_spacer_width' height='1' border='0'><BR><FONT style='font-size:9pt;' face='Courier New, Courier, mono'>$sku_ref1->{Points}</FONT></TD>~;
	                    $team_points = $team_points + $sku_ref1->{Points};
	                }
	                else
	                {
	                    if ($i % 2) {$td_color = $row_color2; }
	                    if ($count_of_weeks % 2) {$td_color = $my_highlight_bkgColor; }
	                    @weeks_table_array[$count_of_weeks-1] = qq~<TD align='right' style='background-color:$td_color;'>
	                    <img src='$my_Images_folder/spacer.gif' width='$column_spacer_width' height='1' border='0'><BR><FONT style='font-size:9pt;' face='Courier New, Courier, mono'>$sku_ref1->{Points}</FONT></TD>~;
	                    $team_points = $team_points + $sku_ref1->{Points};
	                }

	                $count_of_weeks++;
	            }
	            $sth->finish();

                $team_points = &format_decimal_places($team_points,1);

	            $weeks_table .= "@weeks_table_array</TR></Table>";

	            $html .= qq~

	                <TR style="font-size:10pt; background-color:$color; height:100%;">

	                    <TD valign="top" width="25%">
	                        <img src='$my_Images_folder/spacer.gif' width='110px' height='1px' border='0'><BR>
                            <B>&nbsp;$team_info->{Team_Names}</B><BR>
	                        &nbsp;&nbsp;$team_info->{Coined_Name}<BR>

	                    </TD>

	                    <TD width="65%">$weeks_table
	                    </TD>

	                    <TD valign="middle" align='right' width="10%">$team_points&nbsp;
	                    </TD>

	                </TR>

	            ~;

	            $division_points += $team_points;
	            $i++;
    	} #end unless
    }
    $html .= qq~

     </TABLE><BR>Grand Total Points = $division_points<BR>
    ~;

    return $html;
}

sub show_hostroom_info(){

    #my ($hosts_found, @hosts) = &get_number_of_hosts_in_division();
    my ($hosts_found, @hosts) = &get_number_of_hosts_in_division($session_info->{Session},$my_division_info->{Division_Name});
    $hosts_found = @hosts;

    my $html= qq~
        <DIV align="center" style="font-size:14pt;">$division_info->{Division_Name} $session_info->{Session} Host Rooms</DIV>
    	<TABLE width="98%" border="1" bgcolor="$second_table_bgcolor">
	        <TR  style='background-color:$report_header_color'>
	            <TD style="font-size:10pt;">
                	<img src="$my_Images_folder/spacer.gif" width="110" height="1" border="0"><BR>
	                <B>&nbsp;Host Room</B>
	            </TD>
                <TD style="font-size:10pt;">
                	<img src="$my_Images_folder/spacer.gif" width="120" height="1" border="0"><BR>
                	<B>&nbsp;Contact</B>
	            </TD>
	            <TD style="font-size:10pt;">
                	<img src="$my_Images_folder/spacer.gif" width="130" height="1" border="0"><BR>
                	<B>&nbsp;Address</B>
	            </TD>
	            <TD style="font-size:10pt;">
                	<img src="$my_Images_folder/spacer.gif" width="80" height="1" border="0"><BR>
                	<B>&nbsp;City</B>
	            </TD>
                <TD style="font-size:10pt;">
                	<img src="$my_Images_folder/spacer.gif" width="50" height="1" border="0"><BR>
                	<B>&nbsp;Zip/ Postal</B>
	            </TD>
                <TD style="font-size:10pt;">
                	<img src="$my_Images_folder/spacer.gif" width="120" height="1" border="0"><BR>
                	<B>&nbsp;Phone</B>
	            </TD>
	        </TR>
    ~;
    my $i=0;
    foreach my $host (@hosts)
    {
        #get host info?
        my $dbquery = qq~SELECT *
	    FROM Host_Rooms
	    WHERE Id LIKE '$host' LIMIT 1
	    ~;
	    my $sth = &DB_query_prepare($dbquery);

	    if( not $sth -> execute())
	    {
	        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
	        $sth -> finish;
	        DisConnectFromDB();
	    }

	    while (my $sku_ref= $sth->fetchrow_hashref())
	    {

            my $color = $row_color1;
	        if ($i % 2) {$color = $row_color2; }

            $html .= qq~
            <TR style='background-color:$color;'>
	            <TD style="font-size:10pt;">
                &nbsp;$sku_ref->{Host_Room}
	            </TD>
                <TD style="font-size:10pt;">&nbsp;
                	$sku_ref->{Contact}
	            </TD>
	            <TD style="font-size:10pt;">&nbsp;
                	$sku_ref->{Address}
	            </TD>
	            <TD style="font-size:10pt;">&nbsp;
                	$sku_ref->{City}
	            </TD>
                <TD style="font-size:10pt;">&nbsp;
                	$sku_ref->{Postal_Code}
	            </TD>
                <TD style="font-size:10pt;">&nbsp;
                	$sku_ref->{Phone_Number}
	            </TD>
	        </TR>
        	~;

        }
        $i++;
        my $rows = $sth->rows;
	    $sth->finish();
    }
    $html .= "</TABLE>";

    return $html;
}

sub RetCal() {
	my($Mo_Yr, $Border) = @_;
    # Initialize variables
	my $calIndex;
	my $tempMonth ="";
	my $eventQUERY = "";
	my @MonthNames = split/ /, "NaM January February March April May June July August September October November December";
	my @MonthNumbers = split/ /, "00 01 02 03 04 05 06 07 08 09 10 11 12";
	my @DayNumbers = split/ /, "00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31";

	($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
	$year = $year + 1900;
	$todaysDate = "$mon/$mday/$year";
	$clock = "$hour:$min:$sec";

	my($ret, @Result, $Month, $dy, $line, $no);

	$Border = 0;

	$Days = "Sun Mon Tue Wed Thr Fri Sat";

	$NumberOfCals = 1;

	for ($i = 1; $i < $NumberOfCals; $i++)
	{
        $targetMon = $mon + $i;
        if ($targetMon > 12)
        {
                $ARGmon = $targetMon - 12;
                $ARGyear = $year + 1;
                @CALS[$i] = "$ARGmon-$ARGyear";
        }
        else
        {
                $ARGmon = $targetMon;
                $ARGyear = $year;
                @CALS[$i] = "$ARGmon-$ARGyear";
        }
	}

    #foreach @CALS

    $calIndex = 1;

    my $column_spacer_width = "35px";
	if ( -x "$CalCMD" )
    {
		if (($Mo_Yr !~ /^\d\d?-\d\d\d\d$/) || ($Mo_Yr eq ""))
        {
			$Mo_Yr = "";
			@date = localtime(time);
			$Today = @date[3];
		}
    	else
        {
			$Mo_Yr =~ s/-/ /g;
            @date = localtime(time);
			$Today = @date[3]+1;
		}

		open(CAL, "$CalCMD $Mo_Yr|");
		        @Result = <CAL>;
		close(CAL);

        @Mo_Yr_ARRAY = split / /, $Mo_Yr;
        $theYEAR = @Mo_Yr_ARRAY[1];
        $theMonth = @MonthNumbers[@Mo_Yr_ARRAY[0]];

		$Month = @Result[0]; shift(@Result);

		$Month =~ s/\s\s\s*//g;

		$ret = "<TABLE border=\"$Border\" >\n<TR><TD colspan=\"7\"><DIV align=\"center\" style=\"font-size: 10pt;\"><B>$Month</B></DIV></TD></TR><TR>";

		shift(@Result);
		foreach $dy (split(/ /, $Days))
        {
			$ret .= "<TD style='font-size:10pt; background-color:$second_table_bgcolor;' align='center'><img src='$my_Images_folder/spacer.gif' width='$column_spacer_width' height='1' border='0'><BR>$dy</TD>";
		}
		$ret .= "</TR>\n";

		foreach $line (@Result)
        {
			$line =~ s/\n//;
			$line =~ s/   /ccs/g;
			$line =~ s/  /sc/g;
			$line =~ s/ /s/g;
			$line =~ s/^s//g;
			$line =~ s/ss/s/g;
			$line =~ s/c//g;
			$ret .= "<TR>";
			foreach $no (split(/s/, $line))
            {
	            # Check for events for this day...
	            if (($no > 0 ) && ($no < 32))
	            {
	                    $theDay      =  @DayNumbers[$no];
	                    $EVENTstring = "";
	                    $CheckDay    =  "$theYEAR$theMonth$theDay";
	                    $EventIndex  = 0;

	                    foreach $event (@EVENTS)
	                    {

	                            @EVENTfields = split/,/, @EVENTS[$EventIndex];

	                            $EVENTstartDate = @EVENTfields[0];
	                            $EVENTendDate   = @EVENTfields[1];
	                            $EVENTname      = @EVENTfields[2];
	                            $EVENTlink      = @EVENTfields[3];

	                            if (($CheckDay eq $EVENTstartDate) && ($EVENTendDate eq ""))
	                            {
	                                    $tempStr = "<DIV bgcolor='#999900'><A href='javascript:' onClick=\"EventOpen = true; EventWin = window.open('/eventpages/$EVENTlink','EventWindow');\">$EVENTname</A></DIV>";
	                                    $EVENTstring = "$EVENTstring$tempStr<BR>\n";
	                            }
	                            elsif (($CheckDay ge $EVENTstartDate) && ($CheckDay le $EVENTendDate))
	                            {
	                                    $tempStr = "<DIV bgcolor='#999999'><A href='javascript:' onClick=\"EventOpen = true; EventWin = window.open('/eventpages/$EVENTlink','EventWindow');\">$EVENTname</A></DIV>";
	                                    $EVENTstring = "$EVENTstring$tempStr<BR>\n";
	                            }
	                            $EventIndex++;
	                    }
	                    #GetEvent();
	            }

	            if (($no eq $Today)  && ($calIndex eq 1))
	            {

	                    $ret .= "<TD align=\"left\" height=\"18px\" valign=\"top\" bgcolor=\"##CCFFCC\"><DIV style=\"font-size: 8pt;\">$no</DIV><DIV align=\"center\" style=\"font-size: 8pt; color: #ffffff;\">$EVENTstring</DIV></TD>\n";
	            }
	            else
	            {

	                    $ret .= "<TD align=\"left\" height=\"18px\" valign=\"top\" style='background-color:$second_table_bgcolor;'><DIV style=\"font-size: 8pt; color: #000000;\">$no</DIV><DIV align=\"center\" style=\"font-size: 8pt; color: #ffffff;\">$EVENTstring</DIV></TD>\n";
	            }
			}
			$ret .= "</TR>\n";
		}
		$ret .= "</TABLE>\n";
	}
    else
    {
		$ret = "Could not find calendar on this system.";
	}
	return $ret;
}

sub verify_divsion(){
	my $dbquery = shift;
	my $sth = &DB_query_prepare($dbquery);
	if( not $sth -> execute())
	{
	    push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
	    $sth -> finish;
	    DisConnectFromDB();
	    return $html;
	}
	my $rows = $sth->rows;
	$sth->finish;
    return $rows;
}

sub Default_Content(){
    my $division_totals_content = get_division_totals_content();
    my $op_info = $my_business_small_html_header;
    $op_info =~ s/\n/<BR>/g;

    my $calendar = &RetCal(@CALS[$calIndex], $Border);

    my $html = qq~
    <TABLE width="95%" border="3" cellpadding=2 cellspacing=0 bordercolor=$report_header_color>
    <TR>
        <TD width="50%" align=center style='font-size:12pt;'  valign="top">
            <TABLE width="100%" border="0">
	            <TR>
	                <TD width="50%" align=center style='font-size:8pt;'  valign="top">
                        <img src="$my_WS_HTTP_URL/league-data-upload/$league_op_info->{League_User_Path}/$league_op_info->{League_User_Path}_logo.jpg" border="0" alt="$league_op_info->{League_Name}"><BR>
             			<B>$CueSport Statistics</B>
	                </TD>
                    <TD width="50%" align=left style='font-size:8pt;'  valign="top">
                        <DIV align="left" style="margin:5px; font-size:8pt;">
	                        <DIV align="center"  style="margin:10px; font-size:10pt;">
	                            <B>League Operator</B><!-- <INPUT type="button" name="opLogin" value="Log In" onclick="window.location='$my_WS_HTTPS_URL$selfURL?cmd=OpLogin';" style="width:100px;; height:20px; font-size:8pt; border-style:solid; ">-->
	                        </DIV>
	                        $league_op_info->{FName} $league_op_info->{LName}<BR>
	                        $league_op_info->{Address}<BR>
	                        $league_op_info->{City}, $league_op_info->{State} <BR>
	                        $league_op_info->{Zip}<BR>
	                        Phone: $league_op_info->{Phone_Number}<BR>
	                        E-Mail: $league_op_info->{Email}<BR>
	                    </DIV>
	                </TD>
	            </TR>
	        </TABLE>

        </TD>
        <TD width="50%" align=left style='font-size:8pt;'  valign="top">
        	<DIV align="left" style="margin:5px; font-size:8pt;">
	            <DIV align="center"  style="margin:5px; font-size:10pt;">
                    $calendar
	            </DIV>

        	</DIV>
        </TD>
    </TR>
    <TR>
        <TD colspan=2 align=center style='font-size:10pt;'  valign="top">
             $division_totals_content
        </TD>
    </TR>
	</TABLE>
    ~;

    return $html;
}

sub Default_Dir(){
    # query db for Sessions
    my $form = get_active_divisions(); #$form  not used here, routine required
    my $form2 = get_active_sessions(); #$form2 not used here, routine required
    my $form3_html;

    foreach my $active_session (@active_session_array)
    {
        $form3_html .= qq~<BR><B>&nbsp;$active_session->{Session}:</B><BR>~;
        my (@active_division_href_array) = &get_divisions_in_session($active_session->{Session});
        foreach my $active_division_hashref (@active_division_href_array)
        {
            $form3_html .=qq~&nbsp;&nbsp;
            <A href="$selfURL?CueSport=$data{CueSport}&cmd=GetMvpRpt&Session=$active_session->{ID}&Division=$active_division_hashref->{Division_ID}" title="Most Valuable Player Report for $active_division_hashref->{Division_Name} $active_session->{Session}">MVP</A>&nbsp;-
            <A href="$selfURL?CueSport=$data{CueSport}&cmd=GetStandings&Session=$active_session->{ID}&Division=$active_division_hashref->{Division_ID}"  title="Team Standings Report for $active_division_hashref->{Division_Name} $active_session->{Session}">Stand</A>&nbsp;-
            <A href="$selfURL?CueSport=$data{CueSport}&cmd=GetStatsRpt&Session=$active_session->{ID}&Division=$active_division_hashref->{Division_ID}"  title="Player Statistics Reports Menu for $active_division_hashref->{Division_Name} $active_session->{Session}">$active_division_hashref->{Division_Name}</A>
            <BR>
            ~;
        }
    }

    my $html = qq~
    <DIV align='center' style="width:200px; font-size:10pt;">
        <B>Click the appropriate link below for MVP reports, team standings, or player statistics.</B>
    </DIV>
    <HR>
    <DIV align='left' style="width:200px; font-size:9pt;">
        $form3_html
    </DIV>
    ~;

    return $html;
}

sub Default_News(){

    my $html;
	my $dbquery = qq~
    SELECT *
    FROM League_News
    ORDER BY Date_Posted DESC LIMIT 5
    ~;

    my $sth = &DB_query_prepare($dbquery);
    if( not $sth -> execute())
    {
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
        DisConnectFromDB();
        return $html;
    }

    my $rows = $sth->rows();
    if ($rows > 0)
    {
    	$html =qq~
    	<TABLE width="95%">
        	<TR>
            <TD align="left" style="font-size:10pt;" valign="bottom" width="15%">
            	<A href="$selfURL?cmd=News">More News</A>
            </TD>
            <TD align="center"  style="font-size:14pt;"  valign="middle" width="70%">
            	<B>League News & Announcements</B><BR>
                <INPUT type="button" name="opLogin" value="Reporter Login" onclick="window.location='$my_WS_HTTPS_URL$selfURL?cmd=RepLogin';" style="width:150px;; height:20px; font-size:8pt;">
            </TD>
            <TD align="right"  style="font-size:10pt;" valign="bottom" width="15%">
            	<A href="$selfURL?cmd=Announcements">Announcements</A>
            </TD>
        </TR>
		~;
    }
    my $i = 0;
    while(my $sku_ref = $sth->fetchrow_hashref())
    {
        $html .=qq~
        	<TR style=" border-style:ridge; border-width:2px; border-color:red; background-color:$report_header_color; color:black; height:30px; ">
                <TD colspan=2 style="font-size:10pt;"><B>&nbsp;$sku_ref->{Headline}</B>
				</TD>
                <TD  style="font-size:8pt;">Date Posted:<BR>$sku_ref->{Date_Posted}
				</TD>
            </TR>
            <TR>
                <TD colspan=3 style="font-size:10pt;">
                	$sku_ref->{Subheading}
                	<DIV style="font-size:8pt;">
                    	$sku_ref->{Content}<BR>-<I>$sku_ref->{Author}</I>
                    </DIV>
				</TD>
            </TR>
        ~;
        $i++;
    }

    $sth-finish;
    if ($rows > 0)
    {
    	$html .=qq~
    	</TABLE>
        ~;
    }
    else
    {
    	$html = qq~
        <TABLE width="95%">
        <TR>
            <TD align="left" style="font-size:10pt;" valign="bottom" width="15%">
            	&nbsp;
            </TD>
            <TD align="center"  style="font-size:14pt;"  valign="middle" width="70%">
            	<B><FONT color="#990000">$league_op_info->{League_Name} League News & Announcements!</FONT></B><BR><BR>
                <A href="/sw-ontario-ccs-league-forum/"><IMG src="$my_Images_folder/$my_fora_logo" border="0"></A>
                <!-- <INPUT type="button" name="opLogin" value="Reporter Login" onclick="window.location='$my_WS_HTTPS_URL$selfURL?cmd=RepLogin';" style="width:150px;; height:20px; font-size:8pt;"> -->
            </TD>
            <TD align="right"  style="font-size:10pt;" valign="bottom" width="15%">
            	&nbsp;
            </TD>
        </TR>
    	</TABLE>
        ~;
    }


    return $html;

}

sub get_News(){
    my ($news_link, $announce_link);

    return &SIT_Show_News_Records("League_News", "General");

    if ($data{Printable} ne "Yes")
    {
        $announce_link=qq~<A href="$selfURL?cmd=Announcements">Announcements</A>~;
    }
	my $html =qq~
    	<TABLE width="95%">
        	<TR>
	            <TD align="left" style="font-size:10pt;" valign="bottom" width="15%">
	                $news_link
	            </TD>
	            <TD align="center"  style="font-size:14pt;"  valign="middle" width="70%">
	                <B>League News</B>
	            </TD>
	            <TD align="right"  style="font-size:10pt;" valign="bottom" width="15%">
	                $announce_link
	            </TD>
            </TR>
    ~;

	my $dbquery = qq~
    SELECT *
    FROM League_News
    WHERE Article_Type LIKE "General"
    ORDER BY Date_Posted DESC LIMIT 15
    ~;

    my $sth = &DB_query_prepare($dbquery);
    if( not $sth -> execute())
    {
        $html .= qq~</TABLE>~;
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
        DisConnectFromDB();
        return $html;
    }
    my $i = 0;

    while(my $sku_ref = $sth->fetchrow_hashref())
    {
        $html .=qq~
        	<TR style=" border-style:ridge; border-width:2px; border-color:red; background-color:$report_header_color; color:black; height:30px; ">
                <TD colspan=2 style="font-size:10pt;"><B>&nbsp;$sku_ref->{Headline}</B>
				</TD>
                <TD  style="font-size:8pt;">Date Posted:<BR>$sku_ref->{Date_Posted}
				</TD>
            </TR>
            <TR>
                <TD colspan=3 style="font-size:10pt;">
                	$sku_ref->{Subheading}
                	<DIV style="font-size:8pt;">
                    	$sku_ref->{Content}<BR>-<I>$sku_ref->{Author}</I>
                    </DIV>
				</TD>
            </TR>
        ~;
        $i++;
    }
    $sth-finish;

    $html .=qq~
          	<TR>
	            <TD colspan=3 align="center"  valign="top"><BR>
	                <B><I>Information Technology Solution<BR>Provided by Spark-IT</I></B><BR><BR>
	            </TD>
	        </TR>
    	</TABLE>~;
    return $html;
}

sub get_Announcements(){

	my ($news_link, $announce_link);
    return &SIT_Show_News_Records("League_News","Announcement");

    if ($data{Printable} ne "Yes")
    {
    	$news_link=qq~<A href="$selfURL?cmd=News">League News</A>~;
    }

	my $html =qq~
    	<TABLE width="95%">
        	<TR>
            <TD align="left" style="font-size:10pt;" valign="bottom" width="15%">
            	$news_link
            </TD>
            <TD align="center"  style="font-size:14pt;"  valign="middle" width="70%">
            	<B>Announcements</B>
            </TD>
            <TD align="center"  style="font-size:10pt;" valign="bottom" width="15%">
        		$announce_link
            </TD>
            </TR>
    ~;

	my $dbquery = qq~
    SELECT *
    FROM League_News
    WHERE Article_Type LIKE "Announcement"
    ORDER BY Date_Posted DESC LIMIT 15
    ~;

    my $sth = &DB_query_prepare($dbquery);
    if( not $sth -> execute())
    {
        $html .= qq~</TABLE>~;
        push(@error_messages,"Can't execute query:<BR>$dbquery. Reason: $DBI::errstr.");
        $sth -> finish;
        DisConnectFromDB();
        return $html;
    }
    my $i = 0;

    while(my $sku_ref = $sth->fetchrow_hashref())
    {
        $html .=qq~
        	<TR style=" border-style:ridge; border-width:2px; border-color:red; background-color:$report_header_color; color:black; height:30px; ">
                <TD colspan=2 style="font-size:10pt;"><B>&nbsp;$sku_ref->{Headline}</B>
				</TD>
                <TD  style="font-size:8pt;">Date Posted:<BR>$sku_ref->{Date_Posted}
				</TD>
            </TR>
            <TR>
                <TD colspan=3 style="font-size:10pt;">
                	$sku_ref->{Subheading}
                	<DIV style="font-size:8pt;">
                    	$sku_ref->{Content}<BR>-<I>$sku_ref->{Author}</I>
                    </DIV>
				</TD>
            </TR>
        ~;
        $i++;
    }
    $sth-finish;

    $html .=qq~
          	<TR>
	            <TD colspan=3 align="center"  valign="top"><BR>
	                <B><I>Information Technology Solution<BR>Provided by Spark-IT</I></B><BR><BR>
	            </TD>
	        </TR>
    	</TABLE>~;
    return $html;
}



sub login_dir(){
	my $html = qq~
    <DIV align="left" style="font-size:10pt; margin:4px;">
    <FONT style="font-size:12pt;"><I><B>Login Directions:</B></I></font><BR><BR>
    Enter your League User login information and click [Login].<BR>
    <BR>
    For assistance with lost passwpords, Enter your League User ID e-mail address and then click [Help].
    We'll e-mail you help for your password.
    <DIV>
    ~;

    return $html;
}

sub main_HTML_login_doc(){

    my $league_user_type = "";
    $league_user_type = "Operator" if ($data{cmd} eq "OpLogin");
    $league_user_type = "Reporter" if ($data{cmd} eq "RepLogin");
    #$league_user_type = "" if ($data{cmd} eq "");

    my $html = qq~
	<TABLE rows="1" cols="3" border="0" width="100%">
        <TR>
            <TD class="frmbkg" colspan="2" height="75" valign="top" align="center" >
                <FORM name="LogIn" action="$my_WS_HTTPS_URL$selfURL" method="POST" >
                    <TABLE width="94%" border="0" >
                        <TR>
                            <TD width="50%">
                                <DIV style="font-size: 14pt;"><B>League $league_user_type Login:</B></DIV>
                            </TD>
                            <TD width="50%">
                                <DIV align="left">
                                      $gen_err_title
                                </DIV>
                            </TD>
                        </TR>
                        <TR>
                            <TD width="50%"  align="left">
                                <DIV style="font-size: 10pt;"  align="left"><BR>
                                	League User ID:<BR>
                                    <INPUT type="text" name="ID" tabindex="1" value="$data{ID}" maxlength="50">
                                    <BR>
                                </DIV>
                            </TD>
                            <TD width="50%"  align="left">
                                 $ID_Error_msg
                            </TD>
                        </TR>
                        <TR>
                            <TD width="50%"  align="left">
                                <DIV style="font-size: 10pt;"  align="left">
                                <BR>Password: (CaSe SEnsITivE)
                                <BR>
                                    <INPUT type="hidden"   name="cmd"  value="DoLogin" maxlength="50">
                                    <INPUT type="hidden"   name="cmd2"  value="$data{cmd}" maxlength="50">
                                    <INPUT type="hidden"   name="type"  value="$league_user_type" maxlength="50">
                                    <INPUT type="password" name="Pass"   tabindex="2" maxlength="16"><BR>
                                    <BR>
                                    <INPUT type="submit"   name="Submit"  value="Login"  style="background-color:#009900; color:#ffffff; width:70; height:25; font-weight:bold; font-family:Ariel, Helvetica, sans-serif;">&nbsp;&nbsp;&nbsp;
                                    <INPUT type="button"   name="helpBTN"  value="Help"   style="background-color:#FFFF00; color:#000000; width:70; height:25; font-weight:bold; font-family:Ariel, Helvetica, sans-serif;" onClick="document.LogIn.type.value='Help'; document.LogIn.submit();">&nbsp;&nbsp;&nbsp;
                                    <INPUT type="button"   name="cancelBTN" value="Cancel" style="background-color:#FF0000; color:#ffffff; width:70; height:25; font-weight:bold; font-family:Ariel, Helvetica, sans-serif;" onClick="window.location='$my_WS_HTTP_URL$selfURL';">
                                </DIV><BR>
                            </TD>
                            <TD width="50%"  align="left">
                                <DIV  align="left">
                                     $Password_Error_msg
                                </DIV>
                            </TD>
                        </TR>
                        <TR>
                            <TD colspan="2" bgcolor="#000000">
                                <div align="center"><font color="gold">*** This is
                                a secure login. ***</font></div>
                            </TD>
                        </TR>
                	</TABLE>
            	</FORM>
        	</TD>
    	</TR>
    </TABLE>
    ~;

    return $html;
}

sub Main_HTML_Doc(){
	my $left_content="";
	my $main_content="";

    my $news_content="";

    my $page_title_text="";
    my $keywords="";
	if ($My_Feature_Online == 1)
    {
        if (($data{cmd} ne "News") && ($data{cmd} ne "Announcements"))
    	{
	        $left_content = Default_Dir();
	        if($data{cmd} eq "")
	        {
	            $session_info = get_info_current_session(); #default session
	            $main_content = Default_Content() ; #Default Content
                $news_content = Default_News();
	        }
	        elsif ($data{cmd} ne "SearchNews")
	        {
	            $session_info = &get_session_info($data{Session});
	            $division_info = &get_division_info($data{Division});

                $main_content = get_player_mvp_report() if($data{cmd} eq "GetMvpRpt");
	            $main_content = get_player_statistics_report() if($data{cmd} eq "GetStatsRpt");
	            $main_content = get_team_standings_report() if($data{cmd} eq "GetStandings");
	            $main_content = show_hostroom_info() if($data{cmd} eq "ShowHosts");

	        }
            else
            {
            	$news_content = &SIT_Show_News_Records("League_News");
                $left_content = get_news_search_form();
            }
        }
        else
        {
            if ($data{cmd} eq "Announcements")
            {
            	$news_content = get_Announcements();
            }
            else
            {
            	$news_content = get_News();
            }
            $left_content = get_news_search_form();
        }
    }

    my $printable_link;
    if ($data{Printable} eq "Yes")
    {
    	$printable_link = "";
    }
    else #($data{cmd} ne "")
    {
        $printable_link = qq~
        <A href="$selfURL?Printable=Yes&CueSport=$data{CueSport}&cmd=$data{cmd}&Division=$division_info->{Division_ID}&Session=$session_info->{ID}&Team_ID=$data{Team_ID}" target="_blank">Printable Version</A>
        ~;
    }

    if (($data{cmd} eq "OpLogin") || ($data{cmd} eq "RepLogin"))
    {
    	$left_content = login_dir();
        $main_content = main_HTML_login_doc();
        $printable_link = "";
    }
    elsif ($data{cmd} eq "DoLogin")
    {
        $left_content = login_dir();
        $main_content = do_user_login();
        $printable_link = "";
    }

    my $page_title_text;
    if ($data{cmd} eq "GetStandings")
    {
    	$page_title_text=qq~ | Team Standings: $division_info->{Division_Name} $session_info->{Session}~;
        $keywords = "Team Standings, $division_info->{Division_Name},$session_info->{Session}";
    }
    elsif (($data{cmd} eq "GetStatsRpt") && ($data{Team_ID} ne ""))
    {
    	$page_title_text=qq~ | Player Statistics: $team_info->{Team_Names} - $division_info->{Division_Name} $session_info->{Session}~;
        $keywords = "Player Statistics, $division_info->{Division_Name},$session_info->{Session}";
    }
    elsif ($data{cmd} eq "GetMvpRpt")
    {
    	$page_title_text=qq~ | Most Valuable Player Report: - $division_info->{Division_Name} $session_info->{Session}~;
        $keywords = "Player Statistics, Most Valuable Player, $division_info->{Division_Name},$session_info->{Session}";
    }
    elsif ($data{cmd} eq "ShowHosts")
    {
    	$page_title_text=qq~ | Host Rooms: $division_info->{Division_Name} $session_info->{Session}~;
        $keywords = "Host Rooms, Pool Halls, Billiard Rooms, $division_info->{Division_Name},$session_info->{Session}";
    }
    elsif ($data{cmd} eq "ShowTeams")
    {
    	$page_title_text=qq~ | Team Rosters: $division_info->{Division_Name} $session_info->{Session}~;
        $keywords = "Host Rooms, Pool Halls, Billiard Rooms, $division_info->{Division_Name},$session_info->{Session}";
    }
    else
    {
        $page_title_text=qq~ | $league_op_info->{League_Name} ~;
        $keywords = "";
    }

    $keywords .= join(",",split(" ",$page_title_text)) unless ($page_title_text eq "");


  	print qq~

    <html>
	<head>
	    <title>$Feature_Name $page_title_text </title>
	    <meta http-equiv="Content-Type" content="text/html;">
	    <LINK rel="stylesheet" href="/ws_styles.css" type="text/css">
	    <META name='description' content='$Feature_Name at BunjeeCanada.com.'>
	    <META name='keywords' content='$Feature_Name, $league_op_info->{League_Name}, $keywords '>
	</HEAD>

    <body bgcolor="#ffffff" style='font-family:Ariel,Helvetica,sans-serif;'>

    <table border="0" cellpadding="0" cellspacing="0" width="100%"  >
	   <tr>
	      <td width="178"><img src="$my_Images_folder/spacer.gif" width="170" height="1" border="0"></td>
	      <td width="32"><img src="$my_Images_folder/spacer.gif" width="32" height="1" border="0"></td>
	      <td width="914" ><img src="$my_Images_folder/spacer.gif"  height="1" border="0"></td>
	      <td width="17"><img src="$my_Images_folder/spacer.gif" width="1" height="1" border="0"></td>
	   </tr>

	   <tr>
	      <td colspan="3" valign="top" class='Header'>
	          <TABLE width="100%" border="0" cellpadding="2">
	            <TR>
	               <TD width="600px" valign="top">
	                        <div style="margin-left:8px; margin-top:2px; margin-right:8px; ">

                                <div style='font-size:16pt; font-family:Arial,Helvetica,sans-serif;'>$my_ws_logo_code  Bunjee Canada.com&#153;
                                <BR><FONT size='3' style='font-size:16pt;'><B>$Feature_Name - $league_op_info->{League_Name} </B></FONT>
			                     </div>

                         	$my_main_links
	                  </div>
	               </TD>
                   <TD align="right"><img src="$my_WS_HTTP_URL/league-data-upload/$league_op_info->{League_User_Path}/$league_op_info->{League_User_Path}_logo.jpg" border="0" width="100"><BR>
                   	<DIV align="right"><A href="$my_WS_HTTP_URL/ccs-championships.html" title="CSS Championship Information">Championship Info</A></DIV>
                   </TD>
	            </TR>
	         </TABLE>
	      </td>
	      <td width="7"><img src="$my_Images_folder/spacer.gif" width="1px" height="90px" border="0"></td>
	   </tr>
	   <tr>
	      <td rowspan="2" class='LeftColumn' valign="top" align="left" width="200"><BR>

                   <DIV align="center" style="border-style:solid;  border-color:$report_header_color; font-size:9pt; background-color:#ffffff; font-family:Arial,Helvetica,sans-serif;">
	                  <BR>
                      $left_content<BR>
                   </DIV>

	      </td>
	      <td style="font-family:Arial,Helvetica,sans-serif; font-size:12pt;" width="70%" ><B>&nbsp;&nbsp;&nbsp; <A href="$my_WS_HTTP_URL$selfURL?CueSport=8ball">8-Ball Stats</A> | <A href="$my_WS_HTTP_URL$selfURL?CueSport=9ball">9-Ball Stats</A><!-- | <A href="$my_WS_HTTP_URL$selfURL?cmd=Announcements">Announcements</A> | <A href="$my_WS_HTTP_URL$selfURL?cmd=News">News</A>--></B></td>
	      <td style="font-family:Arial,Helvetica,sans-serif; font-size:12pt;" align=right width="30%">$printable_link</td>
	      <td width="7"><img src="$my_Images_folder/spacer.gif" width="1" height="29" border="0"></td>
	   </tr>
	   <tr>

	      <td colspan=2 width="914" valign="top">

              <div style="margin-left:10px; margin-top:0px; margin-right:10px; ">
              	<FONT color='red'>@error_messages</FONT>
                $main_content<BR><BR>
                $news_content
	         </div>

	        </td>
	      <td width="7"><img src="$my_Images_folder/spacer.gif" width="1" height="370" border="0"></td>
	   </tr>
	</table>
    <TABLE align='center' width="100%" border="0" cellpadding="10" bgcolor="#FFFFFF">
	   <TR>
	      <TD align='center'><FONT face="Arial, Helvetica, sans-serif" size="1" style="font-size:8pt;">
          	&copy; Copyright 2004 $my_Business_tradename&#153;
			All Rights Reserved. Trademarks and images not proprietary to $my_Business_tradename are used under license or with permission from their respective owners.<BR>Spark-IT Driven&#153</FONT></TD>
	   </TR>
	</TABLE>
	</body>
	</html>
    ~;
}

sub Main_PRINTER_Doc(){

	return Main_HTML_Doc() if ($My_Feature_Online == 0);

    my $left_content = Default_Dir();
    my $main_content;
    	if ($My_Feature_Online == 1)
    {
        if (($data{cmd} ne "News") && ($data{cmd} ne "Announcements"))
    	{
	        $left_content = Default_Dir();
	        if($data{cmd} eq "")
	        {
	            $session_info = get_info_current_session(); #default session
	            $main_content = Default_Content() ; #Default Content
                $news_content = Default_News();
	        }
	        else
	        {
	            $session_info = &get_session_info($data{Session});
	            $division_info = &get_division_info($data{Division});

                $main_content = get_player_mvp_report() if($data{cmd} eq "GetMvpRpt");
                $main_content = get_player_statistics_report() if($data{cmd} eq "GetStatsRpt");
	            $main_content = get_team_standings_report() if($data{cmd} eq "GetStandings");
	            $main_content = show_hostroom_info() if($data{cmd} eq "ShowHosts");

	            #$main_content = get_team_list() if($data{cmd} eq "GetTeams");
	            #$main_content = get_team_roster() if($data{cmd} eq "GetTeamRoster");
	            #$main_content = get_player_stats() if($data{cmd} eq "GetPlayerStats");
	        }
        }
        else
        {
            if ($data{cmd} eq "Announcements")
            {
            	$news_content = get_Announcements();
            }
            else
            {
            	$news_content = get_News();
            }


        }
    }
    my $op_info = $my_business_small_html_header;
    $op_info =~ s/\n/<BR>/g;


    my $page_title_text;
    if ($data{cmd} eq "GetStandings")
    {
    	$page_title_text=qq~ | Team Standings: $division_info->{Division_Name} $session_info->{Session}~;
        $keywords = "Team Standings, $division_info->{Division_Name},$session_info->{Session}";
    }
    elsif (($data{cmd} eq "GetStatsRpt") && ($data{Team_ID} ne ""))
    {
    	$page_title_text=qq~ | Player Statistics: $team_info->{Team_Names} - $division_info->{Division_Name} $session_info->{Session}~;
        $keywords = "Player Statistics, $division_info->{Division_Name},$session_info->{Session}";
    }
    elsif ($data{cmd} eq "ShowHosts")
    {
    	$page_title_text=qq~ | Host Rooms: $division_info->{Division_Name} $session_info->{Session}~;
        $keywords = "Host Rooms, Pool Halls, Billiard Rooms, $division_info->{Division_Name},$session_info->{Session}";
    }
    elsif ($data{cmd} eq "ShowTeams")
    {
    	$page_title_text=qq~ | Team Rosters: $division_info->{Division_Name} $session_info->{Session}~;
        $keywords = "Host Rooms, Pool Halls, Billiard Rooms, $division_info->{Division_Name},$session_info->{Session}";
    }
    else
    {
        $page_title_text=qq~ | $league_op_info->{League_Name} ~;
        $keywords = "";
    }

    $keywords .= join(",",split(" ",$page_title_text)) unless ($page_title_text eq "");


	print qq~
    <html>
	<head>
	    <title>$Feature_Name $page_title_text</title>
	    <meta http-equiv="Content-Type" content="text/html;">
	    <LINK rel="stylesheet" href="/ws_styles.css" type="text/css">
        <META name='description' content='$Feature_Name at BunjeeCanada.com.'>
	    <META name='keywords' content='$Feature_Name, $league_op_info->{League_Name}, $keywords '>
	</HEAD>

    <body bgcolor="#ffffff" style='font-family:Ariel,Helvetica,sans-serif;'>
    <TABLE width="98%" border="0">
	    <TR>
	        <TD align="left" width="33%">
                <img src="$my_WS_HTTP_URL/league-data-upload/$league_op_info->{League_User_Path}/$league_op_info->{League_User_Path}_logo.jpg" border="0">
	        </TD>
	        <TD align="center" width="33%">
                $my_Business_contact1

                $op_info

                <!--
                $league_op_info->{FName} $league_op_info->{LName}<BR>
                $league_op_info->{Address}<BR>
                $league_op_info->{City}, $league_op_info->{State} <BR>
                $league_op_info->{Zip}<BR><BR>
                $league_op_info->{Phone_Number}<BR>
                $league_op_info->{Email}<BR> -->
	        </TD>
	        <TD align="right" width="33%">
            	<img src="$my_WS_HTTP_URL/league-data-upload/$league_op_info->{League_User_Path}/$league_op_info->{League_User_Path}_logo.jpg" border="0">
	        </TD>
	    </TR>
	</TABLE>
    <HR>
	<div style="margin:10px;">

	    <FONT color='red'>@error_messages</FONT>
	    $main_content<BR>
        $news_content
	</div>
	</body>
	</html>
    ~;
}

#End app specific subs
__END__



