#!/usr/bin/perl

###############################################
###                                                                                  
###     John Jan Popovic, http://1stmuse.com
###     for Etranet                                    
###                                                                                 
###                                    
###                                                                             
###############################################

use CGI qw (:standard);
use CGI::Carp qw(fatalsToBrowser);
use lib qw(.);
use CGI qw(nph);
###############################################
###                  Set Configurations Below
###############################################
### Specify database OPERE fields in the array below 
@fields = 
( 
"CARD_Broj_kartice",
"CARD_ID_OIB",
"CARD_Ime",
"CARD_Prezime",
"CARD_Datum_rodjenja",
"CARD_Exp_date",
"CARD_Bodovi",
"CARD_Brand",
"CARD_Email",
"CARD_Popup_message"
);


### Set URL and email fields to be hyperlinks 
### The number used corresponds to its placement in the array above 
### Remeber to start your count at zero
### Leave the variables empty to remove the hyperlink
$script_name ="$ENV{'SCRIPT_NAME'}";
  
$homedir = $ENV{'DOCUMENT_ROOT'};
$root_   = $ENV{'DOCUMENT_ROOT'};
### Specify the required fields below. This may be left empty 
@required = ();

### Specify the filtered words below.  This may be left empty 
@filter = ("word1","word2");
$database    = "$ENV{'DOCUMENT_ROOT'}/fido/fido_clients.txt";	# Data file OPERE name and path
$user_file   = "$ENV{'DOCUMENT_ROOT'}/fido/users.txt";			   # User file name and path

	   # This script name
$db_name = "Fido - cards";	   	   # The database name
$table_width = "90%";		           # The display width of the entire table
$record_width = "80%";			   # The display width of the database records
$max_rows_returned = "20";	  	   # Max number of rows displayed per page
$filter_html_tags = "yes";		   # Removes HTML tags from record entries
$check_user_duplicates = "yes";		   # Checks for duplicate user names in user file
$use_external_html = "no";		   # Set to "yes" to use your own html template
$external_html_header = "header.html";     # File name and path to html template header
$external_html_footer = "footer.html";	   # File name and path to html template footer
$authenticate = "yes";			   # Prompts users for a user name and password
$register	= "yes";		   # Allows new user registration
$record_ownership = "yes";		   # Users can modify/delete only their records
$admin_user_name = "admin";		   # This is the default Administrator user name
$default_user_permission_search = "yes";   # Gives newly registered users Search permission
$default_user_permission_add = "yes";	   # Gives newly registered users Add permission
$default_user_permission_modify = "no";    # Gives newly registered users Modify permission
$default_user_permission_delete = "no";    # Gives newly registered users Delete permission
$defult_search_index = "0";
$image_path = 'http://loyalty.hr/opere';

###############################################
###            Change Nothing Below This Line                 
###############################################


############## Global Viariables ##################

$q = new CGI;
$field_count = @fields;
$colspan = $field_count+1;
$EXCLUSIVE = 2;
$UNLOCK    = 8;
$user = $q->param(user);
$user   = $q->cookie(user) if($user eq "");
$user_search = $q->param(user_search);
$user_search = "yes" if($authenticate eq "no");
$user_add = $q->param(user_add);
$user_add = "yes" if($authenticate eq "no");
$user_trans = $q->param(user_trans);
$user_trans = "yes" if($authenticate eq "no");
$user_modify = $q->param(user_modify);
$user_modify = "yes" if($authenticate eq "no");
$user_delete = $q->param(user_delete);
$user_delete = "yes" if($authenticate eq "no");
$selected_user = $q->param(selected_user);
$admin_add    = $q->param(admin_add);
$sort         = $q->param(sort_on);
$search_for   = $q->param(search_for);
$fido_customer= $q->param(fido_customer);
$Supply       = $q->param(Supply);
$search_field = $q->param(search_field);
$action       = $q->param(action);
$display      = $q->param(display);
@keys         = $q->param(key);
$key          = $q->param(key);
$bodovi       = $q->param(bodovi);
$email        = $q->param(email);
$key_matches  = @keys;
$search_field = "all" if($search_field eq "");
$search_for   = '.'   if ($search_for eq "");
$action = $q->param(which_search) if($action =~ /^View/i);
$find_           = $q->param(find_);
$id_             = $q->param(id_);
$filter_         = $q->param(filter_);
$search_field_   = $q->param(search_field_);
################# Main Logic ##################
if($q->param('operation') eq 'opere')  { $action='opere'};
if($q->param('operation') eq 'logout')  { $action='logout'};
if($q->param('operation') eq 'main_menu')  { $action='Main Menu'};
if($q->param('operation') eq 'search')  { $action='search'};
########

	
## To perform search NADJI, click here:
## http://1stmuse.com/cgi-bin/fido_clients.cgi?operation=nadji_card&find_=1938


	if($q->param('operation') eq 'nadji_card') 	{ 
	 $action='nadji_card';
	 my $find_ = $q->param('find_');	 
         $search_for = $find_;
	}


########
if($action =~ /add administrator/i){ &add_user; exit;}
if ($authenticate eq "yes"){ unless (-e $user_file){ $title="Set Administrative Password"; &create_admin; } }
if($register eq "yes" && $action =~ /register/i){ &register; exit;}
if($action =~ /add user/i){ &add_user; exit;}
if($action =~ /submit login/i){ &authenticate; exit;}
if ($authenticate eq "yes" && $user eq ""){ &login; exit;}
if($action =~ /logout/i){ &logout; exit;}

if($authenticate eq "yes"){
# the following operations can be performed, only if AUTHENTICATION IS VALID
	if($q->param('operation') eq 'search')  { 
	    $action='search';
	    my $buffer;
	    my $id = 0;
	    my $filter_ = $q->param('filter_');
	    my $find_   = $q->param('find_');
	    my $search_field_   = $q->param('search_field_');
	    my $id_     = $q->param('id_');
	    my $user_   = $q->param('user_');
	    $search_for = $find_;
	    $user=$user_;
	    $search_field = $search_field_;
#	    $id = 12345;
	}

	if($q->param('operation') eq 'main_menu')
	  { 
	    $action='main_menu';
	    my $buffer;
	    my $user_   = $q->param('user_');
	    $search_for = $find_;
	    $user=$user_;
	}

	if($action =~ /new_card/i){ &print_add_screen;}
	elsif($action =~ /conferma opera/i){ &add_record; $message="Record Added"; $title="Main Menu"; &print_default($title, $message);}
	elsif($action =~ /Edit_opera/i){ $title="Edittion Error"; $error_message="You forgot to select a record to modify!"; &access_problem if($key < 1); &search_db($key);  &print_modify_page;}
	elsif($action =~ /modify this record/i){ $title="Modify"; &delete_records; $key=$keys[0]; &add_record; &print_back;}
	elsif($action =~ /conferma_Edit/i){ $title="Modify"; &delete_records; $key=$keys[0]; &add_record; &print_back;}
	elsif($action =~ /delete record/i){ $title="Delete Record"; $error_message="You forgot to select a record to delete!"; &access_problem if($key < 1); &delete_records; $message="Record Updated"; $title="Main Menu"; &print_default($title, $message);}
	elsif($action =~ /modify/i){ &search_db($search_for); $title="Modify Which Record?"; $button_text="Modify Record"; $choose="modify"; &search_results;}
	elsif($action =~ /billing_report/i){ $title="Billing results"; &billing_results($search_for,3); }
	elsif($action =~ /email_billing/i){ $title="Billing results"; &mail_billing($search_for,3); }

        elsif($action =~ /mailinglist/i){ $title="Extract mailinglist"; &extract_mailinglist; $message="Mailinglist was created."; $title="Main Menu"; &print_default($title, $message);}

        elsif($action =~ /backup/i){ $title="Backup Archive"; &backup_fido; $message="The backup was successful."; $title="Main menu"; &print_default($title, $message);}
	elsif($action =~ /delete/i){ &search_db($search_for); $title="Delete Which Record?"; $button_text="Eliminate card"; $choose="delete"; &search_results;}
	elsif($action =~ /search/i){ &search_db($search_for); $title="Search Results"; $button_text = "";  $choose="search"; $what="search"; &search_results;}
	elsif($action =~ /email_search_/i){ &search_db($search_for); $title="Search Results"; $button_text = "";  $choose="email_search_"; $what="email_search_"; &search_email_results;}
	elsif($action =~ /user manager/i){ $title="User Manager"; &user_manager;}
	elsif($action =~ /create new user/i){ $title="User Manager - Create New User"; $perform="add"; $button_text ="Add User"; &edit_user;}
	elsif($action =~ /edit selected user/i){ $title="User Manager - Edit Selected User"; $perform="edit"; $button_text ="Edit User"; &edit_user;}
	elsif($action =~ /edit user/i){ $old_password = $q->param(old_password); &delete_user; $perform="edit"; &add_user;}
	elsif($action =~ /remove selected user/i){ $perform="delete"; &delete_user; $title="User Manager"; &user_manager;}
        elsif($action =~ /nadji_card/i){ &search_cards($search_for);}
	else { $title="Main Menu"; &print_default($title); }
}

exit;

################# Add Record ##################

sub add_record {
  foreach $required (@required){
  if($q->param($required) eq "") { 
  $title = "Add A Record"; $error_message = "You did not fill out the required information!"; &access_problem($error_message); exit; } }
  $when_added = &get_date;
  $key   = time();
  $record=$key;
  $record  .= "\|$user";
  $record  .= "\|$when_added";
  foreach $field (@fields){ ${$field}  = $q->param($field); ${$field}  = filter(${$field}); $record  .= "\|${$field}"; }
   unless (-e $database){ open (DB, ">$database") || die "Error creating database.  $!\n"; }
   else { open (DB, ">>$database") || die "Error opening database.  $!\n"; }
   flock DB, $EXCLUSIVE;
   seek DB, 0, 2;
   print DB "$record\n";
   flock DB, $UNLOCK;
  close(DB);
} # End of add_record subroutine.




################# Add Screen: Add new Card ##################

sub print_add_screen{
$title="Add new Card";

&html_header($title);
  print<<HTML;
<SCRIPT LANGUAGE="JavaScript">

<!-- This script locksout <CR> i.e. Enter Key and requires the SUBMIT button to be clicked to send form -->
<!-- Begin

function tabOnEnter (field, evt) {
      var keyCode = document.layers ? evt.which : document.all ? 
     evt.keyCode : evt.keyCode;
      if (keyCode != 13)
        return true;
      else {
        getNextElement(field).focus();
        return false;
      }
}


function getNextElement (field) 
{
    var frm = field.form;
    var bIs = false;
    for (var e=0;e<frm.length;e++)
    {
      if(frm[e].type!="hidden" && bIs) return frm.elements[e];
      if (field==frm[e]) bIs=true;
    }
}

//  End -->
</script>



     <P>
      <TABLE BORDER=0 CELLSPACING=0>

HTML
  foreach $field (@fields){

$input_txt="<INPUT TYPE=TEXT NAME=\"$field\"   onkeydown=\"return tabOnEnter (this, event);\"  >";
$cerca=$search_for;
$input_provenienza="<SELECT NAME=\"$field\"  onkeydown=\"return tabOnEnter (this, event);\"  >
<OPTION VALUE='gi\E0 opera'>gi\E0 opera<OPTION VALUE='Fiera'>Fiera<OPTION VALUE='per conoscenza'>per conoscenza
<OPTION VALUE='pagine gialle'>pagine gialle<OPTION VALUE='Internet'>Internet</SELECT>";

     $input_html=$input_txt;



print<<HTML;
        <TR>
         <TD><B>\u$field:</B></TD>
         <TD>$input_html</TD>
         </TR>
HTML

  } # End of foreach.
      print<<HTML;
       <TR>
        <TD COLSPAN=2>
         <CENTER><BR>
<INPUT TYPE=button  onClick=" myForm.action.value='Conferma opera';this.form.submit();"  VALUE="Conferma card" >

         </CENTER>
        </TD>
       </TR>
      </TABLE>
     <P>
    </FONT>
<SCRIPT LANGUAGE="JavaScript" >
// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// ===================================================================

//-------------------------------------------------------------------
// getElementIndex(input_object)
//   Pass an input object, returns index in form.elements[] for the object
//   Returns -1 if error
//-------------------------------------------------------------------
function getElementIndex(obj) {
	var theform = obj.form;
	for (var i=0; i<theform.elements.length; i++) {
		if (obj.name == theform.elements[i].name) {
			return i;
			}
		}
	return -1;
	}

// -------------------------------------------------------------------
// tabNext(input_object)
//   Pass an form input object. Will focus() the next field in the form
//   after the passed element.
//   a) Will not focus to hidden or disabled fields
//   b) If end of form is reached, it will loop to beginning
//   c) If it loops through and reaches the original field again without
//      finding a valid field to focus, it stops
// -------------------------------------------------------------------
function tabNext(obj) {
	if (navigator.cgiatform.toUpperCase().indexOf("SUNOS") != -1) {
		obj.blur(); return; // Sun's onFocus() is messed up
		}
	var theform = obj.form;
	var i = getElementIndex(obj);
	var j=i+1;
	if (j >= theform.elements.length) { j=0; }
	if (i == -1) { return; }
	while (j != i) {
		if ((theform.elements[j].type!="hidden") && 
		    (theform.elements[j].name != theform.elements[i].name) && 
			(!theform.elements[j].disabled)) {
			theform.elements[j].focus();
			break;
			}
		j++;
		if (j >= theform.elements.length) { j=0; }
		}
	}
</SCRIPT>
HTML
&html_footer;
} # End of print_add_screen subroutine.



############## Delete Records #################

sub delete_records   {              
  open (DATABASE, "$database") or die "Error opening file: $!\n";
  while (<DATABASE>)   {
    $line = $_;
    chop $line;
    @dbfields = split (/\|/, $line);
    $deleted = "no";
    if ($dbfields[0] eq $q->param(key)) { $deleted = "yes"; if ($user eq $dbfields[1]) { $security_satisfied = "yes"; } }
    elsif ($deleted ne "yes") { $new_data .= "$line\n"; }
    } #end of while
  close (DATABASE);
  if ($authenticate ne "yes") { $security_satisfied = "yes"; }
  if ($security_satisfied ne "yes" && $record_ownership eq "yes" && $admin_user_name ne "$user")
    {
    $error_message = "Lei non ha le permessi necessari per l\92accesso a questa card!";
    &access_problem($error_message);
    exit;
    }  else  {
    flock DATABASE, $EXCLUSIVE;
    open (DATABASE, ">$database") or die "Error opening file: $!\n";
    print DATABASE "$new_data";
    close (DATABASE);
    flock DATABASE, $UNLOCK;
    }
  } 








############# Results Screen ################
sub search_results{
&html_header($title);
  $rows_left_to_view = $total_row_count - $new_hits_seen;
  $start_hit = $hits_seen + 1;
  $end_hit = $new_hits_seen;
  $hits_displayed = $end_hit - $start_hit + 1;
  if ($total_row_count > 1) {
    print qq~<P>Total Found: <B>$total_row_count</B> records<BR>~;
    if ($total_row_count > $max_rows_returned) {
      if ($hits_displayed == 2) {  print qq~<B>Last two</B> records shown below<BR>~;  }
      elsif ($hits_displayed == 1) {  print qq~<B>Last</B> record shown below<BR>~;  }
      else { print qq~<B>$start_hit</B> - <B>$end_hit</B> shown below<BR>~;  }
    } #end if
  } #end if ... > 1
  else { print qq~<P>Total Found: <B>1</B> record\n~; }
 
$cerca = $search_for;
print "<br>";




$which_search = $choose;

&next_page_buttons($rows_left_to_view);



    print "<INPUT TYPE=\"hidden\" NAME=\"key\" VALUE='0'>\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"fido_customer\" VALUE='0'>\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"bodovi\" VALUE='0'>\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"email\" VALUE='0'>\n";

if($display =~/columns/i) {
 print<<HTML;
	<p><TABLE BORDER=0 CELLSPACING=2 CELLPADDING=2 WIDTH=$record_width>
    <TR BGCOLOR="#e0e0e0">
HTML
  if($choose =~ /(modify|delete)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2>
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Modify Record';this.form.submit();\"  VALUE=\"Modify Record\" >
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit();\"  VALUE=\"Eliminate card\" >
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='nuovo';this.form.submit();\" VALUE=\"aggiungere card\" >
</TD></TR>\n";
  }

  foreach $field (@fields){
    print "<TD ALIGN=CENTER><B>\u$field</B></TD>\n";
  } # End of foreach


  print "</TR>";
  foreach $record (@results){
    ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $record); 
    print "<TR BGCOLOR=\"#efefef\">\n";
    if($choose =~ /(modify|delete)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2>
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Modify Record';this.form.submit();\"  VALUE=\"Modify Record\" >
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit();\"  VALUE=\"Eliminate card\" >
</TD></TR>\n";
    } # End of if.
      for($x=0;$x<$field_count;$x++){
      $item = &check_item($field_vals[$x], $x);
      print "<TD>$item</TD>\n";
    }
     print "</TR> ";
  } # End of foreach loop.
  print<<HTML;
</TR></TABLE>
HTML
} else {
  foreach $record (@results){
    ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $record); 

print<<HTML;
	<P><TABLE BORDER=0 CELLSPACING=2 CELLPADDING=2 WIDTH=$record_width>
HTML
   $x=0;
   foreach $field (@fields){
     ${$field} = $field_vals[$x];
     $x++;
   } 
  $x=0;
  foreach $field (@fields){
  $item = $field_vals[$x];

$background_color="#e0e0e0";
$line= "<TD BGCOLOR='#efefef' WIDTH=100%>$item</TD>";
if ($x > 9) {$background_color='#B6DB91'; $line= "<TD BGCOLOR='#D5FFD5' WIDTH=100%>$item</TD>" };

$campo = $field;

print<<HTML;
     <TR>
      <TD BGCOLOR=$background_color><B>\u$campo</B></TD>
      $line
     </TR>
HTML
   $x++;
   } # End of foreach field loop.

    $fido_customer ="$CARD_Ime $CARD_Prezime";

    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2> ";

    chomp $CARD_Email;
    print "<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Edit_opera';this.form.submit();\"  VALUE=\"Edit card\" >
           <INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit();\"  VALUE=\"Eliminate card\" >
           <INPUT TYPE=button  onClick=\"myForm.email.value='$CARD_Email';myForm.bodovi.value='$CARD_Bodovi';myForm.fido_customer.value='$fido_customer';myForm.search_for.value='$CARD_Broj_kartice';myForm.action.value='billing_report';this.form.submit();\" VALUE=\"Billing report\" > 
           <INPUT TYPE=button  onClick=\"myForm.email.value='$CARD_Email';myForm.bodovi.value='$CARD_Bodovi';myForm.fido_customer.value='$fido_customer';myForm.search_for.value='$CARD_Broj_kartice';myForm.action.value='email_billing';this.form.submit();\" VALUE=\"Email billing\" > 

";



  print "</TABLE><P>";

  } # End of foreach record loop.

### intervention

} # End of if display loop



$which_search = $choose;
############### next page buttons 
&next_page_buttons($rows_left_to_view);

    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"display\" VALUE=\"$display\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_field\" VALUE=\"$search_field\">\n";

print "<p>";
$cerca_t=$cerca;
if ($cerca eq '.') {$cerca_t='tutto'};

&html_footer;
} # End of search_results subroutine.



################ Default Screen ##################
sub print_default {
### intervention
$i_analisi =0;
if ($action eq 'Avanti') { &print_add_screen;exit;};
&html_header;
 print<<HTML;
  <TABLE BORDER=0 CELLSPACING="0" CELLPADDING="3"><TR><TD COLSPAN=3>
  <TR><TD width="210"><B>Search for:</B><BR>
<INPUT TYPE="text" NAME="search_for" SIZE="35" 
onkeydown="if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))
           {myForm.action.value='search';this.form.submit();return false;} 
else return true;" ></TD>
          <TD width="234" > 
<br>
<input onclick="myForm.action.value='search';this.form.submit();" value="Find" type="button">
</TD>
        
        </TR>
<TR>
    <TD><B>Search in the fields:</B><BR><SELECT NAME="search_field"><OPTION VALUE="all">All 
HTML
   $x=0;
   $selected='';
   foreach $field (@fields){  
      print "<OPTION VALUE=$x $selected>\u$field";
      $x++;
      $selected='';
      if ($x eq $defult_search_index) { $selected='selected';}
  }
  print<<HTML;
    </SELECT></TD><TD><B>Sort on:</B><BR><SELECT NAME="sort_on">
HTML
  $x=0;
  $selected='';
  foreach $field (@fields){  print "<OPTION VALUE=$x  $selected>\u$field";  
      $x++;
      $selected='';
      if ($x eq $defult_search_index) { $selected='selected';}
  }
  print<<HTML;
</SELECT></TD>
	<TD><B>Display: </B><BR><SELECT NAME="display">
HTML
if($display eq "rows") { print "<OPTION VALUE=\"rows\" SELECTED>Cards"; }
else { print "<OPTION VALUE=\"rows\">cards"; }
if($display eq "columns") { print "<OPTION VALUE=\"columns\" SELECTED>Table"; }
else { print "<OPTION VALUE=\"columns\">Tabellone"; }
  print<<HTML;
</SELECT></TD></TR></TABLE><br>
HTML
$footer="default";
&html_footer;
} # End of print_default subroutine.













########### Search & Sort Database #############
sub search_db{
  my $search_for = $_[0];
   unless (-e $database){ open (DB, ">$database") || die "Error creating database.  $!\n"; }
   else { open (DB, "$database") || die "Error opening database.  $!\n"; }
    while(<DB>){
      if($search_field =~ /all/i) {

          if (/$search_for/oi){ push @results, $_};

      } else {
        ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $_);
        
          if ($field_vals[$search_field] =~ /$search_for/oi) { push @results, $_};

      } # End of else.
    } # End of while.
  close (DB);
  foreach $curr (@results){
    ($key,$dbuser,$when_added,@rest) = split(/\|/, $curr);
     $max = @fields;
     $code='$record{$key} = { key => "$key", ';
     $code .='dbuser => "$dbuser", ';
     $code .='when_added => "$when_added", ';
     for($x=0;$x<$max;$x++){
      $code .= "\$fields[$x] => \"\$rest[$x]\",\n";
    } # End of for
     $code .= '};';
    eval $code;
  } # End of foreach curr
   $sort_on = "$fields[$sort]";
   @results=();
  foreach $rp (sort { $a->{$sort_on} cmp $b->{$sort_on} } values %record){
    $new_rec = $rp->{key};
    $new_rec .= "\|$rp->{dbuser}";
    $new_rec .= "\|$rp->{when_added}";
    for($x=0;$x<$max;$x++){
      $new_rec .= "\|$rp->{$fields[$x]}";
    } # End of for
    push @results, $new_rec;
  } # End of foreach
$count = @results;
if($count < 1){ 
  $message="No Matches Found For '$search_for'";
  $title="Main Menu";
  &print_default($title, $message);  
### intervention
  exit;
}
$total_row_count = @results;
if ($total_row_count > $max_rows_returned) {
$hits_seen = $q->param(new_hits_seen);
  for ($i = 1; $i <= $hits_seen; $i++)
    { $seen_row = shift (@results);  }
  $length_of_database_rows = @results;
  for ($i = $length_of_database_rows-1; $i >= $max_rows_returned; $i--)
    { $extra_row = pop (@results); }
  $new_hits_seen = $hits_seen + @results; } else { $show="no"; }
} # End of search_db subroutine.

################### Filter ####################
sub filter{
  $temp = $_[0];
  $temp =~ s/\|//g; 
  $temp =~ s/\"/'/g; 
  foreach $removed (@filter) { $temp =~ s/$removed/\?\$\%\&/gi; }
  if ($filter_html_tags eq "yes") { $temp =~ s/<[^>]*>//gs;  }
  return ($temp);
}

############### Check Item #################

sub check_item{
  $r_val = $_[0];
  $index = $_[1];
  if($r_val =~ /^\s*$/){$r_val="&nbsp;"; return($r_val);}
  if( ($index_of_image_url ne "") && (($index eq $index_of_image_url)|($index eq $index2_of_image_url)) ) { 
  if ($r_val =~ /http:\/\//i){ $link = "$r_val"; }                        
  else { $link = "http://1stmuse.com/opere/"; $link .= "$r_val";  }
  $r_val2 = "<a href=\"$link\">$r_val</a>"; $r_val = $r_val2; 
   }
  if($index_of_URL ne "" && $index eq $index_of_URL) { $r_val2 = "<a href=\"$r_val\">$r_val</a>"; $r_val = $r_val2; }
  if($index_of_email ne "" && $index eq $index_of_email) { $r_val2 = "<a href=\"mailto:$r_val\">$r_val</a>"; $r_val = $r_val2; }
  return($r_val);
}
################### Login ###################
sub login {
$message = $_[0];
$title = "Login";
&html_header($title,$message);
print<<HTML;
<TABLE><TR>
<TD><B>User Name</B><BR><INPUT TYPE="text" NAME="user" SIZE="30"></TD></TR>
<TR><TD><B>Password</B><BR><INPUT TYPE="password" NAME="password" SIZE="30" onkeydown="if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))
    {myForm.action.value='Submit Login';this.form.submit();return false;} 
    else return true;"></TD>
</TR>
<TR><TD ALIGN=MIDDLE><BR>
<INPUT TYPE=button  onClick=\" myForm.action.value='Submit Login';this.form.submit();\"  VALUE="Submit Login" >
HTML
if($register eq "yes") { print "<INPUT TYPE=button onClick=\" myForm.action.value='Register';this.form.submit();\" VALUE=\"Register\">"; }
print<<HTML;
</TD>
</TR>
</TABLE>
HTML
$footer = "login";
&html_footer;
}

################ Authenticate ################

sub authenticate {
    $form_password = $q->param(password);
    open (USERFILE, "$user_file") || die "Error opening user file.  $!\n";
    $user_matched = 0;
    while (<USERFILE>) {
	chop($_);
	($password, $user, $u_search, $u_add, $u_modify, $u_delete) = split(/\|/, $_);
	if ($q->param(user) eq $user) {
	    $user_matched = 1;
	    $username = $user;
	    $user_add = $u_add;
	    $user_modify = $u_modify;
	    $user_search = $u_search;
	    $user_delete = $u_delete;
	if (&auth_encrypt ($form_password, $password) eq $password) {
  	    $cookie = cookie(-NAME=>'user',-VALUE=>"$user",-EXPIRES=>'+3d');
	} # End of if passwords match
	} # End of if username matches
    } # End of While
    close (USERFILE);
    if ($user_matched == 1 && $cookie eq "") {
	    $footer = "login";
	    $title = "Login";
	    $error_message = "Your password did not match your user name!";
	    &access_problem($error_message);
	    exit;    }
    if ($user_matched == 0) {
	    $footer = "login";
	    $title = "Login";
	    $error_message = "Your user name was not found!";
	    &access_problem($error_message);
	    exit;    }
print header(-cookie=>[$cookie]);
$set_cookie = "yes";
$message = "User \"$username\" is now logged in";
$title = "Main Menu"; 
$user = $username;
&print_default($title, $message);
exit;
}

############### Register Form ################

sub register {
$title = "Register A New User";
&html_header($title);
 print<<HTML;
<TABLE><TR>
<TD><B>User Name</B><BR><INPUT TYPE="text" NAME="user" SIZE="30"></TD></TR>
<TR><TD><B>Password</B><BR><INPUT TYPE="password" NAME="password" SIZE="30"></TD></TR>
<TR><TD><B>Re-Type Password</B><BR><INPUT TYPE="password" NAME="password2" SIZE="30"></TD></TR>
HTML

 print<<HTML;
<TR><TD ALIGN=MIDDLE><BR>
<INPUT TYPE="hidden" NAME="search" value="$default_user_permission_search">
<INPUT TYPE="hidden" NAME="add" value="$default_user_permission_add">
<INPUT TYPE="hidden" NAME="modify" value="$default_user_permission_modify">
<INPUT TYPE="hidden" NAME="delete" value="$default_user_permission_delete">
<INPUT TYPE=button  onClick=" myForm.action.value='Add User';this.form.submit();"  VALUE="Add User" >
<INPUT TYPE=button  onClick=" myForm.action.value='Back To Login';this.form.submit();"  VALUE="Back To Login" >
</TD>
</TR>
</TABLE>
HTML
$footer = "login";
&html_footer;
}

################ Add User ##################

sub add_user {
$user = $q->param(user);
$password = $q->param(password);
$password2 = $q->param(password2);
if ($perform eq "edit" && $password eq "") { $use_old = "yes"; $password = "$old_password"; $password2 = "$old_password";}
	if ($password ne $password2 || $password eq "" || $password2 eq "") {
	    $footer = "login";
	    $title = "Register A New User";
	    $error_message = "Your passwords didn't match!";
	    &access_problem($error_message);
	    exit;	}
@form_vars = ('user', 'search', 'add', 'modify', 'delete');
    foreach $x (@form_vars) {
	if ($q->param($x) eq "" || $q->param($x) =~ /\|/) {
             $footer = "login";
	    $title = "Register A New User";
	    $error_message = "You must fill in all of the fields in the registration form!";
	    &access_problem($error_message);
	    exit;	}     }
    if ($check_user_duplicates eq "yes") {
	open (USERFILE, "$user_file");
	$user_matched = 0;
	while (<USERFILE>) {
	    chop($_);
	    @f = split(/\|/, $_);
	    if ($f[1] eq $user) {
		$user_matched = 1;
		last;	    }	} # End of while userfile open
	close (USERFILE);
	if ($user_matched == 1) {
	    $footer = "login";
	    $title = "Register A New User";
	    $error_message = "That user name is already taken!";
	    &access_problem($error_message);
	    exit;	} # End of user matched (found duplicate)    
	} # End of if check duplicates on
    srand(time|$$);
    $random = "abcdefghijklmnopqrstuvwxyz1234567890";
    $real_password = $password;
    $salt = "";
    for (1..2) { $salt .= substr($random,int(rand(36)),1); }
  if ($use_old ne "yes") {  $password = &auth_encrypt ($password, $salt); }
  $auth=$password;
  foreach $field (@form_vars){
    ${$field}  = $q->param($field);
    $auth   .= "\|${$field}";  }
   unless (-e $user_file){
    open (AUTH_FILE, ">$user_file") || die "Error creating user file.  $!\n";
  } else {
    open (AUTH_FILE, ">>$user_file") || die "Error opening user file.  $!\n";
  }
   flock AUTH_FILE, $EXCLUSIVE;
   seek AUTH_FILE, 0, 2;
   print AUTH_FILE "$auth\n";
   flock AUTH_FILE, $UNLOCK;
  close(AUTH_FILE);
if ($admin_add eq ""){
   $message = "New User Added<br>You may now login with your new user name below.";
   &login($message);
   } else { 
   $title = "User Manager";
   $message = "User Added/Modified";
   &user_manager($message);
   }
}

################ Create Admin ###############

sub create_admin{
&html_header($title);
 print<<HTML;
<center><TABLE WIDTH=275>
<TR>
<TD>Please start out by setting the Administrator information below.  When logged in as the below user, you will be able to access additional options which are only available to the database administrator.</TD>
</TR><TR>
<TD><br><B>User Name:</B> $admin_user_name<br>This can be changed in the script configurations.</TD></TR>
<TR><TD><br><B>Password</B><BR><INPUT TYPE="password" NAME="password" SIZE="30"></TD></TR>
<TR><TD><B>Re-Type Password</B><BR><INPUT TYPE="password" NAME="password2" SIZE="30"></TD></TR>

<TR><TD ALIGN=MIDDLE><BR><INPUT TYPE="hidden" NAME="user" value="$admin_user_name">
<INPUT TYPE="hidden" NAME="search" value="yes">
<INPUT TYPE="hidden" NAME="add" value="yes">
<INPUT TYPE="hidden" NAME="modify" value="yes">
<INPUT TYPE="hidden" NAME="delete" value="yes">
<INPUT TYPE=button  onClick=" myForm.action.value='Add Administrator';this.form.submit();"  VALUE="Add Administrator" >
</TD>
</TR>
</TABLE></center>
HTML
$footer = "login";
&html_footer;
exit;
}

################ User Manager ###############

sub user_manager{
$message = $_[0];
&html_header($title,$message);
 print<<HTML;
<center>
<TABLE>
<TR>
<TD><select name="selected_user" size=8>
HTML
    open (USERFILE, "$user_file") || die "Error opening user file.  $!\n";
    while (<USERFILE>) {
	chop($_);
	($password, $user, $u_search, $u_add, $u_modify, $u_delete) = split(/\|/, $_);
	print "<option value=\"$user\">$user</option>\n";
    } # End of While
    close (USERFILE);
  print<<HTML;
</select></TD>
<td valign=top>
<input TYPE=button onClick=" myForm.action.value='Create New User';this.form.submit();" value="Create New User"><p>
<input TYPE=button onClick=" myForm.action.value='Edit Selected User';this.form.submit();" value="Edit Selected User"><p>
<input TYPE=button onClick=" myForm.action.value='Remove Selected User';this.form.submit();" value="Remove Selected User">
</TR>
</TABLE>
</center>
HTML
&html_footer;
exit;
}

############### Add/Edit User ################

sub edit_user {
if ($perform eq "edit" && $selected_user eq "" ) {
	    $title = "User Manager - Edit Selected User";
	    $error_message = "You forgot to select a user record to edit!";
	    &access_problem($error_message);
	    exit;
}
if ($perform eq "edit") {
    open (USERFILE, "$user_file") || die "Error opening user file.  $!\n";
    while (<USERFILE>) {
	chop($_);
	($password, $userfound, $u_search, $u_add, $u_modify, $u_delete, @other_user_fields) = split(/\|/, $_);
	if ($selected_user eq $userfound) {
	    @found_other_fields = @other_user_fields;
	    $edit_user = $userfound;
	    $edit_user_add = $u_add;
	    $edit_user_modify = $u_modify;
	    $edit_user_search = $u_search;
	    $edit_user_delete = $u_delete;
	    $old_password = $password;
	} # End of if username matches
    } # End of While
    close (USERFILE);
}
&html_header($title);
 print<<HTML;
<TABLE><TR>
<TD><B>User Name</B><BR><INPUT TYPE="text" NAME="user" SIZE="30" value="$edit_user"></TD></TR>
HTML
if ($perform eq "edit") {
  print<<HTML;
<TR><TD><B>New Password</B><br>Leave blank if you aren't changing passwords.<BR><INPUT TYPE="password" NAME="password" SIZE="30"></TD></TR>
HTML
} else {
  print<<HTML;
<TR><TD><B>Password</B><BR><INPUT TYPE="password" NAME="password" SIZE="30"></TD></TR>
HTML
}
if ($perform eq "edit") {
  print<<HTML;
<TR><TD><B>Re-Type New Password</B><br>Leave blank if you aren't changing passwords.<BR><INPUT TYPE="password" NAME="password2" SIZE="30"></TD></TR>
HTML
} else {
  print<<HTML;
<TR><TD><B>Re-Type Password</B><BR><INPUT TYPE="password" NAME="password2" SIZE="30"></TD></TR>
HTML
}


 print<<HTML;
<tr><td><br><b>User Permissions</b></td></tr>
HTML

if ($edit_user_search eq "no"){
  print<<HTML;
<tr><td>Search: <input type="radio" name="search" value="yes"> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="search" value="no" checked> No</td></tr>
HTML
} else {
  print<<HTML;
<tr><td>Search: <input type="radio" name="search" value="yes" checked> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="search" value="no"> No</td></tr>
HTML
}
if ($edit_user_add eq "no"){
  print<<HTML;
<tr><td>Add: <input type="radio" name="add" value="yes"> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="add" value="no" checked> No</td></tr>
HTML
} else {
  print<<HTML;
<tr><td>Add: <input type="radio" name="add" value="yes" checked> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="add" value="no"> No</td></tr>
HTML
}
if ($edit_user_modify eq "no"){
  print<<HTML;
<tr><td>Modify: <input type="radio" name="modify" value="yes"> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="modify" value="no" checked> No</td></tr>
HTML
} else {
  print<<HTML;
<tr><td>Modify: <input type="radio" name="modify" value="yes" checked> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="modify" value="no"> No</td></tr>
HTML
}
if ($edit_user_delete eq "no"){
  print<<HTML;
<tr><td>Delete: <input type="radio" name="delete" value="yes"> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="delete" value="no" checked> No</td></tr>
HTML
} else {
  print<<HTML;
<tr><td>Delete: <input type="radio" name="delete" value="yes" checked> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="delete" value="no"> No</td></tr>
HTML
}
  print<<HTML;
<TR><TD ALIGN=MIDDLE><BR><input type=hidden name="old_password" value="$old_password"><input type=hidden name="selected_user" value="$edit_user"><input type=hidden name="admin_add" value="yes">
<INPUT TYPE=button  onClick=" myForm.action.value='$button_text';this.form.submit();"  VALUE="$button_text" >
<INPUT TYPE=button  onClick=" myForm.action.value='User Manager';this.form.submit();"  VALUE="User Manager" >
</TD>
</TR>
</TABLE>
HTML
&html_footer;
}

################ Delete User ###############

sub delete_user{
if ($selected_user eq "" ) {
	    $title = "User Manager - Remove Selected User";
	    $error_message = "You forgot to select a user record to remove!";
	    &access_problem($error_message);
	    exit;
}
if ($selected_user eq "$admin_user_name" && $perform eq "delete") {
	    $title = "User Manager - Remove Selected User";
	    $error_message = "You are not allowed to remove the administrator!";
	    &access_problem($error_message);
	    exit;
}
  open (USERFILE, "$user_file") or die "Error opening file: $!\n";
  while (<USERFILE>)
    {
    $line = $_;
    chop $line;
    @dbfields = split (/\|/, $line);
    $deleted = "no";
    if ($dbfields[1] eq $selected_user) { $deleted = "yes"; }
    elsif ($deleted ne "yes") { $new_data .= "$line\n"; }
    } #end of while
  close (USERFILE);
    flock USERFILE, $EXCLUSIVE;
    open (USERFILE, ">$user_file") or die "Error opening file: $!\n";
    print USERFILE "$new_data";
    close (USERFILE);
}

################# Logout ###################

sub logout {
$cookie = cookie(-NAME=>'user',-VALUE=>"$user",-EXPIRES=>'-1d');
print header(-cookie=>[$cookie]);
$set_cookie = "yes";
$message = "User \"$user\" logged out";
&login($message);
 } # end of logout

############ Encrypt Password ###############

sub auth_encrypt {
    local ($field, $salt) = @_;
    $field = crypt ($field, $salt);
    $field;
 } # end of encrypt

############## Access Problem ##############

sub access_problem {
&html_header($title);
 print<<HTML;
<BR>
<FONT SIZE=4 FACE="ARIAL" COLOR=RED><B>Error!</B></FONT><P>
<FONT SIZE=4 FACE="ARIAL">$error_message</FONT><P>
<INPUT TYPE="button" VALUE="  Back  " onClick="history.go(-1)"><br><br>
HTML
&html_footer;
exit;
}

################ Get Date ##################

sub get_date  {
  local ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst,$date);   
  local (@days, @months);
  @days = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
  @months = ('January','February','March','April','May','June','July','August','September','October','November','December');
  ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
  if ($hour < 10)    {    $hour = "0$hour";    }
  if ($min < 10)     {    $min = "0$min";    }
  if ($sec < 10)    { $sec = "0$sec";    }
  $mon++;
 $year += 1900;
 $date = "$mday/$mon/$year at $hour\:$min\:$sec";
  return $date;
  }

############## Form Header #################

sub form_header {
print<<HTML;
<FORM name="myForm" METHOD="post" ACTION="$script_name">
<INPUT TYPE="hidden" NAME="action" VALUE="$action">
HTML
}

############## Form Footer #################

sub form_footer {
if($footer eq "default") {
if ($authenticate  eq "yes") {print "<INPUT TYPE=button  onClick=\" myForm.action.value='new_card';this.form.submit();\"  VALUE=\"New card\" > "; }
print qq~<INPUT TYPE=button onClick="myForm.action.value='Backup';this.form.submit();" VALUE="Backup" > ~;
print qq~<INPUT TYPE=button onClick="myForm.action.value='mailinglist';this.form.submit();" VALUE="Extract mailinglist" > ~;

if ($authenticate eq "yes") { print "<INPUT TYPE=button  onClick=\" myForm.action.value='Logout';this.form.submit();\"  VALUE=\"Logout\" >\n"; }
}
elsif($footer eq "login") { print "\&nbsp\;"; }
 else { print "<INPUT TYPE=button  onClick=\" myForm.action.value='Main Menu';this.form.submit();\"  VALUE=\"Main Menu\" >";
if ($authenticate eq "yes") { print "<INPUT TYPE=button  onClick=\"myForm.action.value='Logout';this.form.submit();\"  VALUE=\"Logout\" >";} }
print "<input type=hidden name=\"user_search\" value=\"$user_search\">\n";
print "<input type=hidden name=\"user_add\" value=\"$user_add\">\n";
print "<input type=hidden name=\"user_modify\" value=\"$user_modify\">\n";
print "<input type=hidden name=\"user_delete\" value=\"$user_delete\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"user\" VALUE=\"$user\">\n";
    print "<input type=hidden name=\"user_trans\" value=\"$user_trans\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"authenticate\" VALUE=\"$authenticate\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"message\" VALUE=\"$message\">\n";
}


############## HTML Header #################

sub html_header{
if($set_cookie eq "") { print $q->header; }
$set_cookie = "";
if($use_external_html eq "yes") { 
%external_variables = (title=>$title, message=>$message,);
print html_template("$external_html_header", \%external_variables); 
&form_header;
} else {
 print<<HTML;
<HTML><HEAD>
   <TITLE>$db_name - $_[0]</TITLE>
<link rel="stylesheet" href="http://1stmuse.com/opere/js/mac_styles_ns.css">
       
  </HEAD><BODY BGCOLOR="#FFFFFF">

  <CENTER><B>
   $db_name
  </B><p><FONT SIZE=3 FACE="ARIAL" COLOR=RED><B>$_[1]</B></FONT></CENTER><P>
   <CENTER>
   <TABLE BORDER=1 WIDTH="$table_width" CELLSPACING="0" CELLPADDING="3">
    <TR> 
    <TD BGCOLOR="#e0e0e0"> 
     <CENTER> 
          <B>$_[0]</B>
     </CENTER>
    </TD>
   </TR>
    <TR> 
     <TD align=middle><BR>
<script language=JavaScript>

</SCRIPT>
HTML
&form_header;
}
}

############## HTML Footer #################

sub html_footer{
if($use_external_html eq "yes") { 
%external_variables = (title=>$title, message=>$message,);
&form_footer;
print html_template("$external_html_footer", \%external_variables); 
if ($user eq "$admin_user_name" && $footer eq "default" && $authenticate eq "yes") {
print "<center><INPUT TYPE=button  onClick=\"myForm.action.value='User Manager';this.form.submit();\"  VALUE=\"User Manager\" ></center><p>";
}
print "<center><p>Powered by <a href=\"http://www.1stmuse.com\">dbSpace</a><br>\&copy\; Spaceout<br><br></center>";
} else {
 print<<HTML;
    <BR></TD></TR>
  <TR> 
    <TD BGCOLOR="#e0e0e0"><CENTER> 
HTML
&form_footer;
 print<<HTML;
     </CENTER>
    </TD>
  </TR>
</TABLE><P>
HTML
if ($user eq "$admin_user_name" && $footer eq "default" && $authenticate eq "yes") {
print "<center><INPUT TYPE=button  onClick=\"myForm.action.value='User Manager';this.form.submit();\"  VALUE=\"User Manager\" ></center><p>";
}
  print<<HTML;




<script language="JavaScript">

<!-- function handler(e) {
    var key = e.which : e.keyCode;
    if (key == 13)     {myForm.action.value='search';this.form.submit();return false;}; 
    else return true;
}


//-->
</script>

</BODY></HTML>
HTML
	}
}

### To avoid usual situation like:
### After filling out the text field, you HAVE to click the specified button to 
### submit the form. If you press enter to submit the form it reloads the form.
### I have written small Javascript code in order to avoid previous behavior and to:
### Process the form by pressing the <ENTER> by putting the focus on the specified (default) button
### In the input field must be inserted the EVENT HANDLER
### like: <INPUT TYPE="text" NAME="search_for" SIZE="40" 
###       onkeydown="if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))
###       {myForm.action.value='Logout';this.form.submit();return false;} else return true;" >






############ Print Next Page Buttons ###########################
sub next_page_buttons {

if ($rows_left_to_view > 0 && $show ne "no") {
    print "<P><INPUT TYPE=\"hidden\" NAME=\"new_hits_seen\" VALUE=\"$new_hits_seen\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"which_search\" VALUE=\"$which_search\">";

if ($rows_left_to_view == 1){ 
print<<HTML;
<INPUT TYPE=button  onClick=" myForm.action.value='$what';this.form.submit();"  VALUE="View Last Record" >
HTML
}; 

if ($rows_left_to_view <= $max_rows_returned){ 
print<<HTML;
<INPUT TYPE=button  onClick=" myForm.action.value='$what';this.form.submit();"  VALUE="View Last $rows_left_to_view Records" >
HTML
};

if ($rows_left_to_view > $max_rows_returned) { 
print<<HTML;
<INPUT TYPE=button  onClick=" myForm.action.value='$what';this.form.submit();"  VALUE="View Next $max_rows_returned Records" >
HTML
} ; 
}

}




################ Back Screen ##################

sub print_back {

&html_header;
 print<<HTML;
<script language="JavaScript">
window.history.go(-3);
</script>
HTML
&html_footer;
} # End of print_default subroutine.




############# Results Screen ################
sub search_email_results{

$display = "columns"; 

# header
&html_header($title);
  $rows_left_to_view = $total_row_count - $new_hits_seen;
  $start_hit = $hits_seen + 1;
  $end_hit = $new_hits_seen;
  $hits_displayed = $end_hit - $start_hit + 1;
  if ($total_row_count > 1) {
    print qq~<P>Total Found: <B>$total_row_count</B> records<BR>~;
    if ($total_row_count > $max_rows_returned) {
      if ($hits_displayed == 2) {  print qq~<B>Last two</B> records shown below<BR>~;  }
      elsif ($hits_displayed == 1) {  print qq~<B>Last</B> record shown below<BR>~;  }
      else { print qq~<B>$start_hit</B> - <B>$end_hit</B> shown below<BR>~;  }
    } #end if
  } #end if ... > 1
  else { print qq~<P>Trovati: <B>1</B> record\n~; }
    #print "<br>nel campo: <b>$search_field_ </b> trova: <b> $find_ </b>";
$cerca = $search_for;
print "<br>";

if ($button_text ne "")
{ 
   if ($button_text eq "Modify Record") {
     print "<INPUT TYPE=button  onClick=\" myForm.action.value='nuovo';this.form.submit();\"  VALUE=\"nuovo\" >";
  };
}
$which_search = $choose;
&next_page_buttons($rows_left_to_view);

    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"display\" VALUE=\"$display\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"key\" VALUE='0'>\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"bodovi\" VALUE=\"$bodovi\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"email\" VALUE=\"\">\n";
# end of header


$display = "columns"; 
if($display =~/columns/i) {
 print<<HTML;
	<p><TABLE BORDER=0 CELLSPACING=2 CELLPADDING=2 WIDTH=$record_width>
    <TR BGCOLOR="#e0e0e0">
HTML
  if($choose =~ /(modify|delete)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2>
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Modify Record';this.form.submit();\"  VALUE=\"Modify Record\" >
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit();\"  VALUE=\"Eliminate card\" >
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='nuovo';this.form.submit();\" VALUE=\"aggiungere card\" >
</TD></TR>\n";
  }

  foreach $field (@fields){
    print "<TD ALIGN=CENTER><B>\u$field</B></TD>\n";
  } # End of foreach


  print "</TR>";
  foreach $record (@results){
    ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $record); 
    print "<TR BGCOLOR=\"#efefef\">\n";
    if($choose =~ /(modify|delete)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2>
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Modify Record';this.form.submit();\"  VALUE=\"Modify Record\" >
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit();\"  VALUE=\"Eliminate card\" >
</TD></TR>\n";
}
 # End of if $display =~columns
      for($x=0;$x<$field_count;$x++){
      $item = &check_item($field_vals[$x], $x);
      print "<TD>$item</TD>\n";
    }
     print "</TR> ";
  } # End of foreach loop.
  print<<HTML;
</TR></TABLE>
HTML
} 

else 
# do rows
{
  foreach $record (@results){
    ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $record); 
### intervention
print<<HTML;
	<P><TABLE BORDER=0 CELLSPACING=2 CELLPADDING=2 WIDTH=$record_width>
HTML

  $x=0;
  foreach $field (@fields){
  $item = &check_item($field_vals[$x], $x);


$background_color="#e0e0e0";
$line= "<TD BGCOLOR='#efefef' WIDTH=100%>$item</TD>";
if ($x > 9) {$background_color='#B6DB91'; $line= "<TD BGCOLOR='#D5FFD5' WIDTH=100%>$item</TD>" };



$campo = $field;

print<<HTML;
     <TR>
      <TD BGCOLOR=$background_color><B>\u$campo</B></TD>
      $line
     </TR>
HTML



   $x++;
 	 } # End of foreach field loop.
######## buttons on the end of record
  if($choose =~ /(modify|delete|search)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2> ";


    print "<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Edit_opera';this.form.submit();\"  VALUE=\"Edit card\" >
           <INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit();\"  VALUE=\"Eliminate card\" >
           ";

};

######## end of buttons 
  print "</TABLE><P>";

  } # End of foreach record loop.

# end of rows display
} # End of if display loop

if ($button_text ne "")
{ 
  if ($button_text eq "Modify Record") {
     print " <INPUT TYPE=button  onClick=\" myForm.action.value='nuovo';this.form.submit();\"  VALUE=\"nuovo\" >";
  };
}

$which_search = $choose;
############### next page buttons 
&next_page_buttons($rows_left_to_view);

    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"display\" VALUE=\"$display\">\n";
    print "<INPUT NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_field\" VALUE=\"$search_field\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"bodovi\" VALUE=\"$bodovi\">\n";
print "<p>";
$cerca_t=$cerca;
if ($cerca eq '.') {$cerca_t='tutto'};

&html_footer;
} # End of search_results_email subroutine.











############### Modify Screen ################

sub print_modify_page{
  ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $results[0]); 
$title="Modify Record";
&html_header($title);
  print<<HTML;

<SCRIPT LANGUAGE="JavaScript">

<!-- This script locksout <CR> i.e. Enter Key and requires the SUBMIT button to be clicked to send form -->
<!-- Begin

function tabOnEnter (field, evt) {
      var keyCode = document.layers ? evt.which : document.all ? 
     evt.keyCode : evt.keyCode;
      if (keyCode != 13)
        return true;
      else {
        getNextElement(field).focus();
        return false;
      }
}


function getNextElement (field) 
{
    var frm = field.form;
    var bIs = false;
    for (var e=0;e<frm.length;e++)
    {
      if(frm[e].type!="hidden" && bIs) return frm.elements[e];
      if (field==frm[e]) bIs=true;
    }
}

//  End -->
</script>


   <INPUT TYPE=HIDDEN NAME=key value="$key">
    <TABLE BORDER=0 CELLSPACING=0>
HTML
  $x=0;
  foreach $field (@fields){

$input_txt="<INPUT TYPE=TEXT NAME=\"$field\" VALUE=\"$field_vals[$x]\" SIZE=40  onkeydown=\"return tabOnEnter (this, event);\" >";
$input_select="<SELECT NAME=\"$field\"  onkeydown=\"return tabOnEnter (this, event);\"   ><OPTION VALUE selected='A'>A-Privati<OPTION VALUE='B'>B-Professionisti
<OPTION VALUE='C'>C-Aziende<OPTION VALUE='D'>D-Ristoranti-Hotel<OPTION VALUE='E'>E-Associazioni-Comunit\E0-Chiese<OPTION VALUE='F'>F-Altri</SELECT>";
  $input_html=$input_txt;


##     if ($field eq "Classe") {   $input_html=$input_select     };

       print<<HTML;
        <TR>
         <TD><B>\u$field:</B></TD>
         <TD>$input_html</TD>
         </TR>
HTML

    $x++;
  } # End of foreach.
print<<HTML;
       	</TABLE>
	<BR>
<INPUT TYPE=button  onClick=" myForm.action.value='Modify This Record';this.form.submit();"  VALUE="Save" >

   <P>
HTML
&html_footer;
}



















############### backup_fido ################
sub backup_fido{
# Author : John Jan Popovic
# Date : July, 2012
# Purpose: This procedure performs DBase adonis Backup



# Create %adonis_hash
 %DBADONIS_hash = ();
 @DB_line = ();
 $homedir = $root_ ;
  open (DB, "$database") || die "Error opening database. $! $database \n";
 @DB_line = <DB>;
 close (DB);

foreach $adonis_record (@DB_line){
   chomp $adonis_record;
   @altro =();
  ($key,$dbuser,$when_added,@altro) = split(/\|/, $adonis_record);
  $DBADONIS_hash{$key} = $adonis_record;
} ;
# end of creating of %adonis_hash

 $date_time = &get_date;
 $date_time =~ s/at/~/g;
 ($date,$day_time) = split (/\~/,$date_time);
 $date =~ s/[\s]//g;
 $date =~ s/[\/]/~/g;
 ($dd,$mm,$yy) = split (/\~/,$date);
# Format $dd,$mm numbers with up to 2 leading zeroes
$dd = sprintf("%02d", $dd);
$mm = sprintf("%02d", $mm);

 $backupdb = $root_ . "/fido_backup/backup_clients" . $yy. "_". $mm ."_$dd" . ".txt";

  # save ADONIS records
  my @ADONIS_line = ();
  @ADONIS_line = values (%DBADONIS_hash);

 flock DATABASE, $EXCLUSIVE;
 open (DATABASE, ">$database") or die "Error opening file: $!\n";

  foreach $adonis_line (@ADONIS_line){ 
    chomp $adonis_line;
    print DATABASE "$adonis_line\n";
  }

  # backup ADONIS records
 flock DATABASE, $EXCLUSIVE;
 open (DATABASE, ">$backupdb") or die "Error opening file: $!\n";

  foreach $adonis_line (@ADONIS_line){ 
    chomp $adonis_line;
    print DATABASE "$adonis_line\n";
  }

  close (DATABASE);
  flock DATABASE, $UNLOCK;
  # end of backuping ADONIS records

  # save ADONIS records
  @ADONIS_line = ();
  @ADONIS_line = values (%DBADONIS_hash);

 flock DATABASE, $EXCLUSIVE;
 open (DATABASE, ">$database") or die "Error opening file: $!\n";

  foreach $adonis_line (@ADONIS_line){ 
    chomp $adonis_line;
    print DATABASE "$adonis_line\n";
  }

  close (DATABASE);
  flock DATABASE, $UNLOCK;
  # end of saving ADONIS db records



} # End of Backup_adonis subroutine.





































############### extract_mailinglist ################
sub extract_mailinglist{
# Author : John Jan Popovic
# Date : July, 2012
# Purpose: This procedure performs DBase adonis Backup



# Create %adonis_hash
 %DBADONIS_hash = ();
 @DB_line = ();
 $homedir = $root_ ;
  open (DB, "$database") || die "Error opening database. $! $database \n";
 @DB_line = <DB>;
 close (DB);

foreach $adonis_record (@DB_line){
   chomp $adonis_record;
   @altro =();
  ($key,$dbuser,$when_added,@altro) = split(/\|/, $adonis_record);
  $DBADONIS_hash{$key} = $adonis_record;
} ;
# end of creating of %adonis_hash



  # save MAILING LIST records
  my @ADONIS_line = ();
  @ADONIS_line = values (%DBADONIS_hash);

 $mailinglist = $root_ . "/fido/fido_mailinglist.txt";

 flock DATABASE, $EXCLUSIVE;
 open (DATABASE, ">$mailinglist") or die "Error opening file: $!\n";

  foreach $adonis_line (@ADONIS_line){ 
    chomp $adonis_line;
           ($key,$owner,$time_stamp,
            $CARD_Broj_kartice,$CARD_OIB,$CARD_Ime,$CARD_Prezime,
            $CARD_Datum_rodjenja,$CARD_Exp_date,$CARD_Bodovi,$CARD_Brand,$CARD_Email,$CARD_popup) = split (/\|/,$adonis_line);

    $mailing_line ="$CARD_Email|$key|$CARD_Ime $CARD_Prezime";
    print DATABASE "$mailing_line\n";
  }

  close (DATABASE);
  flock DATABASE, $UNLOCK;
  # end of saving MAILING LIST records




} # End of extract_mailinglist subroutine.






























































############# Email Billing  ################
sub mail_billing{
  my $search_for = $_[0]; 
  my $search_field = $_[1];
  my @results   =();
  my %shop_hash =();
  my $revenue=0;
  my $expenditure=0;

&html_header($title);

# build shop hash
  $database_shops    = "$ENV{'DOCUMENT_ROOT'}/fido/fido_shops.txt";	

  open (DB, "$database_shops") or die "Error opening database. $database_shops $!\n";
    while(<DB>){

   
           ($key,$owner,$time_stamp,
            $TERMINAL_terminalId,$TERMINAL_terminalPwd,$TERMINAL_salesPoint,$TERMINAL_address,
            $TERMINAL_telephone,$TERMINAL_email,$TERMINAL_GIS_coordinates,$TERMINAL_referral_person,
            $TERMINAL_contractNumber,$TERMINAL_activityStatus) = split(/\|/, $_);


          $terminalId = $TERMINAL_terminalId;
          $terminalId =~ s/\s//g;

          if ($terminalId ne "") { 
             $shop_hash{$terminalId} ="$TERMINAL_salesPoint - $TERMINAL_address";
          };

                
    } # End of while.
  close (DB);


 $date_time = &get_date;
 $datum =$date_time;
 $date_time =~ s/at/~/g;
 ($date,$day_time) = split (/\~/,$date_time);
 $date =~ s/[\s]//g;
 $date =~ s/[\/]/~/g;
 ($dd,$mm,$yy) = split (/\~/,$date);
# Format $dd,$mm numbers with up to 2 leading zeroes
$dd = sprintf("%02d", $dd);
$mm = sprintf("%02d", $mm);

    $billing_file = "$ENV{'DOCUMENT_ROOT'}/fido_billing/billing" . $yy . "_". $mm .  ".txt";

 open (BILL, "$billing_file") or die "Error opening $billing_file  $!\n"; 
 @Billing_line = <BILL>;
 close (BILL);

  foreach $billing_record (@Billing_line){
    ($key,$LOGuser,$when_added,$FIDO_Day,$FIDO_TimeStamp,$FIDO_TerminalId,$FIDO_CardId,$FIDO_Amount) = split(/\|/, $billing_record);      
    if ($FIDO_CardId =~ /$search_for/oi) { push @results,$billing_record};
  } # End of foreach

$count = @results;


  if ($count > 1) {
    $content = qq~<P>Total Found: <B>$count</B> billing records<BR>~;
  } 
  else { print qq~<P>Total Found: <B>1</B> billing record\n~; }
 


print "<br>";


$which_search = $choose;


    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"display\" VALUE=\"$display\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"key\" VALUE='0'>\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"bodovi\" VALUE=\"$bodovi\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"email\" VALUE=\"$email\">\n";

# end of Billing header
$content ="";

  foreach $record (@results){
    ($key,$LOGuser,$when_added,$julian_day,$timeStamp,$terminalId,$cardId,$amount) = split(/\|/, $record); 


     if ($amount > 0) {$revenue +=$amount}
     else {$expenditure +=$amount;}

$class="";


if ($amount < 0) {
  $class="class='textred'";
};

$content .=qq~
$red_font_on
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER $class >$timeStamp</TD>
   <TD width="50%" ALIGN="Right" $class>$shop_hash{$terminalId}</TD>
   <TD width="26%" ALIGN="Right" $class >$amount</TD>
</TR>
$red_font_off
~;
     
  } # End of foreach loop.


$bodovi = sprintf("%.2f", $bodovi);

$revenue      = sprintf("%.2f", $revenue);
$expenditure  = sprintf("%.2f", $expenditure);

$billing_total = $revenue + $expenditure;
$billing_total = sprintf("%.2f", $billing_total);

$content .=qq~
$red_font_on
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER  >Ukupno sakupljeno bodova</b></TD>
   <TD width="50%" ALIGN="Right"></TD>
   <TD width="26%" ALIGN="Right" >$revenue</TD>
</TR>
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER class="textred" >Ukupno potro&scaron;eno bodova</b></TD>
   <TD width="50%" ALIGN="Right"></TD>
   <TD width="26%" ALIGN="Right" class="textred" >$expenditure</TD>
</TR>
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER  ><b>Grand Total</b></TD>
   <TD width="50%" ALIGN="Right"></TD>
   <TD width="26%" ALIGN="Right" ><b>$billing_total</b></TD>
</TR>
$red_font_off
~;
   
$content .=qq~
</TR></TABLE>
~;



#$content .=qq~ revenue=$revenue expenditure=$expenditure~;

  if ($button_text eq "Modify Record") {
     print " <INPUT TYPE=button  onClick=\" myForm.action.value='nuovo';this.form.submit();\"  VALUE=\"nuovo\" > ";
  };




#  Billing header
$datum =~ s/at/ stanje u/;

$header = qq~
<br><br>
<p align="left">
<br>
Datum: $datum<br><br>
FIDO korisnik: <B>$fido_customer</B><br>
Broj_kartice: 	<B>$search_for</B><br><br>



Do danas ste skupili  <b>$bodovi </b> bodova.<br>

Dolje se nalazi ispis svih transakcija u $mm mjesecu. <br>
</p>
<br>
<br>
<TABLE BORDER=0 CELLSPACING=1 CELLPADDING=2 WIDTH=80%>
    <TR BGCOLOR="#e0e0e0">
<TD width="24%" ALIGN=CENTER><B>TimeStamp</B></TD>
<TD width="50%" ALIGN=CENTER><B>Sales point</B></TD>
<TD width="26%" ALIGN=CENTER><B>Amount</B></TD>
</TR>

	
~;


print $header;
print $content;

$style =qq~
<head>
<style>  
.textorange{
	color: #D46300;
}
A.textorange:link {
	color: #D46300;
	text-decoration: none;	
}

A.textorange:visited {
	color: #D46300;
	text-decoration: none;	
}

A.textorange:active {
	color: #D46300;
	text-decoration: none;	
}


.textred{
	color: #ff0000;
}
A.textred:link {
	color: #ff0000;
	text-decoration: none;	
}

A.textred:visited {
	color: #ff0000;
	text-decoration: none;	
}

A.textred:active {
	color: #ff0000;
	text-decoration: none;	
}
</style>
<head>
~;
##########################################################################
#print " <br>SENDMAIL test";

$subject ="FIDO billing report";

# sendmail setup
$SENDMAIL = "/usr/sbin/sendmail -t";
$FROM = "fido testing <jjp\@testing.com>";
$TO = "$email";




open(MAIL, "|$SENDMAIL");


print MAIL <<EOM;
From: $FROM
To: $TO
Subject: $subject
Content-type: text/html; charset="iso-8859-1"
<html>
$style
<body>

$header
$content
<br>
Zahvaljujemo Vam na sudjelovanju u Fido programu vjernosti. 
</body>
</html>
EOM


close (MAIL);
##########################################################################

print "<p>";

&html_footer;
} # End of mail_billing subroutine.































############# Billing Results Screen ################
sub billing_results{
  my $search_for = $_[0]; 
  my $search_field = $_[1];
  my @results   =();
  my %shop_hash =();
  my $revenue=0;
  my $expenditure=0;

&html_header($title);

# build shop hash
  $database_shops    = "$ENV{'DOCUMENT_ROOT'}/fido/fido_shops.txt";	

  open (DB, "$database_shops") or die "Error opening database. $database_shops $!\n";
    while(<DB>){

   
           ($key,$owner,$time_stamp,
            $TERMINAL_terminalId,$TERMINAL_terminalPwd,$TERMINAL_salesPoint,$TERMINAL_address,
            $TERMINAL_telephone,$TERMINAL_email,$TERMINAL_GIS_coordinates,$TERMINAL_referral_person,
            $TERMINAL_contractNumber,$TERMINAL_activityStatus) = split(/\|/, $_);


          $terminalId = $TERMINAL_terminalId;
          $terminalId =~ s/\s//g;

          if ($terminalId ne "") { 
             $shop_hash{$terminalId} ="$TERMINAL_salesPoint - $TERMINAL_address";
          };

                
    } # End of while.
  close (DB);


 $date_time = &get_date;
 $datum =$date_time;
 $date_time =~ s/at/~/g;
 ($date,$day_time) = split (/\~/,$date_time);
 $date =~ s/[\s]//g;
 $date =~ s/[\/]/~/g;
 ($dd,$mm,$yy) = split (/\~/,$date);
# Format $dd,$mm numbers with up to 2 leading zeroes
$dd = sprintf("%02d", $dd);
$mm = sprintf("%02d", $mm);

    $billing_file = "$ENV{'DOCUMENT_ROOT'}/fido_billing/billing" . $yy . "_". $mm .  ".txt";

 open (BILL, "$billing_file") or die "Error opening $billing_file  $!\n"; 
 @Billing_line = <BILL>;
 close (BILL);

  foreach $billing_record (@Billing_line){
    ($key,$LOGuser,$when_added,$FIDO_Day,$FIDO_TimeStamp,$FIDO_TerminalId,$FIDO_CardId,$FIDO_Amount) = split(/\|/, $billing_record);      
    if ($FIDO_CardId =~ /$search_for/oi) { push @results,$billing_record};
  } # End of foreach

$count = @results;


  if ($count > 1) {
    $content = qq~<P>Total Found: <B>$count</B> billing records<BR>~;
  } 
  else { print qq~<P>Total Found: <B>1</B> billing record\n~; }
 


print "<br>";


$which_search = $choose;


    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"display\" VALUE=\"$display\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"key\" VALUE='0'>\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"bodovi\" VALUE=\"$bodovi\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"email\" VALUE=\"$email\">\n";

# end of Billing header
$content ="";

  foreach $record (@results){
    ($key,$LOGuser,$when_added,$julian_day,$timeStamp,$terminalId,$cardId,$amount) = split(/\|/, $record); 


     if ($amount > 0) {$revenue +=$amount}
     else {$expenditure +=$amount;}

$class="";


if ($amount < 0) {
  $class="class='textred'";
};

$content .=qq~
$red_font_on
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER $class >$timeStamp</TD>
   <TD width="50%" ALIGN="Right" $class>$shop_hash{$terminalId}</TD>
   <TD width="26%" ALIGN="Right" $class >$amount</TD>
</TR>
$red_font_off
~;
     
  } # End of foreach loop.


$bodovi = sprintf("%.2f", $bodovi);

$revenue      = sprintf("%.2f", $revenue);
$expenditure  = sprintf("%.2f", $expenditure);

$billing_total = $revenue + $expenditure;
$billing_total = sprintf("%.2f", $billing_total);

$content .=qq~
$red_font_on
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER  >Ukupno sakupljeno bodova</b></TD>
   <TD width="50%" ALIGN="Right"></TD>
   <TD width="26%" ALIGN="Right" >$revenue</TD>
</TR>
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER class="textred" >Ukupno potro&scaron;eno bodova</b></TD>
   <TD width="50%" ALIGN="Right"></TD>
   <TD width="26%" ALIGN="Right" class="textred" >$expenditure</TD>
</TR>
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER  ><b>Grand Total</b></TD>
   <TD width="50%" ALIGN="Right"></TD>
   <TD width="26%" ALIGN="Right" ><b>$billing_total</b></TD>
</TR>
$red_font_off
~;
   
$content .=qq~
</TR></TABLE>
~;



#$content .=qq~ revenue=$revenue expenditure=$expenditure~;

  if ($button_text eq "Modify Record") {
     print " <INPUT TYPE=button  onClick=\" myForm.action.value='nuovo';this.form.submit();\"  VALUE=\"nuovo\" > ";
  };




#  Billing header
$datum =~ s/at/ stanje u/;

$header = qq~
<br><br>
<p align="left">
<br>
Datum: $datum<br><br>
FIDO korisnik: <B>$fido_customer</B><br>
Broj_kartice: 	<B>$search_for</B><br><br>



Do danas ste skupili  <b>$bodovi </b> bodova.<br>

Dolje se nalazi ispis svih transakcija u $mm mjesecu. <br>
</p>
<br>
<br>
<TABLE BORDER=0 CELLSPACING=1 CELLPADDING=2 WIDTH=80%>
    <TR BGCOLOR="#e0e0e0">
<TD width="24%" ALIGN=CENTER><B>TimeStamp</B></TD>
<TD width="50%" ALIGN=CENTER><B>Sales point</B></TD>
<TD width="26%" ALIGN=CENTER><B>Amount</B></TD>
</TR>

	
~;


print $header;
print $content;

$style =qq~
<head>
<style>  
.textorange{
	color: #D46300;
}
A.textorange:link {
	color: #D46300;
	text-decoration: none;	
}

A.textorange:visited {
	color: #D46300;
	text-decoration: none;	
}

A.textorange:active {
	color: #D46300;
	text-decoration: none;	
}


.textred{
	color: #ff0000;
}
A.textred:link {
	color: #ff0000;
	text-decoration: none;	
}

A.textred:visited {
	color: #ff0000;
	text-decoration: none;	
}

A.textred:active {
	color: #ff0000;
	text-decoration: none;	
}
</style>
<head>
~;

print "<p>";

&html_footer;
} # End of billing_results subroutine.



























########### Search Cards Database #############
sub search_cards{
  my $search_for   = $_[0];
  my $target_record ="";
  my @results =();
  my $cardId;

  $search_for =~ s/\s//g;
  $search_for =~ s/\D//g;

  
  open (DB, "$database") or die "Error opening database. $database $!\n";
    while(<DB>){

        ($key,$dbuser,$when_added,$CARD_Broj_kartice,
         $CARD_OIB,$CARD_Ime,$CARD_Prezime,$CARD_Datum_rodjenja,
         $CARD_Exp_date,$CARD_Bodovi,$CARD_Brand,$CARD_email,$CARD_popup) = split(/\|/, $_);

          $cardId = +$CARD_Broj_kartice;
          $cardId =~ s/\s//g;

          if ($cardId > 0) { 
             if ($cardId eq $search_for) { push @results, $_};
          };

                
    } # End of while.
  close (DB);

print "Content-type: text/html; charset=iso-8859-2\n\n";

my $count = @results;
if ($count < 1){ 
    $target_record =""; 
    $err_message="Error=100 Neregistrirana kartica $search_for"; 
}

if($count > 1){ 
    $target_record =""; 
    $err_message="Error=101 Too many results found for CardId $search_for"; 
}

if($count == 1){ 
    $target_record = @results[0];
    $err_message="";
};

# Print HTTP header for PLAIN TEXT
print "$CARD_Ime";

} # End of search_cards subroutine.






