#!/usr/local/bin/perl
##############################################################################
# IntraLinks ShoppingCart Version 2.6         
# Copyright 2000 IntraLinks Corporation
# Coded by Matt Champneys mchampneys@intralinkscorp.com
# Please direct comments or bug reports to mchampneys@intralinkscorp.com
#                                                                            
# This program may be used and modified free of charge by anyone so long as      
# this copyright notice is included.  By using this code you agree to
# hold IntraLinks Corporation free from any liability that might arise 
# from it's use.   You may not sell or redistribute this code without prior written
# consent from IntraLinks Corporation    

require "config.pl";


###########################################################
### program start

$top_page=top_page($template_file);
$bottom_page=bottom_page($template_file);

# get input if any
&get_data;

# Clean up the customer folder
$customer_time=86400*$customer_days;
&customer_cleanup;

# check to see if user has established ID.  If not, establish one
if ($FORM{'uid'} eq "") {
	# get the cookie
	@cookievalues=split(/;/,$ENV{'HTTP_COOKIE'});
	foreach $value (@cookievalues) {
		if ($value=~/storecustomer=/) {
			@cookie=split(/=/,$value);
			$FORM{'uid'}=$cookie[1];
			chomp($FORM{'uid'});
		}
	}
	
	# no cookie data?  Establish one
	if ($FORM{'uid'} eq "") {
		$FORM{'uid'}=&key_counter;
		print "Set-Cookie: storecustomer=$FORM{'uid'}; path=/; expires=Tue, 04-Oct-2061 12:00:00 GMT;\n";
	}
	
	#check to see if there is a customer file and if not, create one
	if (!open(IN,"$customer_folder/$FORM{'uid'}.txt")) {
		open(OUT,">$customer_folder/$FORM{'uid'}.txt");
		print OUT "";
		close(OUT);
	}
	
}

$customer_file="$customer_folder/$FORM{'uid'}.txt";


# send content header right away
print "Content-type: text/html\n\n";


## If no action is specified, show search page
if ($FORM{'action'} eq "") {
	print qq| $top_page $title_front Revisar Tienda $title_back   
Use una de las siguientes opciones de busqueda
	<ul>
	<li><a href="$script_url?action=search&uid=$FORM{'uid'}&listall=1">Listar Todos Los Productos</a><br><br>
	<li><form action="$script_url" method="post">
	Buscar por nombre<br>
	<input type="text" name="keyword" size="20">
	<input type="submit" value="Buscar">
	<input type="hidden" name="uid" value="$FORM{'uid'}">
	<input type="hidden" name="action" value="search">
	</form>
	<li><form action="$script_url" method="post">
	Listar por Categoría<br>
	<select name="category"><option>Seleccionar</option>|;

	@categories=&get_categories;
	foreach $category (@categories) {print "<option>$category</option>";}

	print qq | </select>
<input type="submit" value="Buscar">
<input type="hidden" name="uid" value="$FORM{'uid'}">
<input type="hidden" name="action" value="search"></form>
	</ul> $bottom_page |;
}

## if action is search display search results
if ($FORM{'action'} eq "search") {
	open(IN,"$product_file");
	while(<IN>){
		@field=split(/\|/,$_);
		if ($FORM{'keyword'} ne "") {
			if (/$FORM{'keyword'}/i) {
				$results[$z]=&short_display;
				$z++;
				if ($z==1) {$first_sku=$field[0];}
			}
		}
		if ($FORM{'category'} ne "") {
			if ($field[5] eq $FORM{'category'}) {
				$results[$z]=&short_display;
				$z++;
				if ($z==1) {$first_sku=$field[0];}
			}
		}
		if ($FORM{'listall'} ne "") {
			$results[$z]=&short_display;
			$z++;
			if ($z==1) {$first_sku=$field[0];}
		}
	} # end of while loop
	close(IN);
	$z="";
	if ($FORM{'category'} ne "") {
		$results_title="$title_front $FORM{'category'} $title_back ";
	} else {
			$results_title="$title_front  Resultados de 
la búsqueda  $title_back ";
		}
		
	$array_length=@results;
	
	if ($reverse_order eq "Yes") {@results=reverse(@results);}
	
	# if there is only one result, display the link, otherwise display the thumbnail page
	if ($array_length==1) {
		$FORM{'sku'}="$first_sku";
		$FORM{'action'}="link";
	} else {
		# thumbnail page
		$FORM{'keyword'}=~s/ /\+/g;
		$FORM{'category'}=~s/ /\+/g;
		$FORM{'skucategory'}=~s/ /\+/g;
		
		if ($FORM{'startlist'} eq "") {$FORM{'startlist'}=0;}
		$items_per_page=$display_rows * $display_columns;
		$next_page_start=$FORM{'startlist'}+$items_per_page;
		$prev_page_start=$FORM{'startlist'}-$items_per_page;
		
		if ($prev_page_start >= 0) {
			$previous=qq|<a href="$script_url?action=search&keyword=$FORM{'keyword'}&category=$FORM{'category'}&startlist=$prev_page_start&sku=$FORM{'sku'}&skucategory=$FORM{'skucategory'}&listall=$FORM{'listall'}&uid=$FORM{'uid'}"><- Previous Page</a> |;
		}
		if ($next_page_start < $array_length) {
			$next=qq|<a href="$script_url?action=search&keyword=$FORM{'keyword'}&category=$FORM{'category'}&startlist=$next_page_start&sku=$FORM{'sku'}&skucategory=$FORM{'skucategory'}&listall=$FORM{'listall'}&uid=$FORM{'uid'}">Next Page -></a> |;
		}
	
		$number_displayed=$array_length-$FORM{'startlist'};
		if ($number_displayed > $items_per_page) {$number_displayed=$items_per_page;}
		$number_pages=int($array_length/$items_per_page);
		$dec_number_pages=($array_length/$items_per_page);
		if ($dec_number_pages > $number_pages) {$number_pages++;}
		if ($FORM{'startlist'}==0){$number_display_pages=1;} else {$number_display_pages=int($FORM{'startlist'}/$items_per_page)+1;}
	
		print qq| $top_page $results_title $array_length items encontrados. Mostrando Página $number_display_pages de $number_pages  <br> 
<table width=$display_width cellpadding=0 cellspacing=0 border=0>
<tr><td align=left>$font $previous</td><td align=right>$font $next</tr>
</table>
<table width=$display_width cellpadding=$display_padding>|;

		$y=$FORM{'startlist'};
	
		for($x=0;$x<$display_rows;$x++) {
			print "<tr>";
			for($z=0;$z<$display_columns;$z++) {
				print "$results[$y]";
				$y++;
			}
			print "</tr>";
		}
		print qq|</table> 
	<table width=$display_width cellpadding=0 cellspacing=0 border=0>
<tr><td align=left>$font $previous</td><td align=right>$font $next</tr>
</table>$statgraphic
	$bottom_page|;
	} # end of else
}

## if action is link display selected page
if ($FORM{'action'} eq "link") {
	@field=&get_sku($FORM{'sku'});
	print qq| $top_page |;
	if ($field[9] ne "") {$photo=qq| <img src="$photo_url/$field[8]" border="0" align="$photo_align"> |;}
	print qq|$photo $font <h2>$field[1] $field[2]</h2> $field[4] 
<h2><b>\$$field[6]</b></h2> Código\#: $field[0]
<form action="$script_url" method="post"> <table>|;
	
	# this part displays the option drop down menus
	$z=20;
	for($a=0;$a<$option_types;$a++) {
		if ($field[$z] ne "") {$show=1;} else {$show="";}
		if ($show) {print qq| <tr><td>$font $field[$z]:&nbsp;&nbsp;</td><td><select name="$field[$z]"> |;}
		$z++;
		$high=$option_number*2;
		for($x=0;$x<$high;$x=$x+2){
			if ($field[$z] ne "") {
				if ($show) {print qq|<option>$field[$z]</option>|;}
			}
			$z=$z+2;
		}
		print "</select></td></tr>";
	}
	
	print qq| <tr><td>$font 
Cantidad:&nbsp;&nbsp;</td><td><input 
type="text" name="quantity" value="1" size="4" maxlength="4"></td></tr></table>
<input type="hidden" name="action" value="add_to_cart">
<input type="hidden" name="uid" value="$FORM{'uid'}">
<input type="hidden" name="sku" value="$FORM{'sku'}">
			<input type="submit" value="Agregar a su pedido"> </form> 
			<a href="$script_url?uid=$FORM{'uid'}&action=view_cart">Ver su Pedido</a> 
			$bottom_page |; 
}


## if action is add_to_cart get that taken care of
if ($FORM{'action'} eq "add_to_cart") {

	@field=&get_sku($FORM{'sku'});
	
	$z=20;
	for($a=0;$a<$option_types;$a++) {
		$option[$a]=$FORM{$field[$z]};
		$z++;
		$high=$option_number*2;
		for($x=0;$x<$high;$x=$x+2){
			if ($field[$z] eq $option[$a]) {$field[6]=$field[6]+$field[$z+1];}
			$z=$z+2;
		}
	}
	
	
	open(IN,"$customer_file");
	($customer)=<IN>; 
	chomp($customer);
	$line="$customer$field[0]~$field[1] $field[2]"; 
	for($a=0;$a<$option_types;$a++) {if ($option[$a]) {$line.=", $option[$a]";}}
	$line.="~$field[6]~$FORM{'quantity'}~$field[7]~";
	for($a=0;$a<$option_types;$a++) {$line.="~$option[$a]";}
	$line.="%%";
	close(IN);	
	open(OUT,">$customer_file");
	print OUT $line;
	close(OUT);
	
	@summary=&get_summary($FORM{'uid'});
	print qq | $top_page $title_front Pedido $title_back  a 
continuación mostramos un detalle de su pedido. <br><br><table 
border=1>$summary[0]<tr><td colspan=4 align=right>$font <b>Total:</b>&nbsp;&nbsp;&nbsp;</td><td align=right>$font \$$summary[1]</td></tr></table>
<ul>
<li><a href="$script_url_secure?uid=$FORM{'uid'}&action=check_out">Confirmar Compra</a>
<li><a href="$script_url?uid=$FORM{'uid'}">Continuar Comprando</a>
<li><a href="$script_url?uid=$FORM{'uid'}&action=clear_cart">Vaciar Pedido</a>
</ul>
$bottom_page |;
}

## if action is clear cart then do it
if ($FORM{'action'} eq "clear_cart") {
	
	open(OUT,">$customer_file");
	print OUT "";
	close(OUT);
	print qq| $top_page $title_front Pedido Vaciado $title_back  Su 
pedido ha sido Vaciado. <a
 href="$script_url?uid=$FORM{'uid'}">Continuar 
Comprando.</a> $bottom_page |; }

##  view the cart
if ($FORM{'action'} eq "view_cart") {
	@summary=&get_summary($FORM{'uid'});
	if ($summary[2]==1) {
		print qq| $top_page $title_front Su Pedido Esta Vacío 
$title_back  Actualmente Su Pedido no contiene ningún item.
<a href="$script_url?uid=$FORM{'uid'}">Continuar Comprando.</a> 
$bottom_page |;
	} else {

	print qq | $top_page $title_front Tienda en Línea $title_back  A 
continuación hay un resumen del contenido de su pedido. <br><br><table border=1>$summary[0]<tr><td colspan=4 align=right>$font <b>Total:</b>&nbsp;&nbsp;&nbsp;</td><td align=right>$font \$$summary[1]</td></tr></table>
<ul>
<li><a href="$script_url_secure?uid=$FORM{'uid'}&action=check_out">Confirmar Compra</a>
<li><a href="$script_url?uid=$FORM{'uid'}">Continuar Comprando</a>
<li><a href="$script_url?uid=$FORM{'uid'}&action=clear_cart">Vaciar Pedido</a>
</ul>
$bottom_page |; 
	}
}

##########################################################
## Check Out
if ($FORM{'action'} eq "check_out") {
	open(IN,"$shipping_file");
	(@file=<IN>);
	close(IN);
	@field=split(/\|/,$file[0]);
	
	open(IN,"$tax_file");
	@tax_states=<IN>;
	close(IN);
	foreach $state (@tax_states) {
		chomp($state);
		$d++;
		if ($state ne "" && $d != 1) {$select_state=1;}
	}
	
	if ($select_state == 1 || $field[0] eq "") {
		print qq | $top_page $title_front Check Out Info $title_back 
		<form action="$script_url_secure" method="post">|;
		
		if ($select_state == 1) {
			print qq | Please select your State: <br><SELECT NAME="state"><OPTION>Alabama<OPTION>Alaska<OPTION>Arizona<OPTION>Arkansas<OPTION>California<OPTION>Colorado<OPTION>Connecticut<OPTION>Delaware<OPTION>District of Columbia<OPTION>Florida<OPTION>Georgia<OPTION>Hawaii<OPTION>Idaho<OPTION>Iowa<OPTION>Illinois<OPTION>Indiana<OPTION>Kansas<OPTION>Kentucky<OPTION>Louisiana<OPTION>Maine<OPTION>Maryland<OPTION>Massachusetts<OPTION>Michigan<OPTION>Minnesota<OPTION>Mississippi<OPTION>Missouri<OPTION>Montana<OPTION>Nebraska<OPTION>Nevada<OPTION>New Hampshire<OPTION>New Jersey<OPTION>New Mexico<OPTION>New York<OPTION>North Carolina<OPTION>North Dakota<OPTION>Ohio<OPTION>Oklahoma<OPTION>Oregon<OPTION>Pennsylvania<OPTION>Rhode Island<OPTION>South Carolina<OPTION>South Dakota<OPTION>Tennessee<OPTION>Texas<OPTION>Utah<OPTION>Vermont<OPTION>Virginia<OPTION>Washington<OPTION>West Virginia<OPTION>Wisconsin<OPTION>Wyoming<OPTION>Outside US</SELECT><br><br>|;
		}
		
		if ($field[0] eq "") {
			print qq | Please select a shipping option:<br>
			<select name="shipping_option"><option>$field[1]</option>|;
			if ($field[17] ne "") {print "<option>$field[17]</option>";}
			if ($field[33] ne "") {print "<option>$field[33]</option>";}
			print qq| </select> |;
		} 
		
		print qq| <input type="hidden" name="action" value="finalize">
		<input type="hidden" name="uid" value="$FORM{'uid'}">
		<input type="submit" value="Continue">
		</form> $bottom_page |;
		
	} else {
		$FORM{'action'}="finalize";
		$shipping=$field[0];	
	}
	
}

##########################################################
## Finalize an Order
if ($FORM{'action'} eq "finalize") {
	
	&get_final;
	
	$order=qq|<table border=1>$summary[0]
<tr><td colspan=4 align=right>$font <b>Subtotal:</b>&nbsp;&nbsp;&nbsp;</td><td align=right>$font \$$summary[1]</td></tr> |;
 $order.= qq| <tr><td colspan=4 align=right>$font <b>$shipping_pre $FORM{'shipping_option'}:</b>&nbsp;&nbsp;&nbsp;</td><td align=right>$font \$$shipping</td></tr> |;
	if ($tax != 0) {$order.=qq|<tr><td colspan=4 align=right>$font <b>Sales Tax:</b>&nbsp;&nbsp;&nbsp;</td><td align=right>$font \$$tax</td></tr>|;}
	$order.=qq|<tr><td colspan=4 align=right>$font <b>Total:</b>&nbsp;&nbsp;&nbsp;</td><td align=right>$font \$$total</td></tr>
</table> |;
	
	print qq | $top_page $title_front Confirmación Final $title_back  
A continuación mostramos un sumario final de su orden incluyendo gastos 
de envío (si son aplicables) e impuestos. <br><br>
$order
<br><br>


Para formalizar su pedido, por favor llene el siguiente formato y envíelo.|;

if ($PayPal eq "No") {
	print qq| 
<form action="$script_url_secure" method="post" name="checkout" id="checkout">
<table>
<tr>
	<td>$font Su Nombre: &nbsp;&nbsp;</td>
	<td><input type="text" name="name" size="30" onBlur="addname()"></td>
</tr>
<tr>
	<td>$font Email: &nbsp;&nbsp;</td>
	<td><input type="text" name="email" size="30"></td>
</tr>
<tr>
	<td>$font Teléfono: &nbsp;&nbsp;</td>
	<td><input type="text" name="phone" size="30"></td>
</tr>
<tr>
	<td colspan=2>$font <br><h3>Información Sobre el Envío</h3></td>
</tr>
<tr>
	<td>$font Enviar A (Nombre): &nbsp;&nbsp;</td>
	<td><input type="text" name="shipping_name" size="30"></td>
</tr>
<tr>
	<td>$font Dirección de Envío: &nbsp;&nbsp;</td>
	<td><input type="text" name="shipping_address" size="30" onBlur="addaddress()"></td>
</tr>
<tr>
	<td>$font Ciudad: &nbsp;&nbsp;</td>
	<td><input type="text" name="shipping_city" size="30" onBlur="addcity()"></td>
</tr>
<tr>
	<td>$font Estado: &nbsp;&nbsp;</td>
	<td><input type="text" name="shipping_state" size="30" onBlur="addstate()"></td>
</tr>
<tr>
	<td>$font Codigo Postal (opcional): &nbsp;&nbsp;</td>
	<td><input type="text" name="shipping_zip" size="30" onBlur="addzip()"></td>
</tr>
<tr>
	<td>$font Pais: &nbsp;&nbsp;</td>
	<td><input type="text" name="shipping_country" size="30" onBlur="addcountry()"></td>
</tr>
<tr>
	<td colspan=2>$font <br><h3>Información sobre 
su facturación</h3></td>
</tr>
<tr>
	<td>$font Nombre o razón social: 
&nbsp;&nbsp;</td>
	<td><input type="text" name="billing_name" size="30"></td>
</tr>
<tr>
	<td>$font Dirección Facturación: &nbsp;&nbsp;</td>
	<td><input type="text" name="billing_address" size="30"></td>
</tr>
<tr>
	<td>$font Ciudad: &nbsp;&nbsp;</td>
	<td><input type="text" name="billing_city" size="30"></td>
</tr>
<tr>
	<td>$font Estado: &nbsp;&nbsp;</td>
	<td><input type="text" name="billing_state" size="30"></td>
</tr>
<tr>
	<td>$font Código Postal (opcional): &nbsp;&nbsp;</td>
	<td><input type="text" name="billing_zip" size="30"></td>
</tr>
<tr>
	<td>$font País: &nbsp;&nbsp;</td>
	<td><input type="text" name="billing_country" size="30"></td>
</tr>
<tr>
	<td colspan=2>$font <br><h3>Información de Pago</h3></td>
</tr>
<tr>
	<td>$font Credit Card Type: &nbsp;&nbsp;</td>
	<td><select name="cc_type">|;
	foreach $card (@cards_accepted) {
		print "<option>$card</option>";
	}
	
	print qq|</select></td>
</tr>
<tr>
	<td>$font Card Number: &nbsp;</td>
	<td><input type="text" name="cc_number" size="30"></td>
</tr>
<tr>
	<td>$font Expires (mm/yy): &nbsp;</td>
	<td><input type="text" name="expires" size="5" maxlength="5"></td>
</tr>|;
} else {
	print qq|
<form action="$script_url_secure" method="post" name="checkout" id="checkout">
<table>
<tr>
	<td>$font Your Name: &nbsp;&nbsp;</td>
	<td><input type="text" name="name" size="30"></td>
</tr>
<tr>
	<td>$font Email Address: &nbsp;&nbsp;</td>
	<td><input type="text" name="email" size="30"></td>
</tr>
<tr>
	<td>$font Phone: &nbsp;&nbsp;</td>
	<td><input type="text" name="phone" size="30"></td>
</tr>
<tr>
	<td colspan=2>$font <br><h3>Shipping Information</h3></td>
</tr>
<tr>
	<td>$font Ship To: &nbsp;&nbsp;</td>
	<td><input type="text" name="shipping_name" size="30"></td>
</tr>
<tr>
	<td>$font Shipping Address: &nbsp;&nbsp;</td>
	<td><input type="text" name="shipping_address" size="30"></td>
</tr>
<tr>
	<td>$font City: &nbsp;&nbsp;</td>
	<td><input type="text" name="shipping_city" size="30"></td>
</tr>
<tr>
	<td>$font State: &nbsp;&nbsp;</td>
	<td><input type="text" name="shipping_state" size="30"></td>
</tr>
<tr>
	<td>$font Zip: &nbsp;&nbsp;</td>
	<td><input type="text" name="shipping_zip" size="30"></td>
</tr>
<tr>
	<td>$font Country: &nbsp;&nbsp;</td>
	<td><input type="text" name="shipping_country" size="30"></td>
</tr> |;
}
print qq|
<tr>
	<td valign=top>$font Comments: &nbsp;&nbsp;</td>
	<td><textarea cols="25" rows="4" name="comments"></textarea></td>
</tr>
</table>

<input type="hidden" name="action" value="purchase">
<input type="hidden" name="uid" value="$FORM{'uid'}">
<input type="hidden" name="shipping_option" value="$FORM{'shipping_option'}">
<input type="hidden" name="state" value="$FORM{'state'}">
<input type="hidden" name="total" value="$total">
<input type="submit" value="Confirmar Compra"><input 
type="Reset">
</form>
<script language="JavaScript">
function addname() {
	document.checkout.shipping_name.value = document.checkout.name.value;
	document.checkout.billing_name.value = document.checkout.name.value;
}
function addaddress() {
	document.checkout.billing_address.value = document.checkout.shipping_address.value;
}
function addcity() {
	document.checkout.billing_city.value = document.checkout.shipping_city.value;
}
function addstate() {
	document.checkout.billing_state.value = document.checkout.shipping_state.value;
}
function addzip() {
	document.checkout.billing_zip.value = document.checkout.shipping_zip.value;
}
function addcountry() {
	document.checkout.billing_country.value = document.checkout.shipping_country.value;
}
</script>
$bottom_page |; 
}

## Make the purchase
if ($FORM{'action'} eq "purchase") {
	if ($FORM{'name'} eq "") {
		$message.="<li>Usted debe proporcionar su nombre.<br><br>";
	}
	$FORM{'email'}=~s/ //g;
	if (&check_email($FORM{'email'}) != 1) {
		$message.="<li>Usted debe proporcionar un email válido.<br><br>";
	}
	if ($FORM{'shipping_address'} eq "") {
		$message.="<li>Usted debe proporcionar una 
dirección de envío.<br><br>";
	}
	if ($FORM{'shipping_city'} eq "") {
		$message.="<li>Usted debe especificar su ciudad.<br><br>";
	}
	if ($FORM{'shipping_zip'} eq "") {
		$message.="<li>You must enter your zip code.<br><br>";
	}
	if ($FORM{'billing_name'} eq "" && $PayPal eq "No") {
		$message.="<li>You must enter the name on your credit card.<br><br>";
	}
	if ($FORM{'cc_number'} eq "" && $PayPal eq "No") {
		$message.="<li>You must enter your credit card number.<br><br>";
	}
	if ($FORM{'expires'} eq "" && $PayPal eq "No") {
		$message.="<li>You must enter your credit card expiration date.<br><br>";
	}
	if ($message ne "") {
		print qq| $top_page $title_front Sorry! $title_back  The following problems existed with your purchase information: <ul><font color=red>$message</font></ul> Please click your browser's back button to return to the form and complete it properly.<br><br> $bottom_page |;
	} else 	{	
				$FORM{'comments'}=~s/[\r\n]/<br>/g;
				if ($FORM{'shipping_name'} ne "same as above") {
					$shipping_address="$FORM{'shipping_name'}<br>";
				} else {$shipping_address="$FORM{'name'}<br>";}
							 $shipping_address.="$FORM{'shipping_address'}<br>$FORM{'shipping_city'}, $FORM{'shipping_state'} $FORM{'shipping_zip'}<br>$FORM{'shipping_country'}<br>$FORM{'phone'}";
				$order_date=&get_date;
				$order_number=&order_counter;
				$cc_info="$FORM{'billing_name'}<br>$FORM{'cc_type'} $FORM{'cc_number'} exp: $FORM{'expires'}<br>$FORM{'shipping_address'}<br>$FORM{'shipping_city'}, $FORM{'shipping_state'} $FORM{'shipping_zip'}<br>$FORM{'shipping_country'}";
				if ($PayPal eq "Yes") {$cc_info="<a href=http://www.paypal.com>PayPal</a>";}
				
				&get_final;
				open(IN,"$customer_file");
				$cart_data=<IN>;
				close(IN);
				chomp($cart_data);
				
				# create new order file
				$new_order_file="$order_folder/$order_number.txt";
				open(OUT,">$new_order_file");
				$line= "$order_number|$FORM{'name'}|$FORM{'email'}|$FORM{'phone'}|$FORM{'shipping_name'}|$FORM{'shipping_address'}|$FORM{'shipping_city'}|$FORM{'shipping_state'}|$FORM{'shipping_zip'}|$FORM{'shipping_country'}|$FORM{'billing_name'}|$FORM{'billing_address'}|$FORM{'billing_city'}|$FORM{'billing_state'}|$FORM{'billing_zip'}|$FORM{'billing_country'}|$FORM{'cc_type'}|$FORM{'cc_number'}|$FORM{'expires'}|$FORM{'comments'}|$cart_data|$summary[1]|$shipping|$FORM{'shipping_option'}|$tax|$order_date||";
				chomp($line);
				$line.="\n";
				print OUT $line;
				close(OUT);
				
				# add order to order index file
				open(OUT,">>$order_file");
				$line= "$order_number|$FORM{'name'}|$FORM{'email'}|$order_date|";
				chomp($line);
				$line.="\n";
				print OUT $line;
				close(OUT);
				
				# clear the customer file
				open(OUT,">$customer_file");
				print OUT "";
				close(OUT);
				
				if ($PayPal eq "Yes") {
					print qq| $top_page $title_front Thank You! $title_back  $FORM{'name'}, your order has been entered into our database.  We will process it as soon as we have confirmation of your payment.  Click below to proceed to <b>PayPal.com</b> to make your payment.

<!-- Begin PayPal Logo -->
<FORM ACTION="https://www.paypal.com/cgi-bin/webscr" METHOD="POST">
<INPUT TYPE="hidden" NAME="cmd" VALUE="_xclick">
<INPUT TYPE="hidden" NAME="business" VALUE="$PayPal_email">
<INPUT TYPE="hidden" NAME="return" VALUE="$order_url?order_number=$order_number">
<INPUT TYPE="hidden" NAME="item_name" VALUE="Purchase from $site_name order number $order_number">
<INPUT TYPE="hidden" NAME="amount" VALUE="$FORM{'total'}">
<input type="hidden" name="item_number" value="$order_number">
<INPUT TYPE="hidden" NAME="no_shipping" VALUE="1">
<INPUT TYPE="hidden" NAME="cancel_return" VALUE="$script_url">
<input type="submit" name="submit" value="Continue to Payment ->">
</FORM>
<!-- End PayPal Logo -->

$bottom_page |;
				
				} else {
				
				$order=qq|<table border=1>$summary[0]
<tr><td colspan=4 align=right>$font <b>Subtotal:</b>&nbsp;&nbsp;&nbsp;</td><td align=right>$font \$$summary[1]</td></tr> |;
 $order.= qq| <tr><td colspan=4 align=right>$font <b>$shipping_pre $FORM{'shipping_option'}:</b>&nbsp;&nbsp;&nbsp;</td><td align=right>$font \$$shipping</td></tr> |;
				if ($tax != 0) {$order.=qq|<tr><td colspan=4 align=right>$font <b>Sales Tax:</b>&nbsp;&nbsp;&nbsp;</td><td align=right>$font \$$tax</td></tr>|;}
				$order.=qq|<tr><td colspan=4 align=right>$font <b>Total:</b>&nbsp;&nbsp;&nbsp;</td><td align=right>$font \$$total</td></tr>
</table> |;
				
				print qq| $top_page $title_front Gracias! $title_back  $FORM{'name'}, your order has been placed and a confimation has been emailed to you. You may print out this page as a receipt.<br><br>
Fecha de la Orden: $order_date<br><br>
$order <br>
Esta orden será enviada a:<br><br>
$shipping_address<br><br>
$bottom_page |;	
				}
				
				# send email notification that order has taken place
				$to=$customer_service;
				$from=$FORM{'email'};
				$subject="Orden Completa";
				$body="Una orden fue recibida en $site_name web site.  Go to $office_url to view the order. ";
				if ($email_method eq "sendmail") {&sendmail($to,$from,$subject,$body);} else {&smtp_sendmail($to,$from,$subject,$body);}
				
				# send email confirmation to customer
				$to=$FORM{'email'};
				$code=$order_number*$order_encrypt;
				$from=$customer_service;
				$subject="Gracias por su orden!";
				$body="Apreciado $FORM{'name'},
				
Gracias por preferir a $site_name. Apreciamos su decisión de negociar con 
nosotros!  
Su número de orden es: $order_number

Para en cualquier momento, chequear el status de su orden, use el 
siguiente link:
$order_url?set=$code

Sientase libre de contactarnos para cualquier duda sobre este pedido a $customer_service ";
				if ($email_method eq "SMTP") {&smtp_sendmail($to,$from,$subject,$body);} else {&sendmail($to,$from,$subject,$body);}
					
			} # end of else
}




#  Increments key counter and returns value
sub key_counter {

my @countermyfile;
my $keycounter;

open(IN,"$working_folder/counter.txt");
(@countermyfile=<IN>);

$keycounter=$countermyfile[0];
$keycounter++;
close(IN);
if ($keycounter > 99999999) {$keycounter=10000000;}

open(OUT,">$working_folder/counter.txt") or die "cannot create counter file";
print OUT $keycounter;
close(OUT);

return ($keycounter);

}

########################################
## Returns all categories in the product file as an array
sub get_categories {

my ($x, $marker);
my (@field, @categories);
	open(IN,"$product_file");
	while (<IN>) {
		@field=split(/\|/,$_);
		foreach $category (@categories) {
			if ($field[5] eq $category) {$marker=1;}
		}
		if ($marker!=1) {
			$categories[$x]=$field[5];
			$x++;
		}
		$marker="";
	}
	close(IN);
	@categories=sort(@categories);

return (@categories);
}

#####################################################
## Returns the format of a short display
sub short_display {
	my $return;
	my $photo;
	if ($field[9] ne "") {$photo=qq| <a href="$script_url?action=link&sku=$field[0]&uid=$FORM{'uid'}"><img src="$photo_url/$field[9]" border="0"></a><br> |;}
	$return=qq|<td valign="top">$photo $font_short <a 
href="$script_url?action=link&sku=$field[0]&uid=$FORM{'uid'}"><b>$field[1] 
$field[2]</b></a> $field[3] <b>\$$field[6]</b> <br>Código: 
$field[0]</td>|;
	return($return);
}

#####################################################
## Returns an array full of values for a SKU
sub get_sku {
	my (@field, @return);
	my $sku=$_[0];
	open(IN,"$product_file");
	while(<IN>){
		chomp;
		@field=split(/\|/,$_);
		if ($sku eq $field[0]) {
			@return=@field;
		}
	}
	close(IN);
	return(@return);
}

#####################################################
## Returns order summary
sub get_summary {
	my $cart;
	my (@product,@item);
	my ($return,$line_total,$total,$empty);
	
	open(IN,"$customer_file");
	($cart)=<IN>; 
	chomp($cart);
	close(IN);
	
	if ($cart eq "") {$empty=1;}
	@product=split(/%%/,$cart);
	$return="<tr><td align=center>$font <b>Código</b></td><td 
align=center>$font <b>Descripción</b></td><td align=center>$font 
<b>Precio</b></td><td align=center>$font <b>Cantidad</b></td><td 
align=center>$font <b>Total</b></td></tr>";
	foreach $product (@product) {
		@item=split(/~/,$product);
		if ($item[0] =~/\w/) {
			$line_total=$item[3]*$item[2];
			$shipping_total=$shipping_total+($item[4]*$item[3]);
			$line_total=sprintf("%.2f", $line_total);
			$item[2]=sprintf("%.2f", $item[2]);
			$return.="<tr><td>$font $item[0]</td><td>$font $item[1]</td><td align=right>$font \$$item[2]</td><td align=right>$font $item[3]</td><td align=right>$font \$$line_total</td></tr>";
			$total=$total+$line_total;
		}
	}
	$total=sprintf("%.2f", $total);
	return($return, $total, $empty, $shipping_total);
}

######################################################
## Send Email via SMTP (to,from,subject,body) $SMTP_SERVER must 
## be a global variable assigned with a valid smtp server

sub smtp_sendmail {

	use Socket;

    local($to, $from, $subject, $body) = @_;
    local($i, $error, $name, $status, $message) = '';
    local(@to) = split(/, */, $to);
    local($CRLF) = "\015\012";
    local($SMTP_SERVER_PORT) = 25;
    local($AF_INET) = ($] > 5 ? AF_INET : 2);
    local($SOCK_STREAM) = ($] > 5 ? SOCK_STREAM : 1);
    local(@bad_addresses) = ();
    $, = ', ';
    $" = ', ';
    
    local($local_address) = (gethostbyname($WEB_SERVER))[4];
    local($local_socket_address) = pack('S n a4 x8', $AF_INET, 0, $local_address);

    local($server_address) = (gethostbyname($SMTP_SERVER))[4];
    local($server_socket_address) = pack('S n a4 x8', $AF_INET, $SMTP_SERVER_PORT, $server_address);

    local($protocol) = (getprotobyname('tcp'))[2];
    
    if (!socket(SMTP, $AF_INET, $SOCK_STREAM, $protocol)) {
        $Error_Message = "Could not make socket filehandle ($!).";
        return(1);
    }
    
    bind(SMTP, $local_socket_address);
    
    if (!(connect(SMTP, $server_socket_address))) {
        $Error_Message = "Could not connect to server ($!).";
        return(1);
    }
    
    local($old_selected) = select(SMTP); 
    $| = 1; 
    select($old_selected);
   
    $* = 1;
    
    select(undef, undef, undef, .75);
    sysread(SMTP, $_, 1024);

    print SMTP "HELO $WEB_SERVER$CRLF";
    sysread(SMTP, $_, 1024);
    while (/(^|(\r?\n))[^0-9]*((\d\d\d).*)$/g) { $status = $4; $message = $3}
    if ($status != 250) { $Error_Message = $message; return(3) }

    print SMTP "MAIL FROM:<$from>$CRLF";
    sysread(SMTP, $_, 1024);
    if (!/[^0-9]*250/) { $Error_Message = $_; return(4) }
    
    local($good_addresses) = 0;
    foreach $address (@to) {
        
        if ($address) {
        
            $address =~ /(\(.*\))/;
            $name = $1 ? "$1 " : '';
            $address =~ /([^<)\s]+@\S+\.[^>(\s]+)/;
            $address = "<$1>";

            print SMTP "RCPT TO:$address$CRLF";
            sysread(SMTP, $_, 1024);
            /[^0-9]*(\d\d\d)/;
            if ($1 ne '250') { push(@bad_addresses, $name, $address, $_) }
            else { ++$good_addresses }
        }
    }
    if (!$good_addresses) {
        $Error_Message = $_;
        return(5, @bad_addresses)
    }

    print SMTP "DATA$CRLF";
    sysread(SMTP, $_, 1024);
    if (!/[^0-9]*354/) { $Error_Message = $_; return(6) }
    print SMTP "To: @to$CRLF";
    print SMTP "From: $from$CRLF";
    print SMTP "Subject: $subject$CRLF$CRLF";

    print SMTP "$body$CRLF";
    
    print SMTP "$CRLF.$CRLF";
    sysread(SMTP, $_, 1024);
    if (!/[^0-9]*250/) { $Error_Message = $_; return(7) }
        
    if (!shutdown(SMTP, 2)) { 
        $Error_Message = "Could not shut down server ($!).";
        return(8, @bad_addresses);
    }
    elsif (@bad_addresses) {
        return(2, @bad_addresses);
    }
    else { return(0) }
}

######################################################
## Send Email via Unix sendmail (to,from,subject,body) $SENDMAIL must 
## be a global variable assigned with the path to sendmail


sub sendmail {
	
	local($to, $from, $subject, $body) = @_;
            
    open(MAIL, "|$SENDMAIL -t");
       
    print MAIL "To: $to\n";
    print MAIL "From: $from\n";
    print MAIL "Subject: $subject\n\n";
	
    print MAIL "$body\n";
        
    close(MAIL);    
    return(0);
}

#####################################################
## Check for valid email address
sub check_email {
    local($email) = $_[0];

    # Check that the email address doesn't have 2 @ signs, a .., a @., a 
    # .@ or begin or end with a .

    if ($email =~ /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)|(\.$)/ || 

        # Allow anything before the @, but only letters numbers, dashes and 
        # periods after it.  Also check to make sure the address ends in 2 or 
        # three letters after a period and allow for it to be enclosed in [] 
        # such as [164.104.50.1]
    
        ($email !~ /^.+\@localhost$/ && 
         $email !~ /^.+\@\[?(\w|[-.])+\.[a-zA-Z]{2,3}|[0-9]{1,3}\]?$/)) {
        return(0);
    }

    # If it passed the above test, it is valid.
    
    else {
        return(1);
    }
}




#  Increments order counter and returns value
sub order_counter {

my @countermyfile;
my $keycounter;

open(IN,"$working_folder/ordercounter.txt");
(@countermyfile=<IN>);

$keycounter=$countermyfile[0];
$keycounter++;
close(IN);
if ($keycounter > 99999999) {$keycounter=10000000;}

open(OUT,">$working_folder/ordercounter.txt") or die "cannot create counter file";
print OUT $keycounter;
close(OUT);

return ($keycounter);

}
###################################################
sub get_date {
    my ($time);
    $_[0] ? ($time = $_[0]) : ($time = time());

    my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime ($time);
    $year = $year + 1900;
    ($mday < 10) and ($mday = "0$mday");


        my @months = qw!Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec!;
        return "$mday-$months[$mon]-$year";
    
}
####################################################
sub customer_cleanup {
	my (@files);
	
	opendir (AUTHDIR, "$customer_folder") || die;
		@files = readdir(AUTHDIR);			
	closedir (AUTHDIR);

	FILE: foreach $file (@files) {
		next if ($file =~ /^\./);			
		next if ($file =~ /^index/);		
		next if ($file eq $password_file);		
		if ((stat("$customer_folder/$file"))[9] + $customer_time < time) {
			unlink ("$customer_folder/$file");		
		}
	}
}
######################################################
sub get_final {
	@summary=&get_summary;
	# tax info
	open(IN,"$tax_file");
	@tax_states=<IN>;
	close(IN);
	chomp($tax_states[0]);
	if ($tax_states[0] ne "") {
		$tax_states[0]=$tax_states[0]*.01;
		$tax=$summary[1]*$tax_states[0];
	} else {
		foreach $state (@states) {
			$z++;
			chomp($state);
			if ($state eq $FORM{'state'}) {
				$tax_states[$z]=$tax_states[$z]*.01;
				$tax=$summary[1]*$tax_states[$z];
			}
		}	
	}
	

    # Shipping Info 
	open(IN,"$shipping_file");
	(@file=<IN>);
	close(IN);
	if ($calc_shipping eq "weight") {$base_num=$summary[3];} else {$base_num=$summary[1];}
	
	if ($FORM{'shipping_option'} ne "") {
		@field=split(/\|/,$file[0]);
		if ($FORM{'shipping_option'} eq $field[1]) {
			for($x=2;$x<17;$x=$x+3) {
				if ($base_num >= $field[$x] && $base_num <= $field[$x+1]) {$shipping=$field[$x+2];}
			}
		}
		if ($FORM{'shipping_option'} eq $field[17]) {
			for($x=18;$x<33;$x=$x+3) {
				if ($base_num >= $field[$x] && $base_num <= $field[$x+1]) {$shipping=$field[$x+2];}
			}
		}
		if ($FORM{'shipping_option'} eq $field[33]) {
			for($x=34;$x<50;$x=$x+3) {
				if ($base_num >= $field[$x] && $base_num <= $field[$x+1]) {$shipping=$field[$x+2];}
			}
		}
		$shipping_pre="Envío Via";
	} else {
		$shipping_pre="Envío";
		$shipping=$file[0];
	} 
	
	$total=$shipping+$tax+$summary[1];
	$total=sprintf("%.2f", $total);
	$tax=sprintf("%.2f", $tax);
	$shipping=sprintf("%.2f", $shipping);
	

}
