#!/usr/bin/perl
##################################################################
#
#               COPYRIGHT NOTICE:
#	  FBS ZipCode Locator PopUp v3.0
#         Copyright 2003 PageSkills.com
#
#
#
#      Web site: http://www.findbystate.com
#      E-Mail: programs@pageskills.com
#      Released Date: August 7, 2003
#
#   FBS ZipCode Locator PopUp v3.0 is protected by the copyright
#   laws and international copyright treaties, as well as other
#   intellectual property laws and treaties.
#   Distribution without approved license is illegal and is
#   punishable by law.
#
#   You must leave all references and links to the FindByState.com
#   website intact with this copyrighted script.
###################################################################


# IF YOU ARE HAVING DIFFICULTY WITH THE SCRIPT FINDING YOUR CORRECT SERVER PATHS, PLEASE TYPE YOUR CORRECT SERVER
# PATH IN THE AREA BELOW.  THE SCRIPT WILL USE THIS PATH INSTEAD OF TRYING TO FIND THE PATH ON ITS OWN:
#
# Leave this blank if you wish for the script to auto detect your server path.
# Unix EG: $MyServerPath = "/home/www/cgi-bin/states";
# Windows EG: $MyServerPath = "c:\www\findbystate.com\cgi-bin\states";

$MyServerPath = "";

###############################################################################################
#       DO NOT EDIT BELOW THIS LINE
###############################################################################################

###############################################################################################
# Get the document root: if $ENV{'DOCUMENT_ROOT'}
# doesn't exist, use the value in $doc_root
$doc_root = $ENV{'SCRIPT_FILENAME'} || $0;
$doc_root =~ s/\\/\//g;
my(@doc_roots) = split(/\//,$doc_root);
pop(@doc_roots);
pop(@doc_roots);
$doc_root = join("/",@doc_roots);
$document_root = $ENV{'DOCUMENT_ROOT'} || $doc_root;
$scriptNamePath = $ENV{'SCRIPT_NAME'};
$scriptNamePath =~ s/\\/\//g;
my(@scriptNamePath) = split(/\//,$scriptNamePath);
$size = @scriptNamePath;
pop(@scriptNamePath);
$cgibin = $scriptNamePath[-1]; #$size - 1
my($root);
if ($size > 2){
# We need to extend the root
my(@root) = @scriptNamePath;
pop(@root);
$root = join("/",@root);
}
$scriptNamePath = join("/",@scriptNamePath);
# Set the page directory
my($page_dir);
if ($ENV{'WINDIR'}){
$page_dir = $root || "/";
}
else {
  $page_dir = $document_root;
}
$system_path = "$doc_root/$cgibin";

###############################################################################################
# This must point to your configuration file.  MUST be the server path, not a url
if ($MyServerPath ne "") {
	$cfg="$MyServerPath/states.cfg"; }
	else { $cfg = "$system_path/states.cfg"; }

###############################################################################################
#opens the configuration file, dumps it into an array

open (CONFIG,"$cfg") || &error("Can\'t open or find the Configuration file located at $cfg. Reason: $! . This script will not run without a configuration file. Please read the help file HELP.htm and reconfigure accordingly.");
@Config=<CONFIG>;
close(CONFIG);

#for each item in the array, do the following
foreach $variable (@Config)
{
    #cut off newline characters so that all we have is actual data
    #from the config file. Believe it or not, this can be a very
    #annoying problem if you don't know it's there...
    chomp($variable);
    #split item into key/value pairs for config hash
    ($Ckey,$Cvalue) = split(/=/,$variable,2);
    #create config hash, using values above
    $cfg{$Ckey} = $Cvalue;
}
###############################################################################################
&get_form_data; # parse arguments from post
#############################################################################################
# Lets check to see if program CFG settings have been set by admin
if ($cfg{fresh_install} == 1) { &cfg_setup_needed; }
##############################################################################################
# Direct user to Admin Section to setup program configurations
#

sub cfg_setup_needed {
print "Content-type: text/html\n\n";
print <<"SCREEN";
<html>
<head>
<title>Online Setup</title>
</head>
<body>
<h2 align="center"><font color="#666666">Find-by-State Professional<br>
Settings Utility</font></h2>
<div align="center">
  <center>
  <table border="0" cellpadding="3" cellspacing="0">
    <tr>
      <td align="center" bgcolor="#CCCCCC">
      <h2><font color="#000080"><b>Welcome to
      Find-by-State Online Setup</b></font></span></h2>
      <p><font color="black"><b>Setup had determined that this is the first time
      you have run this program. </b></p>
      <blockquote>
        <p>Before you can use this program, you must run the
        <a href="statessetup.pl">
        Program Settings Utility</a>.<br>
        <font size="2">You must have the <i>statessetup.pl </i>file
        uploaded to your server in ASCII format and CHMOD 755 in order to run
        the settings utility.</font></p>
        <hr color="#000000" size="1">
        <p>&nbsp;</p>
        <font color="#800000">
        <p><b>Having Difficulties?<br>
        </b></font><font color="black">If you are experiencing problems with
        installation, you may also wish to run the
        <a href="servertest.pl">
        Server Test</a> script.<br>
        This script will test your installation and help get your program up and
        running more quickly.<br>
        <font size="2">You must have the <i>servertest.pl </i>file uploaded to
        your server in ASCII format and CHMOD 755 in order to run the server
        test script.</font></p>
        <p><b>Note:</b><br>
        <font size="-1">Server Path to config file (states.cfg): <i>$cfg</i></font></p>
      </blockquote>
      </font></td>
    </tr>
    <tr>
      <td align="center">&nbsp;</td>
    </tr>
  </table>
  </center>
</div>
</body>
</html>
SCREEN
exit;
}

##############################################################################################
#-------------------------   You do not need to edit this file.   ---------------------------#
##############################################################################################

$myversion="3.0";
$database = "$cfg{systempath}/$cfg{database_name}";
$starttemplatefile = "$cfg{systempath}/$cfg{start_templatefile_name}";
$resultstemplatefile = "$cfg{systempath}/$cfg{results_templatefile_name}";
$nomatchtemplatefile = "$cfg{systempath}/$cfg{nomatch_templatefile_name}";
$counter_file = "$cfg{systempath}/$cfg{counter_file_name}";

#########################################################################################
# Print The Page Header
#
print "Content-type: text/html\n\n";

##############################################################################################
################################# Main Program   #############################################
##############################################################################################

#  -->  DECISION CODE AND COMMAND PROCESSOR

# DISPLAY FUNCTIONS
if ($input{'command'} eq 'display') { &select_state; }
elsif ($input{'command'} eq 'statesearch') { &display_matching_records; }
elsif ($input{'command'} eq 'details') { &view_records_details; }
elsif ($input{'command'} eq 'zipsearch') { &zc_display_matching_records; }

# ADMIN FUNCTIONS
elsif (($input{'command'} eq 'admin') && ($input{'pw'} eq '$cfg{adminloginpassword}')) { print "Not Authorized"; exit;}  # security trigger
elsif ($input{'command'} eq 'admin') { &admin_show_menu; }
elsif ($input{'command'} eq 'add') { &admin_add_new_form; }
elsif ($input{'command'} eq 'process_new') { &admin_do_process_new; }
elsif ($input{'command'} eq 'delete') { &admin_are_you_sure; }
elsif ($input{'command'} eq 'admin_confirm_delete') { &admin_do_process_delete; }
elsif ($input{'command'} eq 'edit') { &admin_edit_form; }
elsif ($input{'command'} eq 'admin_process_edit') { &admin_do_process_edit; }
elsif (($input{'command'} eq 'login') && ($input{'pw'} eq '$cfg{adminloginpassword}')) { print "Not Authorized"; exit;}  # security trigger
elsif ($input{'command'} eq 'login') { &admin_check_password; }
elsif ($input{'command'} eq 'adminviewall') { &admin_search_list; }
elsif ($input{'command'} eq 'sortdb') { &admin_sort_screen; }
elsif ($input{'command'} eq 'admin_do_sort') { &admin_process_sort_db; }
elsif ($input{'command'} eq 'backupdb') { &admin_backup_screen; }
elsif ($input{'command'} eq 'admin_do_backup') { &admin_process_backup_db; }
elsif ($input{'command'} eq 'adminsearch') { &admin_search_records_form; }
elsif ($input{'command'} eq 'adminfindrecord') { &admin_do_search_records; }
else { &select_state; }

##############################################################################################
# Print The Page Footer
#
exit;

##############################################################################################
# Print No Match Template to Screen
#
sub nomatch {
open (template, "<$nomatchtemplatefile") or &error("Unable to open the no match template file<br>The path is $nomatchtemplatefile");
if ($cfg{flock} eq "y") {
flock template, 2;
}
@template=<template>;
close(template);
foreach $template(@template) {
print "$template\n";
}#end foreach template line
} #end show_template

#########################################################################################################################
# BEGIN USER DISPLAY CODE
#########################################################################################################################
# Sub: SELECT A STATE TEMPLATE-

sub select_state{
open (template, "<$starttemplatefile") or &error("Unable to open the Start Template file<br> Make sure this file exists on the server and is chmod 775 or 777");
if ($flock eq "y") { flock template, 2; }
@template=<template>;
close(template);
foreach $template(@template) {
if ($template =~ /<!--DROPDOWNFORM-->/i) { print "<FORM METHOD=\"POST\" ACTION=\"$cfg{formaction}\"><INPUT TYPE=\"HIDDEN\" NAME=\"command\" VALUE=\"statesearch\">" };
if ($template =~ /<!--ZIPCODEFORM-->/i) { print "<FORM METHOD=\"POST\" ACTION=\"$cfg{formaction}\"><INPUT TYPE=\"HIDDEN\" NAME=\"command\" VALUE=\"zipsearch\">" };
print "\n$template\n";
}#end foreach template line
} #end sub

##############################################################################################
# Sub: DISPLAY RESULTS TEMPLATE -

sub display_matching_records{
open (template, "<$resultstemplatefile") or &error("Unable to open the Results Template file<br> Make sure this file exists on the server and is chmod 775 or 777");
if ($flock eq "y") { flock template, 2; }
@template=<template>;
close(template);
foreach $template(@template) {
if ($template =~ /<!--MENU_LINKS-->/i) { print"<a href=\"javascript:history.back(-1)\">Go Back</a> | <a href=\"$cfg{formaction}\">Start Over</a>"; }
if ($template =~ /<!--INSERT_RESULTS_HERE-->/i) { &print_matching_records; }
print "\n$template\n";
}#end foreach template line
} #end sub

#############################################################################################
# Sub: PRINT MATCHING RECORDS TO SCREEN
sub print_matching_records {
&error('State field left blank.  This field is required.') unless ($input{'state'}); #ALWAYS REQUIRED
&error('Text field left blank.  This field is required.') unless ($input{'text'}); #ALWAYS REQUIRED
$state = "$input{'state'}";
$text = "$input{'text'}";

$zipcode_found=0;

#--> open database
open (DAT,"<$database") || print "Could not open up database.  Please try again later.";
if ($LOCK_EX){
      flock(DAT, $LOCK_EX); #Locks the file
}
 @database_array = <DAT>;
 close (DAT);

$record_found=0;
$hidecount=0;
$total_record_found=0;
$displaycount=0;
$showing_top_results=0;

if ($state eq "all") {	print "<tr><td><font size=\"$cfg{text_size_body}\" color=\"$cfg{heading_color}\">Viewing: All States</font></td></tr>\n"; }
	else {		print "<tr><td><font size=\"$cfg{text_size_body}\" color=\"$cfg{heading_color}\">Viewing: $text</font></td></tr>\n"; }

# --> cycle through database and count total number of matches

	foreach $lines(@database_array) {
		$zipcode_found=0;
        	@column = split(/\|/,$lines);
        	if ($column[10] eq "yes") { $hidecount++; } else {
        	if (($stringzip ne "") && ($column[5] eq $stringzip)) { $zipcode_found=1; }
		# find out if its a Zipcod Search with Surrounding Area Displayed
		if ($surrounding == 1) {
			$zipcode_found = 1 if ($column[5] > $stringzipd) && ($column[5] < $stringzipu);
		} # end if surrounding
		if ((lc($state) eq lc($column[4])) || ($state eq "all") || ($zipcode_found==1)) {
			$total_record_found++;
	} #end else
	} #end if
	} #end foreach

$zipcode_found=0;

if ($total_record_found==0) { $total_record_found="No"; }

	print "<tr><td><font size=\"1\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><b>$total_record_found</b> records found.</td></tr>";

#--> cycle through database and look for matches and print them out

	foreach $lines(@database_array) {
		$zipcode_found=0;
        	@column = split(/\|/,$lines);
        	if ($column[10] eq "yes") { $hidecount++; } else {
        	# find out if its a Zipcode Search
		if (($stringzip ne "") && ($column[5] eq $stringzip)) { $zipcode_found=1; }
		# find out if its a Zipcod Search with Surrounding Area Displayed
		if ($surrounding == 1) {
			$zipcode_found = 1 if ($column[5] > $stringzipd) && ($column[5] < $stringzipu);
		} # end if surrounding
		if ((lc($state) eq lc($column[4])) || ($state eq "all") || ($zipcode_found==1)) {
			$record_found++;

if ($input{'displayall'}) { $displayallrecords = 1; }

	if (($displaycount >= $cfg{max_records}) && ($displayallrecords == 0)){
	$showing_top_results=1;
	if ($stringzip eq "") { print "<tr><td><hr color=\"#000000\" width=\"100%\"><font size=\"2\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">Displaying <b>$displaycount</b>/<b>$total_record_found</b> records. <i><a href=\"$cfg{formaction}?command=statesearch&state=$state&text=$text&displayall=1\">View All...</a></i></font></tr></td>"; }
	else { print "<tr><td><hr color=\"#000000\" width=\"100%\"><font size=\"2\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">Displaying <b>$displaycount</b>/<b>$total_record_found</b> records. <i><a href=\"$cfg{formaction}?command=zipsearch&zip=$stringzip&showsurrounding=$surrounding&state=$state&text=$stringzip&displayall=1\">View All...</a></i></font></tr></td>"; }
	$displayall=0;
	last;
	} # End if max display
	else {
		print "<tr><td><font size=1>&nbsp</td></tr>\n";
		if ($cfg{hide_company_name}==0) { print "<tr><td colspan=2><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><b>$record_found.</b> <a href=\"$cfg{formaction}?command=details&id=$column[11]\">$column[0]</a></font>\n";} else { print "<tr><td colspan=2>\n"; }

		print "<br><font size=\"1\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">";
		if ($cfg{hide_city}==0) { print "$column[3],";} else { print "&nbsp;"; }
		if ($cfg{hide_state}==0) { print "\&nbsp;$column[4]";}
		if ($cfg{hide_zip}==0) { print "\&nbsp;$column[5]</font>";}
		print "</td></tr>\n\n";

		$displaycount++;
		} # end if match found
		} # end if column 9 (hide profile)
	} #end else
	}# end foreach
if ($record_found == 0) { print "<tr><td>";
			  &nomatch;
			  print "</tr></td>"; }
if ($showing_top_results == 0) { print "<tr><td><hr color=\"#000000\" width=\"100%\"><font size=\"1\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><b>$total_record_found</b> records found.</font></tr></td>"; }
}# end of sub view_records

##############################################################################################
# Sub: VIEW RECORD DETAILS -

sub view_records_details{
open (template, "<$resultstemplatefile") or &error("Unable to open the Results Template file<br> Make sure this file exists on the server and is chmod 775 or 777");
if ($flock eq "y") { flock template, 2; }
@template=<template>;
close(template);
foreach $template(@template) {
if ($template =~ /<!--MENU_LINKS-->/i) { print"<a href=\"javascript:history.back(-1)\">Go Back</a> | <a href=\"$cfg{formaction}\">Start Over</a> | <a href=\"javascript:window.print()\">Print</a>"; }
if ($template =~ /<!--INSERT_RESULTS_HERE-->/i) { &print_view_records_details; }
print "\n$template\n";
}#end foreach template line
}#end sub


#############################################################################################
# Sub: PRINT VIEW RECORDS DETAILS
sub print_view_records_details {
&error('Record ID left blank.  This field is required.') unless ($input{'id'}); #ALWAYS REQUIRED
$id = "$input{'id'}";

if ($cfg{website_link_target} == 1) { $websitelinktargetvalue = "target=\"_blank\""; } else {$websitelinktargetvalue = ""; }

#--> open database
open (DAT,"<$database") || print "Could not open up database.  Please try again later.";
if ($LOCK_EX){
      flock(DAT, $LOCK_EX); #Locks the file
}
 @database_array = <DAT>;
 close (DAT);

$record_found=0;
$hidecount=0;
$total_record_round=0;
$displaycount=0;
$showing_top_results=0;

#--> cycle through database and look for matches and print them out

	foreach $lines(@database_array) {
        	@column = split(/\|/,$lines);
        	if ($column[10] eq "yes") { $hidecount++; } else {
		if ($id == $column[11]) {
			$record_found++;

		print "<tr><td><font size=1>&nbsp</td></tr>\n";
		if ($cfg{hide_company_name}==0) { print "<tr><td colspan=2><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><p>$column[0]</font></td></tr>\n";} else { print "<tr><td colspan=2></td></tr>\n"; }
		if ($cfg{hide_address}==0) { print "<td colspan=2><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">$column[1]<br>$column[2]</font></td></tr>";} else { print ""; }
		print "<td colspan=2><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">";
		if ($cfg{hide_city}==0) { print "$column[3],";} else { print "&nbsp;"; }
		if ($cfg{hide_state}==0) { print "\&nbsp;$column[4].";}
		if ($cfg{hide_zip}==0) { print "\&nbsp;$column[5]</font>";}
		print "</td></tr>";
		if ($cfg{show_mapquest_link}==1) { print"<td colspan=2>";
			      &mapquest;
			      print "</td></tr>"}
		if ($cfg{hide_telephone}==0) { print "<td width=10%><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><b>Phone:</b></td><td width=90%><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">$column[6]</font></td></tr>";}
		if ($cfg{hide_email}==0) { print "<td width=10%><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><b>Email:</b></td><td width=90%><a href=\"mailto:$column[7]\"><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">$column[7]</a></font></td></tr>";}
		if ($cfg{hide_website}==0) { print "<td width=10%><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><b>Website:</b></td><td width=90%><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><a href=\"http://$column[8]\" $websitelinktargetvalue>$column[8]</a></font></td></tr>";}
		if ($cfg{hide_notes}==0) { print "<td colspan=\"2\"><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">$column[9]</font></td></tr>";}
		$displaycount++;
		} # end if match found
		} # end if column 9 (hide profile)
}# end foreach

if ($record_found == 0) { print "<tr><td>";
			  &nomatch;
			  print "</tr></td>"; }
if ($cfg{show_mapquest_link}==1) {
print "<tr><td colspan=2 align=\"center\"><hr width=\"100%\" color=\"#000000\"><font size=\"1\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">Maps by <a href=\"http://www.mapquest.com\" target=\"_blank\">Mapquest</a></font></td></tr>";
} # end if hide_mapquest
}# end of sub view_records

##############################################################################################
# Sub: ZIP CODE SHOW RECORD MATCHES

sub zc_display_matching_records{
open (template, "<$resultstemplatefile") or &error("Unable to open the Results Template file<br> Make sure this file exists on the server and is chmod 775 or 777");
if ($flock eq "y") { flock template, 2; }
@template=<template>;
close(template);
foreach $template(@template) {
if ($template =~ /<!--MENU_LINKS-->/i) { print"<a href=\"javascript:history.back(-1)\">Go Back</a> | <a href=\"$cfg{formaction}\">Start Over</a>"; }
if ($template =~ /<!--INSERT_RESULTS_HERE-->/i) { &print_zc_display_matching_records; }
print "\n$template\n";
}#end foreach template line
} #end sub

##############################################################################################
# Sub: PRINT ZIP CODE SHOW RECORD DETAILS
sub print_zc_display_matching_records {

# If zip search, lets check to see if zip code was entered.  If not, lets tell them to go back and retry
if ($input{'zip'} eq "") { &error('Zip Code left blank.  This field is required.') } # ALWAYS REQUIRE ZIP CODE ON A ZIP SEARCH

if ($input{'zip'} eq "") { $input{'showsurrounding'} = 999; }

$input{'state'}="9";
$input{'text'}=$input{'zip'};

$stringzip = $input{'zip'};
$stringzipu = ($input{'zip'} + $cfg{zipcodearea});
$stringzipd = ($input{'zip'} - $cfg{zipcodearea});
$surrounding = $input{'showsurrounding'};
&print_matching_records;
}# end zip code searchmini

#############################################################################################
# MAP QUEST LINK
#
sub mapquest {

#Read fields and if spaces are found, replace them with + signs.
$column[1] =~ tr/ /+/; #address
$column[3] =~ tr/ /+/; #city
$column[4] =~ tr/ /+/; #state
$column[5] =~ tr/ /+/; #zip

if ($cfg{map_target} == 1) { $map_target_value = "target=\"_blank\""; } else {$map_target_value = ""; }

print <<"maplink";
<font size="$cfg{map_link_text_size}">( <a href="$cfg{mapquest_link}?city=$column[3]&state=$column[4]&address=$column[1]&zip=$column[5]&zoom=5" $map_target_value>$cfg{map_link_text}</a> )</font>
maplink
}# end of sub mapquest




#########################################################################################################################
# BEGIN ADMIN CONTROL PANEL CODE
#########################################################################################################################
# ADMIN LOGIN SCREEN
#
sub admin_show_login {

print <<"endofsub";
<center>
<h$cfg{heading_size}><font color="$cfg{heading_color}">$cfg{mytext}</font></h$cfg{heading_size}><br>
<h$cfg{heading_size}><font color="$cfg{heading_color}">Administrative Login</font></h$cfg{heading_size}>
<table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
  <tr>
    <td>
      &nbsp;
    </td>
    <td>
      <form method="POST" action="$cfg{formaction}">
      <input type="hidden" name="command" value="login">
        <table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
          <tr>
            <td align="center"><font color="red">$loginmessage</font><br>
            Password: <input type="password" name="password" value="" size="20"><br>
              <input type="submit" value=" Login... ">
              <p><font color="red">$temploginmessage</font><br>Powered by <a href="http://www.findbystate.com">FBS Locator PopUp</a> v$myversion</p>
            </td>
          </tr>
        </table>
      </form>
    </td>
  </tr>
</table>
endofsub
} # end of sub show_login

#############################################################################################
# ADMIN CHECK PASSWORD
#
sub admin_check_password {

my $passwordok=0;
my $passwordvalid=0;

if ($input{'password'} eq "$cfg{adminloginpassword}") { $passwordok = 1; }

if ($passwordok == 0) { $loginmessage = "Password Incorrect. Please try again";
			&admin_show_login; }
if ($passwordok == 1) { $passwordvalid = 1;
		       &admin_show_menu; }
}# end of sub check_password

#############################################################################################
# Show Menu Screen
#
sub admin_show_menu {

my $passwordvalid=0;
if ($input{'password'} eq "$cfg{adminloginpassword}") { $passwordvalid=1;}
if ($passwordvalid == 0) { &admin_show_login; }
else {

$records_found=0;
#--> open database and cound records
open (DAT,"<$database") || print "Could not open up database.  Please try again later.";
if ($LOCK_EX){
      flock(DAT, $LOCK_EX); #Locks the file
}
 @database_array = <DAT>;
 close (DAT);

#--> cycle through database
	foreach $lines(@database_array) {
        	$records_found++;
        } # end counting records

print <<"endofsub";
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin Locator PopUp Code
function NewWindow(mypage, myname, w, h, scroll) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
win = window.open(mypage, myname, winprops)
if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}
// End -->
</script>

<center>
<h$cfg{heading_size}><font color="$cfg{heading_color}">$cfg{mytext}</font></h$cfg{heading_size}>
<table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
  <tr>
    <td valign="top" align="center" width="300">
    <h$cfg{heading_size}><font color="$cfg{heading_color}">Administrative Menu</font></h$cfg{heading_size}></td>
    <td align="right"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Welcome: Admin</td>
  </tr>
  <tr>
    <td valign="top" align="center" rowspan="11" width="300">
    <img src="$cfg{imagedirectory}/$cfg{admin_menu_pic}"><br>
     <font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">
    Database contains $records_found records.</font>
    <p>
    <font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">
    ZipCode Locator PopUp v$myversion<br>
    Latest Version Available:
    <img border="0" src="http://www.findbystate.com/images/currentversionnumber.gif" align="bottom" width="25" height="20"></font></p>
    <p>
    <font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">
    <br><small>
    © 2003 PageSkills.com. All Rights Reserved</font></small<br>
    <font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">
    <font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">
    <a href="http://www.findbystate.com">www.FindbyState.com</a></font></td>
    <td bgcolor="#C0C0C0"><b>Records:</b></td>
  </tr>
  <tr>
    <td>
    <form method="POST" action="$cfg{formaction}">
      <input type="hidden" name="command" value="add">
      <input type="hidden" name="password" value="$input{'password'}">
      <table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
        <tr>
          <td><input type="submit" value="Add New &gt;&gt;"></td>
        </tr>
      </table>
    </form>
    </td>
  </tr>
  <tr>
    <td>
    <form method="POST" action="$cfg{formaction}">
      <input type="hidden" name="command" value="adminsearch">
      <input type="hidden" name="password" value="$input{'password'}">
      <table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
        <tr>
          <td><input type="submit" value="Search &gt;&gt;"></td>
        </tr>
      </table>
    </form>
    </td>
  </tr>
  <tr>
    <td>
    <form method="POST" action="$cfg{formaction}">
      <input type="hidden" name="command" value="adminviewall">
      <input type="hidden" name="password" value="$input{'password'}">
      <table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
        <tr>
          <td><input type="submit" value="View All &gt;&gt;"></td>
        </tr>
      </table>
    </form>
    </td>
  </tr>
  <tr>
    <td bgcolor="#C0C0C0"><b>Utilities:</b></td>
  </tr>
  <tr>
    <td>
    <form method="POST" action="$cfg{formaction}">
      <input type="hidden" name="command" value="sortdb">
      <input type="hidden" name="password" value="$input{'password'}">
      <table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
        <tr>
          <td><input type="submit" value="Sort Database &gt;&gt;"></td>
        </tr>
      </table>
    </form>
    </td>
  </tr>
  <tr>
    <td>
    <form method="POST" action="$cfg{formaction}">
      <input type="hidden" name="command" value="backupdb">
      <input type="hidden" name="password" value="$input{'password'}">
      <table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
        <tr>
          <td><input type="submit" value="Backup Database &gt;&gt;"></td>
        </tr>
      </table>
    </form>
    </td>
  </tr>
  <tr>
    <td>
    <form method="POST" action="statessetup.pl">
      <input type="hidden" name="command" value="login">
      <input type="hidden" name="password" value="$input{'password'}">
      <table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
        <tr>
          <td><input type="submit" value="Settings Utility &gt;&gt;"></td>
        </tr>
      </table>
    </form>
    </td>
  </tr>
  <tr>
    <td>
    <form method="POST" action="servertest.pl">
      <input type="hidden" name="password" value="$input{'password'}">
      <table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
        <tr>
          <td><input type="submit" value="Server Test &gt;&gt;"></td>
        </tr>
      </table>
    </form>
    </td>
  </tr>
  <tr>
    <td bgcolor="#C0C0C0"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}"><a href="$cfg{formaction}" onClick="NewWindow(this.href,'name','330','400','yes');return false;">Launch Program</a> >></font></td>
  </tr>
</table>
endofsub

}# end else
}# end of sub show_menu

#############################################################################################
# ADD NEW RECORD FORM
#
sub admin_add_new_form {

my $passwordvalid=0;
if ($input{'password'} eq "$cfg{adminloginpassword}") {$passwordvalid=1;}
if ($passwordvalid == 0) { &admin_show_login; }
else {

# Opens the counter file:
open THECOUNTER, "$counter_file";
($counter_num) = <THECOUNTER>;
close THECOUNTER;

print <<"endofsub";
<center>
<h$cfg{heading_size}><font color="$cfg{heading_color}">$cfg{mytext}</font></h$cfg{heading_size}><br>
<h$cfg{heading_size}><font color="$cfg{heading_color}">Add new Record</font></h$cfg{heading_size}>
 <form method="POST" action="$cfg{formaction}">
 <input type="hidden" name="command" value="process_new">
 <input type="hidden" name="password" value="$input{'password'}">
<table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
  <tr>
    <td valign="top"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Record ID:</font></td>
    <td valign="top" colspan="2"><input type="text" name="id" value="$counter_num" size="5"><br><small><font color="red">This number is assigned automatically!<br>But can be changed to any number. (no spaces)</font></small></td>
  </tr>
    <td valign="top" colspan="3"><hr size="1" color="#000000"></td>
  <tr>
    <td valign="top"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Name:</font></td>
    <td valign="top" colspan="2"><input type="text" name="name" size="20"></td>
  </tr>
  <tr>
    <td valign="top" nowrap><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Street Address:</font></td>
    <td valign="top" colspan="2"><input type="text" name="address1" size="20"><br><input type="text" name="address2" size="20"></td>
  </tr>
  <tr>
    <td valign="top"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">City:</font></td>
    <td valign="top" colspan="2"><input type="text" name="city" size="15"></td>
  </tr>
  <tr>
    <td valign="top"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">State/Province:</font></td>
    <td valign="top">
				<select name="state" size="1">
                                  <option value=""></option>
                                  <option value="AK">AK
                                  <option value="AL">AL
                                  <option value="AR">AR
                                  <option value="AZ">AZ
                                  <option value="CA">CA
                                  <option value="CO">CO
                                  <option value="CT">CT
                                  <option value="DC">DC
                                  <option value="DE">DE
                                  <option value="FL">FL
                                  <option value="GA">GA
                                  <option value="HI">HI
                                  <option value="IA">IA
                                  <option value="ID">ID
                                  <option value="IL">IL
                                  <option value="IN">IN
                                  <option value="KS">KS
                                  <option value="KY">KY
                                  <option value="LA">LA
                                  <option value="MA">MA
                                  <option value="MD">MD
                                  <option value="ME">ME
                                  <option value="MI">MI
                                  <option value="MN">MN
                                  <option value="MO">MO
                                  <option value="MS">MS
                                  <option value="MT">MT
                                  <option value="NC">NC
                                  <option value="ND">ND
                                  <option value="NE">NE
                                  <option value="NH">NH
                                  <option value="NJ">NJ
                                  <option value="NM">NM
                                  <option value="NV">NV
                                  <option value="NY">NY
                                  <option value="OH">OH
                                  <option value="OK">OK
                                  <option value="OR">OR
                                  <option value="PA">PA
                                  <option value="PR">PR
                                  <option value="RI">RI
                                  <option value="SC">SC
                                  <option value="SD">SD
                                  <option value="TN">TN
                                  <option value="TX">TX
                                  <option value="UT">UT
                                  <option value="VA">VA
                                  <option value="VT">VT
                                  <option value="WA">WA
                                  <option value="WI">WI
                                  <option value="WV">WV
                                  <option value="WY">WY
                                  <option value="XX">Other</option>
            </select></td>
   <td valign="top"> if other <input type="text" name="other" size="20"></td>
  </tr>
  <tr>
    <td valign="top"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Zip/Postal:</font></td>
    <td valign="top" colspan="2"><input type="text" name="zip" size="10"></td>
  <tr>
    <td valign="top" colspan="3"><hr size="1" color="#000000"></td>
  </tr>
  <tr>
    <td valign="top"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Telephone:</font></td>
    <td valign="top" colspan="2"><input type="text" name="telephone" size="20"></td>
  </tr>
  <tr>
    <td valign="top"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Email:</font></td>
    <td valign="top" colspan="2"><input type="text" name="email" size="20"></td>
  </tr>
  <tr>
    <td valign="top"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Website:</font></td>
    <td valign="top" colspan="2">http://<input type="text" name="website" size="20"></td>
  </tr>
  <tr>
    <td valign="top"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Notes:</font></td>
    <td valign="top" colspan="2"><textarea rows="4" name="notes" cols="35"></textarea></td>
  </tr>
  <tr>
    <td valign="top"></td>
    <td valign="top" colspan="2"><input type="submit" value="Add New Record"></td>
  </tr>
</table>
</form>
endofsub

print "<br><hr width=\"$cfg{table_width}\" color=\"#000000\" size=\"1\"><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><form method=\"POST\" action=\"$cfg{formaction}\"><input type=\"hidden\" name=\"command\" value=\"admin\"><input type=\"hidden\" name=\"password\" value=\"$input{'password'}\"><input type=\"submit\" value=\" Main Menu >> \"></form></font>\n";
} # end else admincheck
}# end of sub add_new_form

#############################################################################################
# PROCESS NEW RECORD
#
sub admin_do_process_new {

my $passwordvalid=0;
if ($input{'password'} eq "$cfg{adminloginpassword}") {$passwordvalid=1;}
if ($passwordvalid == 0) { &admin_show_login; }
else {

&error('Record ID Left Blank.  This field is required.') unless ($input{'id'}); #ALWAYS REQUIRED
$input{'state'} = $input{'other'} unless ($input{'other'} eq "");

if ($cfg{name_required}) { &error('Name field left blank.  This is a required field.') unless ($input{'name'}); }
if ($cfg{address1_required}) { &error('Street Address field left blank.  This is a required field.') unless ($input{'address1'}); }
if ($cfg{city_required}) { &error('City field left blank.  This is a required field.') unless ($input{'city'}); }
if ($cfg{state_required}) { &error('State or Country field left blank.  This is a required field.') unless ($input{'state'});	}
if ($cfg{zip_required}) { &error('Zip field left blank.  This is a required field.') unless ($input{'zip'}); }
if ($cfg{telephone_required}) { &error('Telephone field left blank.  This is a required field.') unless ($input{'telephone'}); }
if ($cfg{email_required}) { &error('Email field left blank.  This is a required field.') unless ($input{'email'});	}
if ($cfg{website_required}) { &error('Website field left blank.  This is a required field.') unless ($input{'website'}); }
if ($cfg{notes_required}) { &error('Notes field left blank.  This is a required field.') unless ($input{'notes'});	}

open (DAT,"<$database");
if ($LOCK_EX){
      flock(DAT, $LOCK_EX); #Locks the file
	}
 @database_array = <DAT>;
close (DAT);

open (DAT, ">$database");
if ($LOCK_EX){
      flock(DAT, $LOCK_EX); #Locks the file
	}
foreach $lines(@database_array) {
@edit_array = split(/\|/,$lines);
$oldrecords = join
("\|",@edit_array);
chomp($oldrecords);
print DAT "$oldrecords\n";
}
chomp($input{'name'},$input{'address1'},$input{'address2'},$input{'city'},$input{'state'},$input{'zip'},$input{'telephone'},$input{'email'},$input{'website'},$input{'notes'},$input{'id'});
print DAT "$input{'name'}|$input{'address1'}|$input{'address2'}|$input{'city'}|$input{'state'}|$input{'zip'}|$input{'telephone'}|$input{'email'}|$input{'website'}|$input{'notes'}|no|$input{'id'}\n";
close DAT;

&count_records;

print "<center><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">$input{'name'} has been added to the database.</font><br>\n";
print "<br><hr width=\"$cfg{table_width}\" color=\"#000000\" size=\"1\"><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><form method=\"POST\" action=\"$cfg{formaction}\"><input type=\"hidden\" name=\"command\" value=\"admin\"><input type=\"hidden\" name=\"password\" value=\"$input{'password'}\"><input type=\"submit\" value=\" Main Menu >> \"></form></font><br><form method=\"POST\" action=\"$cfg{formaction}\"><input type=\"hidden\" name=\"command\" value=\"add\"><input type=\"hidden\" name=\"password\" value=\"$input{'password'}\"><input type=\"submit\" value=\"Add Another &gt;&gt;\"></form>\n";
} # end else admincheck
}# end of sub do_process_new

#############################################################################################
# Search Form - allows admin to enter in name, city, state or zip to find a record to edit/delete/hide
#
sub admin_search_records_form {

my $passwordvalid=0;
if ($input{'password'} eq "$cfg{adminloginpassword}") {$passwordvalid=1;}
if ($passwordvalid == 0) { &admin_show_login; }
else {

print <<"adminsearchform";
<center>
<h$cfg{heading_size}><font color="$cfg{heading_color}">$cfg{mytext}</font></h$cfg{heading_size}><br>
<h$cfg{heading_size}><font color="$cfg{heading_color}">Administrative Advanced Search</font></h$cfg{heading_size}>
<form method="POST" action="$cfg{formaction}">
<input type="hidden" name="password" value="$input{'password'}">
<input type="hidden" name="command" value="adminfindrecord">
  <table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
    <tr>
      <td colspan="2"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Enter as much information into the fields below to find a record:</font></td>
    </tr>
    <tr>
      <td colspan="2">&nbsp;</td>
    </tr>
    <tr>
      <td colspan="2"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}"><b>Field Search:</b></td>
    </tr>
    <tr>
      <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Name:</font></td>
      <td><input type="text" name="name" size="35"></td>
    </tr>
    <tr>
      <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Street:</font></td>
      <td><input type="text" name="street1" size="35"><br><input type="text" name="street2" size="35"></td>
    </tr>
    <tr>
      <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">City:</font></td>
      <td><input type="text" name="city" size="35"></td>
    </tr>
    <tr>
      <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Zip- Code:</font></td>
      <td><input type="text" name="zip" size="6" maxlength="5"> </td>
    </tr>
    <tr>
      <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Telephone:</font></td>
      <td><input type="text" name="telephone" size="14" maxlength="14"></td>
    </tr>
    <tr>
      <td colspan="2"><input type="submit" value="Search..."></td>
    </tr>
    <tr>
      <td colspan="2">
        <hr size="1">
      </td>
    </tr>
    <tr>
      <td colspan="2"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Or
        you may also view all records for any state by typing in the state
        below:</font></td>
    </tr>
    <tr>
      <td colspan="2">&nbsp;</td>
    </tr>
    <tr>
      <td colspan="2"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}"><b>State Search:</b></td>
    </tr>
    <tr>
      <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">State:</font></td>
      <td><input type="text" name="state" size="3" maxlength="2"></td>
    </tr>
    <tr>
      <td colspan="2"><input type="submit" value="Search..."></td>
    </tr>
  </table>
</form>
adminsearchform
print "<br><hr width=\"$cfg{table_width}\" color=\"#000000\" size=\"1\"><p><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><form method=\"POST\" action=\"$cfg{formaction}\"><input type=\"hidden\" name=\"command\" value=\"admin\"><input type=\"hidden\" name=\"password\" value=\"$input{'password'}\"><input type=\"submit\" value=\" Main Menu >> \"></form></font>\n";
}# end else admincheck
}# end of sub admin_search_records_form

#############################################################################################
# Search List - Shows all records and allows admin to edit/delete each record
#
sub admin_do_search_records {

my $passwordvalid=0;
if ($input{'password'} eq "$cfg{adminloginpassword}") {$passwordvalid=1;}
if ($passwordvalid == 0) { &admin_show_login; }
else {

$show_record =0;

# lets check to see if search fields are blank.  If so, lets tell them to go back and retry
if (($input{'name'} eq "") && ($input{'street1'} eq "") && ($input{'street2'} eq "") && ($input{'zip'} eq "") && ($input{'city'} eq "") && ($input{'telephone'} eq "")) {
	print "<font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">You did not enter any data into the search fields.<br>Please go <a href=\"javascript:history.back(1)\">back</a> and try again.</font>\n";
}# end if fields are blank

$num_fields_search_on =0;

$stringname = lc($input{'name'});
$stringstreet1 = $input{'street1'};
$stringstreet2 = $input{'street2'};
$stringcity = lc($input{'city'});
$stringstate = uc($input{'state'});
$stringzip = $input{'zip'};
$stringtelephone = $input{'telephone'};

if ($input{'name'} ne "") { $num_fields_search_on++; }
if ($input{'street1'} ne "") { $num_fields_search_on++; }
if ($input{'street2'} ne "") { $num_fields_search_on++; }
if ($input{'city'} ne "") { $num_fields_search_on++; }
if ($input{'state'} ne "") { $num_fields_search_on++; }
if ($input{'zip'} ne "") { $num_fields_search_on++; }
if ($input{'telephone'} ne "") { $num_fields_search_on++; }

#--> open database
open (DAT,"<$database") || print "Could not open up database.  Please try again later.";
if ($LOCK_EX){
      flock(DAT, $LOCK_EX); #Locks the file
}
@database_array = <DAT>;
close (DAT);

$record_found=0;
$hidecount=0;
$displaycount=0;
$recordishidden = "";
$percentage=0;
$matchpercentage=0;
$matchcount=0;

print <<"tableheader";
<center>
<h$cfg{heading_size}><font color="$cfg{heading_color}">$cfg{mytext}</font></h$cfg{heading_size}><br>
<h$cfg{heading_size}><font color="$cfg{heading_color}">Edit/Delete Records</font></h$cfg{heading_size}>
<p><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Choose a Record to edit or delete</font></p>
<table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="80%" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
<tr>
    <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}"><b>ID &nbsp; Name</b></font></td>
    <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}"><b>Location</b></font></td>
    <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}"><b>Action</b></font></td>
</tr>
<tr>
    <td colspan="3"><hr></td>
</tr>
tableheader

#--> cycle through database and look for matches and print them out
	foreach $lines(@database_array) {
		@column = split(/\|/,$lines);
		$recordishidden = "";
        	# find out if its a name Search
        	if (($stringname ne "") && ($column[0] =~ /$stringname/i)) { $show_record=1; $percentage++;}
        	# find out if its a street 1 Search
        	if (($stringstreet1 ne "") && ($column[1] =~ /$stringstreet1/i)) { $show_record=1; $percentage++;}
        	# find out if its a street 2 Search
        	if (($stringstreet2 ne "") && ($column[2] =~ /$stringstreet2/i)) { $show_record=1; $percentage++;}
        	# find out if its a city Search
        	if (($stringcity ne "") && ($column[3] =~ /$stringcity/i)) { $show_record=1; $percentage++;}
		# find out if its a state Search
        	if (($stringstate ne "") && ($column[4] =~ /$stringstate/i)) { $show_record=1; $percentage++;}
		# find out if its a Zipcode Search
		if (($stringzip ne "") && ($column[5] eq $stringzip)) { $show_record=1; $percentage++;}
		# find out if its a Telephone Search
		if (($stringtelephone ne "") && ($column[6] =~ /$stringtelephone/i)) { $show_record=1; $percentage++;}

if ($column[10] eq "yes") { $recordishidden = "<font color=\"red\"> \- Hidden</font>"; }

$matchpercentage = &roundnd($percentage/$num_fields_search_on);

if (($show_record == 1) && ($matchpercentage >= 66)){
$record_found++;
print <<"recordline";
<tr>
    <td valign="top"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">$column[11] &nbsp; $column[0]</font> <font color="red" size=2>$recordishidden</font><br><font color="green" size=2>$matchpercentage\% match</font></td>
    <td valign="top"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">$column[1]<br>$column[3], <b>$column[4]</b>. $column[5]</font></td>
    <td valign="top">
        <table><tr><td><form method="POST" action="$cfg{formaction}">
	<input type="hidden" name="command" value="edit">
	<input type="hidden" name="password" value="$input{'password'}">
	<input type="hidden" name="id" value="$column[11]">
	<input type="submit" value="Edit">
	</form></td>
	<td><form method="POST" action="$cfg{formaction}">
	<input type="hidden" name="command" value="delete">
	<input type="hidden" name="password" value="$input{'password'}">
	<input type="hidden" name="id" value="$column[11]">
	<input type="submit" value="Delete">
	</form></td></tr></table>
     </td>
</tr>
<tr><td colspan=3><hr size=1 color="#000000"></td></tr>
recordline

$recordishidden = "";
}# end if show_record

$recordishidden = "";
$show_record=0;
$percentage=0;
$matchcount=0;
#$num_fields_search_on=0;
}# end foreach

print "</table>";
print "<p><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">$record_found record\(s\) found.<br><a href=\"javascript:history.back(-1)\">Click Here</a> to search again.</font></p>";
print "<br><hr width=\"$cfg{table_width}\" color=\"#000000\" size=\"1\"><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><form method=\"POST\" action=\"$cfg{formaction}\"><input type=\"hidden\" name=\"command\" value=\"admin\"><input type=\"hidden\" name=\"password\" value=\"$input{'password'}\"><input type=\"submit\" value=\" Main Menu >> \"></form></font>\n";
}# end else admincheck
}# end sub admin_do_search_records

#############################################################################################
# Search List - Shows all records and allows admin to edit/delete each record
#
sub admin_search_list {

my $passwordvalid=0;
if ($input{'password'} eq "$cfg{adminloginpassword}") {$passwordvalid=1;}
if ($passwordvalid == 0) { &admin_show_login; }
else {

$recordishidden = "";

#--> open database
open (DAT,"<$database") || print "Could not open up database.  Please try again later.";
if ($LOCK_EX){
      flock(DAT, $LOCK_EX); #Locks the file
}
 @database_array = <DAT>;
 close (DAT);

$record_found=0;

print <<"tableheader";
<center>
<h$cfg{heading_size}><font color="$cfg{heading_color}">$cfg{mytext}</font></h$cfg{heading_size}><br>
<h$cfg{heading_size}><font color="$cfg{heading_color}">Edit/delete Records</font></h$cfg{heading_size}>
<p><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Choose a Record to edit or delete</font></p>
<table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="80%" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
<tr>
    <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}"><b>ID &nbsp; Name</b></font></td>
    <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}"><b>Location</b></font></td>
    <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}"><b>Action</b></font></td>
</tr>
<tr>
    <td colspan="3"><hr></td>
</tr>
tableheader

#--> cycle through database
	foreach $lines(@database_array) {
        	@column = split(/\|/,$lines);
        	$recordishidden = "";
        	if ($column[0] ne "") {
       		if ($column[10] eq "yes") { $recordishidden = "<font color=\"red\"> \- Hidden</font>"; }
		$record_found++;

print <<"recordline";
<tr>
    <td valign="top"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">$column[11] &nbsp; $column[0]</font> <font color="red" size=2>$recordishidden</font></td>
    <td valign="top"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">$column[1]<br>$column[2]<br>$column[3], <b>$column[4]</b>. $column[5]</font></td>
    <td valign="top">
        <table><tr><td><form method="POST" action="$cfg{formaction}">
	<input type="hidden" name="command" value="edit">
	<input type="hidden" name="password" value="$input{'password'}">
	<input type="hidden" name="id" value="$column[11]">
	<input type="submit" value="Edit">
	</form></td>
	<td><form method="POST" action="$cfg{formaction}">
	<input type="hidden" name="command" value="delete">
	<input type="hidden" name="password" value="$input{'password'}">
	<input type="hidden" name="id" value="$column[11]">
	<input type="submit" value="Delete">
	</form></td></tr></table>
     </td>
</tr>
<tr><td colspan=3><hr size=1 color="#000000"></td></tr>
recordline
}# end if column[0] not blank
else { }
}# end foreach
print "</table>";
print "<p><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">We found $record_found total records.</font></p>";
print "<br><hr width=\"$cfg{table_width}\" color=\"#000000\" size=\"1\"><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><form method=\"POST\" action=\"$cfg{formaction}\"><input type=\"hidden\" name=\"command\" value=\"admin\"><input type=\"hidden\" name=\"password\" value=\"$input{'password'}\"><input type=\"submit\" value=\" Main Menu >> \"></form></font>\n";
} # end else admincheck
}# end of sub search_list

#############################################################################################
# EDIT DATABASE FORM
#
sub admin_edit_form {

my $passwordvalid=0;
if ($input{'password'} eq "$cfg{adminloginpassword}") {$passwordvalid=1;}
if ($passwordvalid == 0) { &admin_show_login; }
else {

$checkedvalue = "";

#--> open database
open (DAT,"<$database") || print "Could not open up database.  Please try again later.";
if ($LOCK_EX){
      flock(DAT, $LOCK_EX); #Locks the file
}
 @database_array = <DAT>;
 close (DAT);

#--> cycle through database and find record to edit and populate form
	foreach $lines(@database_array) {
		$checkedvalue = "";
        	@column = split(/\|/,$lines);
        	if ($column[11] == $input{'id'}) {
		if ($column[10] eq "yes") { $checkedvalue = "checked"; }

print <<"endofsub";
<center>
<h$cfg{heading_size}><font color="$cfg{heading_color}">$cfg{mytext}</font></h$cfg{heading_size}><br>
<h$cfg{heading_size}><font color="$cfg{heading_color}">Edit Record</font></h$cfg{heading_size}>
<table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
  <tr>
    <td width="100%">
      <form method="POST" action="$cfg{formaction}">
      <input type="hidden" name="command" value="admin_process_edit">
       <input type="hidden" name="password" value="$input{'password'}">
       <input type="hidden" name="origid" value="$column[11]">
        <table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
          <tr>
            <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Record ID:</font></td>
            <td><input type="text" name="id" value="$column[11]" size="20"><br><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">(unique record ID)</font></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
          <tr>
            <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Name:</font></td>
            <td><input type="text" name="name" value="$column[0]" size="40"></td>
          </tr>
          <tr>
            <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Address:</font></td>
            <td><input type="text" name="address1"  value="$column[1]" size="40"><br>
            <input type="text" name="address2"  value="$column[2]" size="40"></td>
          </tr>
          <tr>
            <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">City, State, Zip</font></td>
            <td><input type="text" name="city"  value="$column[3]" size="25">, <input type="text" name="state"  value="$column[4]" size="3" maxlength="2">.
              <input type="text" name="zip"  value="$column[5]" size="6" maxlength="5"></td>
          </tr>
          <tr>
            <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Telephone:</font></td>
            <td><input type="text" name="telephone"  value="$column[6]" size="20"></td>
          </tr>
          <tr>
            <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Email:</font></td>
            <td><input type="text" name="email"  value="$column[7]" size="20"></td>
          </tr>
          <tr>
            <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Website:</font></td>
            <td>http://<input type="text" name="website"  value="$column[8]" size="40"></td>
          </tr>
          <tr>
            <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Notes:</font></td>
            <td><textarea rows="4" name="notes" cols="35">$column[9]</textarea></td>
          </tr>
          <tr>
            <td><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Hide Record:</font></td>
            <td><input type="checkbox" $checkedvalue name="hide" value="yes"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Yes, hide this record from displaying.</font></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
          <tr>
            <td></td>
            <td><input type="submit" value="Save Changes"></td>
          </tr>
        </table>
      </form>
    </td>
  </tr>
</table>
endofsub

}# end if record matches
}# end foreach

print "<br><hr width=\"$cfg{table_width}\" color=\"#000000\" size=\"1\"><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><form method=\"POST\" action=\"$cfg{formaction}\"><input type=\"hidden\" name=\"command\" value=\"admin\"><input type=\"hidden\" name=\"password\" value=\"$input{'password'}\"><input type=\"submit\" value=\" Main Menu >> \"></form></font>\n";

} # end else admincheck
}# end of sub edit_form

#############################################################################################
# EDIT RECORD PROCESS
#
sub admin_do_process_edit {

my $passwordvalid=0;
if ($input{'password'} eq "$cfg{adminloginpassword}") {$passwordvalid=1;}
if ($passwordvalid == 0) { &admin_show_login; }
else {

&error('Record ID Left Blank.  This field is required.') unless ($input{'id'}); #ALWAYS REQUIRED

open (DAT,"<$database") || print "Could not open up database.  Please try again later.";
if ($LOCK_EX){
      flock(DAT, $LOCK_EX); #Locks the file
	}
 @database_array = <DAT>;
close (DAT);
open (DAT2, ">$database") || print "Could not open up database.  Please try again later.";
if ($LOCK_EX){
      flock(DAT2, $LOCK_EX); #Locks the file
	}

#####--> RE-WRITE THE UPDATED FILE TO DATABASE

foreach $lines(@database_array) {
          @column = split(/\|/,$lines);
            if ($column[11] == $input{'origid'}) {

# lets check to see if there are any inputs from the edit form
$column[0] = $input{'name'} if $input{'name'};
$column[1] = $input{'address1'} if $input{'address1'};
$column[2] = $input{'address2'} if $input{'address2'};
$column[3] = $input{'city'} if $input{'city'};
$column[4] = $input{'state'} if $input{'state'};
$column[5] = $input{'zip'} if $input{'zip'};
$column[6] = $input{'telephone'} if $input{'telephone'};
$column[7] = $input{'email'} if $input{'email'};
$column[8] = $input{'website'} if $input{'website'};
$column[9] = $input{'notes'} if $input{'notes'};
$column[10] = $input{'hide'} if $input{'hide'};
$column[10] = "no" if ($input{'hide'} eq "");
$column[11] = $input{'id'} if $input{'id'};

$column[0] = "" if ($input{'name'} eq "");
$column[1] = "" if ($input{'address1'} eq "");
$column[2] = "" if ($input{'address2'} eq "");
$column[3] = "" if ($input{'city'} eq "");
$column[4] = "" if ($input{'state'} eq "");
$column[5] = "" if ($input{'zip'} eq "");
$column[6] = "" if ($input{'telephone'} eq "");
$column[7] = "" if ($input{'email'} eq "");
$column[8] = "" if ($input{'website'} eq "");
$column[9] = "" if ($input{'notes'} eq "");
$column[10] = "no" if ($input{'hide'} eq "");
}

$newline = join
("\|",@column);

chomp($newline);
print DAT2 "$newline\n" || print "Error Saving Record To Database.";
}

close (DAT2);

print "<center><h$cfg{heading_size}><font color=\"$cfg{heading_color}\">The database has been updated</font></h$cfg{heading_size}>";
print "<br><hr width=\"$cfg{table_width}\" color=\"#000000\" size=\"1\"><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><form method=\"POST\" action=\"$cfg{formaction}\"><input type=\"hidden\" name=\"command\" value=\"admin\"><input type=\"hidden\" name=\"password\" value=\"$input{'password'}\"><input type=\"submit\" value=\" Main Menu >> \"></form></font>\n";
} # end else admincheck
} # end sub admin_do_edit_process

#############################################################################################
# DELETE PROCESS - ARE YOU SURE???
#
sub admin_are_you_sure {

my $passwordvalid=0;
if ($input{'password'} eq "$cfg{adminloginpassword}") {$passwordvalid=1;}
if ($passwordvalid == 0) { &admin_show_login; }
else {

&error('Record ID Left Blank.  This field is required.') unless ($input{'id'}); #ALWAYS REQUIRED

print <<endofsub;
<center>
<h$cfg{heading_size}><font color="$cfg{heading_color}">$cfg{mytext}</font></h$cfg{heading_size}><br>
<h$cfg{heading_size}><font color="$cfg{heading_color}">Confirm Deletion</font></h$cfg{heading_size}><br>
<p><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">You have chosen to delete a record from the database. <b>The Record ID is $input{'id'}.</b></font><br>
<font color="red">Are you sure you wish to continue?</font>
<p>
<form method="post" action="$cfg{formaction}">
<input type="hidden" name="command" value="admin_confirm_delete">
<input type="hidden" name="id" value="$input{'id'}">
<input type="hidden" name="password" value="$input{'password'}">
<input type="submit" value="YES">
</form>
&nbsp;&nbsp;
<form method="post" action="$cfg{formaction}">
<input type="hidden" name="command" value="admin">
<input type="hidden" name="password" value="$input{'password'}">
<input type="submit" value="NO">
</form>
endofsub

print "<br><hr width=\"$cfg{table_width}\" color=\"#000000\" size=\"1\"><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><form method=\"POST\" action=\"$cfg{formaction}\"><input type=\"hidden\" name=\"command\" value=\"admin\"><input type=\"hidden\" name=\"password\" value=\"$input{'password'}\"><input type=\"submit\" value=\" Main Menu >> \"></form></font>\n";
} # end else admincheck
} # end sub admin_are_you_sure

#############################################################################################
# DELETE RECORD PROCESS
#
sub admin_do_process_delete {

my $passwordvalid=0;
if ($input{'password'} eq "$cfg{adminloginpassword}") {$passwordvalid=1;}
if ($passwordvalid == 0) { &admin_show_login; }
else {

open (DAT,"<$database");
if ($LOCK_EX){
      flock(DAT, $LOCK_EX); #Locks the file
	}
 @database_array = <DAT>;
close (DAT);

open (DAT2, ">$database");
if ($LOCK_EX){
      flock(DAT2, $LOCK_EX); #Locks the file
	}
foreach $lines(@database_array) {
          @edit_array = split(/\|/,$lines);

# Rewrite the record only if ID does not match.  Thus deleting the record we want to exclude
if ($edit_array[11] != $input{'id'}) {
chomp($lines);
print DAT2 "$lines\n" || print "Error Deleting Record From Database.";
   }
}
close (DAT2);
print "<center><h$cfg{heading_size}><font color=\"$cfg{heading_color}\">The database has been updated</font></h$cfg{heading_size}>";
print "<br><hr width=\"$cfg{table_width}\" color=\"#000000\" size=\"1\"><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><form method=\"POST\" action=\"$cfg{formaction}\"><input type=\"hidden\" name=\"command\" value=\"admin\"><input type=\"hidden\" name=\"password\" value=\"$input{'password'}\"><input type=\"submit\" value=\" Main Menu >> \"></form></font>\n";

} # end else admincheck
} # end sub admin_do_process_delete

#############################################################################################
# Sort Database Screen
#
sub admin_sort_screen {

#determine current date
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
$curDay=(Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday)[$wday];
$curMonth=(Jan,Feb,Mar,Apr,May,June,July,Aug,Sept,Oct,Nov,Dec)[$mon];
$liveDate=($year+1900).".$curMonth.$mday-H$hour-M$min-S$sec";

my $passwordvalid=0;
if ($input{'password'} eq "$cfg{adminloginpassword}") {$passwordvalid=1;}
if ($passwordvalid == 0) { &admin_show_login; }
else {

print <<"sortscreen";
<center>
<h$cfg{heading_size}><font color="$cfg{heading_color}">Sort Database</font></h$cfg{heading_size}>
   <form method="POST" action="$cfg{formaction}">
      <input type="hidden" name="command" value="admin_do_sort">
      <input type="hidden" name="password" value="$input{'password'}">
<table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
  <tr>
    <td align="center" colspan="2"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">To sort the database, please select the field
      you wish to perform the sort on.</td>
  </tr>
  <tr>
    <td align="center" width="10%" colspan="2">
      <hr size="1" color="#000000">
    </td>
  </tr>
  <tr>
    <td align="center" colspan="2">&nbsp;</td>
  </tr>
  <tr>
    <td align="right" width="10%" nowrap><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">Field To Sort On:</font></td>
    <td vAlign="top"><font face="Arial" size="2"><select name="field_to_sort_on" size="1">
        <option value="4" selected>State</option>
        <option value="0">Name</option>
        <option value="5">Zip Code</option>
      </select></font></td>
  </tr>
  <tr>
    <td colspan="2">&nbsp; </td>
  </tr>
  <tr>
    <td vAlign="bottom" align="left" colSpan="2"><input type="submit" value="  Run Sort  " name="submit">
    <p><small><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">A backup database will be created and saved before the sort is performed and will be named simular to: <b>states.db.$liveDate</b></small>
    </td>
  </tr>
</table>
</form>
sortscreen

print "<p><hr width=\"$cfg{table_width}\" color=\"#000000\" size=\"1\"><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><form method=\"POST\" action=\"$cfg{formaction}\"><input type=\"hidden\" name=\"command\" value=\"admin\"><input type=\"hidden\" name=\"password\" value=\"$input{'password'}\"><input type=\"submit\" value=\" Main Menu >> \"></form></font>\n";

} # end else admincheck
} # end sub admin_sort_screen

#############################################################################################
# Sort Database
#

sub admin_process_sort_db {

my $passwordvalid=0;
if ($input{'password'} eq "$cfg{adminloginpassword}") {$passwordvalid=1;}
if ($passwordvalid == 0) { &admin_show_login; }
else {

#determine current date
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
$curDay=(Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday)[$wday];
$curMonth=(Jan,Feb,Mar,Apr,May,June,July,Aug,Sept,Oct,Nov,Dec)[$mon];
$liveDate=($year+1900).".$curMonth.$mday-H$hour-M$min-S$sec";

my($fieldToSortOn);
my($sortType);

$fieldToSortOn = $input{'field_to_sort_on'};

if ($fieldToSortOn ==4 ) { $sortType = "alpha"; } # Alpha Sort on State Field
if ($fieldToSortOn ==0 ) { $sortType = "alpha"; } # Alpha Sort on Name Field
if ($fieldToSortOn ==5 ) { $sortType = "numeric"; } # Numeric Sort on ZipCode Field


   if(-e $database){
     open (DATA_FILE, "<$database")||
          &error($database,
          "Cannot Read Database File", __FILE__, __LINE__);
          undef $/;
          $dataFile = <DATA_FILE>;   # read in whole file
          $/ = "\n";                 # back to normal input delim
     close(DATA_FILE);
     chmod(0777,$database);

# Let's make an unsorted backup
     my($unsortedFile) = $database . ".$liveDate";
     open (DATA_FILE, ">$unsortedFile") || &error($unsortedFile,"Cannot write unsorted database backup file", __FILE__, __LINE__);
        print DATA_FILE $dataFile;
     close(DATA_FILE);

        # Build file array

     my(@dataFileArray) = split(/\n/,$dataFile);
     undef $dataFile;

       # Sort the data by the ID number

     my(@sortedData) = ();

     if($sortType =~ /alpha/i){
     @sortedData = map  { $_->[0] }
                   sort {
                           "\u$a->[1]" cmp "\u$b->[1]"
                   }
                   map  { [ $_, (split /\|/,$_)[$fieldToSortOn] ] }
                   @dataFileArray;
     }
     else{
     @sortedData = map  { $_->[0] }
                   sort {
                           $a->[1] <=> $b->[1]
                   }
                   map  { [ $_, (split /\|/,$_)[$fieldToSortOn] ] }
                   @dataFileArray;
     }

     open (DATA_FILE, ">$database")|| &error($database,"Cannot open Database File to resort", __FILE__, __LINE__);
     my $row;
     foreach $row (@sortedData){
        print DATA_FILE "$row\n" || print "Error Saving Re-Sorted Records To Database.";
     }
     close(DATA_FILE);
   }
   print "<center><table align=\"center\" width=\"400\" border=0><tr><td><center><h$cfg{heading_size}><font color=\"$cfg{heading_color}\">Sort Database</font></h$cfg{heading_size}></center>";
   print "<center><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">Database Sorting Complete</center><p><br>An backup file (before sort) is located on your server at <b>$database.$liveDate</b></font><br><br><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">Note: The backup database has the following naming rules: <b>Year.Month.Day-Hour-Minute-Seconds</b> appended to the end.</font>\n";
   print "<br><hr width=\"100%\" color=\"#000000\" size=\"1\"><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><center><form method=\"POST\" action=\"$cfg{formaction}\"><input type=\"hidden\" name=\"command\" value=\"admin\"><input type=\"hidden\" name=\"password\" value=\"$input{'password'}\"><input type=\"submit\" value=\" Main Menu >> \"></form></font></td></tr></table>\n";

} # end else admincheck
} # end sub admin_sort_db

#############################################################################################
# Backup Database Screen
#
sub admin_backup_screen {

#determine current date
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
$curDay=(Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday)[$wday];
$curMonth=(Jan,Feb,Mar,Apr,May,June,July,Aug,Sept,Oct,Nov,Dec)[$mon];
$liveDate=($year+1900).".$curMonth.$mday-H$hour-M$min-S$sec";

my $passwordvalid=0;
if ($input{'password'} eq "$cfg{adminloginpassword}") {$passwordvalid=1;}
if ($passwordvalid == 0) { &admin_show_login; }
else {

print <<"sortscreen";
<center>
<h$cfg{heading_size}><font color="$cfg{heading_color}">Backup Database</font></h$cfg{heading_size}>
   <form method="POST" action="$cfg{formaction}">
      <input type="hidden" name="command" value="admin_do_backup">
      <input type="hidden" name="password" value="$input{'password'}">
<table border="$cfg{table_border}" bordercolor="$cfg{table_border_color}" width="$cfg{table_width}" cellpadding="$cfg{table_padding}" cellspacing="$cfg{table_spacing}" bgcolor="$cfg{table_background_color}">
  <tr>
    <td align="center" colspan="2"><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">To backup the database, please click the
      Run Button below.</td>
  </tr>
  <tr>
    <td align="center" width="10%" colspan="2">
      <hr size="1" color="#000000">
    </td>
  </tr>
    <tr>
    <td align="center" colspan="2">&nbsp;</td>
  </tr>
  <tr>
    <td colspan="2">&nbsp; </td>
  </tr>
  <tr>
    <td vAlign="bottom" align="center" colspan="2"><input type="submit" value="  Run Backup  " name="submit">
    <p><small><font size="$cfg{text_size_body}" color="$cfg{text_color_body}" face="$cfg{font_face}">A backup database will be created and saved to your server and will be named simular to: <b>states.db.$liveDate</b></small>
    </td>
  </tr>
</table>
</form>
sortscreen

print "<p><hr width=\"$cfg{table_width}\" color=\"#000000\" size=\"1\"><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><form method=\"POST\" action=\"$cfg{formaction}\"><input type=\"hidden\" name=\"command\" value=\"admin\"><input type=\"hidden\" name=\"password\" value=\"$input{'password'}\"><input type=\"submit\" value=\" Main Menu >> \"></form></font>\n";

} # end else admincheck
} # end sub admin_sort_screen

#############################################################################################
# Backup Database
#

sub admin_process_backup_db {

my $passwordvalid=0;
if ($input{'password'} eq "$cfg{adminloginpassword}") {$passwordvalid=1;}
if ($passwordvalid == 0) { &admin_show_login; }
else {

#determine current date
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
$curDay=(Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday)[$wday];
$curMonth=(Jan,Feb,Mar,Apr,May,June,July,Aug,Sept,Oct,Nov,Dec)[$mon];
$liveDate=($year+1900).".$curMonth.$mday-H$hour-M$min-S$sec";

   if(-e $database){
     open (DATA_FILE, "<$database")||
          &error($database,
          "Cannot Read Database File", __FILE__, __LINE__);
          undef $/;
          $dataFile = <DATA_FILE>;   # read in whole file
          $/ = "\n";                 # back to normal input delim
     close(DATA_FILE);
     chmod(0777,$database);

# Let's make an backup
     my($unsortedFile) = $database . ".$liveDate";
     open (DATA_FILE, ">$unsortedFile") || &error($unsortedFile,"Cannot write unsorted database backup file", __FILE__, __LINE__);
        print DATA_FILE $dataFile;
     close(DATA_FILE);
     chmod(0777,$database . ".$liveDate");
   }
   print "<table align=\"center\" width=\"400\" border=0><tr><td><center><h$cfg{heading_size}><font color=\"$cfg{heading_color}\">Backup Database</font></h$cfg{heading_size}></center>";
   print "<center><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">Backup Process Complete</center><p><br>The backup file is located on your server at <b>$database.$liveDate</b></font><p>\n\n<font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\">Note: The backup database has the following naming rule: <b>Year.Month.Day-Hour-Minute-Seconds</b> appended to the end.</font>\n";
   print "<br><hr width=\"100%\" color=\"#000000\" size=\"1\"><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><center><form method=\"POST\" action=\"$cfg{formaction}\"><input type=\"hidden\" name=\"command\" value=\"admin\"><input type=\"hidden\" name=\"password\" value=\"$input{'password'}\"><input type=\"submit\" value=\" Main Menu >> \"></form></font></td></tr></table>\n";

} # end else admincheck
} # end sub admin_sort_db

#############################################################################################
# ROUND NUMERIC VALUES
#
sub round {
	$_[0] =~ s/\,//g;
	@bidamt = split(/\./, $_[0]);
	$bidamt[0] = "0" if (!($bidamt[0]));
	$bidamt[0] = int($bidamt[0]);
	$bidamt[1] = substr($bidamt[1], 0, 2);
	$bidamt[1] = "00" if (length($bidamt[1]) == 0);
	$bidamt[1] = "$bidamt[1]0" if (length($bidamt[1]) == 1);
	return "$bidamt[0].$bidamt[1]";
}

sub roundnd {
	$_[0] =~ s/\,//g;
	@bidamt = split(/\./, $_[0]);
	$bidamt[0] = "0" if (!($bidamt[0]));
	$bidamt[0] = int($bidamt[0]);
	$bidamt[1] = substr($bidamt[1], 0, 2);
	$bidamt[1] = "00" if (length($bidamt[1]) == 0);
	$bidamt[1] = "$bidamt[1]0" if (length($bidamt[1]) == 1);
	return "$bidamt[0]$bidamt[1]";
}

#############################################################################################
# COUNTER FILE
# Sub: OPEN COUNTER FILE AND ADD 1 TO IT

sub count_records {
	open (DAT, "$counter_file");
	if ($LOCK_EX){
	flock(DAT, $LOCK_EX); #Locks the file
}
	$num = <DAT>;
	close(DAT);
	$new_num = $num + 1;
	open (OUT, ">$counter_file");
	if ($LOCK_EX){
	flock(DAT, $LOCK_EX); #Locks the file
}
	print OUT "$new_num" || print "Error Accessing File statescounter.txt";
	close(OUT);
}

###########################################################################################
# GET FORM DATA
# This gets data from a post.

sub get_form_data {
if ($ENV{'REQUEST_METHOD'} eq 'POST') {
  read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
} else {
  $buffer = $ENV{'QUERY_STRING'};
}
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
  ($name, $value) = split(/=/, $pair);
  $value =~ tr/+/ /;
  $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
  $input{$name} = $value;
}
}#END SUB

#########################################################################################
# Error
# This generates an error message and dies.

sub error {
	print "<br><font size=\"$cfg{text_size_body}\" color=\"$cfg{text_color_body}\" face=\"$cfg{font_face}\"><b>An error has occurred with your request.</b><br><br> Please hit your browser's back button and try again.<br><br><font color=\"navy\"><b>Reason:</b><br>$_[0]</font><br><br><br>If you can not resolve this matter, please send an email to <A HREF=\"mailto:$cfg{orgemail}\">$cfg{orgemail}</A><br><br>\n";
	die "An error has occurred.<br>Reason: <b>$_[0]</b><br>Hit your browsers back button to try again!\n";
};