#!/usr/bin/perl -w

################################################################################
################################################################################
#####      The code in this script is the property of Spark-IT Group       #####
#####     All rights reserved. No unauthorized replication permitted.      #####
#####          SIT PERL PayPal catalog script for WSDBI (C) 2009           #####
#####                            Version 1.0.1                             #####
################################################################################
################################################################################
# start user configuration
################################################################################
################################################################################

$Feature_Name       = "Online Billiard Supply Store";
$Feature_Short_Name = "Billiard Supply Store";

# the database table name and fields that this script will use for data source
$item_data_table        = "products";
$item_number_field      = "Product_ID";
$item_active_field      = "Active";
$item_category_field    = "Category";
$item_name_field        = "Product_Name";
$item_description_field = "Description";
$item_details_field     = "Details";
$item_options_field     = "Options";
$item_amount_field      = "Reg_Price";
$item_sale_price_field  = "Sale_Price";
$item_imgType_field     = "File_Type";

$cart_type = "PayPal"; # see more configuration settings below

#======================================================================
#  optional PayPal user configurations
#======================================================================

#load required perl modules or libraries before configuring paypal
#my $dbh;
my $db_params = "wsdbi_params.pm";
my $db_common = "admin/params.pl";
eval {
    #use strict;
    use DBI;
    require $db_params;
    require $db_common;
};

#check for load errors
if ($@) {
    &my_load_error_doc($@);
    exit(0);
}

#======================================================================
#  optional PayPal user configurations
#======================================================================
$selfURL = $ENV{SCRIPT_NAME};
#$selfURL = "/cgi-bin/store.pl";

# default background color for table data
$bgcolor = "#ffffff";

#$PP_lc = Paypal language control: Set to param specified for your language.
$PP_lc = "US";

# $image_url4_PayPal = Add Your Logo!
# Customize the look of your PayPal payment pages by adding your logo. This
# image, which must be 150 by 50 pixels in size, will appear in the upper left
# hand corner of the page when your customer presses your Shopping Cart
# button. Always use secure HTTPS URL protocol if possible.
$image_url4_PayPal = "https://$op_info->{HTTP_Host}$my_Business_logo_URL ";

# $return_url = Successful Payment URL
# Enter the URL where you would like to send your customers after they have
# completed payment. Once your customer has completed their payment, they will
# see a payment confirmation page. From this page, they will press the
# 'Continue' button and return to the Successful Payment URL you have
# specified. If you do not enter a Successful Payment URL, customers who click
# this link will be taken to a PayPal web page.
$return_url = "http://$op_info->{HTTP_Host}$selfURL";

#$shopping_url = Continue Shopping (PayPal's "Return to Merchant" param)
$shopping_url = "http://$op_info->{HTTP_Host}$selfURL";

#$cancel_return = URL where shopper is returned after Cancel Checkout at PayPal
$cancel_return = "http://$op_info->{HTTP_Host}$selfURL";

# Enter the currency symbols PayPal uses to designate US dollars
# or Euros or Pounds Sterlings. [Enter a backslash before the $ symbol!]
# US: $
# Euros:  €
# Pounds Sterling: £
# Canadian Dollar (C$)
# Japanese Yen (¥)
$m_symbol = "\$";

# The currency of the payment is U.S.Dollars: USD
# The currency of the payment is British Pounds Sterling: GBP
# The currency of the payment is Euros: EUR
# The currency of the payment is Canadian Dollar: CAD
# The currency of the payment is Yen: JPY
$currency_code = "CAD";

# End user configuration - DO NOT EDIT BELOW
print "Content-type: text/html \n\n\r\n\r\n\r" unless ($content_type_printed);
$content_type_printed++;
################################################################################
################################################################################
use CGI::Carp qw(fatalsToBrowser);
#comment out the above line unless developing and when done debugging the script

################################################################################
################################################################################
#####          This code tells the browser what MIME type the content is.  #####
#####          All content delivered by this script is HTML                #####
################################################################################
################################################################################


#dont't buffer output
$|++;    

# find out the OS
if ( $^O eq 'MSWin32' || $ENV{'OS'} eq 'Windows_NT' ) {

    # this one for windows
    $windows = 'Yes';
    $slash   = '\\';
}
else {
    $windows = 'No';
    $slash   = '/';
}


# connect to DB, read CGI data, verify Login,
ConnectToDB();
my_read_CGI_input();

##### define time variables
my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
  localtime(time);
$mon        = $mon + 1;
$year       = $year + 1900;
$accessTime = "$hour:$min:$sec";
$AN         = int( rand(10000) );


#init_cart_buttons
if ( $cart_type eq "PayPal" ) {
    $view_cart_button = qq~
         <FORM ACTION="https://www.paypal.com/cgi-bin/webscr" METHOD=POST target="_top">
                <INPUT TYPE="HIDDEN" NAME="business" VALUE="$op_info->{PP_Email}">
                <INPUT TYPE="HIDDEN" NAME="cmd" VALUE="_cart">
                <INPUT TYPE="HIDDEN" NAME="display" VALUE="1">
                <INPUT TYPE="HIDDEN" NAME="lc" VALUE="$PP_lc">
                <INPUT TYPE="HIDDEN" NAME="rm" VALUE="2">
                <INPUT TYPE="HIDDEN" NAME="return" VALUE="$selfURL?cmd=Thanks">
                <INPUT TYPE="HIDDEN" NAME="cancel_return" VALUE="$selfURL">
                <INPUT TYPE="HIDDEN" NAME="image_url" VALUE="$image_url4_PayPal">

                <INPUT TYPE="HIDDEN" NAME="bn" VALUE="PP%2dBuyNowBF%3abtn_paynowCC_LG%2egif%3aNonHosted">

                <BUTTON TYPE="SUBMIT" NAME="submit_btn" VALUE="">View Cart</BUTTON>
         </FORM>
    ~;
}
else
{
    $view_cart_button = qq~~;

}



#################################################################################
#################################################################################

if    ( $data{cmd} eq "Sign-Off" ) { Log_Out();      }
elsif ( $data{cmd} eq "PayPalOK" ) {Confirm_PayPal();}
else  { Main_HTML_Doc(); }

DisConnectFromDB();

#End of main perl code, begin subroutines

sub Main_HTML_Doc() {

    $top_right_link_content = qq~
                    <div align="center"><font size="2"><BR>Want a <BR>
                           <A href="/cgi-bin/billiard-product-price-list.pl"><IMG src="$my_Images_folder/p-list-btn.jpg" width="61" height="30" border="0"><BR>price list?</A><br>
                    </div>
                    ~;

    #Determine Page Content
    $left_content = Active_Product_Category_Links(); #Default Content
    $left_content = Dir_Help() if ( $data{cmd} eq "Help" );

    $left_content = Dir_Thanks() if ( $data{cmd} eq "Thanks" );

    $main_content = Default_Content();   #if($data{cmd} eq ""); #Default Content

    $main_content = Read_Inventory_DB()
      if ( ( $data{$item_category_field} ne "" )
        || ( $data{cmd} eq "ShowItem" ) );
    $main_content = Help_Html() if ( $data{cmd} eq "Help" );

    $main_content = Thanks() if ( $data{cmd} eq "Thanks" );

    my $page_title_text = "$data{$item_category_field} - "
      if ( defined $data{$item_category_field} );

    if ( defined $item_name ) {
        my @item_keyword_list = split( " ", $item_name );
        $item_keywords = join( ",", @item_keyword_list );
        $item_keywords .= ",";
        $page_title_text = "$item_name - " if ( defined $data{Item} );
    }

    print "Content-type: text/html \n\n\r\n\r\n\r"
      unless ($content_type_printed);
    $content_type_printed++;

    do "main_html_doc.pl";

}

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

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

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

sub Active_Product_Category_Links() {
    my $html    = "";
    my $dbquery = "SELECT * FROM $item_data_table WHERE $item_active_field = 'TRUE' ORDER BY $item_category_field ";
    my $sth = $dbh->prepare($dbquery)
      or print "Query syntax error. $dbquery. Reason: $DBI::errstr.";
    if ( not $sth->execute() ) {
        print "<p>Can't execute query:<br> $dbquery.<p> Reason: $DBI::errstr.";
        $sth->finish;
        DisConnectFromDB();
        exit;
    }
    while ( my $sku_ref = $sth->fetchrow_hashref() ) {
        $entry_found = 0;
        foreach $this_category (@my_unique_categories) {
            if ( $this_category eq $sku_ref->{$item_category_field} ) {
                $entry_found = 1;
            }
        }
        if ( $entry_found == 0 ) {
            push( @my_unique_categories, $sku_ref->{$item_category_field} );
        }
    }
    $sth->finish();

    $i = 0;
    foreach $this_category (@my_unique_categories) {
        if (   ( $data{$item_category_field} ne "" )
            && ( $data{$item_category_field} eq $this_category ) )
        {
            $this_link = qq~<DIV  align='left' style='font-size:9pt; margin-top:8px; margin-bottom:8px; margin-left:2px; margin-right:2px; background-color:#FFCC66;'>&nbsp;<B>$this_category</B></DIV>\n~;
        }
        else {
            $this_link = qq~<DIV  align='left' style='font-size:9pt; margin-top:8px; margin-bottom:8px; margin-left:2px; margin-right:2px; background-color:#FCEBA7;'>&nbsp;<A class="catlink" href="$my_WS_HTTP_URL$selfURL?Category=$this_category&AN=$AN" target='_self' title="@my_unique_cat_link_alt[$i]"><B>$this_category</B></A></DIV>\n~;
        }
        push( @category_links, $this_link );
        $i++;
    }
    $html = qq~
     @category_links
    ~;

    return $html;
}

sub get_field_names() {
    my $dbtable = shift;
    my @fields  = ();
    if ( $dbtable eq "" ) {
        &show_my_error_doc("Can't execute query:<br> DESC.<p><B>Reason:</B><BR>Unknown DB table name: $dbtable"
        );
        &DisConnectFromDB;
        exit(0);
    }
    my $sth = $dbh->prepare("DESC $dbtable");
    if ( not $sth->execute() ) {
        &show_my_error_doc("Can't execute query:<br> $dbquery.<p><B>Reason:</B><BR>$DBI::errstr."
        );
        &DisConnectFromDB;
        exit(0);
    }

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

sub Dir_Help() {
    my $help_content;
    $help_content = Default_Content();    #Default Content
    $help_content = Dir_Account() if ( $data{option} eq "AcctMngr" );

    $help_content = Dir_Help() if ( $data{option} eq "Help" );

}

sub Dir_Thanks() {
    my $html = qq~
		<DIV align="left" style="font-size:10pt; background-color:#ffffff; margin-right:8px;font-family:Arial,Helvetica,sans-serif;">
	        <DIV style=" margin:8px;">

	        </DIV>
		</DIV>
	~;
    return $html;

}

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

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

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

        ########## Process $content ##############
        $content =~ tr/+/ /;                              # Convert plus's to spaces
        $content =~ s/%(..)/pack("c",hex($1))/ge;         # Convert %XX from hex numbers to alphanumeric
        # Convert %XX from hex numbers to alphanumeric
        # when using hidden input tags:
        $content =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
        
        # get rid of attempts to insert illegal characters
        $content =~ s/\\//g;    # remove black slashes
        $content =~ s/\0//g;    # remove nulls
        
        # get rid of attempts to insert special characters
        $content =~ s/[\\\&\;\`\'\"\|\*\~\^\[\]\{\}\$]//gs;

        # get rid of attempts to insert HTML tags
        $content =~ s/>/&gt;/gs;       #convert < to special HTML Character
        $content =~ s/</&lt;/gs;       #convert > to special HTML Character
        $content =~ s/\cM/\n/g;        #convert CR to LF
        $content =~ s/[\r\n]/ /g;      #convert LF to to single space?
        
        $content =~ s/TRUNCATE/ /ig;
        $content = substr( $content, 0, 4096 );
        $content =~ s/^\s+|\s+$//gs;

        # Convert Name/Value pair into %data Key/Content HashRef
        if ( !defined( $data{$key} ) ) {     $data{$key} = $content;   }
        else {  # there should be only ONE value for these keys:
            if ( $key !~ /username/ and $key !~ /password/ and $key !~ /RecordID/ and $key !~ /cmd/ and $key !~ /action/)
            {
                # adds a comma seperated value to the key when duplicate keys are found
                $data{$key} .= ",$content" if ( $content ne "" );  
            }
        }

        $i++;
    }
    ########## end process Name/Valye pairs ##############
    return 1;
}

sub Read_Inventory_DB() {

    # urlencode the PayPal business email address
    my $email = urlencode($business_email);
    my $dbquery;
    if ( $data{cmd} eq "ShowItem" ) {
        $dbquery = "SELECT * FROM $item_data_table WHERE $item_number_field LIKE '$data{Item}'  LIMIT 1";
        $third_column_header_HTML = qq~~;

        #$content_name = lc($item_number);
        $content_name = uc($item_number);
    }
    elsif ( $data{$item_category_field} ne "" ) {
        $dbquery = qq~SELECT * FROM $item_data_table WHERE $item_active_field = "TRUE" AND $item_category_field LIKE '$data{$item_category_field}' ORDER BY $item_name_field ~;
        $third_column_header_HTML = qq~<td class="cartHDR" valign='top'><IMG src="$my_Images_folder/spacer.gif" width="175" height="1" ><BR>Features</td>~;

        #$content_name = lc($data{$item_category_field});
        $content_name = uc( $data{$item_category_field} );
    }
    else {
        Show_default_content();
        return;
    }

    my $sth = $dbh->prepare($dbquery)
      or print "Query syntax error. $dbquery. Reason: $DBI::errstr.";
    if ( not $sth->execute() ) {
        print "<p>Can't execute query:<br> $dbquery.<p> Reason: $DBI::errstr.";
        $sth->finish;
        DisConnectFromDB();
        exit;
    }

    my $html = qq~
        <TABLE align='left' width='95%' cellpadding='4' cellspacing='0'>
        <TR bgcolor='#FCEBA7'>
            <TD align='center' width='20%'>
                $view_cart_button
            </TD>
            <TD valign='top' align='center' width='60%'>
                <DIV style='font-size:20pt;'><B>
                    $content_name</B>
                </DIV>
            </TD>
            <TD align='center' width='20%'>
                <img src="$my_Images_folder/cart_by_sit.gif" width='150px' border="0">
            </TD>
        </TR>
        ~;

        # loop through the array of products and display the HTML add to cart buttons */
        $listIndex = 1;
        while ( $sku_ref = $sth->fetchrow_hashref() ) {

                my $item_number = $sku_ref->{$item_number_field};
                $item_name = $sku_ref->{$item_name_field};
                my $item_amount     = $sku_ref->{$item_amount_field};
                my $item_sale_price = "<FONT color='#990000' size=3><B>SALE! </B>$m_symbol$sku_ref->{$item_sale_price_field}</FONT>"
                  if ( $sku_ref->{$item_sale_price_field} < $item_amount );

                my $conversion_rate = 1;

                my $item_MSRP = &money_format( $sku_ref->{$item_amount_field} * $conversion_rate );
                my $item_amount     = $item_MSRP;
                my $item_sale_price =
                  ( $sku_ref->{$item_sale_price_field} * $conversion_rate );
                if ( $sku_ref->{$item_sale_price_field} <
                    $sku_ref->{$item_amount_field} )
                {
                    $item_amount =
                      ( $sku_ref->{$item_sale_price_field} * $conversion_rate );
                    $item_amount     = &money_format($item_amount);
                    $item_sale_price = "<FONT color='#990000' size=3 class='sale'><B>SALE! </B>$m_symbol$item_amount</FONT>";
                }

                my @options_html = ();

                if (( defined $sku_ref->{$item_options_field} ) && ( $sku_ref->{$item_options_field} ne "" ) )
                {
                    my $o = 0; my $optionIndex_switch = -1;
                    my @option_types_array = ();
                    @option_types_array = split (/\|/, $sku_ref->{$item_options_field} );
                    foreach my $option_type (@option_types_array)
                    {
                            @temp_option_values_html = ();
                            @temp_option_nameValue_array = ();
                            @temp_option_nameValue_array = split( /\:/,  $option_type );
                            my $option_name = $temp_option_nameValue_array[0];
                            
                            push( @temp_option_values_html,qq~<OPTION value="" selected>Choose:</OPTION>\n~ );
                            
                            my @temp_option_list_array = ();
                            @temp_option_list_array = split(/;/,$temp_option_nameValue_array[1]);
                            
                            my $temp_option_select_html_code = "";
                            if ($temp_option_nameValue_array[1] =~ "=")
                            {
                                if ($optionIndex_switch == -1)
                                {
                                    $optionIndex_switch = $o;
                                    $temp_option_select_html_code = qq~
                                                <INPUT type="hidden" name="option_index" value="$optionIndex_switch">\n~
                                    if ($o >-1);
                                }
                            }
                            
                            my $my_option_select_html_code = "";
                            my $oListIndex = 0;
                            foreach my $temp_option (@temp_option_list_array)
                            {
                                    my @temp_option_select_html_array = ();
                                    my @temp_option_data_array=();
                                    @temp_option_data_array = split ("=",$temp_option);
                                    my $temp_option_name = $temp_option_data_array[0];
                                    if (($temp_option =~ "=") && ($optionIndex_switch == $o))
                                    {
                                            my $temp_option_price = 0;
                                            $temp_option_data_array[1] =~ s/\$//sg;
                                            $temp_option_price = $temp_option_data_array[1] if ((defined $temp_option_data_array[1]) && ($temp_option_data_array[1] > 0));
                                            
                                            $temp_option_price = $temp_option_price + $item_amount;
                                            $temp_option_price = &money_format($temp_option_price);
                                            $temp_option_price  =~ s/\$//sg;

                                            $temp_option_select_html_code .= qq~
                                                <INPUT type="hidden" name="option_select$oListIndex" value="$temp_option_name">
                                                <INPUT type="hidden" name="option_amount$oListIndex" value="$temp_option_price">
                                            ~;

                                            push( @temp_option_select_html_array, $temp_option_select_html_code);
                                    }
                                    else
                                    {
                                       #?
                                    }
                                    push(@temp_option_values_html, qq~
                                                <OPTION value="$temp_option_name">$temp_option</OPTION>\n~);
                                    $my_option_select_html_code =qq~@temp_option_select_html_array~;
                                    $oListIndex++;
                                    
                            }
                            push(@options_html, qq~
                                                <INPUT type="hidden" name="on$o" value="$option_name">
                                                <B>$option_name Options:</B><BR>
                                                <SELECT name="os$o" >
                                                    @temp_option_values_html
                                                </SELECT><BR>
                                                $my_option_select_html_code
                                        ~);
                            $o++;
                    }
                }


                my $add_form_HTML = "";


                if ( $cart_type eq "PayPal" )
                {
                    #code not finished! Conver this PayPal "buy now" code to "add to cart" code
                    $add_form_HTML= qq~
                           <FORM ACTION="https://www.paypal.com/cgi-bin/webscr" METHOD=POST>
                                <INPUT TYPE="HIDDEN" NAME="business" VALUE="$op_info->{PP_Email}">
                                <INPUT TYPE="HIDDEN" NAME="cmd" VALUE="_cart">
                                <INPUT TYPE="HIDDEN" NAME="add" VALUE="1">
                                
                                <INPUT TYPE="HIDDEN" NAME="item_name" VALUE="$item_name">
                                <INPUT TYPE="HIDDEN" NAME="item_number" VALUE="$item_number">
                                <INPUT TYPE="HIDDEN" NAME="amount" VALUE="$item_amount">
                                
                                <INPUT TYPE="HIDDEN" NAME="currency_code" VALUE="$currency_code">
                                <INPUT TYPE="HIDDEN" NAME="no_note" VALUE="1">
                                
                                <INPUT TYPE="HIDDEN" NAME="lc" VALUE="$PP_lc">
                                <INPUT TYPE="HIDDEN" NAME="rm" VALUE="2">
                                <INPUT TYPE="HIDDEN" NAME="image_url" VALUE="$image_url4_PayPal">
                                
                                <INPUT TYPE="HIDDEN" NAME="return" VALUE="$return_url?cmd=Thanks">
                                <INPUT TYPE="HIDDEN" NAME="cbt" VALUE="$op_info->{Trade_Name}">
                                
                                
                                <INPUT TYPE="HIDDEN" NAME="cancel_return" VALUE="$cancel_return">
                                <INPUT TYPE="HIDDEN" NAME="shopping_url" VALUE="$shopping_url">
                                Qty:<BR>
                                <INPUT TYPE="text"   NAME="quantity" VALUE="1" size=3 max=3><BR>
                                @options_html
                                <BUTTON TYPE="SUBMIT" NAME="submit_btn" VALUE="">Add to Cart</BUTTON>
                         </FORM>
                	 ~;
                }
                else
                {
                    $add_form_HTML = qq~~;
                }

                $detail_link = qq~<a href="$my_WS_HTTP_URL$selfURL?cmd=ShowItem&Item=$sku_ref->{$item_number_field}">Show Bigger Picture...</A><BR><BR>~;
                $detail_link2 = qq~
        	                <DIV style='height:24px; overflow:hidden;'>
                                     <FORM  name="List"   method="POST" action="$selfURL">
                	                     <INPUT type="hidden" name="login"    value="$LOGIN">
                	                     <INPUT type="hidden" name="AN"       value="$AN">
                	                     <INPUT type="hidden" name="cmd"      value="ShowItem">
                                             <INPUT type="hidden" name="Item"      value="$sku_ref->{$item_number_field}">
                	                     <INPUT type="submit" name="Submit"   Value='Show me more...' style='font-size:8pt; width:85px; height:18px; background-color:#eeeeee; text-align:left;'>
       	                             </FORM>
                                </DIV>
        	             	~;
                $this_row_bg_color = '#FFF7F0';
                if ( $listIndex % 2 ) { $this_row_bg_color = '#ffffff'; }

                # create the code for the add to cart buttons for each product
                if ( $data{cmd} eq "ShowItem" ) {
                   my $ImgFileLoc = "$item_data_table/large/$item_number.$sku_ref->{LrgFile_Type}";

                    if ( -e "../$ImgFileLoc" ) {
                        $product_img_URL = qq~<img src="$my_WS_HTTP_URL/$ImgFileLoc" align="left" border="0" alt="$item_name">~;
                    }
                    else {
                        $product_img_URL =  "<FONT color='#990000'><B>No Photo</B></FONT>";
                    }
                    my $item_details = $sku_ref->{$item_details_field};

                    $item_details =~ s/<vbTab \/>/\t/gs;
                    $item_details =~ s/<vbCrLf \/>/\n/gs;
                    #$item_details =~ s/<vbLf \/>/\n/gs;
                    #$item_details =~ s/<vbCr \/>/\cM/gs;

                    $html_row = qq~
                                      <tr>
                                            <TD align="center" style="font-size:18pt;" colspan=3>
                                                <B>$item_name</B>
                                            </TD>
                                      </TR>
                 	              <tr bgcolor='$this_row_bg_color'>
        	                            <td class="cartTD" valign='top'>
                                                <FONT style='font-size:10pt; font-weight:bold;'>$item_number</FONT><BR>
                                                MSRP:<BR>
                                                $m_symbol$sku_ref->{$item_amount_field} $currency_code<BR>
                                                $item_sale_price<BR>
        	                                $add_form_HTML <BR>
        	                            </td>
        	                            <td colspan='2' class="cartTD" valign='top'>
        	                                $product_img_URL
                                                $sku_ref->{$item_description_field}
        	                            </td>
        	                      </tr>
                                      <TR>
                                    	    <TD colspan='2' class="cartTD" valign='top'>
                                                $item_details
                                                <BR><BR><A href="#Top">Top</A>
                                            </TD>
                                            <TD>&nbsp;</TD>
                                      </TR>
                                    ~;
                }
                else {
                    my $ImgFileLoc = "$item_data_table/med/$item_number.$sku_ref->{File_Type}";
                    if ( -e "../$ImgFileLoc" ) {
                        $product_img_URL = qq~<img src="$my_WS_HTTP_URL/$ImgFileLoc" border="0" alt="$item_name">~;
                    }
                    else {
                        $product_img_URL =
                          "<FONT color='#990000'><B>Photo Pending</B></FONT>";
                    }
                    $html_row = qq~
                                            <tr>
        	                                <td class="cartHDR" valign='top'><IMG src="$my_Images_folder/spacer.gif" width="100" height="1" ><BR>Item</td>
        	                                <td class="cartHDR" colspan='2' valign='top'><IMG src="$my_Images_folder/spacer.gif" width="225" height="1" ><BR>Description</td>
        	                            </tr>
                                            <tr bgcolor='$this_row_bg_color'>
                                                <td class="cartTD" valign='top'>
                                                    <FONT style='font-size:10pt; font-weight:bold;'>$item_number</FONT><BR>
                                                    MSRP:<BR>
                                            	    $m_symbol$sku_ref->{$item_amount_field} $currency_code<BR>
                                                    $item_sale_price<BR>
                                                    $add_form_HTML<BR>
                                                    $detail_link<BR>
                                                    
                                                </td>
                                                <td class="cartTD" colspan='2' valign='top'>
                                                    <FONT style='font-size:10pt; font-weight:bold;'>$item_name</FONT><BR>
                                                    $product_img_URL<BR>
                                                    <DIV style='width:400px;'>
                                                    $sku_ref->{$item_description_field}
                                                    </DIV>
                                                </td>
                                            </tr>
        	                	~;
                }

                # display the code for the add to cart buttons for each product
                $html .= $html_row;
                $listIndex++;
        }

    $html .= qq~  </TABLE>~;
    $sth->finish;
    return $html;
}

sub Default_Content() {

    if ( $cart_type eq "PayPal" )
    {
        $pay_methods = qq~
        	<IMG src="$my_Images_folder/logo-xclick.gif"><BR>
            You are safe shopping with us at $op_info->{Trade_Name} <BR>
        ~;
    }
    else
    {
        $pay_methods = qq~~;
    }

    my $default_policy_content = &SITe_get_include("../$item_data_table/default-policy-content.html");

    my $html = qq~

    <TABLE align='left' width='95%' cellpadding='4' cellspacing='0'>
        <TR>
	    <TD colspan='3'>
                <DIV style="margin:10px;">
	                <P align='center'><IMG BORDER="0" SRC="$my_Images_folder/spacer.gif" HEIGHT="1" ALIGN="bottom" WIDTH="390" HSPACE="0" VSPACE="0"><BR>
	                    <B>Welcome to the $op_info->{Trade_Name} Online Store </B><BR>
	                </P>
	        </DIV>
	    </TD>
	</TR>
        <TR bgcolor='#FCEBA7'>
            <TD align='left' width='20%'>
            	$view_cart_button
            </TD>
            <TD valign='top' align='center' width='60%'>
                <DIV style='font-size:20pt;'><B>
                    $content_name</B>
                </DIV>
            </TD>
            <TD  valign='top' align='center' width='20%'>
                <img src="$my_Images_folder/cart_by_sit.gif" width='150px' height='41px' border="0">
            </TD>
        </TR>
        <TR>
	        <TD colspan='3'>
                <DIV style="margin-left:12px; margin-top:10px; margin-right:10px; ">
	                <P align='center'>
	                    To begin shopping, select a product category from the category list at left.
	                </P><BR>
	        	</DIV>
	        </TD>
	    </TR>

        <TR>
	        <TD colspan='3' align='center'>
        		<FONT face="Arial, Helvetica, sans-serif" size="1" style="font-size:8pt;">
                 	$pay_methods
	            </FONT>
	        </TD>
	    </TR>
        <TR>
	     <TD colspan='3'><BR><HR><BR>
	            $default_policy_content
	     </TD>
	</TR>
    </TABLE>
    ~;
    return $html;
}

sub show_error() {
    my ($item) = shift;
    my $server      = ( $ENV{HTTP_HOST} ) ? $ENV{HTTP_HOST}     : 'localhost';
    my $REQUEST_URI = $ENV{'SCRIPT_NAME'} ? $ENV{'SCRIPT_NAME'} : $0;
    $item =~ s/\]/\]<br>/g;
    $item =~ s/\(/<br>\(/g;
    $item =~ s/\)/\)<br>/g;
    $item =~ s/\bat\b/<br>at/g;
    my $error = qq~

    <br>Reason:<br>$item
    ~;

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

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


sub Thanks() {
    my $html = qq~Thank you for your order. You can expect to hear from us very soon.<BR><BR>Thanks,<BR>CueValue.~;
    return $html;
}

sub urlencode() {
    my ($esc) = @_;
    $esc =~ s/^\s+|\s+$//gs;
    $esc =~ s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
    $esc =~ s/ /\+/g;
    $esc =~ s/%20/\+/g;
    return $esc;
}

sub money_format() {
    my $amount = shift;
    my ( $temp_dollar_amount_str, $temp_cent_amount ) = split( /\./, $amount );
    if ( ( length($temp_cent_amount) < 1 ) || ( $temp_cent_amount == 0 ) ) {
        $temp_cent_amount_str = "00";
    }
    elsif ( length($temp_cent_amount) == 1 ) {
        $temp_cent_amount_str = "$temp_cent_amount" . "0";
    }
    elsif ( length($temp_cent_amount) == 2 ) {
        $temp_cent_amount_str = $temp_cent_amount;
    }
    elsif ( length($temp_cent_amount) > 2 ) {
        my $thousanths_place = substr( $temp_cent_amount, 2, 1 );
        $temp_cent_amount_str = substr( $temp_cent_amount, 0, 2 );
        if ( $thousanths_place => 5 ) {
            $temp_cent_amount_str++;
        }

    }

    #$amount = $amount * 100;

  #my $temp_dollar_amount_str = substr($amount,0,length($amount)-2);
  #my $temp_cent_amount_str = substr($amount,length($amount)-2,length($amount));
    my $temp_amount_str = "$temp_dollar_amount_str" . ".$temp_cent_amount_str";
    return $temp_amount_str;
}





sub query_INV_DB_for_record_data() {

    # Query DB for Inventory Item data
    #print "selecting $data{Item} from $dbtable<BR>\n";
    my $db_query = "SELECT * FROM $item_data_table WHERE $item_number_field LIKE '$data{Item}' LIMIT 1";

    unless ( $sth = $dbh->prepare($db_query) ) {
        &show_error("Inventory query syntax error. $db_query. Reason: $DBI::errstr.");
        &DisConnectFromDB;
        exit(0);
    }
    unless ( $sth->execute() ) {
        &show_error("Can't execute Inventory query:<br> $db_query.<p><B>Reason:</B><BR>$DBI::errstr."
        );
        &DisConnectFromDB;
        exit(0);
    }
    unless ( $INV_recordRef = $sth->fetchrow_hashref() ) {
        &show_error("Can't read Inventory record:<br> $db_query.<p><B>Reason:</B><BR>Record not found."
        );
        &DisConnectFromDB;
        exit(0);
    }
    $sth->finish();
}



sub ConnectToDB() {

    if ( defined $sth ) { $sth->finish(); }
    $dbh = DBI->connect( "DBI:mysql:$op_info->{WSDBI_DB_Name}:$op_info->{WSDBI_DB_Host}", $op_info->{WSDBI_DB_User}, $op_info->{WSDBI_DB_Pass} );
    if ( not $dbh ) {
        print "<p>Can't connect to  server.<p>Reason: $DBI::errstr";
        exit;
    }

}

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






__END__




