use warnings;
use strict;

use lib '../../../lib';

use HBCU::Database::HBCUCentral;
use HBCU::Database::Marketplace;
use HBCU::FileUpload;

### The configuration
my $config = &getConfiguration();

### Libraries to include
require "$config->{LIB_ROOT}/hbcuAuth.pl";

### The database connections
my $db = HBCU::Database::Marketplace->new(Database => 'marketplace_test');
my $hdb = new HBCU::Database::HBCUCentral;

### The maximum number of records to display on the search form
my $maxRecords = 24;

### Tells if the user is logged in
my $authorized = &authorized();

################################################################################
############################ SITE FUNCTIONS ####################################
################################################################################
sub isAuthorized {
  return $authorized;
}

################################################################################
sub getDBHandle {
  my ($database) = @_;

  return $hdb if $database eq 'hbcu_central';
  return $db if $database eq 'marketplace';
}
################################################################################
############################ END SITE FUNCTIONS ################################
################################################################################

################################################################################
########################## HTML FUNCTIONS ######################################
################################################################################
sub printAccountInfo {
  my ($q) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Account Info</th>
	</tr>
      </thead>
      <form id="formx" name="formx" method="post" action="$config->{MARKETPLACE_REGISTRY}" onSubmit="return verifyAccountInfo();">
      <tbody>
	<tr>
	  <th>
	     <font class=required>*</font>Email :
	  </th>
	  <td>
	    <input type="text" name="email" value="" size="40" />
	  </td>
	</tr>
	<tr>
	  <th>
	     <font class=required>*</font>Password :
	  </th>
	  <td>
	    <input type="password" name="password" size="40" />
	  </td>
	</tr>
	<tr>
	  <th>
	    HBCU :
	  </th>
	  <td>
	    <select name="hbcu">
	      <option value="Non HBCU College">Non HBCU College</option>
~;
  foreach my $hbcu ( $hdb->getHbcuDatas(ORDER => 'hbcu_name') ) {
print qq~
		    <option value="$hbcu->{hbcu_name}">$hbcu->{hbcu_name}</option>
~;
}
print qq~
	    </select>
	  </td>
	</tr>
	<tr>
	  <th>
	    <font class=required>*</font>Name :
	  </th>
	  <td>
	    <input type="text" name="name" value="" size="40" />
	  </td>
	</tr>
	<tr>
	  <th>
	     <font class=required>*</font>Phone :
	  </th>
	  <td>
	    <input type="text" name="phone" value="" size="40" />
	  </td>
	</tr>
	<tr>
	  <th>
	    <font class=required>*</font>Address :
	  </th>
	  <td>
	    <input type="text" name="address" value="" size="40" />
	  </td>
	</tr>
	<tr>
	  <th>
	     <font class=required>*</font>City :
	  </th>
	  <td>
	    <input type="text" name="city" value="" size="40" />
	  </td>
	</tr>
	<tr>
	  <th>
	     <font class=required>*</font>State :
	  </th>
	  <td>
	    <select name="state">
	      <option value="">Select a State</option>
~;
foreach my $state ( $hdb->getStateTbls(ORDER => 'label') ) {
print qq~
		    <option value="$state->{state_id}">$state->{label}</option>
~;
}
print qq~
	    </select>
	  </td>
	</tr>
	<tr>
	  <th>
	     <font class=required>*</font>Zip Code :
	  </th>
	  <td>
	    <input type="text" name="zip" value="" size="40" />
	  </td>
	</tr>
	<tr class=buttons>
	  <td colspan=2 align=center>
	    <input type="submit" name="submitAccountInfo" value="Continue >" />
	  </td>
	</tr>
      </tbody>
    </table>
  </form>
    <br>
~;

  printFooter($q);
}

################################################################################
sub printBrowseCategories {
  my ($q) = @_;

print qq~
<table class=data style="width: 175;">
  <tr>
    <th colspan=2><div align=left>&nbsp;Browse Categories</div></th>
  </tr>
  <tbody>
    <tr><td colspan="2"></td></tr>
~;
  foreach my $cat ( getCategories() ) {
print qq~
      <tr>
	<td>
	  <img src=$config->{BULLET} />
	  <a href="$config->{MARKETPLACE_SEARCH}?submitSearch=1&category=$cat->{id}">$cat->{name} ($cat->{item_count})</a>
	</td>
      </tr>
~;
}
print qq~
    <tr><td></td></tr>
  </tbody>
</table>
    <br>
~;
}

################################################################################
sub printContactUs {
  my ($q, $confirm) = @_;

  print $q->header();

print qq~
<html>
  <head>
    <link rel="StyleSheet" href=$config->{CSS_URL} type="text/css">
  </head>
  <body>
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Contact Us</th>
	</tr>
      </thead>
      <form id="formx" name="formx" method="post" action="$config->{MARKETPLACE_CONTACT_US}" onSubmit="return verifySendMessage();">
      <tbody>

~;
  if ($confirm) {
print qq~
	  <tr>
	    <td colspan=2>
	      You message was successfully sent!<br><br><br>	
	      <div align="center"><a href="#" onClick="window.close()">Click here to close this window</a></div>
	    </td>
	  </tr>
~;
} else {
print qq~
	    <tr>
	      <th>
		<font class=required>*</font>Name :
	      </th>
	      <td>
		<input type="text" name="name" size="40" />
	      </td>
	    </tr>
	    <tr>
	      <th>
		<font class=required>*</font>Email :
	      </th>
	      <td>
		<input type="text" name="email" size="40" />
	      </td>
	    </tr>
	    <tr>
	      <th>
		<font class=required>*</font>Subject :
	      </th>
	      <td>
		<input type="text" name="subject" size="65" />
	      </td>
	    </tr>
	    <tr>
	      <th>
		<font class=required>*</font>Message :
	      </th>
	      <td>
		<textarea name="comments" rows="8" cols="50"></textarea>
	      </td>
	    </tr>
	    <tr class=buttons>
	      <td align="center" colspan=2>
		<input type="submit" name="submitMessage" value="Submit" />
	      </td>
	    </tr>
      </tbody>
    </table>
    </form>
    <br>
~;
}
print qq~
</body>
</html>
~;
}

################################################################################
sub printEmailExists {
  my ($q) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th>$config->{SITE}: Merchant Registration</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    <br>
	    Our records show that you are already a registered $config->{SITE} member. Please login above to access your account.<br><br>
	  </td>
	</tr>
      </tbody>
    </table>
    <br>
~;

  printFooter($q);
}

################################################################################
sub printFeaturedItems {
  my ($q, @params) = @_;

  return unless scalar(@params);

print qq~
<table class=data style="width: 100%;">
  <tr>
    <th><div align=left>&nbsp;Featured Items in the Marketplace</div></th>
  </tr>
  <tbody>
    <tr><td></td></tr>
    <tr>
      <td valign=top>
~;
  foreach my $item ( @params ) {
print qq~
  <table width="100%" border="0" cellspacing="4" cellpadding="1">
    <tr>
~;
foreach my $column ( @{ $item->{columns} } ) {
print qq~
	<td align="center" valign="top" width="25%">
	  <a href="$config->{MARKETPLACE_VIEW_ITEM}?id=$column->{id}"><img src="$column->{path}" width="75" height="75" border="0" /></a><br>
	  <a href="$config->{MARKETPLACE_VIEW_ITEM}?id=$column->{id}">$column->{title}</a><br>
	  <b>Price: $column->{price}<br><br>
	</td>
~;
}
print qq~
    </tr>
  </table>
~;
}
print qq~
      </td>
    </tr>
    <tr><td></td></tr>
  </tbody>
  </table>
    <div align=right>
      <a href=$config->{MARKETPLACE_SEARCH}?submitSearch=1>More Items--></a>
    </div>
    <br>
~;
}

################################################################################
sub printFeaturedSeller {
  my ($q, @params) = @_;

  return unless scalar(@params);

print qq~
<table class=data style="width: 100%;">
  <tr>
    <th><div align=left>&nbsp;Featured Sellers in the Marketplace</div></th>
  </tr>
  <tbody>
~;
  my $i;
  foreach my $seller ( @params ) {
    if ($i) {
      print "<tr class=odd>\n"; $i = 0;
    } else {
      print "<tr class=even>\n"; $i = 1;
    }
print qq~
	  <td valign="top">
	    <b><a href="$config->{MARKETPLACE_VIEW_SELLER}?id=$seller->{id}">$seller->{name}</a></b>
~;
    if ($seller->{totalReviews}) {
      print "&nbsp;(";
      foreach my $star ( @{ $seller->{stars} } ) {
	print "<img src=$star->{star} />\n";
      }
print qq~
		  )<br>
		  <a href="sellerReview.cgi?seller=$seller->{id}&showReviews=1">Read $seller->{totalReviews} Reviews</a>
~;
}
print qq~
		  <br>$seller->{description}<br>
		  <br>
	  </td>
	</tr>
~;
  }
print qq~
  </tbody>
  </table>
    <br>
~;
}

################################################################################
sub printFooter {
  my ($q) = @_;

print qq~
</td>
</tr>
</table>
~;

  print $config->{FOOTER};
}

################################################################################
sub printGridItems {
  my ($q, $records) = @_;

  foreach my $record (@$records) {
print qq~

  <table width="100%" border="0" cellspacing="4" cellpadding="1">
    <tr>

~;
foreach my $item ( @{ $record->{columns} } ) {
print qq~

	<td align="center" valign="top" width="25%">
	  <a href="$config->{MARKETPLACE_VIEW_ITEM}?id=$item->{id}"><img src="$item->{path}" width="75" height="75" border="0" /></a><br>
	  <a href="$config->{MARKETPLACE_VIEW_ITEM}?id=$item->{id}">$item->{title}</a><br>
	  <b>Price: $item->{price}<br><br>
	</td>
~;
}
print qq~

    </tr>
  </table>
~;
}
}

################################################################################
sub printHeader {
  my ($q) = @_;

  print $q->header();

  # The entire site header
  print $config->{HEADER};

  # This is in hbcuAuth.pl
  &printQuickLogin($q) unless $authorized;

print qq~
  <table cellspacing=0 cellpadding=0 width=100%>
    <tr>
      <td valign=top>
~;
  printAdminMenu($q) if $ENV{'SCRIPT_NAME'} =~ /\/admin\//;

  if ($authorized) {
    printMarketplaceToolkit($q);
  } else {
    printWelcomeGuest($q);
  }

  printBrowseCategories($q);

print qq~
      </td>
      <td cellspacing=0 cellpadding=0 width=100% valign=top>
~;
}

################################################################################
sub printItemInformation {
  my ($q, $item) = @_;

  my @cats = map {
    if ($item->{categories}) {
      foreach my $cat (split /:/, $item->{categories}) {
	$_->{default} = 1 if $_->{id} == $cat;
      }
    }
    $_;
  } getCategories();

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Item Information</th>
	</tr>
      </thead>
      <form name="formx" method="post" action="$config->{MARKETPLACE_SELL_ITEM}" onSubmit="return verifyItemInformation();">
~;
  if ($q->param('edit')) {
print qq~
        <input type="hidden" name="id" value="$item->{id}" />
	<input type="hidden" name="edit" value="1" />
~;
}
print qq~
      <tbody>
	<tr>
	  <th>
	    HBCU :
	  </th>
	  <td>
	    <select name="hbcu">
	      <option value="">All HBCUs</option>
~;
  foreach my $x ( $hdb->getHbcuDatas(ORDER => 'hbcu_name') ) {
    print "<option value=\"$x->{hbcu_name}\"";
    print " selected" if $item->{hbcu} && $x->{default} && ($item->{hbcu} eq $x->{default});
    print ">$x->{hbcu_name}</option>\n";
  }
print qq~
	    </select>
	  </td>
	</tr>
	<tr>
	  <th>
	    <font class=required>*</font>Title :
	  </th>
	  <td>
	    <input type="text" name="title" value="$item->{title}" size="60" />
	  </td>
	</tr>
	<tr>
	  <th nowrap>
	    <font class=required>*</font>Categories :
	  </th>
	  <td>
	    <select name="categories" multiple>
~;
  foreach my $x ( @cats ) {
    print "<option value=$x->{id}";
    print " selected" if $x->{default};
    print ">$x->{name}</option>\n";
  }
print qq~
	      </select>
	  </td>
	</tr>
	<tr>
	  <th>
	    <font class=required>*</font>Price :
	  </th>
	  <td>
	    <input type="text" name="price" value="$item->{price}" size="20" />
	    <input type="checkbox" name="shipping_included" value="1"
~;
  print " checked" if $item->{shipping_included};
print qq~
	    >Shipping Included?</input>
	  </td>
	  </tr>
	<tr>
	  <th nowrap>
	    <font class=required>*</font>Description :
	  </th>
	  <td>
	    <textarea name="description" cols="45" rows="8">$item->{description}</textarea>
	  </td>
	</tr>
	<tr>
	  <th>&nbsp;</th>
	  <td>
	    <input type="checkbox" name="more_than_one" value="1" 
~;
  print " checked" if $item->{more_than_one};
print qq~
	    >Do you have more than one?</input>
	  </td>
	</tr>
	<tr class=buttons>
	  <td colspan=2 align=center>
	    <input type="submit" name="submitItemInformation" value="Continue >" />
	  </td>
	</tr>
      </tbody>
    </table>
  </form>
    <br>
~;
  printFooter($q);
}

################################################################################
sub printItemPaymentReturn {
  my ($q, $item) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <form name="formx" method="post" action="$config->{MARKETPLACE_SELL_ITEM}" enctype="multipart/form-data">
      <input type="hidden" name="id" value="$item->{id}" />
      <input type="hidden" name="edit" value="1" />
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Payment Information</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    <b>Preview/Purchase Link :</b>
	  </td>
	  <td>
	    <input type="text" name="payment_url" value="$item->{payment_url}" size="50"  />
	  </td>
	</tr>
	<tr><td colspan="2"><hr></td></tr>
	<tr>
	  <td colspan="2">
	    <b>Select the payment methods you will accept :</b>
	  </td>
	</tr>
	<tr>
	  <td>
	    <input type="checkbox" name="visa" value="1"
~;
  print " checked" if $item->{visa};
print qq~
	    >Visa</input>
	  </td>
	  <td>
	    <input type="checkbox" name="paypal" value="1"
~;
  print " checked" if $item->{paypal};
print qq~
	    >PayPal</input>
	  </td>
	</tr>
	<tr>
	  <td>
	    <input type="checkbox" name="mastercard" value="1"
~;
  print " checked" if $item->{mastercard};
print qq~
	    >MasterCard</input>
	  </td>
	  <td>
	    <input type="checkbox" name="checks" value="1"
~;
  print " checked" if $item->{checks};
print qq~
	    >Personal Check</input>
	  </td>
	</tr>
	<tr>
	  <td>
	    <input type="checkbox" name="amex" value="1"
~;
  print " checked" if $item->{amex};
print qq~
	    >American Express</input>
	  </td>
	  <td>
	    <input type="checkbox" name="money_order" value="1"
~;
  print " checked" if $item->{money_order};
print qq~
	    >Money Order/Cashier's Check</input>
	  </td>
	</tr>
	<tr>
	  <td>
	    <input type="checkbox" name="discover" value="1"
~;
  print " checked" if $item->{discover};
print qq~
	    >Discover Card</input>
	  </td>
	  <td>
	    <input type="checkbox" name="other" value="1"
~;
  print " checked" if $item->{other};
print qq~
	    >Other / See Payment Instructions</input>
	  </td>
	</tr>
	<tr><td colspan="2"><hr></td></tr>
	<tr>
	  <td colspan=2>
	    <b>Enter some clear instructions to assist the buyer with payment and shipping :</b><br />
	    <textarea name="instructions" cols="65" rows="6">$item->{instructions}</textarea>
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Return Policy</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    <input type="checkbox" name="accepted" value="1"
~;
  print " checked" if $item->{accepted};
print qq~
	    >Returns Accepted</input><br />
	  </td>
	</tr>
	<tr>
	  <td>
	    Items must be returned within:
	    <select name="grace">
	      <option value="">--Select One--</option>
	      <option value="3"
~;
  print " selected" if $item->{grace} == 3;
print qq~
	    >3 Days</option>
	    <option value="7"
~;
  print " selected" if $item->{grace} == 7;
print qq~
	    >7 Days</option>
	    <option value="14"
~;
  print " selected" if $item->{grace} == 14;
print qq~
	    >14 Days</option>
	    <option value="30"
~;
  print " selected" if $item->{grace} == 30;
print qq~
	    >30 Days</option>
	  </select>
	  </td>
	</tr>
	<tr>
	  <td>
	    Refunds will be dispensed in the form of:
	    <select name="type">
	      <option value="">--Select One--</option>
	      <option value="Exchange"
~;
  print " selected" if $item->{type} eq 'Exchange';
print qq~
	    >Exchange</option>
	    <option value="Merchandise"
~;
  print " selected" if $item->{type} eq 'Merchandise';
print qq~
	    >Merchandise</option>
	    <option value="Money"
~;
  print " selected" if $item->{type} eq 'Money';
print qq~
	    >Money Back</option>
	  </select>
	  </td>
	</tr>
	<tr>
	  <td>
	    <b>Refund Policy</b><br>
	    <textarea name="policy" cols="65" rows="6">$item->{policy}</textarea>
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <div align="center">
      <input type="submit" name="submitItemPaymentReturn" value="Continue >" />
    </div>
    <br />
~;
  printFooter($q);
}

################################################################################
sub printItemPictures {
  my ($q, $item) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=3>Current Item Pictures</th>
	</tr>
      </thead>
      <form name="formx" method="post" action="$config->{MARKETPLACE_SELL_ITEM}" enctype="multipart/form-data" onSubmit="return verifyPicturesCaptions();">
	<input type="hidden" name="id" value="$item->{id}" />
	<input type="hidden" name="numPictures" value="$item->{numPictures}" />
	<input type="hidden" name="whichButton" value="0" />
	<input type="hidden" name="edit" value="1" />
      <tbody>
~;
  if (scalar(@{$item->{pictures}})) {
    my $i;
    foreach my $picture ( @{ $item->{pictures} } ) {
      if ($i) {
	print "<tr class=odd>\n";
      } else {
	print "<tr class=even>\n";
      }
print qq~
		<td width="8%">
		  [<a href="$config->{MARKETPLACE_SELL_ITEM}?submitDeletePictureCaption=1&id=$picture->{item}&picture_id=$picture->{id}" class=small>delete</a>]
		</td>
		<td width="100" height="75" align=left>
		  <img src="$picture->{path}" width="75" height="75" />
		</td>
		<td width="92%">
		  $picture->{caption}
		</td>
	      </tr>
~;
    }
  } else {
print qq~
	      <tr>
		<td colspan=3>
		  Currently, there are no pictures for this item
		</td>
	      </tr>
~;
}
print qq~
      </tbody>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Add a Picture</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <th nowrap>
	    Picture :
	  </th>
	  <td>
	    <input type="file" name="filename" size=60 />
	  </td>
	</tr>
	<tr>
	  <th nowrap>
	    Caption :
	  </th>
	  <td>
	    <textarea name="caption" cols="65" rows="3"></textarea>
	  </td>
	</tr>
	<tr><td colspan=2></td></tr>
	<tr class=buttons>
	  <td colspan=2 align=center>
	    <input type=submit name=submitAddPictureCaption value="Upload Picture" onClick="document.formx.whichButton.value=1" />
            &nbsp;&nbsp;&nbsp;
            <input type="submit" name="submitPicturesCaptions" value="Continue >" />
	  </td>
	</tr>
      </tbody>
    </table>
    <br>
  </form>
    <br />
~;
  printFooter($q);
}

################################################################################
sub printItemReview {
  my ($q, $item) = @_;

  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Review $item->{title}</th>
	</tr>
      </thead>
      <form name="formx" method="post" action="$config->{MARKETPLACE_ITEM_REVIEW}" enctype="multipart/form-data" onSubmit="return verifyItemReview();">
	<input type="hidden" name="item" value="$item->{id}" />
      <tbody>
	<tr>
	  <th>
	    Rating:
	  </th>
	  <td>
	    <input type="radio" name="rating" value="1">1</input>
	    <input type="radio" name="rating" value="2">2</input>
	    <input type="radio" name="rating" value="3" checked>3</input>
	    <input type="radio" name="rating" value="4">4</input>
	    <input type="radio" name="rating" value="5">5</input>
	  </td>
	</tr>
	<tr>
	  <th>
	     <font class=required>*</font> Title:
	  </th>
	  <td>
	    <input type="text" name="title" size="40" />
	  </td>
	</tr>
	<tr>
	  <th>
	    Pros:
	  </th>
	  <td>
	    <input type="text" name="pros" size="40" />
	  </td>
	</tr>
	<tr>
	  <th>
	    Cons:
	  </th>
	  <td>
	    <input type="text" name="cons" size="40" />
	  </td>
	</tr>
	<tr>
	  <th>
	     <font class=required>*</font> Comment:
	  </th>
	  <td>
	    <textarea name="comments" cols="30" rows="5"></textarea>
	  </td>
	</tr>
	<tr class=buttons>
	  <td colspan=2 align=center>
	    <input type="submit" name="submitItemReview" value="Submit Review" />
	  </td>
	</tr>
      </tbody>
    </table>
  </form>
    <br>
~;

  printFooter($q);
}

################################################################################
sub printItemReviewConfirm {
  my ($q, $item) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Item Information</th>
	</tr>
      </thead>
      <form name="formx" method="post" action="$config->{MARKETPLACE_SELL_ITEM}" enctype="multipart/form-data">
	<input type="hidden" name="id" value="$item->{id}" />
	<input type="hidden" name="edit" value="1" />
      <tbody>
	<tr>
	  <th>
	    Seller :
	  </th>
	  <td>
	    $item->{seller_name}
	  </td>
	</tr>
	<tr>
	  <th>
	    HBCU :
	  </th>
	  <td>
	    $item->{hbcu}
	  </td>
	</tr>
	<tr>
	  <th>
	    Title :
	  </th>
	  <td>
	    $item->{title}
	  </td>
	</tr>
	<tr>
	  <th>
	    Categories :
	  </th>
	  <td>
	    $item->{categoryNames}
	  </td>
	</tr>
	<tr>
	  <th>
	    Price :
	  </th>
	  <td>
	    $item->{price}
	  </td>
	</tr>
	<tr>
	  <th>
	    Description :
	  </th>
	  <td>
	    $item->{description}
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th>Pictures & Captions</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    <table width="100%" border="0" cellspacing="3" cellpadding="1">
~;
  my $i;
  foreach my $picture ( @{ $item->{pictures} } ) {
    if ($i) {
      print "<tr class=odd>\n";
    } else {
      print "<tr class=even>\n";
    }
print qq~
		    <td align="center" valign="top" width=75>
		      <img src="$picture->{path}" width="75" height="75" />
		    </td>
		    <td valign="top">
		      $picture->{caption}
		    </td>
		  </tr>
~;
  }
print qq~
	    </table>
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th>Payment Methods</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
~;
  if ($item->{visa}) { print "<img src=$config->{VISA} />&nbsp;&nbsp;\n"; }
  if ($item->{mastercard}) { print "<img src=$config->{MASTERCARD} />&nbsp;&nbsp;\n"; }
  if ($item->{amex}) { print "<img src=$config->{AMEX} />&nbsp;&nbsp;\n"; }
  if ($item->{discover}) { print "<img src=$config->{DISCOVER} />&nbsp;&nbsp;\n"; }
  if ($item->{paypal}) { print "<img src=$config->{PAYPAL} />&nbsp;&nbsp;\n"; }
  print "<br><br>\n";
  if ($item->{checks}) { print "Personal Check<br><br>\n"; }
  if ($item->{money_order}) { print "Money Order / Cashier's Check<br><br>\n"; }
  if ($item->{other}) { print "Other / See Payment Instructions<br><br>\n"; }
print qq~
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th>Payment Instructions</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    $item->{instructions}
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th>Return Policy</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
~;
			if ($item->{accepted}) {
print qq~
	      Returns Accepted<br>
	      Items must be returned within: $item->{grace}<br>
		Refunds will be dispensed in the form of: $item->{type}<br>

~;
if ($item->{policy}) {
  print "<b>Return Policy:</b> $item->{policy}\n";
} else {
  print "Returns not accepted\n";
}
}
print qq~
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <div align=center>
      <input type="submit" name="submitReviewConfirm"
~;
			if ($q->param('edit')) {
			  print "value=\"Save Item\"";
			} else {
			  print "value=\"Activate Item\"";
			}
print qq~
	/>
    </div>
    <br>
</form>
~;
  printFooter($q);
}

################################################################################
sub printItemReviews {
  my ($q, $item) = @_;

  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=4>$item->{title}</th>
	</tr>
      </thead>
      <form name="formx" method="post" action="$config->{MARKETPLACE_VIEW_ITEM}" enctype="multipart/form-data">
	<input type="hidden" name="id" value="$item->{id}" />
      <tbody>
	<tr>
	  <td align="center" width="100" valign="top">
~;
  foreach my $picture (@{ $item->{pictures} }) {
print qq~
	    <img src="$picture->{path}" width="100" height="100" /><br>
	    <img src=$config->{MAGNIFY_GLASS} />
	      <a href="#" onClick="window.open('$config->{MARKETPLACE_VIEW_ITEM}?submitShowLargeImage=1&id=$picture->{item}','LargeView','left=20,top=20,width=725,height=650,toolbar=0,location=0,menubar=0,resizable=1'); return false;">View Larger</a>
~;
last;
}
print qq~
	  </td>
	  <td valign="top">
	    <b>Seller :</b> <a href="$config->{MARKETPLACE_VIEW_SELLER}?id=$item->{seller}">$item->{seller_name}</a><br>
	      <b>Category :</b> $item->{categoryNames}<br>
		<b>HBCU :</b> $item->{hbcu}<br>
		  <b>Price :</b> $item->{price}<br>
		    <b>Item Views :</b> $item->{hits}<br><br>
		      <input type="submit" name="submitGotoPurchase" value="Buy Now!" />
	  </td>
	  <td height="100%" width="1">
	    <table background=$config->{VSEP} width="1" height="100%" cellspacing="0" cellpadding="0"><tr><td></td></tr></table></td>
	  <td valign="top" width=125 align=center>
~;
  if ($item->{totalReviews}) {
    foreach my $star (@{ $item->{stars} }) {
      print "<img src=$star->{star} />";
    }
    print "<br>\n";
  } else {
    print "No Ratings<br>\n";
  }
  print "Average User Rating<br>\n";

  if ($item->{totalReviews}) {
    print "<a href=\"$config->{MARKETPLACE_ITEM_REVIEW}?item=$item->{id}&showReviews=1\">Read $item->{totalReviews} Reviews</a><br>\n";
  }
print qq~
		  <a href="$config->{MARKETPLACE_ITEM_REVIEW}?item=$item->{id}">Write a Review</a><br>
	  </td>
	</tr>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th>Product Description</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    $item->{description}
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th>User Reviews</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
                            <table width="100%" border="0" cellspacing="2" cellpadding="2">
~;
  foreach my $review ( @{ $item->{reviews} } ) {
print qq~
                              <tr>
                                <td valign="top" width="150">
                                  <font size=2>Rating:</font>
~;
foreach my $star ( @{ $review->{stars} } ) {
  print "<img src=$star->{star} />\n";
}
print qq~
                                </td>
                                <td>
                                  <font size=3><b>$review->{title}</b></font>, <font size=2>$review->{date_created}</font><br />
                                  <font size=2>Reviewer: <a href="$config->{MEMBER_MAIN}?registry_id=$review->{registry_id}\"><font size=2>$review->{registry_data}->{name}</a>
 <!-- - <a href="$config->{MARKETPLACE_ITEM_REVIEW}?showSellerReviews=1&id=$review->{registry_data}->{registry_id}"><font size=2>See all $review->{registry_data}->{name}'s reviews</font></a><br> -->
~;
if ($review->{useful} || $review->{not_useful}) {
  print "<font size=2>$review->{useful} out of ", ($review->{not_useful} + $review->{useful}), " found this review helpful!<br>\n";
}
print qq~
                                  <br>
                                  <b>Pros:</b> $review->{pros}<br>
                                  <b>Cons:</b> $review->{cons}<br><br>
                                  $review->{comments}
                                  <br><br>
                                  <b>Was this review helpful to you?
                                  <a href="$config->{MARKETPLACE_ITEM_REVIEW}?addUseful=1&id=$review->{id}&item=$item->{id}">Yes</a>
                                  &nbsp;&nbsp;
                                  <a href="$config->{MARKETPLACE_ITEM_REVIEW}?addNotUseful=1&id=$review->{id}&item=$item->{id}">No</a>
                                </td>
                              </tr>
                              <tr><td colspan=2><hr style="border: thin dotted #632100"></td></tr>
~;
}
print qq~
                            </table>
	  </td>
	</tr>
      </tbody>
    </table>
    <br>
~;

  printFooter($q);
}

################################################################################
sub printItemReviewThankYou {
  my ($q, $item) = @_;

  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th>Review $item->{title}</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    <br>
	    Thank you for submitting your review for the $item->{title}!<br /><br /><a href="$config->{MARKETPLACE_VIEW_ITEM}?id=$item->{id}">Click here</a> to return to the item page.
	      <br><br>
	  </td>
	</tr>
      </tbody>
    </table>
    <br>
~;

  printFooter($q);
}

################################################################################
sub printLargeViewItem {
  my ($q, $item) = @_;

  print $q->header();

print qq~
<html>
  <head>
    <link rel="StyleSheet" href=$config->{CSS_URL} type="text/css">
  </head>
  <body>
    <table class=data width=100%>
      <thead>
	<tr>
	  <th>$item->{title}</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
~;
  foreach my $picture (@{ $item->{pictures} }) {
    print "<img src=\"$picture->{path}\" width=700 height=600 /><br>";
    last;
  }
print qq~
	  </td>
	</tr>
      </tbody>
    </table>

    <div align=center>
      <br><a href="#" onClick="window.close();">Click here to close this window</a><br>
    </div>

</body>
</html>
~;
}

################################################################################
sub printListItems {
  my ($q, $records) = @_;

print qq~
  <table width="100%" border="0" cellspacing="2" cellpadding="1">

~;
  foreach my $item (@$records) {
print qq~

    <tr><td colspan=2><hr></td></tr>
    <tr>
      <td align="center" valign="top" width="100" height="100">
        <a href="$config->{MARKETPLACE_VIEW_ITEM}?id=$item->{id}"><img src="$item->{path}" width="75" height="75" border="0" /></a><br>

~;
if ($item->{totalReviews}) {
  foreach my $star (@{ $item->{stars} }) {
print qq~
	    <img src=$config->{STAR} />
~;
}
print qq~
		<br />
		<a class=small href="$config->{MARKETPLACE_ITEM_REVIEW}?item=$item->{id}&showReviews=1">Read $item->{totalReviews} Reviews</a>
~;
} else {
print qq~
		    <a class=small href="$config->{MARKETPLACE_ITEM_REVIEW}?item=$item->{id}">Write a Review</a>
~;
}
print qq~

      </td>
      <td valign="top">
	<a href="$config->{MARKETPLACE_VIEW_ITEM}?id=$item->{id}">$item->{title}</a><br>
	$item->{description}<br>
	$item->{price} - 
        <a href="$config->{MARKETPLACE_VIEW_SELLER}?id=$item->{seller}">$item->{seller_name}</a>
        <br>
      </td>
    </tr>
~;
}
print qq~
  </table>
~;
}

################################################################################
sub printLogIn {
  my ($q) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th>$config->{SITE}: Access Denied</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    <br>
	    You must be logged in to access this part of the marketplace. Please log in above. If you don't have a $config->{SITE} account, please signup above and join the community!<br><br>
	  </td>
	</tr>
      </tbody>
    </table>
    <br>
~;
  printFooter($q);
}

################################################################################
sub printMain {
  my ($q) = @_;

  ### Now we output
  printHeader($q);

  printQuickSearch($q);
  printMarketplaceNews($q);

  if (my @x = getFeaturedItems()) {
    printFeaturedItems($q, @x);
  }
  if (my @x = $db->getFeaturedStores()) {
    printFeaturedSeller($q, @x);
  }

  printFooter($q);
}

################################################################################
sub printMarketplaceNews {
  my ($q) = @_;

print qq~
<table class=data style="width: 100%;">
  <tr>
    <th><div align=left>&nbsp;Marketplace News</div></th>
  </tr>
  <tbody>
    <tr><td></td></tr>
    <tr>
      <td>
	The $config->{SITE} Marketplace is unveiled!<br>
	You've been asking for it, anxiously anticipating it. Well it is here! We are happy to unveil for you the $config->{SITE} Marketplace. What is our vision for the Marketplace? We envision the $config->{SITE} Marketplace as a place where you can find and acquire the latest and hottest Gear fresh from the hottest suppliers all over the country!
	Got Ideas? <a href=$config->{MARKETPLACE_CONTACT_US}>Send Feedback!</a>.
      </td>
    </tr>
    <tr><td></td></tr>
  </tbody>
</table>
<br />
~;
}

################################################################################
sub printMarketplaceToolkit {
  my ($q) = @_;

print qq~
<table class=data style="width: 175;">
  <tr>
    <th colspan=2><div align=left>&nbsp;Marketplace Toolkit</div></th>
  </tr>
  <tbody>
    <tr><td></td></tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MAIN}">Marketplace Home</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_SELL_ITEM}">Sell Item</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_SEARCH}">Advanced Search</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MY_SUMMARY}">My Summary</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_REGISTRY}?edit=1">My Store</a>
      </td>
    </tr>
     <tr>
       <td>
 	<img src=$config->{BULLET} />
 	<a href="$config->{MARKETPLACE_MERCHANT_SERVICES}">Merchant Services</a>
       </td>
     </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="#" onClick="window.open('$config->{MARKETPLACE_CONTACT_US}','$config->{DOMAIN}','width=550,height=500,toolbar,resizable');">Ask a Quick Question</a>
      </td>
    </tr>
    <tr><td></td></tr>
  </tbody>
</table>
    <br>
~;
}

################################################################################
sub printMerchantInfo {
  my ($q) = @_;

  printMerchantInfoHow($q) && exit if $q->param('how');
  printMerchantInfoPricing($q) && exit if $q->param('pricing');
  printMerchantInfoRequirements($q) && exit if $q->param('requirements');
  printMerchantInfoOverview($q);
}

################################################################################
sub printMerchantInfoHow {
  my ($q) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>How It Works</th>
	</tr>
      </thead>
      <tbody>
	<tr><td colspan=2><hr></td></tr>
	<tr>
	  <td width=25% valign=top>
	    <b>Create Your Account</b>
	  </td>
	  <td>
	    Fill out our online registration form to create your account in just minutes.  No credit card or account information is required.
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr>
	  <td valign=top>
	    <b>Manage Your Account</b>
	  </td>
	  <td>
	    Add product information on items you are offering to your account. View reports of how your products are doing on the $config->{SITE}. Set up email notifications in connection with your products.
	  </td>
	</tr>
	<tr>
	  <td colspan=2 align=center>
	    <br>
	    <a href="$config->{MARKETPLACE_REGISTRY}">Signup</a> now and start listing your products today!
	  </td>
	</tr>
	<tr><td colspan=2></td></tr>
      </tbody>
    </table>
    <br>

</td>
<td valign=top>
~;

  printMerchantInfoLinks($q);

  printFooter($q);
}

################################################################################
sub printMerchantInfoOverview {
  my ($q) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Merchant Overview</th>
	</tr>
      </thead>
      <tbody>
	<tr><td colspan=2><hr></td></tr>
	<tr>
	  <td width=25% valign=top>
	    <b>Promote Your Products</b>
	  </td>
	  <td>
	    Thousands of people visit $config->{DOMAIN} each day, and many are looking for the products you are selling.
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr>
	  <td valign=top>
	    <b>It's Free!!!</b>
	  </td>
	  <td>
	    Unlike other online shopping web sites such as Yahoo and Ebay, $config->{SITE} Marketplace currently costs nothing! No credit card numbers are required and no cost-per-click fees.  The $config->{SITE} Marketplace is <b>FREE</b>!!!
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr>
	  <td valign=top>
	    <b>It's Easy</b>
	  </td>
	  <td>
	    With the $config->{site} Marketplace, you easily manage and monitor your product information through our simple web interface.
	  </td>
	</tr>
	<tr>
	  <td colspan=2 align=center>
	    <br>
	    <a href="$config->{MARKETPLACE_REGISTRY}">Signup</a> now and start listing your products today!
	  </td>
	</tr>
	<tr><td colspan=2></td></tr>
      </tbody>
    </table>
    <br>

</td>
<td valign=top>
~;
  printMerchantInfoLinks($q);

  printFooter($q);
}

################################################################################
sub printMerchantInfoLinks {
  my ($q) = @_;

print qq~
<table class=data style="width: 175;">
  <tr>
    <th><div align=left>&nbsp;Merchant Links</div></th>
  </tr>
  <tbody>
    <tr><td></td></tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MERCHANT_INFO}">Merchant Overview</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MERCHANT_INFO}?how=1">How It Works</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MERCHANT_INFO}?pricing=1">Pricing</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MERCHANT_INFO}?requirements=1">Requirements</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_REGISTRY}">Signup Now!</a>
      </font>
      </td>
    </tr>
    <tr><td></td></tr>
  </tbody>
</table>
<br />
~;
}


################################################################################
sub printMerchantInfoPricing {
  my ($q) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Pricing</th>
	</tr>
      </thead>
      <tbody>
	<tr><td colspan=2><hr></td></tr>
	<tr>
	  <td width=25% valign=top>
	    <b>It's FREE!!!</b>
	  </td>
	  <td>
	    The $config->{SITE} Marketplace is absolutely free!
	  </td>
	</tr>
	<tr>
	  <td colspan=2 align=center>
	    <br>
	    <a href="$config->{MARKETPLACE_REGISTRY}">Signup</a> now and start listing your products today!
	  </td>
	</tr>
	<tr><td colspan=2></td></tr>
      </tbody>
    </table>
    <br>

</td>
<td valign=top>
~;

  printMerchantInfoLinks($q);
  printFooter($q);
}

################################################################################
sub printMerchantInfoRequirements {
  my ($q) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Requirements</th>
	</tr>
      </thead>
      <tbody>
	<tr><td colspan=2><hr></td></tr>
	<tr>
	  <td width=25% valign=top>
	    <b>$config->{SITE} Account</b>
	  </td>
	  <td>
	    All you need to list products in the $config->{SITE} Marketplace is an $config->{SITE} account.  The $config->{SITE} Marketplace is absolutely free!
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr>
	  <td width=25% valign=top>
	    <b>Shipping</b>
	  </td>
	  <td>
	    You must be able to sell and ship products anywhere in the United States of America.
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr>
	  <td width=25% valign=top>
	    <b>Terms of Use</b>
	  </td>
	  <td>
	    You must agree to and abide by the $config->{SITE} Terms of Use policy.  To view the policy, <a href="$config->{DOMAIN}/terms.shtml">click here</a>.
	  </td>
	</tr>
	<tr>
	  <td colspan=2 align=center>
	    <br>
	    <a href="$config->{MARKETPLACE_REGISTRY}">Signup</a> now and start listing your products today!
	  </td>
	</tr>
	<tr><td colspan=2></td></tr>
      </tbody>
    </table>
    <br>

</td>
<td valign=top>
~;

  printMerchantInfoLinks($q);
  printFooter($q);
}

################################################################################
sub printMerchantServices {
  my ($q) = @_;

  printMerchantServicesEmailBlast($q) && exit if $q->param('emailBlast');
  printMerchantServicesFeaturedMerchant($q) && exit if $q->param('featuredMerchant');
  printMerchantServicesFeaturedItem($q) && exit if $q->param('featuredItem');
  printMerchantServicesSponsoredSearch($q) && exit if $q->param('sponsoredSearch');
  printMerchantServicesOverview($q);
}

################################################################################
sub printMerchantServicesEmailBlast {
  my ($q) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Targeted Email Blast</th>
	</tr>
      </thead>
      <form name=formx method=post action=$config->{MARKETPLACE_MERCHANT_SERVICES}>
      <tbody>
	<tr><td colspan=2></td></tr>
	<tr class=odd>
	  <td width=25% valign=top>
	    <b>Reach</b>
	  </td>
	  <td>
	    Advertise to the thousands of people who visit $config->{DOMAIN} each day looking for the products you are selling and drive them to your products or to your web site.
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr>
	  <td valign=top>
	    <b>Value</b>
	  </td>
	  <td>
	    At just \$999, sending a targeted email is an affordable and extremely effective way to advertise your organization.
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr><td colspan=2></td></tr>
        <tr>
          <td colspan=2 align=center>
	      <a href="$config->{MARKETPLACE_MERCHANT_SERVICES}?submitEmailBlast=1">Click here</a> to set up your Targeted Email Blast!
          </td>
        </tr>
	<tr><td colspan=2></td></tr>
	<tr><td colspan=2></td></tr>
      </tbody>
      </form>
    </table>
    <br>

</td>
<td valign=top>
~;
  printMerchantServicesLinks($q);

  printFooter($q);
}

################################################################################
sub printMerchantServicesFeaturedMerchant {
  my ($q) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Featured Merchant</th>
	</tr>
      </thead>
      <form name=formx method=post action=$config->{MARKETPLACE_MERCHANT_SERVICES}>
      <tbody>
	<tr><td colspan=2></td></tr>
	<tr class=odd>
	  <td width=25% valign=top>
	    <b>Reach</b>
	  </td>
	  <td>
	    Advertise to the thousands of people who visit $config->{DOMAIN} each day looking for the products you are selling and drive them to your products or to your web site.
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr>
	  <td valign=top>
	    <b>Value</b>
	  </td>
	  <td>
	    At just \$99.95/month, becoming a $config->{SITE} Marketplace Featured Merchant is as affordable as it is powerful.
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr><td colspan=2></td></tr>
        <tr>
          <td colspan=2 align=center>
	      <a href="$config->{MARKETPLACE_MERCHANT_SERVICES}?submitFeaturedMerchant=1">Signup now</a> to become a Featured Merchant!
          </td>
        </tr>
	<tr><td colspan=2></td></tr>
	<tr><td colspan=2></td></tr>
      </tbody>
      </form>
    </table>
    <br>

</td>
<td valign=top>
~;
  printMerchantServicesLinks($q);

  printFooter($q);
}

################################################################################
sub printMerchantServicesFeaturedItem {
  my ($q) = @_;

  ### Now we output
  printHeader($q);

print qq~

~;
  printFooter($q);
}

################################################################################
sub printMerchantServicesLinks {
  my ($q) = @_;

print qq~
<table class=data style="width: 175;">
  <tr>
    <th><div align=left>&nbsp;Merchant Services</div></th>
  </tr>
  <tbody>
    <tr><td></td></tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MERCHANT_SERVICES}?featuredMerchant=1">Featured Merchant</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MERCHANT_SERVICES}?featuredItems=1">Featured Items</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MERCHANT_SERVICES}?sponsoredSearch=1">Sponsored Search Listings</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MERCHANT_SERVICES}?enhancedSearch=1">Enhanced Search Listing</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MERCHANT_SERVICES}?merchantShowcase=1">Merchant Showcase</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MERCHANT_SERVICES}?newsletter=1">Newsletter Listing</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MERCHANT_SERVICES}?emailBlast=1">Targeted Email Blast</a>
      </td>
    </tr>
    <tr><td></td></tr>
  </tbody>
</table>
<br />
~;
}

################################################################################
sub printMerchantServicesSponsoredSearch {
  my ($q) = @_;

  ### Now we output
  printHeader($q);

print qq~

~;
  printFooter($q);
}

################################################################################
sub printMerchantServicesOverview {
  my ($q) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Merchant Services</th>
	</tr>
      </thead>
      <tbody>
	<tr><td colspan=2></td></tr>
	<tr class=odd>
	  <td width=25% valign=top>
	    <b>Featured Merchant</b>
	  </td>
	  <td>
	    Advertise to the thousands of people who visit $config->{DOMAIN} each day looking for the products you are selling and drive them to your web site.
	      <br /><br />
	      <img src=$config->{BULLET} />&nbsp;<a class="small" href="$config->{MARKETPLACE_MERCHANT_SERVICES}?featuredMerchant=1">Learn More</a>
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr>
	  <td valign=top>
	    <b>Featured Items</b>
	  </td>
	  <td>
	    Advertise to the thousands of people who visit $config->{DOMAIN} each day looking for the products you are selling and drive them to your products.
	      <br /><br />
	      <img src=$config->{BULLET} />&nbsp;<a class="small" href="$config->{MARKETPLACE_MERCHANT_SERVICES}?featuredItem=1">Learn More</a>
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr class=odd>
	  <td valign=top>
	    <b>Sponsored Search Listing</b>
	  </td>
	  <td>
	    Drive customers to your items and store. Generate sales by determining which searches you want to come up 1st in. This is an effective way to make sure that the users who are searching for your products see them 1st in your store front.
	      <br /><br />
	    <img src=$config->{BULLET} />&nbsp;<a class="small" href="$config->{MARKETPLACE_MERCHANT_SERVICES}?sponsoredSearch=1">Learn More</a>
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr>
	  <td valign=top>
	    <b>Enhanced Search Listing</b>
	  </td>
	  <td>
	    Make your listing in the search results more appealing to the thousands of members who search the $config->{SITE} Marketplace looking for the products you are selling.
	      <br /><br />
	      <img src=$config->{BULLET} />&nbsp;<a class="small" href="$config->{MARKETPLACE_MERCHANT_SERVICES}?enhancedListing=1">Learn More</a>
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr class=odd>
	  <td valign=top>
	    <b>Merchant Showcase</b>
	  </td>
	  <td>
	    A Merchant Showcase listing serves as a billboard to promote your products and to share information about your company with the thousands of members who visit the $config->{SITE} Marketplace.
	      <br /><br />
	      <img src=$config->{BULLET} />&nbsp;<a class="small" href="$config->{MARKETPLACE_MERCHANT_SERVICES}?merchantShowcase=1">Learn More</a>
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr>
	  <td valign=top>
	    <b>Newsletter Listing</b>
	  </td>
	  <td>
	    A sponsored $config->{SITE} Marketplace listing in our weekly Marketplace newsletter. The listing will include a brief paragraph, a company logo, and a link to your products on the $config->{SITE} Marketplace.
	      <br /><br />
	      <img src=$config->{BULLET} />&nbsp;<a class="small" href="$config->{MARKETPLACE_MERCHANT_SERVICES}?newsletter=1">Learn More</a>
	  </td>
	</tr>
	<tr><td colspan=2><hr></td></tr>
	<tr class=odd>
	  <td valign=top>
	    <b>Targeted Email Blast</b>
	  </td>
	  <td>
	    Send a direct email blast to the members of our website that you would like to target. Advertise your company and the products you want to feature. The mailings are sent our in plain text and graphical html formats, highly effective!
	      <br /><br />
	      <img src=$config->{BULLET} />&nbsp;<a class="small" href="$config->{MARKETPLACE_MERCHANT_SERVICES}?emailBlast=1">Learn More</a>
	  </td>
	</tr>
	<tr><td colspan=2></td></tr>
      </tbody>
    </table>
    <br>

</td>
<td valign=top>
~;
  printMerchantServicesLinks($q);

  printFooter($q);
}

################################################################################
sub printMessage {
  my ($q, $message, $back) = @_;

  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Marketplace Message</th>
	</tr>
      </thead>
      <tbody>
	<tr><td colspan=2>&nbsp;</td></tr>
	<tr>
	  <td colspan=2>
	    $message
	  </td>
	</tr>
	<tr><td colspan=2>&nbsp;</td></tr>
~;
  if ($back) {
print qq~
	<tr class=buttons>
	  <td colspan=2 align=center>
	    <input type="submit" name="back" value="Go Back" onClick="history.go(-$back);" />
	  </td>
	</tr>
~;
}
print qq~
      </tbody>
    </table>
    <br>
~;

  printFooter();

  exit;
}

################################################################################
sub printMySummary {
  my ($q, $summary) = @_;

  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=6>My Items For Sale</th>
	</tr>
      </thead>
      <form name="items_for_sale_form" method="post" action="$config->{MARKETPLACE_MY_SUMMARY}">
	<input type="hidden" name="items_for_sale_order_by" value="$summary->{order_by}" />
	<input type="hidden" name="items_for_sale" value="1" />
      <tbody>
~;
  if ($summary->{items_for_sale_records}) {
print qq~
	  <tr class=search_columns>
	    <td width=5%>&nbsp;</td>
	    <td>
	      Item #
	    </td>
	    <td>
	      <a class=white href="$config->{MARKETPLACE_MY_SUMMARY}?items_for_sale_current_page=$summary->{items_for_sale_current_page}&items_for_sale_order_by=title">Title</a>
	    </td>
	    <td>
	      <a class=white href="$config->{MARKETPLACE_MY_SUMMARY}?items_for_sale_current_page=$summary->{items_for_sale_current_page}&items_for_sale_order_by=hits"># of Views
	    </td>
	    <td>
	      <a class=white href="$config->{MARKETPLACE_MY_SUMMARY}?items_for_sale_current_page=$summary->{items_for_sale_current_page}&items_for_sale_order_by=num_sold"># Sold
	    </td>
	    <td>
	      <a class=white href="$config->{MARKETPLACE_MY_SUMMARY}?items_for_sale_current_page=$summary->{items_for_sale_current_page}&items_for_sale_order_by=status">Status
	    </td>
	  </tr>

~;
my $i;
foreach my $record ( @{ $summary->{items_for_sale_records} } ) {
  if ($i) {
    print "<tr class=odd>\n"; $i = 0;
  } else {
    print "<tr class=even>\n"; $i = 1;
  }
print qq~
		<td>
		  <input type="checkbox" name="items_for_sale_ids" value="$record->{id}" />
		</td>
		<td>
		  $record->{id}
		</td>
		<td>
		  <a href="$config->{MARKETPLACE_SELL_ITEM}?edit=1&id=$record->{id}">$record->{title}</a>
		</td>
		<td>
		  $record->{hits}
		</td>
		<td>
		  $record->{num_sold}
		</td>
		<td>
		  $record->{status}
		</td>
	      </tr>
~;
}
print qq~

	    <tr class=buttons>
	      <td colspan=3 valign=top>
		&nbsp;
		<img src=$config->{LEFT_ARROW} />
		  With Selected:
		  <select name="action" onChange="if (document.items_for_sale_form.action.value) { document.items_for_sale_form.submit();}">
		    <option value="">--Select--</option>
		    <option value="Activate">Activate</option>
		    <option value="Deactivate">Deactivate</option>
		    <option value="Delete">Delete</option>
		  </select>
	      </td>
	      <td colspan=3>
		$summary->{items_for_sale_start_record} - $summary->{items_for_sale_end_record} of $summary->{items_for_sale_total_records} Records
		      |
~;
if ($summary->{items_for_sale_previous_page}) {
  print "<a href=\"$config->{MARKETPLACE_MY_SUMMARY}?items_for_sale_current_page=$summary->{items_for_sale_previous_page}&items_for_sale_order_by=$summary->{items_for_sale_order_by}\">Previous Page</a>\n";
} else {
  print "Previous Page\n";
}
print "|\n";

if ($summary->{items_for_sale_next_page}) {
  print "<a href=\"$config->{MARKETPLACE_MY_SUMMARY}?items_for_sale_current_page=$summary->{items_for_sale_next_page}&items_for_sale_order_by=$summary->{items_for_sale_order_by}\">Next Page</a>\n";
} else {
  print "Next Page\n";
}
print qq~
	      </td>
	    </tr>
~;
} else {
print qq~
	      <tr>
		<td colspan="2">
		  You currently have no items for sale.
		</td>
	      </tr>
~;
}
print qq~
      </tbody>
    </table>
  </form>
    <br>


    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=5>My Saved Items</th>
	</tr>
      </thead>
      <form name="saved_items_form" method="post" action="$config->{MARKETPLACE_MY_SUMMARY}">
	<input type="hidden" name="saved_items_order_by" value="$summary->{order_by}" />
	<input type="hidden" name="saved_items" value="1" />
      <tbody>
~;
  if ($summary->{saved_items_records}) {
print qq~
	  <tr class=search_columns>
	    <td width="5%">&nbsp;</td>
	    <td align="center">
	      Picture
	    </td>
	    <td>
	      <a class=white href="$config->{MARKETPLACE_MY_SUMMARY}?saved_items_current_page=$summary->{saved_items_current_page}&saved_items_order_by=title">Title
	    </td>
	    <td>
	      <a class=white href="$config->{MARKETPLACE_MY_SUMMARY}?saved_items_current_page=$summary->{saved_items_current_page}&saved_items_order_by=price">Price</a>
	    </td>
	    <td>
	      <a class=white href="$config->{MARKETPLACE_MY_SUMMARY}?saved_items_current_page=$summary->{saved_items_current_page}&saved_items_order_by=seller">Seller
	    </td>
	  </tr>
~;
my $i;
foreach my $record (@{ $summary->{saved_items_records} }) {
  if ($i) {
    print "<tr class=odd>\n"; $i = 0;
  } else {
    print "<tr class=even>\n"; $i = 1;
  }
print qq~
		<td width="5%">
		  <input type="checkbox" name="saved_items_ids" value="$record->{id}" />
		</td>  
		<td align="left" width="60" height="60">
		  <a href="$config->{MARKETPLACE_VIEW_ITEM}?id=$record->{id}"><img src="$record->{path}" width="60" height="60" border="0" /></a>
		</td>
		<td>
		  <a href="$config->{MARKETPLACE_VIEW_ITEM}?id=$record->{id}">$record->{title}</a>
		</td>
		<td>
		  <font class=emph>$record->{price}</font>
		</td>
		<td>
		  $record->{seller_name}
		</td>
	      </tr>
~;
}
print qq~
	    <tr class=buttons>
	      <td>
		&nbsp;
		<img src=$config->{LEFT_ARROW} />
	      </td>
	      <td colspan=4>
		With Selected:
		<select name="action" onChange="if (document.saved_items_form.action.value) { document.saved_items_form.submit();}">
		  <option value="">--Select--</option>
		  <option value="Delete">Delete</option>
		</select>
		$summary->{saved_items_start_record} - $summary->{saved_items_end_record} of $summary->{saved_items_total_records} Records
		      |
~;
if ($summary->{saved_items_previous_page}) {
  print "<a href=\"$config->{MARKETPLACE_MY_SUMMARY}?saved_items_current_page=$summary->{saved_items_previous_page}&saved_items_order_by=$summary->{saved_items_order_by}\">Previous Page</a>\n";
} else {
  print "Previous Page\n";
}
print "|\n";

if ($summary->{saved_items_next_page}) {
  print "<a href=\"$config->{MARKETPLACE_MY_SUMMARY}?saved_items_current_page=$summary->{saved_items_next_page}&saved_items_order_by=$summary->{saved_items_order_by}\">Next Page</a>\n";
} else {
  print "Next Page\n";
}
print qq~
	      </td>
	    </tr>
~;
} else {
print qq~
	      <tr>
		<td colspan=5>
		  You currently have no saved items.
		</td>
	      </tr>
~;
}
print qq~
      </tbody>
    </table>
  </form>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>My Saved Searches</th>
	</tr>
      </thead>
      <form name="saved_searches_form" method="post" action="$config->{MARKETPLACE_MY_SUMMARY}">
	<input type="hidden" name="saved_searches_order_by" value="$summary->{order_by}" />
	<input type="hidden" name="saved_searches" value="1" />
      <tbody>
~;
  if ($summary->{saved_searches_records}) {
print qq~
	  <tr class=search_columns>
	    <td width="5%">&nbsp;</td>
	    <td>
	      <a class=white href="$config->{MARKETPLACE_MY_SUMMARY}?saved_searches_current_page=$summary->{saved_searches_current_page}&saved_searches_order_by=name">Name of Search</a>
	    </td>
	  </tr>
~;
my $i;
foreach my $record ( @{ $summary->{saved_searches_records} } ) {
  if ($i) {
    print "<tr class=odd>\n"; $i = 0;
  } else {
    print "<tr class=even>\n"; $i = 1;
  }
print qq~
		<td>
		  <input type="checkbox" name="saved_search_ids" value="$record->{id}" />
		</td>
		<td>
		  <a href="$config->{MARKETPLACE_SEARCH}?submitSavedSearch=1&id=$record->{id}">$record->{name}</a>
		</td>
	      </tr>
~;
}
print qq~
	    <tr class=buttons>
	      <td valign=middle>
		&nbsp;
		<img src=$config->{LEFT_ARROW} />
	      </td>
	      <td>
		With Selected:
		<select name="action" onChange="if (document.saved_searches_form.action.value) { document.saved_searches_form.submit();}">
		  <option value="">--Select--</option>
		  <option value="Delete">Delete</option>
		</select>
		$summary->{saved_searches_start_record} - $summary->{saved_searches_end_record} of $summary->{saved_searches_total_records} Records
		      |
~;
if ($summary->{saved_searches_previous_page}) {
  print "<a href=\"$config->{MARKETPLACE_MY_SUMMARY}?saved_searches_current_page=$summary->{saved_searches_previous_page}&saved_searches_order_by=$summary->{saved_searches_order_by}\">Previous Page</a>\n";
} else {
  print "Previous Page\n";
}
print "|\n";

if ($summary->{saved_searches_next_page}) {
  print "<a href=\"$config->{MARKETPLACE_MY_SUMMARY}?saved_searches_current_page=$summary->{saved_searches_next_page}&saved_searches_order_by=$summary->{saved_searches_order_by}\">Next Page</a>\n";
} else {
  print "Next Page\n";
}
print qq~
	      </td>
	    </tr>
~;
} else {
print qq~
	      <tr>
		<td colspan="2">
		  You currently have no saved searches.
		</td>
	      </tr>
~;
}
print qq~
      </tbody>
    </table>
  </form>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=6>My Purchased Items</th>
	</tr>
      </thead>
      <tbody>
~;
  if ($summary->{purchased_items_records}) {
print qq~
	<tr class=search_columns>
	  <td>
	    Item #</font>
	  </td>
	  <td>
	    <a class=white href="$config->{MARKETPLACE_MY_SUMMARY}?purchased_items_current_page=$summary->{purchased_items_current_page}&purchased_items_order_by=title">Title</a></font>
	  </td>
	  <td>
	    <a class=white href="$config->{MARKETPLACE_MY_SUMMARY}?purchased_items_current_page=$summary->{purchased_items_current_page}&purchased_items_order_by=quantity">Qty</font>
	  </td>
	  <td>
	    <a class=white href="$config->{MARKETPLACE_MY_SUMMARY}?purchased_items_current_page=$summary->{purchased_items_current_page}&purchased_items_order_by=total">Total Price</font>
	  </td>
	  <td>
	    <a class=white href="$config->{MARKETPLACE_MY_SUMMARY}?purchased_items_current_page=$summary->{purchased_items_current_page}&purchased_items_order_by=tstamp">Date</font>
	  </td>
	  <td>
	    <a class=white href="$config->{MARKETPLACE_MY_SUMMARY}?purchased_items_current_page=$summary->{purchased_items_current_page}&purchased_items_order_by=seller">Seller</font>
	  </td>
	</tr>
~;
my $i;
foreach my $record (@{ $summary->{purchased_items_records} } ) {
  if ($i) {
    print "<tr class=odd>\n"; $i = 0;
  } else {
    print "<tr class=even>\n"; $i = 1;
  }
print qq~
	      <td>
		$record->{id}
	      </td>
	      <td>
		$record->{title}
	      </td>
	      <td>
		$record->{quantity}
	      </td>
	      <td>
		$record->{total}
	      </td>
	      <td>
		$record->{date_created}
	      </td>
	      <td>
		$record->{seller_name}
	      </td>
	    </tr>
~;
}
print qq~
	  <tr class=buttons align=center>
	    <td colspan=6>
	      $summary->{purchased_items_start_record} - $summary->{purchased_items_end_record} of $summary->{purchased_items_total_records} Records
		    |
~;
if ($summary->{purchased_items_previous_page}) {
  print "<a href=\"$config->{MARKETPLACE_MY_SUMMARY}?purchased_items_current_page=$summary->{purchased_items_previous_page}&purchased_items_order_by=$summary->{purchased_items_order_by}\">Previous Page</a>\n";
} else {
  print "Previous Page\n";
}
print "|\n";

if ($summary->{purchased_items_next_page}) {
  print "<a href=\"$config->{MARKETPLACE_MY_SUMMARY}?purchased_items_current_page=$summary->{purchased_items_next_page}&purchased_items_order_by=$summary->{purchased_items_order_by}\">Next Page</a>\n";
} else {
  print "Next Page\n";
}
print qq~
	    </td>
	  </tr>
~;
} else {
print qq~
	    <tr>
	      <td colspan=6>
		You currently have no purchased items.
	      </td>
	    </tr>
~;
}
print qq~
      </tbody>
    </table>
  </form>
    <br>
~;

  printFooter($q);
}

################################################################################
sub printPurchaseConfirmation {
  my ($q, $id) = @_;

  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th>Purchase Confirmation</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    <br>
	    Thank you for using the $config->{SITE} Marketplace! Information regarding your purchase has been sent to the seller. Remember, all inquiries with regard to items you have purchased should be directed to the seller.<br><br>
	      We encourage you to <a href="#" onClick="window.open('$config->{MARKETPLACE_PURCHASE}?receipt=1&id=$id','$config->{DOMAIN}','width=550,height=500,toolbar,resizable');">click here</a> to view a printable receipt of this transaction.<br><br>
	  </td>
	</tr>
      </tbody>
    </table>
    <br>
~;

  printFooter($q);
}

################################################################################
sub printPurchaseItem {
  my ($q, $item) = @_;

  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Purchase Confirmation</th>
	</tr>
      </thead>
      <form name="formx" method="post" action="$config->{MARKETPLACE_PURCHASE}">
	<input type="hidden" name="id" value="$item->{id}" />
	<input type="hidden" name="total" value="$item->{total}" />
      <tbody>
	<tr>
	  <th>
	    Item ID :
	  </th>
	  <td>
	    $item->{id}
	  </td>
	</tr>
	<tr>
	  <th>
	    Title :
	  </th>
	  <td>
	    $item->{title}
	  </td>
	</tr>
	<tr>
	  <th>
	    Seller :
	  </th>
	  <td>
	    $item->{seller_name}
	  </td>
	</tr>
	<tr>
	  <th>
	    Category :
	  </th>
	  <td>
	    $item->{categoryNames}
	  </td>
	</tr>
	<tr>
	  <th>
	    Price :
	  </th>
	  <td>
	    $item->{price}
~;
  if ($item->{shipping_included}) {
    print "(Shipping Included)\n";
  } else {
    print "(Shipping Not Included)\n";
  }
print qq~
	  </td>
	</tr>

~;
  if ($item->{more_than_one}) {
print qq~
	  <tr>
	    <th>
	      Quantity :
	    </th>
	    <td>
	      <input type="text" name="quantity" value="$item->{quantity}" size="5"/>&nbsp;&nbsp;&nbsp;
	      <input type="submit" name="submitUpdateTotal" value="Update Total" />
	    </td>
	  </tr>
~;
}
print qq~
	  <tr>
	    <td colspan="2"><hr></td>
	  </tr>
	  <tr>
	    <th>
	      <b>Total Price :
	    </th>
	    <td>
	      $item->{total}
	    </td>
	  </tr>
      </tbody>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Confirmation Information</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
~;
if ($item->{payment_url}) {
print qq~
	      <b>It's Simple!</b>
	      Clicking the "Buy Now" button will take you to the vendor's payment page to complete the transaction.  We will also keep track of your attempt to buy this item for your records and also for the seller's fullfillment records.
~;
} else {
print qq~
		<b>It's Simple!</b>
		Clicking the "Buy Now" button will track your desire to purchase this item and also notify the seller such that the seller can make payment and shipping arrangements with you personally.
~;
}
print qq~
	      <br><br>
	      <b>Buyers and sellers will be able to submit positive or negative feedback after the transaction.</b><br /><br />
	  </td>
	</tr>
	<tr class=buttons>
	  <td colspan="2" align="center">
	    <input type="submit" name="submitPurchase" value="Buy Now!" onClick="return confirm('Are you sure you want to purchase this item?');" />
	  </td>
	</tr>
      </tbody>
    </table>
  </form>
    <br>
~;

  printFooter($q);
}

################################################################################
sub printPurchaseReceipt {
  my ($q, $purchase) = @_;

  print $q->header();

print qq~
<html>
  <head>
    <link rel="StyleSheet" href=$config->{CSS_URL} type="text/css">
  </head>
  <body>
    <table class=data>
      <thead>
	<tr>
	  <th colspan=2>Receipt of Purchase</th>
	</tr>
      </thead>
      <form name="formx" method="post" action="$config->{MARKETPLACE_PURCHASE}">
	<input type="hidden" name="id" value="$purchase->{item}->{id}>" />
	<input type="hidden" name="total" value="$purchase->{total}" />
      <tbody>
	<tr>
	  <th>
	    Item ID :
	  </th>
	  <td>
	    $purchase->{item}->{id}
	  </td>
	</tr>
	<tr>
	  <th>
	    Title :
	  </th>
	  <td>
	    $purchase->{title}
	  </td>
	</tr>
	<tr>
	  <th>
	    Seller :
	  </th>
	  <td>
	    $purchase->{seller}->{name}
	  </td>
	</tr>
	<tr>
	  <th>
	    Category :
	  </th>
	  <td>
	    $purchase->{item}->{categoryNames}
	  </td>
	</tr>
	<tr>
	  <th>
	    Price :
	  </th>
	  <td>
	    $purchase->{price}
~;
  if ($purchase->{item}->{shipping_included}) {
    print "(Shipping Included)\n";
  } else {
    print "(Shipping Not Included)\n";
  }
print qq~
	  </td>
	</tr>
	<tr>
	  <th>
	    Quantity :
	  </th>
	  <td>
	    $purchase->{quantity}
	  </td>
	</tr>
	<tr>
	  <td colspan="2"><hr></td>
	</tr>
	<tr>
	  <th>
	    <b>Total Price :
	  </th>
	  <td>
	    $purchase->{total}
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <table class=data>
      <thead>
	<tr>
	  <th colspan=2>Confirmation Information</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    <b>You have agreed to a contract</b> -- You have entered into a legally binding contract to purchase the item from the seller. You are responsible for reading the full item listing, including the seller's instructions and accepted payment methods. Seller assumes all responsibility for listing this item.<br><br>
	  </td>
	</tr>
      </tbody>
    </table>
  </form>
    <br>

    <div align="center">
      <a href="#" onClick="window.close();">Click here to close this window</a>
    </div>
</body>
</html>
~;
}

################################################################################
sub printQuickSearch {
  my ($q) = @_;

print qq~
<table class=data style="width: 100%;">
  <tr>
    <th colspan=2><div align=left>&nbsp;Quick Search (<a class=small href="$config->{MARKETPLACE_SEARCH}">Advanced Search</a>)</div></th>
  </tr>
  <tbody>
    <tr><td colspan=2></td></tr>
    <form name=form method=post action="$config->{MARKETPLACE_SEARCH}">
    <tr>
      <td>
	<select name=category>
	  <option value="">All Categories</option>
~;
  foreach my $cat ( getCategories() ) {
print qq~
	  <option value="$cat->{id}">$cat->{name}</option>
~;
}
print qq~
	</select>
      </td>
      <td align=right>
	<input name=keywords size=40>
	<input type=submit name=submitSearch value="Search">
      </td>
    </tr>
  </form>
    <tr><td colspan=2></td></tr>
  </tbody>
</table>
<br />
~;
}

################################################################################
sub printSearchDisplayInfo {
  my ($q, $results) = @_;

print qq~
    Displaying $results->{start_record} - $results->{end_record} of about $results->{total_records} Items |
~;
  if ($results->{previous_page}) {
print qq~
	      <a class=white href="#" onClick="document.form.submitSearch.value=1;document.form.page.value=$results->{previous_page};document.form.submit();return false;"><--Previous Page</a>
~;
} else {
print qq~
		<--Previous Page
~;
}
print qq~

	      |

~;
  if ($results->{next_page}) {
print qq~
		<a class=white href="#" onClick="document.form.submitSearch.value=1;document.form.page.value=$results->{next_page};document.form.submit();return false;">Next Page--></a>
~;
} else {
print qq~
		  Next Page-->
~;
}
}

################################################################################
sub printSearchForm {
  my ($q, $admin) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <table class=data>
      <thead>
	<tr>
	  <th colspan=2>Advanced Marketplace Search</th>
	</tr>
      </thead>
      <tbody>
	<tr class=odd>
	  <td>
~;
  if ($admin) {
    print "<form name=form method=post action=\"$config->{MARKETPLACE_ADMIN_SEARCH}\">\n";
  } else {
    print "<form name=form method=post action=\"$config->{MARKETPLACE_SEARCH}\">\n";
  }
print qq~
	    <table width=100%>
	      <tr>
		<td valign="top" width="20%">
		  <b>Keyword Search :</b><br />
		  <input type="text" name="keywords" size="60" /><br />
		  <input type="checkbox" name="title_and_description" value="1">Search Title <b>and</b> Description</input>
		</td>
	      </tr>
	      <tr>
		<td>
		  <b>HBCU :</b><br />
		  <select name="hbcu">
		    <option value="">All HBCUs</option>
~;
  foreach my $hbcu ( $hdb->getHbcuDatas(ORDER => 'hbcu_name') ) {
print qq~
		    <option value="$hbcu->{hbcu_name}">$hbcu->{hbcu_name}</option>
~;
}
print qq~
		  </select>
		</td>
	      </tr>
	      <tr>
		<td>
		  <b>Category :</b><br />
		  <select name="category">
		    <option value="">All Categories</option>
~;
  foreach my $cat ( getCategories() ) {
print qq~
		    <option value="$cat->{id}">$cat->{name}</option>
~;
}
print qq~
		  </select>
		</td>
	      </tr>
	      <tr>
		<td>
		  <b>Min Price :</b><br />
		  <input type="text" name="min_price" size="20" />
		</td>
	      </tr>
	      <tr>
		<td>
		  <b>Max Price :</b><br />
		  <input type="text" name="max_price" size="20" />
		</td>
	      </tr>
	      <tr>
		<td>
		  <b>Specific Seller :</b><br />
		  <input type="text" name="sellers" size="40" />
		</td>
	      </tr>
~;
  if ($authorized && !$admin) {
print qq~
		<tr><td></td></tr>
		<tr>
		  <td>
		    <input type="checkbox" name="saveSearch" value="1" onChange="if (document.form.saveSearch.checked) {document.getElementById('search_name').style.display = '';} else {document.getElementById('search_name').style.display = 'none';}">Add this search to my Favorite Searches</input>
		  </td>
		</tr>
		<tr id=search_name style="display: none;">
		  <td>
		    <b>Search Name :</b><br />
		    <input type="text" name="search_name" size="40" />
		  </td>
		</tr>
~;
} elsif ($admin) {
print qq~
	      <tr>
		<td>
		  <b>Status :</b><br />
		  <select name="status">
		    <option value="">All Items</option>
		    <option value="activated">Activated</option>
		    <option value="deactivated">Deactivated</option>
		    <option value="deleted">Deleted</option>
		  </select>
		</td>
	      </tr>

~;
}
print qq~
	    </table>
	  </td>
	  <td valign=top align=center>
	    <table>
	      <thead>
		<tr>
		  <th>Featured Sponsor</th>
		</tr>
	      </thead>
	      <tbody>
		<tr>
		  <td>
		    <iframe id='ad33b334' name='ad33b334' style=text-align:center src='http://hbcuconnect.com/phpAds/adframe.php?n=ad33b334&amp;what=zone:37&amp;refresh=80&amp;resize=1' framespacing='0' frameborder='yes' scrolling='no' width='300' height='250' allowtransparency='true'></iframe>
		  </td>
		</tr>
	      </tbody>
	    </table>
	  </td>
	</tr>
	<tr class=buttons>
	  <td colspan=2 align=center>
	    <input type=radio name=grid_view value="0" checked> List View
	    <input type=radio name=grid_view value="1"> Grid View
	    &nbsp;&nbsp;
	    <input type=submit name=submitSearch value="Start Search!">
	  </td>
	</tr>
      </form>
    </table>
    <br>
~;
  printFooter($q);
}

################################################################################
sub printSearchResults {
  my ($q, $results) = @_;

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Marketplace Search Results</th>
	</tr>
      </thead>
      <tbody>
	<tr><td></td></tr>

~;
  if ($results->{records}) {
print qq~
	  <form name="form" method="post" action="$config->{MARKETPLACE_SEARCH}">
	    <input type=hidden name=submitSearch value="0" />
	    <input type=hidden name=page value="$results->{page}" />
	    <input type=hidden name=order_by value="$results->{order}" />
	    <input type=hidden name=grid_view value="$results->{view}" />
~;
foreach my $param (@{ $results->{params} }) {
print qq~
		<input type=hidden name=$param->{name} value="$param->{value}" />
~;
}
print qq~

	  <tr class=buttons>
	    <td align=center>
~;
printSearchDisplayInfo($q, $results);
print qq~
	    </td>
	  </tr>

	  <tr>
	    <td>
~;
if ($results->{view}) {
  printGridItems($q, $results->{records});
} else {
  printListItems($q, $results->{records});
}
print qq~
	    </td>
	  </tr>

	  <tr class=buttons>
	    <td align=center>
~;
printSearchDisplayInfo($q, $results);
print qq~
	    </td>
	  </tr>

~;
} else {
print qq~
	      <tr>
		<td>
		  No matching items were found. Please try your search again.<br><br>
		</td>
	      </tr>
~;
}
print qq~
	  <tr><td></td></tr>
  </tbody>
  </table>
<br>
~;
  printFooter($q);
}

################################################################################
sub printSeller {
  my ($q, $seller) = @_;

  # Set the default category
  my @cats = map {
    foreach my $cat (split /:/, $seller->{categories}) {
      $_->{default} = 1 if $_->{id} == $cat;
    }
    $_;
  } getCategories();

  ### Now we output
  printHeader($q);

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Store Information</th>
	</tr>
      </thead>
      <form id="formx" name="formx" method="post" action="$config->{MARKETPLACE_REGISTRY}" onSubmit="return verifySeller();">
~;
  print "<input type=hidden name=edit value=1 />\n" if $q->param('edit');
print qq~
      <tbody>
	<tr>
	  <th>
	    <font class=required>*</font>Store Name :
	  </th>
	  <td>
	    <input type="text" name="name" value="$seller->{name}" size="40" />
	  </td>
	</tr>
	<tr>
	  <th>
	    <font class=required>*</font>Categories :
	  </th>
	  <td>
	    <select name="categories" multiple>
~;
  foreach my $x ( @cats ) {
    print "<option value=$x->{id}";
    print " selected" if $x->{default};
    print ">$x->{name}</option>\n";
  }
print qq~
	      </select>
	  </td>
	</tr>
	<tr>
	  <th>
	    Website Url :
	  </th>
	  <td>
	    <input type="text" name="website_url" value="$seller->{website_url}" size="40" />
	  </td>
	</tr>
	<tr>
	  <th>
	    Privacy Policy Url :
	  </th>
	  <td>
	    <input type="text" name="privacy_url" value="$seller->{privacy_url}" size="40" />
	  </td>
	</tr>
	<tr>
	  <th>
	     <font class=required>*</font>Description :
	  </th>
	  <td>
	    <textarea name="description" cols="55" rows="6">$seller->{description}</textarea>
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Payment Information</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    <b>Preview/Purchase Link :</b>
	  </td>
	  <td>
	    <input type="text" name="payment_url" value="$seller->{payment_url}" size="50"  />
	  </td>
	</tr>
	<tr><td colspan="2"><hr></td></tr>
	<tr>
	  <td colspan="2">
	    <b>Select the payment methods you will accept :</b>
	  </td>
	</tr>
	<tr>
	  <td>
	    <input type="checkbox" name="visa" value="1"
~;
  print " checked" if $seller->{visa};
print qq~
	    >Visa</input>
	  </td>
	  <td>
	    <input type="checkbox" name="paypal" value="1"
~;
  print " checked" if $seller->{paypal};
print qq~
	    >PayPal</input>
	  </td>
	</tr>
	<tr>
	  <td>
	    <input type="checkbox" name="mastercard" value="1"
~;
  print " checked" if $seller->{mastercard};
print qq~
	    >MasterCard</input>
	  </td>
	  <td>
	    <input type="checkbox" name="checks" value="1"
~;
  print " checked" if $seller->{checks};
print qq~
	    >Personal Check</input>
	  </td>
	</tr>
	<tr>
	  <td>
	    <input type="checkbox" name="amex" value="1"
~;
  print " checked" if $seller->{amex};
print qq~
	    >American Express</input>
	  </td>
	  <td>
	    <input type="checkbox" name="money_order" value="1"
~;
  print " checked" if $seller->{money_order};
print qq~
	    >Money Order/Cashier's Check</input>
	  </td>
	</tr>
	<tr>
	  <td>
	    <input type="checkbox" name="discover" value="1"
~;
  print " checked" if $seller->{discover};
print qq~
	    >Discover Card</input>
	  </td>
	  <td>
	    <input type="checkbox" name="other" value="1"
~;
  print " checked" if $seller->{other};
print qq~
	    >Other / See Payment Instructions</input>
	  </td>
	</tr>
	<tr><td colspan="2"><hr></td></tr>
	<tr>
	  <td colspan=2>
	    <b>Enter some clear instructions to assist the buyer with payment and shipping :</b><br />
	    <textarea name="instructions" cols="65" rows="6">$seller->{instructions}</textarea>
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Return Policy</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    <input type="checkbox" name="accepted" value="1"
~;
  print " checked" if $seller->{accepted};
print qq~
	    >Returns Accepted</input><br />
	  </td>
	</tr>
	<tr>
	  <td>
	    Items must be returned within:
	    <select name="grace">
	      <option value="">--Select One--</option>
	      <option value="3"
~;
  print " selected" if $seller->{grace} == 3;
print qq~
	    >3 Days</option>
	    <option value="7"
~;
  print " selected" if $seller->{grace} == 7;
print qq~
	    >7 Days</option>
	    <option value="14"
~;
  print " selected" if $seller->{grace} == 14;
print qq~
	    >14 Days</option>
	    <option value="30"
~;
  print " selected" if $seller->{grace} == 30;
print qq~
	    >30 Days</option>
	  </select>
	  </td>
	</tr>
	<tr>
	  <td>
	    Refunds will be dispensed in the form of:
	    <select name="type">
	      <option value="">--Select One--</option>
	      <option value="Exchange"
~;
  print " selected" if $seller->{type} eq 'Exchange';
print qq~
	    >Exchange</option>
	    <option value="Merchandise"
~;
  print " selected" if $seller->{type} eq 'Merchandise';
print qq~
	    >Merchandise</option>
	    <option value="Money"
~;
  print " selected" if $seller->{type} eq 'Money';
print qq~
	    >Money Back</option>
	  </select>
	  </td>
	</tr>
	<tr>
	  <td>
	    <b>Refund Policy</b><br>
	    <textarea name="policy" cols="65" rows="6">$seller->{policy}</textarea>
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <div align="center">
      <input type="submit" name="submitSeller" value="Submit" />
    </div>
    <br />
~;
  printFooter($q);
}

################################################################################
sub printSellerItemCategories {
  my ($q, $seller) = @_;

print qq~
<table class=data style="width: 175;">
  <tr>
    <th><div align=left>&nbsp;Seller Categories</div></th>
  </tr>
  <tbody>
    <tr><td></td></tr>
~;
  foreach my $cat ( @{ $seller->{itemCategories} } ) {
print qq~
      <tr>
	<td>
	  <img src=$config->{BULLET} />
	  <a href="$config->{MARKETPLACE_SEARCH}?submitSearch=1&category=$cat->{id}&grid_view=1">$cat->{name} ($cat->{item_count})</a>
	</td>
      </tr>
~;
}
print qq~
    <tr><td></td></tr>
  </tbody>
</table>
    <br>
~;
}

################################################################################
sub printSendEmail {
  my ($q, $item, $confirm) = @_;

  print $q->header();

print qq~
<html>
  <head>
    <link rel="StyleSheet" href=$config->{CSS_URL} type="text/css">
  </head>
  <body>
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>Send Email</th>
	</tr>
      </thead>
      <form id="formx" name="formx" method="post" action="$config->{MARKETPLACE_SEND_EMAIL}" onSubmit="return verifySendMessage();">
	<input type="hidden" name="id" value="$item->{id}" />
      <tbody>
~;
  if ($confirm) {
print qq~
	  <tr>
	    <td colspan=2>
	      You message was successfully sent!<br><br><br>	
	      <div align="center"><a href="#" onClick="window.close()">Click here to close this window</a></div>
	    </td>
	  </tr>
~;
} else {
print qq~
	    <tr>
	      <th>
		<font class=required>*</font>To :
	      </th>
	      <td>
		<input type="text" name="receiver" size="40" />
	      </td>
	    </tr>
	    <tr>
	      <th>
		<font class=required>*</font>Subject :
	      </th>
	      <td>
		<input type="text" name="subject" value="Interesting $config->{SITE} Item: $item->{title}" size="65" />
	      </td>
	    </tr>
	    <tr>
	      <th>
		<font class=required>*</font>Message :
	      </th>
	      <td>
		<textarea name="comments" rows="8" cols="50">I saw this item for sale on the $config->{SITE} Marketplace, and thought that you might be interested.</textarea>
	      </td>
	    </tr>
	    <tr class=buttons>
	      <td align="center" colspan=2>
		<input type="submit" name="submitMessage" value="Submit" />
	      </td>
	    </tr>
      </tbody>
    </table>
    </form>
    <br>
~;
}
print qq~
</body>
</html>
~;
}

################################################################################
sub printViewItem {
  my ($q, $item) = @_;

  printHeader($q);

  if (&isAdmin()) {
print qq~
      <br>
      <div align=center>
~;
if ($item->{featured}) {
print qq~
	  <img src=$config->{ADD} />&nbsp;<a href="$config->{MARKETPLACE_VIEW_ITEM}?unfeatureItem=1&id=$item->{id}">Remove From Featured Items</a>
~;
} else {
print qq~
	  <img src=$config->{ADD} />&nbsp;<a href="$config->{MARKETPLACE_VIEW_ITEM}?featureItem=1&id=$item->{id}">Add to Featured Items</a>
~;
}
print qq~
	      &nbsp;&nbsp;&nbsp;
~;
unless (isSavedItem($item->{id}, $q->cookie('ID'))) {
print qq~
		<img src=$config->{ADD} />&nbsp;<a href="$config->{MARKETPLACE_VIEW_ITEM}?submitSaveItem=1&id=$item->{id}">Save to My Items</a>
~;
}
print qq~
		&nbsp;&nbsp;&nbsp;
		<img src=$config->{MAIL} />&nbsp;<a href="#" onClick="window.open('$config->{MARKETPLACE_SEND_EMAIL}?id=$item->{id}','Message','left=20,top=20,width=575,height=325,toolbar=0,location=0,menubar=0,resizable=0'); return false;">Send to a Friend</a>
      </div>
~;
}
print qq~
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=4>$item->{title}</th>
	</tr>
      </thead>
      <form name="formx" method="post" action="$config->{MARKETPLACE_VIEW_ITEM}" enctype="multipart/form-data">
	<input type="hidden" name="id" value="$item->{id}" />
      <tbody>
	<tr>
	  <td align="center" width="100" valign="top">
~;
  foreach my $picture (@{ $item->{pictures} }) {
print qq~
	    <img src="$picture->{path}" width="100" height="100" /><br>
	    <img src=$config->{MAGNIFY_GLASS} />
	      <a href="#" onClick="window.open('$config->{MARKETPLACE_VIEW_ITEM}?submitShowLargeImage=1&id=$picture->{item}','LargeView','left=20,top=20,width=725,height=650,toolbar=0,location=0,menubar=0,resizable=1'); return false;">View Larger</a>
~;
last;
}
print qq~
	  </td>
	  <td valign="top">
	    <b>Seller :</b> <a href="$config->{MARKETPLACE_VIEW_SELLER}?id=$item->{seller}">$item->{seller_name}</a><br>
	      <b>Category :</b> $item->{categoryNames}<br>
		<b>HBCU :</b> $item->{hbcu}<br>
		  <b>Price :</b> $item->{price}<br>
		    <b>Item Views :</b> $item->{hits}<br><br>
		      <input type="submit" name="submitGotoPurchase" value="Buy Now!" />
	  </td>
	  <td height="100%" width="1">
	    <table background=$config->{VSEP} width="1" height="100%" cellspacing="0" cellpadding="0"><tr><td></td></tr></table></td>
	  <td valign="top" width=125 align=center>
~;
  if ($item->{totalReviews}) {
    foreach my $star (@{ $item->{stars} }) {
      print "<img src=$star->{star} />";
    }
    print "<br>\n";
  } else {
    print "No Ratings<br>\n";
  }
  print "Average User Rating<br>\n";

  if ($item->{totalReviews}) {
    print "<a href=\"$config->{MARKETPLACE_ITEM_REVIEW}?item=$item->{id}&showReviews=1\">Read $item->{totalReviews} Reviews</a><br>\n";
  }
print qq~
		  <a href="$config->{MARKETPLACE_ITEM_REVIEW}?item=$item->{id}">Write a Review</a><br>
	  </td>
	</tr>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th>Product Description</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    $item->{description}
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th>Payment Methods</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
~;
  if ($item->{visa}) { print "<img src=$config->{VISA} />&nbsp;&nbsp;\n"; }
  if ($item->{mastercard}) { print "<img src=$config->{MASTERCARD} />&nbsp;&nbsp;\n"; }
  if ($item->{amex}) { print "<img src=$config->{AMEX} />&nbsp;&nbsp;\n"; }
  if ($item->{discover}) { print "<img src=$config->{DISCOVER} />&nbsp;&nbsp;\n"; }
  if ($item->{paypal}) { print "<img src=$config->{PAYPAL} />&nbsp;&nbsp;\n"; }
  print "<br><br>\n";
  if ($item->{checks}) { print "Personal Check<br><br>\n"; }
  if ($item->{money_order}) { print "Money Order / Cashier's Check<br><br>\n"; }
  if ($item->{other}) { print "Other / See Payment Instructions<br><br>\n"; }
print qq~
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th>Payment Instructions</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    $item->{instructions}
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th>Return Policy</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
~;
  if ($item->{accepted}) {
print qq~
	      Returns Accepted<br>
	      Items must be returned within: $item->{grace}<br>
		Refunds will be dispensed in the form of: $item->{type}<br>

~;
if ($item->{policy}) {
  print "<b>Return Policy:</b> $item->{policy}\n";
} else {
  print "Returns not accepted\n";
}
}
print qq~
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <div align=center>
      <input type="submit" name="submitGotoPurchase" value="Buy Now!" />
    </div>
    <br>
</form>
~;

  printFooter($q);
}

###############################################################################
sub printViewSeller {
  my ($q, $seller) = @_;

  printHeader($q);

  if (&isAdmin()) {
print qq~
      <br>
      <div align=center>
~;
if ($seller->{featured}) {
  print "<img src=$config->{ADD} />&nbsp;<a href=\"$config->{MARKETPLACE_VIEW_SELLER}?unfeatureSeller=1&id=$seller->{id}\">Remove From Featured Sellers</a>\n";
} else {
  print "<img src=$config->{ADD} />&nbsp;<a href=\"$config->{MARKETPLACE_VIEW_SELLER}?featureSeller=1&id=$seller->{id}\">Add to Featured Sellers</a>\n";
}
print qq~
      </div>
~;
}
print qq~
    <br>
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=3>$seller->{name}</th>
	</tr>
      </thead>
      <form name="formx" method="post" action="$config->{MARKETPLACE_VIEW_ITEM}" enctype="multipart/form-data">
	<input type="hidden" name="id" value="$seller->{id}" />
      <tbody>
	<tr>
	  <td valign="top">
	    <b>Category :</b> $seller->{categoryNames}<br>
	      <b>HBCU :</b> $seller->{hbcu}<br>
		<b>Seller's Website :</b> <a href="$seller->{website_url}">$seller->{website_url}</a>
	  </td>
	  <td height="100%" width="1">
	    <table background=$config->{VSEP} width="1" height="100%" cellspacing="0" cellpadding="0"><tr><td></td></tr></table></td>
	  <td valign="top" width=125 align=center>
~;
  if ($seller->{totalReviews}) {
    foreach my $star ( @{ $seller->{stars} }) {
      print "<img src=$config->{STAR} />";
    }
    print "<br>\n";
  } else {
    print "No Ratings<br>\n";
  }
  print "Average User Rating<br>\n";

  if ($seller->{totalReviews}) {
    print "<a href=\"$config->{MARKETPLACE_SELLER_REVIEW}?item=$seller->{id}&showReviews=1\">Read $seller->{totalReviews} Reviews</a><br>\n";
  }
print qq~
	  </td>
	</tr>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th>Seller Description</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
	    $seller->{description}
	  </td>
	</tr>
      </tbody>
    </table>
    <br>

    <table class=data width=100%>
      <thead>
	<tr>
	  <th>Popular Items</th>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td>
~;
  printGridItems($q, $seller->{records});
print qq~

	  </td>
	</tr>
      </tbody>
    </table>
    <div align=right>
      <a href=$config->{MARKETPLACE_SEARCH}?submitSearch=1&seller_id=$seller->{id}>More Items--></a>
    </div>
    <br>

</td>
<td valign=top>
~;

  printSellerItemCategories($q, $seller);

  printFooter($q);
}

################################################################################
sub printWelcomeGuest {
  my ($q) = @_;

print qq~
<table class=data style="width: 175;">
  <tr>
    <th><div align=left>&nbsp;Welcome, Guest</div></th>
  </tr>
  <tbody>
    <tr><td></td></tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MAIN}">Marketplace Home</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_SEARCH}">Advanced Search</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_MERCHANT_INFO}">Create Your Store</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="#" onClick="window.open('$config->{MARKETPLACE_CONTACT_US}','$config->{DOMAIN}','width=550,height=500,toolbar,resizable');">Ask a Quick Question</a>
      </td>
    </tr>
    <tr><td></td></tr>
  </tbody>
</table>
<br />
~;
}

################################################################################
########################## END HTML FUNCTIONS ##################################
################################################################################

################################################################################
############################ DB FUNCTIONS ######################################
################################################################################
sub addItemPicture {
  my ($q, $params) = @_;

  my $id = $db->addPicture($params);

  my $fu = HBCU::FileUpload->new();
  return unless $fu->download_image($q->param('filename'), "$config->{MARKETPLACE_PHOTO_ROOT}/$id", $q);

  $db->updatePicture(WHERE => "id => $id",
		     PARAMS => {path => "$config->{MARKETPLACE_PHOTO_URL}/$id"});

  return 1;
}

################################################################################
sub addItemReview {
  my ($params) = @_;

  return $db->addReview($params);
}

################################################################################
sub addPurchase {
  my ($params) = @_;

  return $db->addPurchase($params);
}

################################################################################
sub addSavedItem {
  my ($id, $reg_id) = @_;

  $db->addSavedItem({item => $id, registry_id => $reg_id});
}

################################################################################
sub addSeller {
  my ($params) = @_;

  return $db->addSeller($params);
}


################################################################################
sub deactivateItem {
  my ($id) = @_;

  $db->updateItem(WHERE => "id => $id", PARAMS => {activated => 0});
}

################################################################################
sub deleteItem {
  my ($id) = @_;

  $db->updateItem(WHERE => "id = $id", PARAMS => {deleted => 1});
}

################################################################################
sub deleteSavedItem {
  my ($reg_id, $id) = @_;

  $db->deleteSavedItem(WHERE => "registry_id = $reg_id AND item = $id");
}

################################################################################
sub deleteSavedSearch {
  my ($id) = @_;

  $db->deleteSavedSearch(WHERE => "id = $id");
}

################################################################################
sub deleteItemPicture {
  my ($id) = @_;

  $db->deletePicture(WHERE = "id = $id");
}

################################################################################
sub getCategories {
  print STDERR "sub 1\n";
  return map {
    print STDERR "before\n";
    my @subs = $db->getCategories(WHERE => {parent => $_->{id}},
				  ORDER => 'name');
    print STDERR "after\n";
    for (my $i = 0; $i < scalar(@subs) - 1; $i++) {
      $subs[$i]->{comma} = 1;
    }
    $_->{subcategories} = \@subs;
    $_->{item_count} = $db->getCategoryItemCount($_->{id});
    $_;
  } $db->getCategories(WHERE => {parent => 0}, ORDER => 'name');
}

################################################################################
sub getFeaturedItems {
  my @recs = map {
    my $picture = $db->getMainPicture($_->{id});

    $_->{path} = $picture->{path};
    $_->{price} = sprintf("\$%.2f", $_->{price});
    $_->{hbcu} ||= 'All HBCUs';
    $_;
  } $db->getItems(WHERE => {featured => 1});

  my @records = ();
  for (my $i = 0; $i <= $#recs; $i++) {
    my @array = ();
    push @array, $recs[$i++];

    unless ($i > $#recs) {
      push @array, $recs[$i++];
    }

    unless ($i > $#recs) {
      push @array, $recs[$i++];
    }

    unless ($i > $#recs) {
      push @array, $recs[$i];
    }

    push @records, {columns => \@array};
  }

  return @records;
}

################################################################################
sub getItem {
  my ($id) = @_;
  my $item = $db->getItem("id = $id");

  return unless $item;

  my @cats = map {
    $db->getCategory("id = $_")->{name};
  } split(/:/, $item->{categories});

  $item->{item_id} = $item->{id};
  $item->{categoryNames} = join(', ', @cats);
  $item->{price} = sprintf("\$%.2f", $item->{price});
  $item->{hbcu} ||= 'All HBCUs';
  $item->{hits} ||= 0;
  $item->{seller_name} = getSeller(id => $item->{seller})->{name};
  $item->{"grace_$item->{grace}"} = 1 if defined $item->{grace};
  $item->{"$item->{type}"} = 1 if defined $item->{type};

  my @pictures = $db->getPicture("item = $item->{id}");

  $item->{pictures} = \@pictures if @pictures;

  $item->{numPictures} = scalar( @{ $item->{pictures} } ) || 0;

  @{ $item->{reviews} } = map {
    $_->{review_id} = $_->{id};
    $_->{useful} ||= 0;
    $_->{not_useful} ||= 0;
    $_->{registry_data} = $hdb->getRegistryData("registry_id = $_->{registry_id}");
    $_->{registry_name} = $_->{registry_data}->{name};

    for (my $i = 0; $i < $_->{rating}; $i++) {
      push @{$_->{stars}}, {star => $config->{STAR}};
    }
    for (my $i = 0; $i < (5 - $_->{rating}); $i++) {
      push @{$_->{stars}}, {star => $config->{BLANK_STAR}};
    }

    $_;
  } $db->getReviews(WHERE => "item = $item->{id}");

  $item->{totalReviews} = scalar(@{ $item->{reviews} });
  $item->{averageReview} = getItemReviewAverage($item->{id});

  if ($item->{averageReview}) {
    for (my $i = 0; $i < $item->{averageReview}; $i++) {
      push @{$item->{stars}}, {star => $config->{STAR}};
    }
    for (my $i = 0; $i < (5 - $item->{averageReview}); $i++) {
      push @{$item->{stars}}, {star => $config->{BLANK_STAR}};
    }
  }

  return $item;
}

#CAUTIONd########################################################################
sub getItemReviewAverage {
  my ($id) = @_;
  my $sth = $db->dbh->prepare(q(
SELECT round(avg(rating)) As num
  FROM review
 WHERE item = ?
));

  $sth->execute($id);

  my $row = $sth->fetchrow_hashref();

  $sth->finish();

  return $row->{num};
}

#CAUTION#########################################################################
sub getMyItemsForSale {
  my ($params) = @_;
  ###
  # We need:
  # - current_page
  # - previous_page
  # - next_page
  # - start_record
  # - end_record
  # - total_records
  # - records
  # - order_by
  ###
  my %hash = (
	      items_for_sale_start_record => ($params->{items_for_sale_current_page} - 1) * $params->{items_for_sale_max_records},
	      items_for_sale_current_page => $params->{items_for_sale_current_page},
	      items_for_sale_order_by => $params->{items_for_sale_order_by},
	      items_for_sale_url => $params->{items_for_sale_url},
	      items_for_sale_max_records => $params->{items_for_sale_max_records}
	    );

  my $sth = $db->dbh->prepare(qq(
SELECT i.id As id
      ,i.title As title
      ,i.hits As hits
      ,i.activated As activated
      ,unix_timestamp(i.date_expires) As date_expires
      ,unix_timestamp( now() ) As crt_date
  FROM item As i
 WHERE i.seller = ?
   AND deleted != 1
));
  my $sth3 = $db->dbh->prepare(q(
SELECT count(*) As num
  FROM purchase
 WHERE item = ?
));

  $sth->execute($params->{id});

  my @rows = ();
  my $i = 0;

  while(my $row = $sth->fetchrow_hashref()) {
    $sth3->execute($row->{id});
    my $row3 = $sth3->fetchrow_hashref();
    $row->{num_sold} = $row3->{num};

    $row->{status} = $row->{activated} ? 'Active' : 'Not Active';

    $row->{hits} ||= 0;

    ### Uncomment this when we start to care about item expiration
    ###$row->{status} = 'Expired' if $row->{date_expires} <= $row->{crt_date};

    $row->{__even__} = $i;
    $i = ($i == 0) ? 1 : 0;
    push @rows, $row;
  }

  $sth->finish();

  if ($hash{'items_for_sale_order_by'} eq 'hits') {
    @rows = sort { $a->{hits} <=> $b->{hits} } @rows;
    my $i = 0;
    @rows = map {
      $_->{__even__} = $i;
      $i = ($i == 0) ? 1 : 0;
      $_;
    } @rows;
  } elsif ($hash{'items_for_sale_order_by'} eq 'num_sold') {
    @rows = sort { $a->{num_sold} cmp $b->{num_sold} } @rows;
    my $i = 0;
    @rows = map {
      $_->{__even__} = $i;
      $i = ($i == 0) ? 1 : 0;
      $_;
    } @rows;
  } elsif ($hash{'items_for_sale_order_by'} eq 'status') {
    @rows = sort { $a->{status} cmp $b->{status} } @rows;
    my $i = 0;
    @rows = map {
      $_->{__even__} = $i;
      $i = ($i == 0) ? 1 : 0;
      $_;
    } @rows;
  } elsif ($hash{'items_for_sale_order_by'} eq 'title') {
    @rows = sort { $a->{title} cmp $b->{title} } @rows;
    my $i = 0;
    @rows = map {
      $_->{__even__} = $i;
      $i = ($i == 0) ? 1 : 0;
      $_;
    } @rows;
  }

  $hash{'items_for_sale_total_records'} = scalar(@rows);

  $hash{'items_for_sale_start_record'} =
    ($hash{'items_for_sale_current_page'} - 1) * $params->{items_for_sale_max_records} + 1;

  my $max = ($hash{'items_for_sale_max_records'} < scalar(@rows)) ?
    $hash{'items_for_sale_max_records'} : scalar(@rows);

  @rows = splice(@rows, (($hash{'items_for_sale_current_page'} - 1) * ($hash{'items_for_sale_max_records'} + 0)), $max);

  $hash{'items_for_sale_end_record'} =
    scalar(@rows) + ($hash{'items_for_sale_current_page'} - 1) * $params->{items_for_sale_max_records};

  $hash{'items_for_sale_previous_page'} = $hash{'items_for_sale_current_page'} - 1
    unless $hash{'items_for_sale_current_page'} == 1;
  $hash{'items_for_sale_next_page'} = $hash{'items_for_sale_current_page'} + 1
    if ($hash{'items_for_sale_total_records'} - $hash{'items_for_sale_end_record'}) > 0;

  $hash{'items_for_sale_records'} = \@rows;

  return \%hash;
}

################################################################################
sub getMyPurchasedItems {
  my ($params) = @_;

  ###
  # We need:
  # - current_page
  # - previous_page
  # - next_page
  # - start_record
  # - end_record
  # - total_records
  # - records
  # - order_by
  ###
  my %hash = (
	      purchased_items_start_record => ($params->{purchased_items_current_page} - 1) * $params->{purchased_items_max_records},
	      purchased_items_current_page => $params->{purchased_items_current_page},
	      purchased_items_order_by => $params->{purchased_items_order_by},
	      purchased_items_url => $params->{purchased_items_url},
	      purchased_items_max_records => $params->{purchased_items_max_records}
	    );

  my $sth = $db->dbh->prepare(qq(
SELECT *
  FROM purchase
 WHERE buyer = ?
 ORDER
    BY $hash{'purchased_items_order_by'}
));
  $sth->execute($params->{id});

  my @rows = ();
  my $i = 0;

  while(my $row = $sth->fetchrow_hashref()) {
    my $rec = $db->getSeller("id = $row->{seller}");
    $row->{seller_name} = $rec->{name};
    $row->{total} = sprintf("\$%.2f", $row->{total});

    my @t = split /\s/, $row->{date_created};
    $row->{date_created} = $t[0];

    $row->{__even__} = $i;
    $i = ($i == 0) ? 1 : 0;
    push @rows, $row;
  }

  $sth->finish();

  if ($hash{'purchased_items_order_by'} eq 'seller') {
    @rows = sort { $a->{seller_name} cmp $b->{seller_name} } @rows;
    my $i = 0;
    @rows = map {
      $_->{__even__} = $i;
      $i = ($i == 0) ? 1 : 0;
      $_;
    } @rows;
  }

  $hash{'purchased_items_total_records'} = scalar(@rows);

  $hash{'purchased_items_start_record'} =
    ($hash{'purchased_items_current_page'} - 1) * $params->{purchased_items_max_records} + 1;

  my $max = ($hash{'purchased_items_max_records'} < scalar(@rows)) ?
    $hash{'purchased_items_max_records'} : scalar(@rows);

  @rows = splice(@rows, (($hash{'purchased_items_current_page'} - 1) * ($hash{'purchased_items_max_records'} + 0)), $max);

  $hash{'purchased_items_end_record'} =
    scalar(@rows) + ($hash{'purchased_items_current_page'} - 1) * $params->{purchased_items_max_records};

  $hash{'purchased_items_previous_page'} = $hash{'purchased_items_current_page'} - 1
    unless $hash{'purchased_items_current_page'} == 1;
  $hash{'purchased_items_next_page'} = $hash{'purchased_items_current_page'} + 1
    if ($hash{'purchased_items_total_records'} - $hash{'purchased_items_end_record'}) > 0;

  $hash{'purchased_items_records'} = \@rows;

  return \%hash;
}

################################################################################
sub getMySavedItems {
  my ($params) = @_;
  ###
  # We need:
  # - current_page
  # - previous_page
  # - next_page
  # - start_record
  # - end_record
  # - total_records
  # - records
  # - order_by
  ###
  my %hash = (
	      saved_items_start_record => ($params->{saved_items_current_page} - 1) * $params->{saved_items_max_records},
	      saved_items_current_page => $params->{saved_items_current_page},
	      saved_items_order_by => $params->{saved_items_order_by},
	      saved_items_url => $params->{saved_items_url},
	      saved_items_max_records => $params->{saved_items_max_records}
	    );

  my $sth = $db->dbh->prepare(qq(
SELECT s.item As item
      ,i.date_expires As date
      ,i.id As id
      ,i.title As title
      ,i.price As price
      ,i.seller As seller
      ,unix_timestamp(i.date_expires) As date_expires
      ,unix_timestamp( now() ) As crt_date
  FROM saved_item As s
      ,item As i
 WHERE s.registry_id = ?
   AND s.item = i.id
 ORDER
    BY $hash{'saved_items_order_by'}
));
  $sth->execute($params->{id});

  my @rows = ();
  my $i = 0;

  while(my $row = $sth->fetchrow_hashref()) {
    my $rec = $db->getSeller("id = $row->{seller}");
    my $picture = $db->getMainPicture($row->{id});
    $row->{$_} = $picture->{$_} for qw(
				       path
				       caption
				      );
    $row->{seller_name} = $rec->{name};
    $row->{price} = sprintf("\$%.2f", $row->{price});

    if ($row->{date}) {
      my @date = split /\s/, $row->{date};
      $row->{date} = $date[0];
    }

    if ((defined $row->{date_expires}) &&
	(defined $row->{crt_date}) &&
	$row->{date_expires} <= $row->{crt_date}) {
      $row->{expired} = 1;
    }

    $row->{__even__} = $i;
    $i = ($i == 0) ? 1 : 0;
    push @rows, $row;
  }

  $sth->finish();

  if ($hash{'saved_items_order_by'} eq 'seller') {
    @rows = sort { $a->{seller_name} cmp $b->{seller_name} } @rows;
    my $i = 0;
    @rows = map {
      $_->{__even__} = $i;
      $i = ($i == 0) ? 1 : 0;
      $_;
    } @rows;
  }

  $hash{'saved_items_total_records'} = scalar(@rows);

  $hash{'saved_items_start_record'} =
    ($hash{'saved_items_current_page'} - 1) * $params->{saved_items_max_records} + 1;

  my $max = ($hash{'saved_items_max_records'} < scalar(@rows)) ?
    $hash{'saved_items_max_records'} : scalar(@rows);

  @rows = splice(@rows, (($hash{'saved_items_current_page'} - 1) * ($hash{'saved_items_max_records'} + 0)), $max);

  $hash{'saved_items_end_record'} =
    scalar(@rows) + ($hash{'saved_items_current_page'} - 1) * $params->{saved_items_max_records};

  $hash{'saved_items_previous_page'} = $hash{'saved_items_current_page'} - 1
    unless $hash{'saved_items_current_page'} == 1;
  $hash{'saved_items_next_page'} = $hash{'saved_items_current_page'} + 1
    if ($hash{'saved_items_total_records'} - $hash{'saved_items_end_record'}) > 0;

  $hash{'saved_items_records'} = \@rows;

  return \%hash;
}

################################################################################
sub getMySavedSearches {
  my ($params) = @_;
  ###
  # We need:
  # - current_page
  # - previous_page
  # - next_page
  # - start_record
  # - end_record
  # - total_records
  # - records
  # - order_by
  ###
  my %hash = (
	      saved_searches_start_record => ($params->{saved_searches_current_page} - 1) * $params->{saved_searches_max_records},
	      saved_searches_current_page => $params->{saved_searches_current_page},
	      saved_searches_order_by => $params->{saved_searches_order_by},
	      saved_searches_url => $params->{saved_searches_url},
	      saved_searches_max_records => $params->{saved_searches_max_records}
	    );

  my $sth = $db->dbh->prepare(qq(
SELECT *
  FROM saved_search
 WHERE registry_id = ?
   AND name is not null
 ORDER
    BY $hash{'saved_searches_order_by'}
));
  $sth->execute($params->{id});

  my @rows = ();
  my $i = 0;

  while(my $row = $sth->fetchrow_hashref()) {
    $row->{__even__} = $i;
    $i = ($i == 0) ? 1 : 0;
    push @rows, $row;
  }

  $sth->finish();

  $hash{'saved_searches_total_records'} = scalar(@rows);

  $hash{'saved_searches_start_record'} =
    ($hash{'saved_searches_current_page'} - 1) * $params->{saved_searches_max_records} + 1;

  my $max = ($hash{'saved_searches_max_records'} < scalar(@rows)) ?
    $hash{'saved_searches_max_records'} : scalar(@rows);

  @rows = splice(@rows, (($hash{'saved_searches_current_page'} - 1) * ($hash{'saved_searches_max_records'} + 0)), $max);

  $hash{'saved_searches_end_record'} =
    scalar(@rows) + ($hash{'saved_searches_current_page'} - 1) * $params->{saved_searches_max_records};

  $hash{'saved_searches_previous_page'} = $hash{'saved_searches_current_page'} - 1
    unless $hash{'saved_searches_current_page'} == 1;
  $hash{'saved_searches_next_page'} = $hash{'saved_searches_current_page'} + 1
    if ($hash{'saved_searches_total_records'} - $hash{'saved_searches_end_record'}) > 0;

  $hash{'saved_searches_records'} = \@rows;

  return \%hash;
}

################################################################################
sub getPurchase {
  my ($id) = @_;

  my $purchase = $db->getPurchase("id = $id");

  return unless $purchase;

  $purchase->{price} = sprintf("\$%.2f", $purchase->{price});
  $purchase->{total} = sprintf("\$%.2f", $purchase->{total});

  $purchase->{item} = getItem($purchase->{item});
  $purchase->{seller} = getSeller(id => $purchase->{seller});
  $purchase->{buyer} = $hdb->getRegistryData("registry_id = $purchase->{buyer}");

  return $purchase;
}

################################################################################
sub getSeller {
  my ($field, $id) = @_;

  my $seller = $db->getSeller("$field = $id");

  return unless $seller;

  my @cats = map {
    $db->getCategory("id = $_")->{name};
  } split(/:/, $seller->{categories});

  $seller->{seller_id} = $seller->{id};
  $seller->{categoryNames} = join(', ', @cats);
  $seller->{hbcu} ||= 'All HBCUs';
  $seller->{"grace_$seller->{grace}"} = 1;
  $seller->{"$seller->{type}"} = 1;
  $seller->{website_url} = 'http://' . $seller->{website_url}
    unless $seller->{website_url} =~ /^http\:\/\//;

  @{ $seller->{reviews} } = map {
    $_->{useful} ||= 0;
    $_->{not_useful} ||= 0;
    $_->{registry_data} = $hdb->getRegistryData("registry_id = $_->{registry_id}");
    for (my $i = 0; $i < $_->{rating}; $i++) {
      push @{$_->{stars}}, {star => $config->{STAR}};
    }
    for (my $i = 0; $i < (5 - $_->{rating}); $i++) {
      push @{$_->{stars}}, {star => $config->{BLANK_STAR}};
    }

    $_;
  } $db->getReviews(WHERE => "seller = $seller->{id}");

  $seller->{totalReviews} = scalar(@{ $seller->{reviews} });
  $seller->{averageReview} = getSellerReviewAverage($seller->{id});

  $seller->{records} = getSellerPopularItems($seller->{id});
  $seller->{itemCategories} = getSellerItemCategories($seller->{id});

  return $seller;
}

################################################################################
sub getSellerItemCategories {
  my ($seller) = @_;

  my @records = map {
    my @subs = $db->getCategories(WHERE => {parent => $_->{id}}, ORDER => 'name');

    for (my $i = 0; $i < scalar(@subs) - 1; $i++) {
      $subs[$i]->{comma} = 1;
    }
    $_->{subcategories} = \@subs;
    $_->{item_count} = getSellerCategoryItemCount($seller, $_->{id});
    $_;
  } $db->getCategories(WHERE => {parent => 0}, ORDER => 'name');

  return \@records;
}

################################################################################
sub getSellerCategoryItemCount {
  my ($seller, $id) = @_;

  my $sth = $db->dbh->prepare(q(
SELECT count(*) As num
  FROM item
 WHERE deleted != 1
   AND activated = 1
   AND seller = ?
   AND (categories = ?
    OR categories like '%:?:%'
    OR categories like '%:?'
    OR categories like '?:%')
));

  $sth->execute($seller, $id);

  my $row = $sth->fetchrow_hashref();

  $sth->finish();

  return $row->{num};
}

################################################################################
sub getSellerReviewAverage {
  my ($id) = @_;
  my $sth = $db->dbh->prepare(q(
SELECT avg(rating) As num
  FROM review
 WHERE seller = ?
));

  $sth->execute($id);

  my $row = $sth->fetchrow_hashref();

  $sth->finish();

  return $row->{num};
}

################################################################################
sub getSellerPopularItems {
  my ($id) = @_;
  my $sth = $db->dbh->prepare(q(
SELECT i.id As id
      ,i.title As title
      ,i.price As price
  FROM item As i
 WHERE seller = ?
 ORDER
    BY hits desc
 LIMIT 0, 12
));

  my @recs = ();

  $sth->execute($id);

  while (my $row = $sth->fetchrow_hashref()) {
    my $picture = $db->getMainPicture($row->{id});

    $row->{path} = $picture->{path};
    $row->{price} = sprintf("\$%.2f", $row->{price});
    $row->{hbcu} ||= 'All HBCUs';
    push @recs, $row;
  }

  my @records = ();
  for (my $i = 0; $i <= $#recs; $i++) {
    my @array = ();
    push @array, $recs[$i++];

    unless ($i > $#recs) {
      push @array, $recs[$i++];
    }

    unless ($i > $#recs) {
      push @array, $recs[$i];
    }

    push @records, {columns => \@array};
  }

  return \@records;
}

################################################################################
sub isSavedItem {
  my ($id, $reg_id) = @_;

  return $db->getSavedItem("item = $id AND registry_id = $reg_id");
}

################################################################################
sub isSiteMember {
  my ($email) = @_;

  return $hdb->getRegistryData("email = $email");
}

################################################################################
sub logItemHit {
  my ($id) = @_;

  my $item = getItem( $id );

  updateItem($item->{id}, {hits => ($item->{hits} + 1)});
}

################################################################################
sub processSavedSearch {
  my ($q) = @_;

  my $searchInfo = {
		    active => 1
		   };
  my $search = $db->getSavedSearch("id = " . $q->param('id'));
  my %params = ();

  $searchInfo->{page} = $q->param('page') || 1;
  $searchInfo->{view} = $q->param('grid_view') || 0;
  $searchInfo->{order} = $q->param('order_by') || 'asc';

  foreach my $kv (split /\;/, $search->{params}) {
    my @kv = split /:/, $kv;
    $params{$kv[0]} = $kv[1];
  }

  $searchInfo->{params} = \%params;

  return searchItems( $searchInfo );
}

################################################################################
sub processSearch {
  my ($q) = @_;

  my %searchInfo;
  my %params;

  $searchInfo{'page'} = $q->param('page') || 1;
  $searchInfo{'max_records'} = $maxRecords;

  ### Admin parameters
  if ($q->param('status')) {
    $params{'deleted'} = 1 if $q->param('status') eq 'deleted';
    if ($q->param('status') eq 'activated') {
      $params{'activated'} = 1;
    } else {
      $params{'activated'} = 0;
    }
  }
  ### End Admin parameters

  $params{$_} = $q->param($_) for qw(
				     keywords
				     title_and_description
				     hbcu
				     category
				     min_price
				     max_price
				     sellers
				     seller_id
				    );
  $searchInfo{'criteria'} = \%params;

  # Save the search if necessary
  &saveSearch($q->cookie('ID'), $q->param('search_name'), $searchInfo{'criteria'})
    if $q->param('saveSearch');

  my $search = search(\%searchInfo);

  @{ $search->{records} } = map {
    my $row = $_;
    my $picture = $db->getMainPicture($row->{id});
    $row->{path} = $picture->{path};
    $row->{caption} = $picture->{caption};

    my $sth3 = $db->dbh->prepare("SELECT count(*) As num FROM purchase WHERE item = ?");
    $sth3->execute($row->{id});
    my $row3 = $sth3->fetchrow_hashref();
    $row->{num_sold} = $row3->{num};

    # Handle the status
    if ($row->{deleted}) {
      $row->{status} = 'Deleted';
    } else {
      $row->{status} = $row->{activated} ? 'Activated' : 'Deactivated';
    }

    $row->{hits} ||= 0;
    $row;
  } @{ $search->{records} };

  # Handle any sorting
  $search->{order_by} = $q->param('order_by') || 'price';
  if ($search->{order_by} eq 'title' ||
      $search->{order_by} eq 'status') {
    @{ $search->{records} } = sort { $b->{$search->{order_by}} cmp $a->{$search->{order_by}} } @{ $search->{records} };
  } else {
    @{ $search->{records} } = sort { $b->{$search->{order_by}} <=> $a->{$search->{order_by}} } @{ $search->{records} };
  }


  # Handle the view
  if ($q->param('grid_view')) {
    $search->{view} = 1;

    my @records = ();
    my $numRecords = scalar(@{ $search->{records} }) - 1;
    for (my $i = 0; $i <= $numRecords; $i++) {
      my @array = ();
      push @array, $search->{records}->[$i++];
      unless ($i > $numRecords) {
	push @array, $search->{records}->[$i++];
      }
      unless ($i > $numRecords) {
	push @array, $search->{records}->[$i];
      }
      push @records, {columns => \@array};
    }
    $search->{records} = \@records;
  }

  return $search;
}

################################################################################
sub saveSearch {
  my ($reg_id, $name, $params) = @_;
  my %params = ();

  $params{registry_id} = $reg_id;
  $params{name} = $name;

  $params{params} .= "$_:$params->{$_};" for keys %$params;

  $db->insert({TABLE => 'saved_search', PARAMS => \%params});
}

################################################################################
### Here we can have the following parameters:
### - criteria
### - start_record
### - max_records
### - order_by
###
### We return a reference to an array of hash references
###
################################################################################
sub buildSearchSql {
  my ($params) = @_;
  my $sql = "SELECT i.id As id, i.title As title, concat(substring(i.description, 1, 200), '...') As description, format(i.price, 2) As price, i.deleted As deleted, i.activated As activated, s.id As seller, s.name As seller_name, if(locate('http://', s.website_url), s.website_url, concat('http://', s.website_url)) As website_url FROM item As i LEFT JOIN seller As s ON i.seller = s.id WHERE ";

  if ($params->{criteria}->{deleted}) {
    $sql .= 'i.deleted = 1 ';
  } else {
    $sql .= 'i.deleted != 1 ';

    if (defined $params->{criteria}->{activated}) {
      if ($params->{criteria}->{activated} == 1) {
	$sql .= 'AND i.activated = 1 ';
      } else {
	$sql .= 'AND i.activated = 0 ';
      }
    }
  }

  foreach my $kw ( split(/\s+/, $params->{criteria}->{keywords}) ) {
    if ( $params->{criteria}->{title_and_description} ) {
      $sql .= "AND ((i.title like '%$kw%') OR (i.description like '%$kw%')) ";
    } else {
      $sql .= "AND (i.title like '%$kw%') ";
    }
  }

  $sql .= "AND ((i.hbcu = '$params->{criteria}->{hbcu}') OR (i.title like '%$params->{criteria}->{hbcu}%') OR (i.description like '%$params->{criteria}->{hbcu}%')) " if $params->{criteria}->{hbcu};

  if ($params->{criteria}->{category}) {
    $sql .= 'AND (';
    $sql .= "i.categories = $params->{criteria}->{category} ";
    $sql .= "OR i.categories like '$params->{criteria}->{category}:%' ";
    $sql .= "OR i.categories like '%:$params->{criteria}->{category}' ";
    $sql .= ") ";
  }

  $sql .= "AND i.price >= $params->{criteria}->{min_price} " if $params->{criteria}->{min_price};
  $sql .= "AND i.price <= $params->{criteria}->{max_price} " if $params->{criteria}->{max_price};
  $sql .= "AND s.name like '%$params->{criteria}->{sellers}%' " if $params->{criteria}->{sellers};
  $sql .= "AND s.id like '%$params->{criteria}->{seller_id}%' " if $params->{criteria}->{seller_id};

  $sql .= " ORDER BY $params->{order_by} " if defined $params->{order_by};

  $sql .= "LIMIT $params->{start_record}, $params->{max_records}";

  ###print STDERR "search_sql = $sql\n";

  return $sql;
}

################################################################################
sub getSearchTotalRecordCount {
  my ($sql) = @_;

  $sql =~ s/^.*FROM/SELECT\ COUNT\(\*\)\ FROM/g;
  $sql =~ s/LIMIT.*$//g;

  return $db->execute($sql)->{'COUNT(*)'};
}

################################################################################
### Here we can have the following parameters:
### - criteria
### - page
### - max_records
### - order_by
###
### We return the following IN ADDITION TOO the parameters passed in:
### - sql
### - records
### - start_record
### - end_record
### - total_records
### - previous_page
### - next_page
###
################################################################################
sub search {
  my ($params) = @_;
  my ($sql, $records);
  my %search;

  # 1.) Build the sql
  my %vars = (criteria => $params->{criteria},
	      start_record => (($params->{page} - 1) * $params->{max_records}),
	      max_records => $params->{max_records},
	      order_by => $params->{order_by});
  $sql = buildSearchSql(\%vars);

  # 2.) Perform the search
  $search{'sql'} = $sql;
  my @records = $db->execute($sql);
  $search{'records'} = \@records;
  $search{'total_records'} = getSearchTotalRecordCount($sql);

  # 3.) Prepare return data
  $search{$_} = $params->{$_} for qw(
				     page
				     max_records
				     order_by
				    );

  push @{$search{'criteria'}}, {name => $_, value => $params->{criteria}->{$_}}
    for keys %{$params->{criteria}};

  $search{'start_record'} = (($search{'page'} - 1) * $search{'max_records'}) + 1;
  $search{'end_record'} =
    scalar(@{ $search{'records'} }) + (($search{'page'} - 1) * $search{'max_records'});
  $search{'previous_page'} = $search{'page'} - 1 if $search{'page'} != 1;
  $search{'next_page'} = $search{'page'} + 1
    if ($search{'total_records'} - $search{'end_record'}) > 0;

  return \%search;
}

################################################################################
sub searchItems {
  my ($searchInfo) = @_;
  my $search_info = {};

  push @{$search_info->{params}}, {name => $_, value => $searchInfo->{params}->{$_}}
    for keys %{$searchInfo->{params}};

  my $start = (($searchInfo->{page} - 1) * $maxRecords);
  my $csql = q(SELECT count(*) As num FROM item As i LEFT JOIN seller As s ON i.seller = s.id WHERE );
  my $sql = q(SELECT i.id As id, i.title As title, concat(substring(i.description, 1, 200), '...') As description, concat('\$', format(i.price, 2)) As price, s.id As seller, s.name As seller_name, if(locate('http://', s.website_url), s.website_url, concat('http://', s.website_url)) As website_url FROM item As i LEFT JOIN seller As s ON i.seller = s.id WHERE );

  my $sth3 = $db->dbh->prepare(q(SELECT count(*) As num FROM purchase WHERE item = ?));

  if ($searchInfo->{params}->{deleted}) {
    $csql .= 'i.deleted = 1 ';
    $sql .= 'i.deleted = 1 ';
  } else {
    $csql .= 'i.deleted != 1 ';
    $sql .= 'i.deleted != 1 ';

    if (defined $searchInfo->{params}->{activated}) {
      if ($searchInfo->{params}->{activated} == 1) {
	$csql .= 'AND i.activated = 1 ';
	$sql .= 'AND i.activated = 1 ';
      } else {
	$sql .= 'AND i.activated = 0 ';
	$csql .= 'AND i.activated = 0 ';
      }
    }
  }

  foreach my $kw ( split(/\s+/, $searchInfo->{params}->{keywords}) ) {
    if ( $searchInfo->{params}->{title_and_description} ) {
      $sql .= "AND ((i.title like '%$kw%') OR (i.description like '%$kw%')) ";
      $csql .= "AND ((i.title like '%$kw%') OR (i.description like '%$kw%')) ";
    } else {
      $sql .= "AND (i.title like '%$kw%') ";
      $csql .= "AND (i.title like '%$kw%') ";
    }
  }

  $sql .= "AND ((i.hbcu = '$searchInfo->{params}->{hbcu}') OR (i.title like '%$searchInfo->{params}->{hbcu}%') OR (i.description like '%$searchInfo->{params}->{hbcu}%')) " if $searchInfo->{params}->{hbcu};
  $csql .= "AND ((i.hbcu = '$searchInfo->{params}->{hbcu}') OR (i.title like '%$searchInfo->{params}->{hbcu}%') OR (i.description like '%$searchInfo->{params}->{hbcu}%')) " if $searchInfo->{params}->{hbcu};

  if ($searchInfo->{params}->{category}) {
    $sql .= 'AND (';
    $sql .= "i.categories = $searchInfo->{params}->{category} ";
    $sql .= "OR i.categories like '$searchInfo->{params}->{category}:%' ";
    $sql .= "OR i.categories like '%:$searchInfo->{params}->{category}' ";
    $sql .= ") ";
    $csql .= 'AND (';
    $csql .= "i.categories = $searchInfo->{params}->{category} ";
    $csql .= "OR i.categories like '$searchInfo->{params}->{category}:%' ";
    $csql .= "OR i.categories like '%:$searchInfo->{params}->{category}' ";
    $csql .= ") ";
  }

  $sql .= "AND i.price >= $searchInfo->{params}->{min_price} " if $searchInfo->{params}->{min_price};
  $csql .= "AND i.price >= $searchInfo->{params}->{min_price} " if $searchInfo->{params}->{min_price};

  $sql .= "AND i.price <= $searchInfo->{params}->{max_price} " if $searchInfo->{params}->{max_price};
  $csql .= "AND i.price <= $searchInfo->{params}->{max_price} " if $searchInfo->{params}->{max_price};

  $sql .= "AND s.name like '%$searchInfo->{params}->{sellers}%' " if $searchInfo->{params}->{sellers};
  $csql .= "AND s.name like '%$searchInfo->{params}->{sellers}%' " if $searchInfo->{params}->{sellers};

  $sql .= "AND s.id like '%$searchInfo->{params}->{seller_id}%' " if $searchInfo->{params}->{seller_id};
  $csql .= "AND s.id like '%$searchInfo->{params}->{seller_id}%' " if $searchInfo->{params}->{seller_id};


  $sql .= " ORDER BY i.price $searchInfo->{order_by} " if defined $searchInfo->{order_by};

  $sql .= "LIMIT $start, $maxRecords";

  print STDERR "search_sql = $sql\n";
  print STDERR "search_csql = $csql\n";

  # First get the total count
  my $sth = $db->dbh->prepare($csql);
  $sth->execute();
  my $count = $sth->fetchrow_hashref()->{num};

  # Now we can handle the actual search
  $sth = $db->dbh->prepare($sql);
  $sth->execute();

  my @recs = ();
  while (my $row = $sth->fetchrow_hashref()) {
    my $picture = &getMainPicture($row->{id});
    $row->{$_} = $picture->{$_} for qw(
				       path
				       caption
				      );

    $sth3->execute($row->{id});
    my $row3 = $sth3->fetchrow_hashref();
    $row->{num_sold} = $row3->{num};
    $row->{status} = $row->{activated} ? 'Active' : 'Not Active';
    $row->{hits} ||= 0;

    ### Uncomment this when we start to care about item expiration
    ###$row->{status} = 'Expired' if $row->{date_expires} <= $row->{crt_date};

    push @recs, $row;
  }

  $sth->finish();

  $search_info->{records} = \@recs;
  $search_info->{start_num} = (($searchInfo->{page} - 1) * $maxRecords) + 1;
  $search_info->{end_num} = scalar(@recs) + (($searchInfo->{page} - 1) * $maxRecords);
  $search_info->{total_num} = $count;
  $search_info->{page} = $searchInfo->{page};
  $search_info->{order_by} = $searchInfo->{order_by};
  $search_info->{view} = $searchInfo->{view} || 0;
  $search_info->{previous_page} = $search_info->{page} - 1
    if $search_info->{page} != 1;
  $search_info->{next_page} = $search_info->{page} + 1
    if ($search_info->{total_num} - $search_info->{end_num}) > 0;

  return $search_info unless $searchInfo->{view};

  my @records = ();

  for (my $i = 0; $i <= $#recs; $i++) {
    my @array = ();
    push @array, $recs[$i++];

    unless ($i > $#recs) {
      push @array, $recs[$i++];
    }

    unless ($i > $#recs) {
      push @array, $recs[$i];
    }

    push @records, {columns => \@array};
  }

  $search_info->{records} = \@records;

  return $search_info;
}

################################################################################
sub sendEmail {
  my ($params) = @_;

  open(MAIL, "| /usr/sbin/sendmail -t") or die "Can't open sendmail!\n";
  print MAIL "To: ", join(', ', @{$params->{to}}), "\n";
  print MAIL "From: $params->{from}\n";
  print MAIL "Subject: $params->{subject}\n\n";
  print MAIL "$params->{message}\n";
  close MAIL;
}

################################################################################
sub sendNewMerchantEmail {
  my $seller = shift;
  my %params = (
		to => [$config->{MARKETPLACE_ADMIN_EMAIL}],
		from => $config->{MARKETPLACE_ADMIN_EMAIL},
		subject => "$config->{SITE} Marketplace Store Registration"
	       );
  $params{'message'} = qq(
The following merchant has completed registration on the $config->{SITE} Marketplace.

Name: $seller->{name}
Email: $seller->{email}

);

  sendEmail(\%params);
}

################################################################################
sub sendPurchaseEmail {
  my ($id) = @_;
  my $purchase = getPurchase($id);

  my %params = (
		to => ["$purchase->{seller}->{email}", $config->{MARKETPLACE_ADMIN_EMAIL}],
		from => $config->{MARKETPLACE_ADMIN_EMAIL},
		subject => "$config->{SITE} Marketplace Purchase Notification (Item #: $purchase->{item}->{id}, Title: $purchase->{title})"
	       );
  $params{'message'} = qq(
Dear $purchase->{seller}->{name},

A purchase was recorded on the $config->{SITE} Marketplace for one of your items.
Please contact the buyer to handle the transaction. The information below
describes the purchase.

Item #: $purchase->{item}->{id}
Title: $purchase->{title}
Price: $purchase->{price}
Quantity: $purchase->{quantity}
Total: $purchase->{total}
Buyer: $purchase->{buyer}->{name}
Buyer Email: $purchase->{buyer}->{email}
Time of Purchase: $purchase->{date_created}


Thank You for using the $config->{SITE} Marketplace.

$config->{SITE}

);

  sendEmail(\%params);
}

################################################################################
sub sendToFriendEmail {
  my ($params) = @_;

  sendEmail($params);
}

################################################################################
sub updateAccountInfo {
  my ($id, $params) = @_;

  $hdb->update({TABLE => 'registry_data', PARAMS => $params});
}

################################################################################
sub updateItem {
  my ($id, $params) = @_;

  $db->updateItem(WHERE => "id => $id", PARAMS => $params);
}

################################################################################
sub updateItemReview {
  my ($id, $params) = @_;

  $db->update({TABLE => 'review',
	       WHERE => {id => $id},
	       PARAMS => $params});
}

################################################################################
sub updateSeller {
  my ($seller, $params) = @_;

  $db->updateSeller(WHERE => "id = $seller", PARAMS => $params);
}

################################################################################
############################ END DB FUNCTIONS ##################################
################################################################################

################################################################################
############################ ADMIN FUNCTIONS ###################################
################################################################################
sub printAdminFeaturedMerchants {
  my ($q, $merchants) = @_;

  ### Now we output
  printHeader($q);

print qq~
<table class=data width=100%>
  <thead>
    <tr>
     <th colspan=4><div align=left>&nbsp;Marketplace Featured Merchants</div></th>
    </tr>
  </thead>
  <tbody>
~;
  if ($merchants) {
print qq~
    <tr class=search_columns>
      <td width=8%>&nbsp;</td>
      <td width=8%>ID</td>
      <td><a class=white href="$config->{MARKETPLACE_ADMIN_FEATURED_MERCHANTS}?order_by='name'">Name</a></td>
      <td width=20%><a class=white href="$config->{MARKETPLACE_ADMIN_FEATURED_MERCHANTS}?order_by='item_count'"># of Items</a></td>
    </tr>
~;
foreach my $x (@$merchants) {
print qq~
    <tr>
      <td align=center><a href="$config->{MARKETPLACE_ADMIN_FEATURED_MERCHANTS}?id=$x->{id}&unfeature=1">Unfeature</a></td>
      <td align=center>$x->{id}</td>
      <td><a href="$config->{MARKETPLACE_VIEW_SELLER}?id=$x->{id}">$x->{name}</a></td>
      <td align=center><a href="$config->{MARKETPLACE_VIEW_SELLER}">$x->{item_count}</a></td>
    </tr>
~;
}
} else {
print qq~
    <tr>
      <td colspan=4>
        There currently are no Featured Merchants in the Marketplace
      </td>
    </tr>
~;
}
print qq~
  </tbody>
</table>
<br />
~;

  printFooter($q);
}

################################################################################
sub printAdminMain {
  my ($q) = @_;

  ### Now we output
  printHeader($q);

print qq~
<table class=data width=100%>
  <tr>
    <th><div align=left>&nbsp;Marketplace Administrative Tools</div></th>
  </tr>
  <tbody>
    <tr><td></td></tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_ADMIN_MAIN}">Administrative Tools</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_ADMIN_SEARCH}">Marketplace Search</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_ADMIN_STATS}">Marketplace Statistics</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_ADMIN_ITEMS}">Manage Items</a>
      </td>
    </tr>
    <tr><td></td></tr>
  </tbody>
</table>
<br />
~;

  printFooter($q);
}

################################################################################
sub printAdminMenu {
  my ($q) = @_;

print qq~
<table class=data width=100%>
  <tr>
    <th><div align=left>&nbsp;Marketplace Admin Tools</div></th>
  </tr>
  <tbody>
    <tr><td></td></tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_ADMIN_MAIN}">Administrative Tools</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_ADMIN_FEATURED_MERCHANTS}">Featured Merchants</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_ADMIN_SEARCH}">Marketplace Search</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_ADMIN_STATS}">Marketplace Statistics</a>
      </td>
    </tr>
    <tr>
      <td>
	<img src=$config->{BULLET} />
	<a href="$config->{MARKETPLACE_ADMIN_ITEMS}">Manage Items</a>
      </td>
    </tr>
    <tr><td></td></tr>
  </tbody>
</table>
<br />
~;
}

################################################################################
############################ END ADMIN FUNCTIONS ###############################
################################################################################

1;
