<?php
/*
Plugin Name: WP Auctions
Plugin URI: http://www.wpauctions.com
Description: Since 2007, our auction software is trusted by tens of thousands of WordPress users who have auctioned off items for millions of dollars!
Version: 6.0
Author: WP Auctions
Author URI: http://www.wpauctions.com
*/

/* History:
	v0.1 Beta  - OwenC - 29/01/08 - Initial beta release
	v1.0 Free  - OwenC - 21/02/08 - Free public release
	v3.0 Pro  - OwenC - 26/01/09 - Version 3

	------- A lot of features later --------

	v5 RC1	- Multi-user auctions
	        - Fix to Zend errror on some platforms
			- New super auction layout
			- Use wp_mail for UTF email
			- Fix bug in BIN
            - New payment mechanism - new shortcode
            - Split auction widget into widget and shortcode (for list)
            - Millions of bug fixes & perf improvements

	v5 RC2	- Added CSS classes to most everything
			- Updated text
			- Updated CSS styling

	v5.0	- Final release
	
	v5.0.1  - Added option to delete rogue auctions (auctions without engine created previously with free version)
			- Added switch to hide AddThis sharing buttons
			- Applied switch to hide countdown to modern layout
			
	v5.0.2  - Fixed validation issue that occurs on some configurations
	
	v5.0.3 - Removed Pay via Paypal if user has no paypal
	
	v5.0.4 - Image enhancements
		   - Reverse auction engine bug fixes
		   
    v5.0.5 - Bug fix (obfuscated bidders)
           - Added countdown Ajax update
           - Bug fix (counter not always 100% accurate in Ajax update)

	v5.1   - Added auto update feature to time countdown + CSS/text updates
	
	v5.1.1 - Show proxy bids on closed auction bids
	
	v5.2   - Implemented future auctions in modern display
	       - Added 2nd Chance Offer
	       
	v5.3  - Moved away from jquery.tools 
	
	v5.4  - Improved handling of commas in bids
		  - Added double-check to auction extention to make sure auction hasn't been won just before we extend it
		  - Clarified messaging when auction not won due to reserve price
		  - in-place upgrades for depracated Wordpress functions
		  - Added option for custom login/registration pages
		  
    v5.5b  - Introducing Quick-Buy engine
          - Removed access restrictions for admins on 3rd party auctions
          
    v5.6  - Enhancement : Auto refresh now refreshes more parts of traditional style
          - Enhancement : New feature that deletes auctions/bids older than 6 months (clean up)
          
    v5.7  - Switched date time picker to CDN version
          - Remove AddThis sharing buttons feature
          - Remove custom template fields feature
          - Sanitised placeholder data
          
	v5.7.1 - Upgraded date time picker to 2016 version and adjusted time format
	
	v5.8  - Added Gutenberg integration
	      - Removed popup option
	v6.0  - New Modern interface
		  - PHP 8 Support
		  - Several small bugfixes and tweaks	  
	
*/

// cater for stand-alone calls
if (!function_exists('get_option')) {
	require_once('../../../wp-config.php');
}

$wpa_version = "6.0";

load_plugin_textdomain( 'wpauctions', false, 'wp-auctions/languages' );

include 'wpa_constants.php';
require('wpa_managebidders.php');

function report_engine() {
	$options = get_option('wp_auctions');
	$engine = $options['engine'];

	switch ($engine) {
	case 1:
		_e("Standard Engine",'wpauctions');
		break;
	case 2:
		_e("Simple Engine",'wpauctions');
		break;
	case 3:
		_e("Reverse Engine",'wpauctions');
		break;
	case 4:
		_e("Quick Bid Engine",'wpauctions');
		break;	}
}

// include other files
include 'wpa_ajax.php';

//---------------------------------------------------
//--------------RSS FEED-----------------------------
//---------------------------------------------------
if (strstr($_SERVER['PHP_SELF'], WPA_PLUGIN_NAME ) && isset($_GET['rss'])):
	header("Content-Type:application/rss+xml");

global $wpdb;
global $wpa_version;

$options = get_option('wp_auctions');
$currencycode = $options['currencycode'];
$landingpage = $options['landingpage'];
if ($landingpage == "") $landingpage = get_option('siteurl');

// prepare result
$table_name = $wpdb->prefix . "wpa_auctions";
$strSQL = "SELECT * FROM $table_name WHERE '".current_time('mysql',"1")."' < date_end ORDER BY ID desc LIMIT 15";
$rows = $wpdb->get_results ($strSQL);

$now = date("D, d M Y H:i:s T");

$output = "<?xml version=\"1.0\"?>
            <rss version=\"2.0\">
                <channel>
                    <title>".get_option('blogname')." Auctions</title>
                    <link>". WPA_PLUGIN_RSS . "</link>
                    <description>Auction feed generated by wp_auctions (http://www.wpauctions.com) version ".$wpa_version."</description>
                    <language>en-us</language>
                    <pubDate>$now</pubDate>
                    <lastBuildDate>$now</lastBuildDate>
                    <docs>http://someurl.com</docs>
                    <managingEditor>".get_option('admin_email')."</managingEditor>
                    <webMaster>".get_option('admin_email')."</webMaster>
            ";

foreach ($rows as $line)
{
	$output .= "<item><title>".htmlentities($line->name)."</title>
                    <link>".$landingpage."?auction_to_show=".$line->id."</link>
                    <description><![CDATA[<img src='".wpa_resize($line->image_url,50)."' align='left'>".htmlentities(strip_tags($line->description))." - Closing: ".date('dS M Y',strtotime($line->date_end))." - Current Bid: ".$currencycode.number_format($line->current_price, 2, '.', ',')." -]]></description>
                </item>";
}
$output .= "</channel></rss>";

echo $output;
exit;
endif;

//---------------------------------------------------
//--------------HELPER FUNCTIONS---------------------
//---------------------------------------------------

function WPA_get_wordpress_id_from_email( $email ) {
	$user = get_user_by ( 'email', $email );
	return $user->ID;
}

function UTF8_mail($to,$subject,$message,$cc="",$bcc="") {

	$options = get_option('wp_auctions');

	if ($options['bypassUTF8email'] == "Yes") {
		// use non-UTF8 method
		$headers = 'From: '.get_option('blogname').' <'.get_option('admin_email').'>' . "\r\n";
		//$create_function_new = function() {return "text/html";}
		//add_filter('wp_mail_content_type',function('') {return 'text/html';};
		//add_filter('wp_mail_content_type', $create_function_new);

		if ($cc != "" ) {
			$headers[] = 'Cc: '.$cc;
		}
		return wp_mail($to, $subject, wpautop(htmlEscapeAndLinkUrls($message)),$headers);
	} else {
		// use UTF8 method

		$subject= "=?utf-8?b?".base64_encode($subject)."?=";
		$headers[] = "MIME-Version: 1.0\r\n";
		$headers[] = "From: =?utf-8?b?". base64_encode(get_option('blogname'))."?= <".get_option('admin_email').">\r\n";
		$headers[] = "Content-Type: text/html;charset=utf-8";

		if ($cc != "" ) {
			$headers[] = 'Cc: '.$cc;
		}

		return wp_mail($to, $subject, wpautop(htmlEscapeAndLinkUrls($message)), $headers);
	}
}

function wpa_date ( $value ) {
	return date_i18n(get_option('date_format') .' '. get_option('time_format'), strtotime( $value ));
}

function wpa_calculatefee ( $value ) {

	$options = get_option('wp_auctions');
	$feetype = $options['feetype'];
	$feeamount = $options['feeamount'];

	switch ( $feetype ) {
	case "fixed":
		$fee = $feeamount;
		break;
	case "percent":
		$fee = $value * ($feeamount / 100 );
		break;
	default:
		$fee = 0;
	}

	return $fee;
}

function wpa_expressfee () {

	$options = get_option('wp_auctions');
	$feetype = $options['feetype'];
	$feeamount = $options['feeamount'];
	$currencycode = $options['currencysymbol'];

	switch ( $feetype ) {
	case "fixed":
		$fee = $currencycode.number_format($feeamount, 2, '.', ',');
		break;
	case "percent":
		$fee = $feeamount . "%";
		break;
	default:
		$fee = "";
	}

	return $fee;
}

function wpa_cleancurrency ( $value ) {
	
	// using fix from : http://stackoverflow.com/questions/6662105/what-a-quick-way-to-clean-up-a-monetary-string

	// remove everything except a digit "0-9", a comma ",", and a dot "."
	$value = preg_replace('/[^\d,\.]/', '', $value);

	// replace the comma with a dot, in the number format ",12" or ",43"
	$value = preg_replace('/,(\d{2})$/', '.$1', $value);

	return $value;
}

// helper function for multi-dimensional implode
function wpa_implode_r ($glue, $pieces) {
	$out = "";
	foreach ($pieces as $piece)
		if (is_array($piece)) $out .= wpa_implode_r ($glue, $piece);
		else                   $out .= $glue.$piece;
		return $out;
}

// helper function to calculate increment based on amount
function wpa_get_increment ($value, $auctionincrement = 0 ) {

	$options = get_option('wp_auctions');

	$customincrement = ( $auctionincrement != 0 ? $auctionincrement : $options['customincrement'] );

	if (empty($customincrement)) {
		$out = 0.01;

		if ($value >= 1000) {
			$out = 10;
		} elseif ($value >= 250) {
			$out = 5;
		} elseif ($value >= 50) {
			$out = 2;
		} elseif ($value >= 25) {
			$out = 1;
		} elseif ($value >= 10) {
			$out = 0.50;
		} elseif ($value >= 5) {
			$out = 0.25;
		} elseif ($value >= 1) {
			$out = 0.1;
		} elseif ($value >= 0.5) {
			$out = 0.05;
		}
	} else {
		$out = $customincrement;
	}

	return $out;
}

// helper function to validate email address
function wpa_valid_email($address)
{
	// check an email address is valid
	return filter_var($address, FILTER_VALIDATE_EMAIL);
}

if(!function_exists('file_put_contents')) {
	function file_put_contents($filename, $data, $file_append = false) {

		$fp = fopen($filename, (!$file_append ? 'w+' : 'a+'));
		if(!$fp) {
			trigger_error('file_put_contents cannot write in file.', E_USER_ERROR);
			return;
		}
		fputs($fp, $data);
		fclose($fp);
	}
}

function wpa_import_photo( $auctionid, $url ) {

	if( !class_exists( 'WP_Http' ) )
		include_once( ABSPATH . WPINC. '/class-http.php' );

	$photo = new WP_Http();
	$photo = $photo->request( $url );
	if( $photo['response']['code'] != 200 ) {
		echo "ERROR:" . $photo['response']['code'];
		return false;
	}

	$filetype = wp_check_filetype( $url, null );

	//echo "--".$url."--";
	//echo "==".$filetype['ext']."==";

	$attachment = wp_upload_bits( 'Auction' . $auctionid . ".". $filetype['ext'], null, $photo['body'], date("Y-m", strtotime( $photo['headers']['last-modified'] ) ) );
	if( !empty( $attachment['error'] ) ) {
		echo "ERROR:" . $attachment['error'];
		return false;
	}

	$postinfo = array(
		'post_mime_type' => $filetype['type'],
		'post_title'  => 'Auction' . $auctionid,
		'post_content'  => '',
		'post_status'  => 'inherit',
	);
	$filename = $attachment['file'];
	$attach_id = wp_insert_attachment( $postinfo, $filename  );

	echo "## Attachment: ".$attach_id." created ##";

	if( !function_exists( 'wp_generate_attachment_data' ) )
		require_once(ABSPATH . "wp-admin" . '/includes/image.php');
	$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
	wp_update_attachment_metadata( $attach_id,  $attach_data );
	return $attach_id;
}

// new resize function .. using WP's built in resizer
function wpa_resize ( $image, $size, $height = 0 ) {

	// resize now done on upload. All we need to do is produce correct image URL

	if (is_numeric($image) || ($image == "")) {

		switch ( $size ) {
		case 300:
			$class = "WPA_popup";
			break;
		case 150:
			$class = "WPA_page";
			break;
		case 125:
			$class = "WPA_widget";
			break;
		default:
			$class = "WPA_thumbnail";
		}

		$thumbnail = wp_get_attachment_image_src ( $image , $class );

		if (empty($thumbnail[0])) {
			$thumb = WPA_PLUGIN_STYLE . "/default-$size.png";
		} else {
			$thumb = $thumbnail[0];
		}
	} else {
		$thumb = "ERROR: Image not in media library";
	}

	return $thumb;
}


function wpa_log($message) {
	if (WP_DEBUG == true) {
		if (is_array($message) || is_object($message)) {
			error_log(print_r($message, true));
		} else {
			error_log($message);
		}
	}
}

//---------------------------------------------------
//--------------INTERNAL CODE------------------------
//---------------------------------------------------

function wpa_notify_watchers ( $auction_id ) {

	global $wpdb;
	$options = get_option('wp_auctions');
	$title = $options['title'];
	$currencycode = $options['currencycode'];
	$landingpage = $options['landingpage'];
	if ($landingpage == "") $landingpage = get_option('siteurl');

	// Setup email fields.
	$emailoptions = get_option('wp_auctions_email');

	//pull in auction details
	$table_name = $wpdb->prefix . "wpa_auctions";
	$strSQL = "SELECT id, name,description,staticpage,current_price,date_create,date_end,start_price,image_url FROM $table_name WHERE id=".$auction_id;
	$auction = $wpdb->get_row ($strSQL);
	$staticpage = $auction->staticpage;
	$thisbid = $auction->current_price;

	$table_name = $wpdb->prefix . "wpa_watchlist";
	$strSQL = "SELECT * FROM $table_name WHERE auction_id = ".$auction_id;
	$rows = $wpdb->get_results ($strSQL);

	foreach ($rows as $row) {

		$to      = $row->watch_email;
		$subject = "[".$title."] An auction you are watching has changed:  ".$auction->name;

		if (@$emailoptions["watch"] == "") {
			$body   = "Just wanted to let you know that one of the auctions you're watching on {site_name} has been updated\n\n";
			$body  .= "Someone is currently winning {auction_name} after placing a bid for {current_price}. ";
			$body  .= "You're still in time to win the auction, so click the link below.";
			$body  .= "\n\nLink: {auction_link}";
			$body  .= "\n\n--------------------------------------------\n";
		} else {
			$body = $emailoptions["watch"];

			// clean up CRLFs
			$body = str_replace("\r\n", "\n", $body);
		}
		// prepare link
		if (strlen($staticpage) > 0) {
			$link  = $staticpage."?auction_id=".$auction_id;
		} else {
			$link  = $landingpage."?auction_to_show=".$auction_id;
		}

		// replace keywords
		$body = str_replace( "{site_name}", get_option('blogname') , $body );
		$body = str_replace( "{auction_name}", $auction->name , $body );
		$body = str_replace( "{auction_link}", $link , $body );
		$body = str_replace( "{current_price}", $currencycode.number_format($thisbid, 2, '.', ','), $body );

		// Send the email.
		UTF8_mail($to,$subject,$body);
	}
}

function wpa_process_bid( $auction_id, $bidder_name, $bidder_email, $bidder_url, $max_bid, $BIN_amount ) {

	global $wpdb;
	global $BID_WIN, $BID_LOSE, $BIN_WIN, $BID_WIN_REVERSE;

	// let's clean up
	$bidder_email = trim($bidder_email);
	
	// new sanitisation routine
	$bidder_url = filter_var($bidder_url, FILTER_SANITIZE_STRING); 
	$bidder_name = filter_var($bidder_name, FILTER_SANITIZE_STRING);
		
	$max_bid = wpa_cleancurrency($max_bid);

	// establish mode for auction
	$table_name = $wpdb->prefix . "wpa_auctions";
	$strSQL = "SELECT engine,owner FROM $table_name WHERE id=".$auction_id;
	$row = $wpdb->get_row ($strSQL);
	$engine = $row->engine;

	$personalblacklist = get_the_author_meta( 'blacklist', $row->owner );

	// check for blacklist before even hitting engine code
	$options = get_option('wp_auctions');
	$blacklist = $options['blacklist'];
	$blacklistmessage = $options['blacklistmessage'];

	$pos = strrpos( strtoupper($blacklist).strtoupper($personalblacklist)  , strtoupper($bidder_email) );
	if (!($pos === false)) {
		$result = $blacklistmessage;
	} else {

		// facade for engines
		switch ($engine) {
		case STANDARD_ENGINE:
			$result = wpa_process_bid_standard_engine( $auction_id, $bidder_name, $bidder_email, $bidder_url, $max_bid, $BIN_amount );
			break;

		case SIMPLE_ENGINE:
			$result = wpa_process_bid_simple_engine( $auction_id, $bidder_name, $bidder_email, $bidder_url, $max_bid, $BIN_amount );
			break;

		case REVERSE_ENGINE:
			$result = wpa_process_bid_reverse_engine( $auction_id, $bidder_name, $bidder_email, $bidder_url, $max_bid, $BIN_amount );
			break;

		case QUICKBUY_ENGINE: // uses simple engine buy forces $max_bid to next bid
			$result = wpa_process_bid_simple_engine( $auction_id, $bidder_name, $bidder_email, $bidder_url, $max_bid, $BIN_amount );
			break;

		default:
			die ("Oopps - Something went wrong! I'm running without an engine!");
		}

	}

	// we only need to notify if the bid was successful
	if ( $result == $BID_WIN || $result == $BIN_WIN || $result == $BID_WIN_REVERSE ) {
		wpa_notify_watchers ( $auction_id );
	}

	return $result;
}

// Proxy Bidding Engine
function wpa_process_bid_standard_engine( $auction_id, $bidder_name, $bidder_email, $bidder_url, $max_bid, $BIN_amount ) {

	global $wpdb;
	global $BID_WIN, $BID_LOSE, $BIN_WIN, $BID_WIN_REVERSE;

	//echo "<!-- in code -->";

	$result = "";
	$options = get_option('wp_auctions');
	$notify = $options['notify'];
	$whennotify = $options['whennotify'];
	$title = $options['title'];
	$regonly = $options['regonly'];
	$currencysymbol = $options['currencysymbol'];
	$currencycode = $options['currencycode'];
	$landingpage = $options['landingpage'];
	if ($landingpage == "") $landingpage = get_option('siteurl');

	// Setup email fields.
	$emailoptions = get_option('wp_auctions_email');
	$bid_type = "user";

	// validate input
	if (!is_numeric($auction_id)): // ID not numeric
		$result = __('Invalid Auction ID specified','wpauctions');
	elseif (trim($bidder_name == '')):  // Bidder name not specified
		$result = __('Bidder name not supplied','wpauctions');
	elseif (trim($bidder_email == '')):  // Bidder email not specified
		$result = __('Bidder email not supplied','wpauctions');
	elseif (!wpa_valid_email($bidder_email)):  // Bidder email not specified
		$result = __('Please supply a valid email address -'.$bidder_email.'-','wpauctions');
	elseif (!is_numeric($max_bid)):  // Bidder email not specified
		$result = __('Your bid value is invalid - please remove any non-numerical characters like letters or commas','wpauctions');
	elseif (($regonly=="Yes") && !is_user_logged_in()): // Bidder needs to be registered and isn't (HACK TEST)
		$result = __('You need to be signed in to place bids','wpauctions');
	endif;

	if ($result == '') {
		// If we get this far it means that the input data is completely valid, so sanity check the data
		// Before we start .. confirm if auction has ended or not
		check_auction_end($auction_id);

		// Let's also check that the bid is in the right range for the (piggyback staticpage)
		$table_name = $wpdb->prefix . "wpa_auctions";
		$strSQL = "SELECT current_price,start_price,staticpage,customincrement, winner, owner FROM $table_name WHERE id=".$auction_id;
		$rows = $wpdb->get_row ($strSQL);
		$customincrement = $rows->customincrement;
		$winner = $rows->winner;
		$staticpage = $rows->staticpage; // (don't need this here, just more efficient)
		$owner = $rows->owner;

		if ($winner != "") $result=__("Sorry, this auction is now closed",'wpauctions');

		if ($rows->start_price > $max_bid) $result=__("Sorry, your bid must exceed the auction start price",'wpauctions');
		if ($rows->current_price >= $max_bid) $result=__("Sorry, your bid must exceed the current bid price",'wpauctions');
		if ($rows->current_price + wpa_get_increment($rows->current_price, $customincrement ) > $max_bid && $rows->current_price <> 0) $result=__("Sorry, your bid must exceed",'wpauctions')." ".$currencysymbol.number_format($rows->current_price + wpa_get_increment($rows->current_price, $customincrement), 2, '.', ',');;

		// override bidding process if auction in a "Buy It Now"
		if ($BIN_amount > 0) {
			$thisbid = $BIN_amount;
			$result = $BIN_WIN;

			// close the auction
			$table_name = $wpdb->prefix . "wpa_auctions";
			$sql = "UPDATE ".$table_name." SET date_end = '".current_time('mysql',"1")."' WHERE id=".$auction_id;
			$wpdb->query($sql);
		}

		// Step 1 - Retrieve current maximum bid on item
		$table_name = $wpdb->prefix . "wpa_bids";
		$strSQL = "SELECT * FROM $table_name WHERE auction_id=".$auction_id." ORDER BY current_bid_price DESC, bid_type, max_bid_price DESC LIMIT 1";
		$current = $wpdb->get_row ($strSQL);

		// let's just check we don't have a duplicate bid here
		if (@$current->max_bid_price == $max_bid && $bidder_email == $current->bidder_email) {
			$result= __('Sorry, this appears to be a duplicate bid. Your maximum bid is','wpauctions').": ".$currencysymbol.$max_bid;
		}

		// added by mensmaximus - self-outbid-bug + raise auto bid limit
		if (@$result=='' && @$bidder_email == @$current->bidder_email) {
			if ($max_bid < $current->max_bid_price) {
				$result = __('You have already set a higher automatic bidding limit. Your maximum bid is','wpauctions').": ".$currencysymbol.$current->max_bid_price;
			} elseif ($max_bid > $current->max_bid_price) {
				$table_name = $wpdb->prefix . "wpa_bids";
				$sql = "INSERT INTO ".$table_name." (id, auction_id, date, bidder_name ,bidder_email, bidder_wordpress_id, bidder_url, current_bid_price, max_bid_price, bid_type) VALUES (NULL, ".$auction_id.", '".current_time('mysql',"1")."', '".$current->bidder_name."', '".$current->bidder_email."', '".WPA_get_wordpress_id_from_email($current->bidder_email)."', '".$current->bidder_url."', ".$current->current_bid_price.", ".$max_bid.", 'advance');";
				$wpdb->query($sql);
				$result = __('Your automatic bidding limit has been increased to','wpauctions').": ".$currencysymbol.$max_bid;
			}
		}

		if ($result=='') {
			$result = $BID_WIN;

			if (!($current)) {
				$winner = "new";


				// pull in auction details
				$table_name = $wpdb->prefix . "wpa_auctions";
				$strSQL = "SELECT id, name, description, current_price, date_create, date_end, start_price, image_url FROM $table_name WHERE id=".$auction_id;
				$rows = $wpdb->get_row ($strSQL);
				$thisbid = $rows->start_price;

				$to      = $bidder_email;
				$subject = "[".$title."] You hold the winning bid on ".$rows->name;
				if (@$emailoptions["highbid"] == "") {
					$body   = "A new bid has been placed on an auction on {site_name}\n\n";
					$body  .= "You are currently holding the winning bid on {auction_name} with {current_price}. ";
					$body  .= "\n\nLink: {auction_link}";
					$body  .= "\n\n--------------------------------------------\n";
				} else {
					$body = $emailoptions["highbid"];
					$body = str_replace("\r\n", "\n", $body);
				}
				if (strlen($staticpage) > 0) {
					$link  = $staticpage."?auction_id=".$auction_id;
				} else {
					$link  = $landingpage."?auction_to_show=".$auction_id;
				}
				$body = str_replace( "{site_name}", get_option('blogname') , $body );
				$body = str_replace( "{auction_name}", $rows->name , $body );
				$body = str_replace( "{auction_link}", $link , $body );
				$body = str_replace( "{current_price}", $currencycode.number_format($thisbid, 2, '.', ','), $body );
				$body = str_replace( "{contact_email}", get_option('admin_email') , $body );

				UTF8_mail($to,$subject,$body);



			} else {
				// let's compare maximum bids first
				if ($max_bid > $current->max_bid_price) {
					$winner = "new";

					// bid is next available one above current bidder's maximum bid
					$thisbid = $current->max_bid_price + wpa_get_increment($current->max_bid_price, $customincrement);

					// check we haven't exceeded the new bidder's maximum
					if ($thisbid > ($max_bid + 0)) { $thisbid = $max_bid; }

					//pull in auction details
					$table_name = $wpdb->prefix . "wpa_auctions";
					$strSQL = "SELECT id, name,description,current_price,date_create,date_end,start_price,image_url FROM $table_name WHERE id=".$auction_id;
					$rows = $wpdb->get_row ($strSQL);

					$to      = $bidder_email;
					$subject = "[".$title."] You hold the winning bid on ".$rows->name;
					if ($emailoptions["highbid"] == "") {
						$body   = "A new bid has been placed on an auction on {site_name}\n\n";
						$body  .= "You are currently holding the winning bid on {auction_name} with {current_price}. ";
						$body  .= "\n\nLink: {auction_link}";
						$body  .= "\n\n--------------------------------------------\n";
					} else {
						$body = $emailoptions["highbid"];
						$body = str_replace("\r\n", "\n", $body);
					}
					if (strlen($staticpage) > 0) {
						$link  = $staticpage."?auction_id=".$auction_id;
					} else {
						$link  = $landingpage."?auction_to_show=".$auction_id;
					}
					$body = str_replace( "{site_name}", get_option('blogname') , $body );
					$body = str_replace( "{auction_name}", $rows->name , $body );
					$body = str_replace( "{auction_link}", $link , $body );
					$body = str_replace( "{current_price}", $currencycode.number_format($thisbid, 2, '.', ','), $body );
					$body = str_replace( "{contact_email}", get_option('admin_email') , $body );
					UTF8_mail($to,$subject,$body);


					$to      = $current->bidder_email;
					$subject = "[".$title."] You have been outbid on ".$rows->name;

					if (@$emailoptions["outbid"] == "") {
						$body   = "You have just been outbid on an auction on {site_name}\n\n";
						$body  .= "Unfortunately someone else is currently winning {auction_name} after placing a bid for {current_price}. ";
						$body  .= "You're still in time to win the auction, so click the link below and bid again.";
						$body  .= "\n\nLink: {auction_link}";
						$body  .= "\n\n--------------------------------------------\n";
					} else {
						$body = $emailoptions["outbid"];
						// clean up CRLFs
						$body = str_replace("\r\n", "\n", $body);
					}
					// prepare link
					if (strlen($staticpage) > 0) {
						$link  = $staticpage."?auction_id=".$auction_id;
					} else {
						$link  = $landingpage."?auction_to_show=".$auction_id;
					}

					// replace keywords
					$body = str_replace( "{site_name}", get_option('blogname') , $body );
					$body = str_replace( "{auction_name}", $rows->name , $body );
					$body = str_replace( "{auction_link}", $link , $body );
					$body = str_replace( "{current_price}", $currencycode.number_format($thisbid, 2, '.', ','), $body );

					// Send the email.
					UTF8_mail($to,$subject,$body);

				} else {
					$winner = "old";

					// stick in an extra record in the bids table to track that a new bid has been superceeded
					$table_name = $wpdb->prefix . "wpa_bids";
					$sql = "INSERT INTO ".$table_name." (id, auction_id, date, bidder_name ,bidder_email, bidder_wordpress_id, bidder_url, current_bid_price, max_bid_price, bid_type) VALUES (NULL, ".$auction_id.", '".current_time('mysql',"1")."', '".$bidder_name."', '".$bidder_email."', '".WPA_get_wordpress_id_from_email($bidder_email)."', '".$bidder_url."', ".$max_bid.", ".$max_bid.", 'outbid');";
					$wpdb->query($sql);


					//pull in auction details
					$table_name = $wpdb->prefix . "wpa_auctions";
					$strSQL = "SELECT id, name,description,current_price,date_create,date_end,start_price,image_url FROM $table_name WHERE id=".$auction_id;
					$rows = $wpdb->get_row ($strSQL);

					// increase bid to take it above new bid
					$thisbid = $max_bid + wpa_get_increment($max_bid, $customincrement);

					// check we haven't exceeded the old bidder's maximum
					if ($thisbid > ($current->max_bid_price + 0)) { $thisbid = $current->max_bid_price; }

					// if the old bidder wins, update the write variables with old bidder's details
					$bidder_name = $current->bidder_name;
					$bidder_email = $current->bidder_email;
					$bidder_url = $current->bidder_url;
					$max_bid = $current->max_bid_price;
					$bid_type = "auto";

					// email highbidder
					$to      = $bidder_email;
					$subject = "[".$title."] You hold the winning bid on ".$rows->name;
					if (@$emailoptions["highbid"] == "") {
						$body   = "A new bid has been placed on an auction on {site_name}\n\n";
						$body  .= "You are currently holding the winning bid on {auction_name} with {current_price}. ";
						$body  .= "\n\nLink: {auction_link}";
						$body  .= "\n\n--------------------------------------------\n";
					} else {
						$body = $emailoptions["highbid"];
						$body = str_replace("\r\n", "\n", $body);
					}
					if (strlen($staticpage) > 0) {
						$link  = $staticpage."?auction_id=".$auction_id;
					} else {
						$link  = $landingpage."?auction_to_show=".$auction_id;
					}
					$body = str_replace( "{site_name}", get_option('blogname') , $body );
					$body = str_replace( "{auction_name}", $rows->name , $body );
					$body = str_replace( "{auction_link}", $link , $body );
					$body = str_replace( "{current_price}", $currencycode.number_format($thisbid, 2, '.', ','), $body );
					$body = str_replace( "{contact_email}", get_option('admin_email') , $body );
					UTF8_mail($to,$subject,$body);

					$result = $BID_LOSE;
				}
			}
		}

		if ($result == $BID_WIN || $result == $BID_LOSE || $result == $BIN_WIN) {
			// Update bid table with details on bid
			$table_name = $wpdb->prefix . "wpa_bids";
			$sql = "INSERT INTO ".$table_name." (id, auction_id, date, bidder_name ,bidder_email, bidder_wordpress_id, bidder_url, current_bid_price, max_bid_price, bid_type) VALUES (NULL, ".$auction_id.", '".current_time('mysql',"1")."', '".$bidder_name."', '".$bidder_email."', '".WPA_get_wordpress_id_from_email($bidder_email)."', '".$bidder_url."', ".$thisbid.", ".$max_bid.", '".$bid_type."');";
			$wpdb->query($sql);
			//Update auction table
			$table_name = $wpdb->prefix . "wpa_auctions";
			$sql = "UPDATE ".$table_name." SET current_price = ".$thisbid." WHERE id=".$auction_id;
			$wpdb->query($sql);

			$to = "";
			$cc = "";

			// notify site owner if notification requested
			if ($notify != '' && $whennotify != "winonly") {
				$to = $notify;
			}

			// notify auction owner is requested
			@$notifyowner = get_the_author_meta( 'whennotify', $rows->owner );
			if ( $notifyowner == 'always' || $notifyowner == 'bidonly' ) {
				$seller = get_user_by ( 'id', $owner );
				if ($to == "" ) {
					$to = $seller->user_email;
				} else {
					$cc = $seller->user_email;
				}
			}

			if ($to != "") {
				// get details for mail
				$strSQL = "SELECT * FROM $table_name WHERE id=".$auction_id;
				$rows = $wpdb->get_row ($strSQL);
				$subject = "[".$title."] New bid on ".$rows->name;
				$body   = "New bid on your auction.";
				if (strlen($staticpage) > 0) {
					$body  .= "\n\nLink: " . $staticpage."?auction_id=".$auction_id;
				} else {
					$body  .= "\n\nLink: " . $landingpage."?auction_to_show=".$auction_id;
				}
				$body  .= "\n\n--------------------------------------------\n";
				// Send the email.
				UTF8_mail($to,$subject,$body,$cc);
			}

			// check if we need to extend the auction
			check_auction_extend ( $auction_id );
		}
	}

	// finalise auction if BIN
	if ($result == $BIN_WIN)  {
		// wait a bit, to make sure Now() in termination check doesn't match NOW() here.
		sleep(2);
		check_auction_end($auction_id);
	}
	return $result;
}

// Reverse Bidding Engine
function wpa_process_bid_reverse_engine( $auction_id, $bidder_name, $bidder_email, $bidder_url, $max_bid, $BIN_amount ) {

	global $wpdb;
	global $BID_WIN, $BID_LOSE, $BIN_WIN, $BID_WIN_REVERSE;

	//echo "<!-- in code -->";

	$result = "";
	$options = get_option('wp_auctions');
	$notify = $options['notify'];
	$whennotify = $options['whennotify'];
	$title = $options['title'];
	$regonly = $options['regonly'];
	$currencysymbol = $options['currencysymbol'];
	$currencycode = $options['currencycode'];
	$landingpage = $options['landingpage'];
	if ($landingpage == "") $landingpage = get_option('siteurl');

	// Setup email fields.
	$emailoptions = get_option('wp_auctions_email');
	$bid_type = "user";

	// validate input
	if (!is_numeric($auction_id)): // ID not numeric
		$result = __('Invalid Auction ID specified','wpauctions');
	elseif (trim($bidder_name == '')):  // Bidder name not specified
		$result = __('Bidder name not supplied','wpauctions');
	elseif (trim($bidder_email == '')):  // Bidder email not specified
		$result = __('Bidder email not supplied','wpauctions');
	elseif (!wpa_valid_email($bidder_email)):  // Bidder email not specified
		$result = __('Please supply a valid email address -'.$bidder_email.'-','wpauctions');
	elseif (!is_numeric($max_bid)):  // Bidder email not specified
		$result = __('Your bid value is invalid - please remove any non-numerical characters like letters or commas','wpauctions');
	elseif (($regonly=="Yes") && !is_user_logged_in()): // Bidder needs to be registered and isn't (HACK TEST)
		$result = __('You need to be signed in to place bids','wpauctions');
	elseif (!($max_bid > 0)):  // check that bid is positive
		$result = __('Your bid value is invalid','wpauctions');
	endif;

	if ($result == '') {
		// If we get this far it means that the input data is completely valid, so sanity check the data
		// Before we start .. confirm if auction has ended or not
		check_auction_end($auction_id);

		// Let's also check that the bid is in the right range for the (piggyback staticpage)
		$table_name = $wpdb->prefix . "wpa_auctions";
		$strSQL = "SELECT current_price,start_price,staticpage,customincrement, winner, owner, name FROM $table_name WHERE id=".$auction_id;
		$rows = $wpdb->get_row ($strSQL);
		$winner = $rows->winner;
		$customincrement = $rows->customincrement;
		$staticpage = $rows->staticpage; // (don't need this here, just more efficient)
		$owner = $rows->owner; // ditto
		$name = $rows->name; // ditto

		if ($winner != "") $result=__("Sorry, this auction is now closed",'wpauctions');

		if ($rows->start_price < $max_bid) $result=__("Sorry, your bid must be lower than the auction start price",'wpauctions');

		// in reverse auctions we can only perform this check if there IS a current bid
		if ($rows->current_price !=  0 ) {
			if ($rows->current_price <= $max_bid) $result=__("Sorry, your bid must by lower than the current bid price",'wpauctions');
		}

		// override bidding process if auction in a "Buy It Now"
		if ($BIN_amount > 0) {
			$thisbid = $BIN_amount;
			$result = $BIN_WIN;
			// close the auction
			$table_name = $wpdb->prefix . "wpa_auctions";
			$sql = "UPDATE ".$table_name." SET date_end = '".current_time('mysql',"1")."' WHERE id=".$auction_id;
			$wpdb->query($sql);
		}

		if ($result=='') {
			// Step 1 - Retrieve current maximum bid on item !!! - 23/3 !! - This should be MINIMUM as reverse!!!!
			$table_name = $wpdb->prefix . "wpa_bids";
			$strSQL = "SELECT * FROM $table_name WHERE auction_id=".$auction_id." ORDER BY current_bid_price, bid_type LIMIT 1";
			$current = $wpdb->get_row ($strSQL);

			$result = $BID_WIN_REVERSE;

			if (!($current)) {
				$winner = "new";

				// bid is whatever user says it is
				$thisbid = $max_bid;


				// pull in auction details
				$table_name = $wpdb->prefix . "wpa_auctions";
				$strSQL = "SELECT id, name, description, current_price, date_create, date_end, start_price, image_url FROM $table_name WHERE id=".$auction_id;
				$rows = $wpdb->get_row ($strSQL);

				$to      = $bidder_email;
				$subject = "[".$title."] You hold the winning bid on ".$rows->name;
				if (@$emailoptions["highbid"] == "") {
					$body   = "A new bid has been placed on an auction on {site_name}\n\n";
					$body  .= "You are currently holding the winning bid on {auction_name} with {current_price}. ";
					$body  .= "\n\nLink: {auction_link}";
					$body  .= "\n\n--------------------------------------------\n";
				} else {
					$body = $emailoptions["highbid"];
					$body = str_replace("\r\n", "\n", $body);
				}
				if (strlen($staticpage) > 0) {
					$link  = $staticpage."?auction_id=".$auction_id;
				} else {
					$link  = $landingpage."?auction_to_show=".$auction_id;
				}
				$body = str_replace( "{site_name}", get_option('blogname') , $body );
				$body = str_replace( "{auction_name}", $rows->name , $body );
				$body = str_replace( "{auction_link}", $link , $body );
				$body = str_replace( "{current_price}", $currencycode.number_format($thisbid, 2, '.', ','), $body );
				$body = str_replace( "{contact_email}", get_option('admin_email') , $body );
				UTF8_mail($to,$subject,$body);


			} else {
				// let's compare maximum bids first
				if ($max_bid < $current->max_bid_price) {
					$winner = "new";

					// reverse auctions will just accept the user's bid
					$thisbid = $max_bid;

					//pull in auction details
					$table_name = $wpdb->prefix . "wpa_auctions";
					$strSQL = "SELECT id, name,description,current_price,date_create,date_end,start_price,image_url FROM $table_name WHERE id=".$auction_id;
					$rows = $wpdb->get_row ($strSQL);

					$to      = $bidder_email;
					$subject = "[".$title."] You hold the winning bid on ".$rows->name;
					if (@$emailoptions["highbid"] == "") {
						$body   = "A new bid has been placed on an auction on {site_name}\n\n";
						$body  .= "You are currently holding the winning bid on {auction_name} with {current_price}. ";
						$body  .= "\n\nLink: {auction_link}";
						$body  .= "\n\n--------------------------------------------\n";
					} else {
						$body = $emailoptions["highbid"];
						$body = str_replace("\r\n", "\n", $body);
					}
					if (strlen($staticpage) > 0) {
						$link  = $staticpage."?auction_id=".$auction_id;
					} else {
						$link  = $landingpage."?auction_to_show=".$auction_id;
					}
					$body = str_replace( "{site_name}", get_option('blogname') , $body );
					$body = str_replace( "{auction_name}", $rows->name , $body );
					$body = str_replace( "{auction_link}", $link , $body );
					$body = str_replace( "{current_price}", $currencycode.number_format($thisbid, 2, '.', ','), $body );
					$body = str_replace( "{contact_email}", get_option('admin_email') , $body );
					UTF8_mail($to,$subject,$body);

					$to      = $current->bidder_email;
					$subject = "[".$title."] You have been outbid on ".$rows->name;
					if (@$emailoptions["outbid"] == "") {
						$body   = "You have just been outbid on an auction on {site_name}\n\n";
						$body  .= "Unfortunately someone else is currently winning {auction_name} after placing a bid for {current_price}. ";
						$body  .= "You're still in time to win the auction, so click the link below and bid again.";
						$body  .= "\n\nLink: {auction_link}";
						$body  .= "\n\n--------------------------------------------\n";
					} else {
						$body = $emailoptions["outbid"];
						// clean up CRLFs
						$body = str_replace("\r\n", "\n", $body);
					}
					// prepare link
					if (strlen($staticpage) > 0) {
						$link  = $staticpage."?auction_id=".$auction_id;
					} else {
						$link  = $landingpage."?auction_to_show=".$auction_id;
					}
					// replace keywords
					$body = str_replace( "{site_name}", get_option('blogname') , $body );
					$body = str_replace( "{auction_name}", $rows->name , $body );
					$body = str_replace( "{auction_link}", $link , $body );
					$body = str_replace( "{current_price}", $currencycode.number_format($thisbid, 2, '.', ','), $body );
					// Send the email.
					UTF8_mail($to,$subject,$body);

				} else {
					$winner = "old";

					// stick in an extra record in the bids table to track that a new bid has been superceeded
					$table_name = $wpdb->prefix . "wpa_bids";
					$sql = "INSERT INTO ".$table_name." (id, auction_id, date, bidder_name ,bidder_email, bidder_wordpress_id, bidder_url, current_bid_price, max_bid_price, bid_type) VALUES (NULL, ".$auction_id.", '".current_time('mysql',"1")."', '".$bidder_name."', '".$bidder_email."', '".WPA_get_wordpress_id_from_email($bidder_email)."', '".$bidder_url."', ".$max_bid.", ".$max_bid.", 'outbid');";
					$wpdb->query($sql);

					//pull in auction details
					$table_name = $wpdb->prefix . "wpa_auctions";
					$strSQL = "SELECT id, name,description,current_price,date_create,date_end,start_price,image_url FROM $table_name WHERE id=".$auction_id;
					$rows = $wpdb->get_row ($strSQL);
					// highbid_mod_end

					// increase bid to take it above new bid
					$thisbid = $max_bid + wpa_get_increment($max_bid, $customincrement);

					// check we haven't exceeded the old bidder's maximum
					if ($thisbid > ($current->max_bid_price + 0)) { $thisbid = $current->max_bid_price; }

					// if the old bidder wins, update the write variables with old bidder's details
					$bidder_name = $current->bidder_name;
					$bidder_email = $current->bidder_email;
					$bidder_url = $current->bidder_url;
					$max_bid = $current->max_bid_price;
					$bid_type = "auto";

					$to      = $bidder_email;
					$subject = "[".$title."] You hold the winning bid on ".$rows->name;
					if (@$emailoptions["highbid"] == "") {
						$body   = "A new bid has been placed on an auction on {site_name}\n\n";
						$body  .= "You are currently holding the winning bid on {auction_name} with {current_price}. ";
						$body  .= "\n\nLink: {auction_link}";
						$body  .= "\n\n--------------------------------------------\n";
					} else {
						$body = $emailoptions["highbid"];
						$body = str_replace("\r\n", "\n", $body);
					}
					if (strlen($staticpage) > 0) {
						$link  = $staticpage."?auction_id=".$auction_id;
					} else {
						$link  = $landingpage."?auction_to_show=".$auction_id;
					}
					$body = str_replace( "{site_name}", get_option('blogname') , $body );
					$body = str_replace( "{auction_name}", $rows->name , $body );
					$body = str_replace( "{auction_link}", $link , $body );
					$body = str_replace( "{current_price}", $currencycode.number_format($thisbid, 2, '.', ','), $body );
					$body = str_replace( "{contact_email}", get_option('admin_email') , $body );
					UTF8_mail($to,$subject,$body);

					$result = $BID_LOSE;
				}
			}
		}

		if ($result == $BID_WIN_REVERSE || $result == $BID_LOSE || $result == $BIN_WIN) {
			// Update bid table with details on bid
			$table_name = $wpdb->prefix . "wpa_bids";
			$sql = "INSERT INTO ".$table_name." (id, auction_id, date, bidder_name ,bidder_email, bidder_wordpress_id, bidder_url, current_bid_price, max_bid_price, bid_type) VALUES (NULL, ".$auction_id.", '".current_time('mysql',"1")."', '".$bidder_name."', '".$bidder_email."', '".WPA_get_wordpress_id_from_email($bidder_email)."', '".$bidder_url."', ".$thisbid.", ".$max_bid.", '".$bid_type."');";
			$wpdb->query($sql);

			//Update auction table
			$table_name = $wpdb->prefix . "wpa_auctions";
			$sql = "UPDATE ".$table_name." SET current_price = ".$thisbid." WHERE id=".$auction_id;
			$wpdb->query($sql);

			$to = "";
			$cc = "";

			// notify site owner if notification requested
			if ($notify != '' && $whennotify != "winonly") {
				$to = $notify;
			}

			// notify auction owner is requested
			@$notifyowner = get_the_author_meta( 'whennotify', $rows->owner );
			if ( $notifyowner == 'always' || $notifyowner == 'bidonly' ) {
				$seller = get_user_by ( 'id', $owner );
				if ($to == "" ) {
					$to = $seller->user_email;
				} else {
					$cc = $seller->user_email;
				}
			}

			if ($to != "") {
				// get details for mail
				$subject = "[".$title."] New bid on ".$name;
				$body   = "New bid on your auction.";
				if (strlen($staticpage) > 0) {
					$body  .= "\n\nLink: " . $staticpage."?auction_id=".$auction_id;
				} else {
					$body  .= "\n\nLink: " . $landingpage."?auction_to_show=".$auction_id;
				}
				$body  .= "\n\n--------------------------------------------\n";
				// Send the email.
				UTF8_mail($to,$subject,$body,$cc);
			}

			// check if we need to extend the auction
			check_auction_extend ( $auction_id );
		}

	}

	// finalise auction if BIN
	if ($result == $BIN_WIN)  {
		// wait a bit, to make sure Now() in termination check doesn't match NOW() here.
		sleep(2);
		check_auction_end($auction_id);
	}
	return $result;
}


// Simple engine with no proxy bidding
function wpa_process_bid_simple_engine( $auction_id, $bidder_name, $bidder_email, $bidder_url, $max_bid, $BIN_amount ) {

	global $wpdb;
	global $BID_WIN, $BID_LOSE, $BIN_WIN, $BID_WIN_REVERSE;

	//echo "<!-- in code -->";

	$result = "";
	$options = get_option('wp_auctions');
	$notify = $options['notify'];
	$whennotify = $options['whennotify'];
	$title = $options['title'];
	$regonly = $options['regonly'];
	$currencysymbol = $options['currencysymbol'];
	$currencycode = $options['currencycode'];
	$landingpage = $options['landingpage'];
	if ($landingpage == "") $landingpage = get_option('siteurl');

	// Setup email fields.
	$emailoptions = get_option('wp_auctions_email');
	$bid_type = "user";

	// validate input
	if (!is_numeric($auction_id)): // ID not numeric
		$result = __('Invalid Auction ID specified','wpauctions');
	elseif (trim($bidder_name == '')):  // Bidder name not specified
		$result = __('Bidder name not supplied','wpauctions');
	elseif (trim($bidder_email == '')):  // Bidder email not specified
		$result = __('Bidder email not supplied','wpauctions');
	elseif (!wpa_valid_email($bidder_email)):  // Bidder email not specified
		$result = __('Please supply a valid email address -'.$bidder_email.'-','wpauctions');
	elseif (!is_numeric($max_bid)):  // Bidder email not specified
		$result = __('Your bid value is invalid - please remove any non-numerical characters like letters or commas','wpauctions');
	elseif (($regonly=="Yes") && !is_user_logged_in()): // Bidder needs to be registered and isn't (HACK TEST)
		$result = __('You need to be signed in to place bids','wpauctions');
	endif;

	if ($result == '') {
		// If we get this far it means that the input data is completely valid, so sanity check the data
		// Before we start .. confirm if auction has ended or not
		check_auction_end($auction_id);

		// Let's check auction is still active and also check that the bid is in the right range for the (piggyback staticpage)
		$table_name = $wpdb->prefix . "wpa_auctions";
		$strSQL = "SELECT winner, current_price,start_price,staticpage,customincrement, winner, owner, name FROM $table_name WHERE id=".$auction_id;
		$rows = $wpdb->get_row ($strSQL);
		$winner = $rows->winner;
		$customincrement = $rows->customincrement;
		$staticpage = $rows->staticpage; // (don't need this here, just more efficient)
		$owner = $rows->owner; // ditto;
		$name = $rows->name; // ditto

		if ($winner != "") $result=__("Sorry, this auction is now closed",'wpauctions');

		if ($rows->start_price > $max_bid) $result=__("Sorry, your bid must exceed the auction start price",'wpauctions');
		if ($rows->current_price >= $max_bid) $result=__("Sorry, your bid must exceed the current bid price",'wpauctions');
		if ($rows->current_price + wpa_get_increment($rows->current_price, $customincrement) > $max_bid && $rows->current_price <> 0) $result=__("Sorry, your bid must exceed",'wpauctions')." ".$currencysymbol.number_format($rows->current_price + wpa_get_increment($rows->current_price, $customincrement), 2, '.', ',');;

		// override bidding process if auction in a "Buy It Now"
		if ($BIN_amount > 0) {
			$thisbid = $BIN_amount;
			$result = $BIN_WIN;
			// close the auction
			$table_name = $wpdb->prefix . "wpa_auctions";
			$sql = "UPDATE ".$table_name." SET date_end = '".current_time('mysql',"1")."' WHERE id=".$auction_id;
			$wpdb->query($sql);
		}

		if ($result=='') {
			// Step 1 - Retrieve current maximum bid on item
			$table_name = $wpdb->prefix . "wpa_bids";
			$strSQL = "SELECT * FROM $table_name WHERE auction_id=".$auction_id." ORDER BY current_bid_price DESC, bid_type LIMIT 1";
			$current = $wpdb->get_row ($strSQL);

			// simple bidding - bid is whatever user places
			$thisbid = $max_bid;
			$result = $BID_WIN;

			if (!($current)) {
				$winner = "new";

				// simple bidding - bid is whatever user places
				$thisbid = $max_bid;


				// pull in auction details
				$table_name = $wpdb->prefix . "wpa_auctions";
				$strSQL = "SELECT id, name, description, current_price, date_create, date_end, start_price, image_url FROM $table_name WHERE id=".$auction_id;
				$rows = $wpdb->get_row ($strSQL);

				$to      = $bidder_email;
				$subject = "[".$title."] You hold the winning bid on ".$rows->name;
				if (@$emailoptions["highbid"] == "") {
					$body   = "A new bid has been placed on an auction on {site_name}\n\n";
					$body  .= "You are currently holding the winning bid on {auction_name} with {current_price}. ";
					$body  .= "\n\nLink: {auction_link}";
					$body  .= "\n\n--------------------------------------------\n";
				} else {
					$body = $emailoptions["highbid"];
					$body = str_replace("\r\n", "\n", $body);
				}
				if (strlen($staticpage) > 0) {
					$link  = $staticpage."?auction_id=".$auction_id;
				} else {
					$link  = $landingpage."?auction_to_show=".$auction_id;
				}
				$body = str_replace( "{site_name}", get_option('blogname') , $body );
				$body = str_replace( "{auction_name}", $rows->name , $body );
				$body = str_replace( "{auction_link}", $link , $body );
				$body = str_replace( "{current_price}", $currencycode.number_format($thisbid, 2, '.', ','), $body );
				$body = str_replace( "{contact_email}", get_option('admin_email') , $body );
				UTF8_mail($to,$subject,$body);
				// highbid_mod_end

			} else {
				// let's compare maximum bids first
				if ($max_bid > $current->max_bid_price) {
					$winner = "new";

					// simple bidding - bid is whatever user places
					$thisbid = $max_bid;

					//pull in auction details
					$table_name = $wpdb->prefix . "wpa_auctions";
					$strSQL = "SELECT id, name,description,current_price,date_create,date_end,start_price,image_url FROM $table_name WHERE id=".$auction_id;
					$rows = $wpdb->get_row ($strSQL);

					$to      = $bidder_email;
					$subject = "[".$title."] You hold the winning bid on ".$rows->name;
					if (@$emailoptions["highbid"] == "") {
						$body   = "A new bid has been placed on an auction on {site_name}\n\n";
						$body  .= "You are currently holding the winning bid on {auction_name} with {current_price}. ";
						$body  .= "\n\nLink: {auction_link}";
						$body  .= "\n\n--------------------------------------------\n";
					} else {
						$body = $emailoptions["highbid"];
						$body = str_replace("\r\n", "\n", $body);
					}
					if (strlen($staticpage) > 0) {
						$link  = $staticpage."?auction_id=".$auction_id;
					} else {
						$link  = $landingpage."?auction_to_show=".$auction_id;
					}
					$body = str_replace( "{site_name}", get_option('blogname') , $body );
					$body = str_replace( "{auction_name}", $rows->name , $body );
					$body = str_replace( "{auction_link}", $link , $body );
					$body = str_replace( "{current_price}", $currencycode.number_format($thisbid, 2, '.', ','), $body );
					$body = str_replace( "{contact_email}", get_option('admin_email') , $body );
					UTF8_mail($to,$subject,$body);

					$to      = $current->bidder_email;
					$subject = "[".$title."] You have been outbid on ".$rows->name;
					if (@$emailoptions["outbid"] == "") {
						$body   = "You have just been outbid on an auction on {site_name}\n\n";
						$body  .= "Unfortunately someone else is currently winning {auction_name} after placing a bid for {current_price}. ";
						$body  .= "You're still in time to win the auction, so click the link below and bid again.";
						$body  .= "\n\nLink: {auction_link}";
						$body  .= "\n\n--------------------------------------------\n";
					} else {
						$body = $emailoptions["outbid"];
						// clean up CRLFs
						$body = str_replace("\r\n", "\n", $body);
					}
					// prepare link
					if (strlen($staticpage) > 0) {
						$link  = $staticpage."?auction_id=".$auction_id;
					} else {
						$link  = $landingpage."?auction_to_show=".$auction_id;
					}
					// replace keywords
					$body = str_replace( "{site_name}", get_option('blogname') , $body );
					$body = str_replace( "{auction_name}", $rows->name , $body );
					$body = str_replace( "{auction_link}", $link , $body );
					$body = str_replace( "{current_price}", $currencycode.number_format($thisbid, 2, '.', ','), $body );
					// Send the email.
					UTF8_mail($to,$subject,$body);

				} else {
					$winner = "old";

					// stick in an extra record in the bids table to track that a new bid has been superceeded
					$table_name = $wpdb->prefix . "wpa_bids";
					$sql = "INSERT INTO ".$table_name." (id, auction_id, date, bidder_name ,bidder_email, bidder_wordpress_id, bidder_url, current_bid_price, max_bid_price, bid_type) VALUES (NULL, ".$auction_id.", '".current_time('mysql',"1")."', '".$bidder_name."', '".$bidder_email."', '".WPA_get_wordpress_id_from_email($bidder_email)."', '".$bidder_url."', ".$max_bid.", ".$max_bid.", 'outbid');";
					$wpdb->query($sql);

					// increase bid to take it above new bid
					$thisbid = $max_bid + wpa_get_increment($max_bid, $customincrement);

					// check we haven't exceeded the old bidder's maximum
					if ($thisbid > ($current->max_bid_price + 0)) { $thisbid = $current->max_bid_price; }

					// if the old bidder wins, update the write variables with old bidder's details
					$bidder_name = $current->bidder_name;
					$bidder_email = $current->bidder_email;
					$bidder_url = $current->bidder_url;
					$max_bid = $current->max_bid_price;
					$bid_type = "auto";

					$to      = $bidder_email;
					$subject = "[".$title."] You hold the winning bid on ".$rows->name;
					if (@$emailoptions["highbid"] == "") {
						$body   = "A new bid has been placed on an auction on {site_name}\n\n";
						$body  .= "You are currently holding the winning bid on {auction_name} with {current_price}. ";
						$body  .= "\n\nLink: {auction_link}";
						$body  .= "\n\n--------------------------------------------\n";
					} else {
						$body = $emailoptions["highbid"];
						$body = str_replace("\r\n", "\n", $body);
					}
					if (strlen($staticpage) > 0) {
						$link  = $staticpage."?auction_id=".$auction_id;
					} else {
						$link  = $landingpage."?auction_to_show=".$auction_id;
					}
					$body = str_replace( "{site_name}", get_option('blogname') , $body );
					$body = str_replace( "{auction_name}", $rows->name , $body );
					$body = str_replace( "{auction_link}", $link , $body );
					$body = str_replace( "{current_price}", $currencycode.number_format($thisbid, 2, '.', ','), $body );
					$body = str_replace( "{contact_email}", get_option('admin_email') , $body );
					UTF8_mail($to,$subject,$body);

					$result = $BID_LOSE;
				}
			}
		}

		if ($result == $BID_WIN || $result == $BID_LOSE || $result == $BIN_WIN) {
			// Update bid table with details on bid
			$table_name = $wpdb->prefix . "wpa_bids";
			$sql = "INSERT INTO ".$table_name." (id, auction_id, date, bidder_name ,bidder_email, bidder_wordpress_id, bidder_url, current_bid_price, max_bid_price, bid_type) VALUES (NULL, ".$auction_id.", '".current_time('mysql',"1")."', '".$bidder_name."', '".$bidder_email."', '".WPA_get_wordpress_id_from_email($bidder_email)."', '".$bidder_url."', ".$thisbid.", ".$max_bid.", '".$bid_type."');";
			$wpdb->query($sql);

			//Update auction table
			$table_name = $wpdb->prefix . "wpa_auctions";
			$sql = "UPDATE ".$table_name." SET current_price = ".$thisbid." WHERE id=".$auction_id;
			$wpdb->query($sql);

			$to = "";
			$cc = "";

			// notify site owner if notification requested
			if ($notify != '' && $whennotify != "winonly") {
				$to = $notify;
			}

			// notify auction owner is requested
			$notifyowner = get_the_author_meta( 'whennotify', $rows->owner );
			if ( $notifyowner == 'always' || $notifyowner == 'bidonly' ) {
				$seller = get_user_by ( 'id', $owner );
				if ($to == "" ) {
					$to = $seller->user_email;
				} else {
					$cc = $seller->user_email;
				}
			}

			if ($to != "") {
				// get details for mail
				$strSQL = "SELECT * FROM $table_name WHERE id=".$auction_id;
				$rows = $wpdb->get_row ($strSQL);
				$subject = "[".$title."] New bid on ".$rows->name;
				$body   = "New bid on your auction.";
				if (strlen($staticpage) > 0) {
					$body  .= "\n\nLink: " . $staticpage."?auction_id=".$auction_id;
				} else {
					$body  .= "\n\nLink: " . $landingpage."?auction_to_show=".$auction_id;
				}
				$body  .= "\n\n--------------------------------------------\n";

				// Send the email.
				UTF8_mail($to,$subject,$body,$cc);
			}

			// check if we need to extend the auction
			check_auction_extend ( $auction_id );
		}
	}

	// finalise auction if BIN
	if ($result == $BIN_WIN)  {
		// wait a bit, to make sure Now() in termination check doesn't match NOW() here.
		sleep(2);
		check_auction_end($auction_id);
	}

	return $result;
}

function wp_auctions_uninstall () {
	// Cleanup routine. - Deactivated cleanup otherwise we lose data on upgrade
	global $wpdb;
	// $table_name = $wpdb->prefix . "wpa_auctions";
	// $wpdb->query("DROP TABLE {$table_name}");
	// $table_name = $wpdb->prefix . "wpa_bids";
	// $wpdb->query("DROP TABLE {$table_name}");
	wp_clear_scheduled_hook('wpa_daily_check');
}

function wp_auctions_install () {
	global $wpdb;
	$wpa_db_version = "1.15";
	$installed_ver = get_option("wpa_db_version");
	if ($installed_ver != $wpa_db_version) {
		require_once(ABSPATH . 'wp-admin/upgrade-functions.php');
		// Create Auctions Table
		$table_name = $wpdb->prefix . "wpa_auctions";
		$sql = "CREATE TABLE " . $table_name . " (
	    id mediumint(9) NOT NULL AUTO_INCREMENT,
		  date_create datetime NOT NULL,
		  date_start datetime NOT NULL,
		  date_end datetime NOT NULL,
		  date_end_original datetime NOT NULL,
		  name tinytext NOT NULL,
		  description text NOT NULL,
		  image_url tinytext,
		  start_price decimal(10,2) NOT NULL,
		  reserve_price decimal(10,2),
		  current_price decimal(10,2),
		  variable_shipping tinytext,
		  shipping_price decimal(10,2),
	    shipping_to tinytext,
	    shipping_from tinytext,
		  duration tinyint,
		  BIN_price decimal(10,2),
	    winner tinytext,
	    winner_email tinytext,
	    winning_price decimal(10,2),
	    extraimage1 tinytext,
	    extraimage2 tinytext,
	    extraimage3 tinytext,
	    staticpage tinytext,
	    paymentmethod tinytext,
	    terms tinytext,
	    engine tinyint,
	    predesc text,
	    customincrement decimal(10,2),
		owner int,
		  UNIQUE KEY id (id)
		);";
		dbDelta($sql);

		// Create Bids Table
		$table_name = $wpdb->prefix . "wpa_bids";
		$sql = "CREATE TABLE " . $table_name . " (
		  id mediumint(9) NOT NULL AUTO_INCREMENT,
		  auction_id mediumint NOT NULL,
		  date datetime NOT NULL,
		  bidder_name tinytext,
		  bidder_email tinytext,
		  bidder_url tinytext,
		  bidder_IP tinytext,
		  bidder_wordpress_id mediumint,
		  current_bid_price decimal(10,2) NOT NULL,
		  max_bid_price decimal(10,2),
		  bid_type tinytext,
		  second_sent datetime,
		  UNIQUE KEY id (id)
		);";
		dbDelta($sql);

		// Create Watch list Table
		$table_name = $wpdb->prefix . "wpa_watchlist";
		$sql = "CREATE TABLE " . $table_name . " (
		  id mediumint(9) NOT NULL AUTO_INCREMENT,
		  auction_id mediumint NOT NULL,
		  watch_email tinytext,
		  UNIQUE KEY id (id)
		);";
		dbDelta($sql);

		// Create bidder request Table
		$table_name = $wpdb->prefix . "wpa_bidderrequests";
		$sql = "CREATE TABLE " . $table_name . " (
		  id mediumint(9) NOT NULL AUTO_INCREMENT,
		  auction_id mediumint NOT NULL,
		  bidder_id mediumint NOT NULL,
		  RTB_Status tinyint DEFAULT 0,
		  UNIQUE KEY id (id)
		);";
		dbDelta($sql);

		update_option("wpa_db_version", $wpa_db_version);
		//set initial values if none exist
		$options = get_option('wp_auctions');
		if ( !is_array($options) ) {
			$options = array( 'title'=>'WP Auctions', 'currency'=>'2', 'style'=>'default', 'notify'=>'', 'paypal'=>'', 'currencysymbol'=>'$', 'currencycode'=>'USD');
			update_option('wp_auctions', $options);
		}
	}

	// add hourly cron job
	if (!wp_next_scheduled('wpa_daily_check')) {
		wp_schedule_event(time(), 'hourly', 'wpa_daily_check');
	}

	// add 'create_auction' role to any roles that already have 'read'
	//$roles = get_editable_roles();
	//foreach ($GLOBALS['wp_roles']->role_objects as $key => $role)
	//	if (isset($roles[$key]) && $role->has_cap('read'))
	//		$role->add_cap('create_auction');

	$role = get_role ( 'subscriber' );
	if (is_object($role)) {
		$role->add_cap( 'create_auction' );
	}
	
	$user = new WP_User( get_current_user_id() );
	if (is_object($user)) {
    	$user->add_cap( 'create_auction' );
	}
}

function close_expired_auctions() {
	// scheduled event to ensure auctions close properly
	global $wpdb;
	$table_name = $wpdb->prefix . "wpa_auctions";
	$strSQL = "SELECT id FROM $table_name WHERE winner IS NULL";
	$rows = $wpdb->get_results ($strSQL);
	foreach ($rows as $row) {
		check_auction_end ($row->id);
	}
}

function check_auction_extend( $auction_id) {
	// assumption: if this is being called, the auction hasn't closed yet
	global $wpdb;
	// make sure we have a numeric auction number
	$auction_id = $auction_id + 0;
	
	// jump out of auction id is 0
	if ($auction_id != 0 ) {
		// before we do anything .. let's see if we need to extend the auction end time
		$options = get_option('wp_auctions');
		$endtrigger = $options['endtrigger'];
		$endoffset = $options['endoffset'];
		if ( intval($endtrigger) > 0 ) {

			$table_name = $wpdb->prefix . "wpa_auctions";
			$strSQL = "SELECT winner, date_end FROM $table_name WHERE id=".$auction_id;
			$rows = $wpdb->get_row ($strSQL);
			
			if ($rows->winner == "" ) { // double check that auction hasn't closed in the meantime
				// are we within trigger tolerance - comparison done in GMT
				
				$end_date = strtotime($rows->date_end);
				$current_time = strtotime(current_time('mysql',"1"));
				$difference = ($end_date - $current_time);
				// are we in threshold?
				if ( $difference < ($endtrigger * 60)) {
					
					$strSQL = "UPDATE $table_name SET date_end = DATE_ADD(date_end,INTERVAL $endoffset MINUTE) WHERE id=" . $auction_id;
					$wpdb->query($strSQL);
				}
			}
		}
	}
}

function check_auction_end($auction_id) {

	global $wpdb;

	// make sure we have a numeric auction number
	$auction_id = $auction_id + 0;

	// jump out of auction id is 0
	if ($auction_id != 0 ) {

		$options = get_option('wp_auctions');
		$paypal = $options['paypal'];
		$mailingaddress = $options['mailingaddress'];
		$custompayment = $options['custompayment'];
		$bankdetails = $options['bankdetails'];
		$currencysymbol = $options['currencysymbol'];
		$currencycode = $options['currencycode'];
		$title = $options['title'];
		$notify = $options['notify'];
		$whennotify = $options['whennotify'];
		$landingpage = $options['landingpage'];
		if ($landingpage == "") $landingpage = get_option('siteurl');
		$paymentpage = $options['paymentpage'];

		// Setup email fields.
		$emailoptions = get_option('wp_auctions_email');

		// prepare result
		$table_name = $wpdb->prefix . "wpa_auctions";
		$strSQL = "SELECT id, '".current_time('mysql',"1")."' <= date_end, winner, shipping_price, paymentmethod, reserve_price, engine FROM $table_name WHERE id=".$auction_id;
		$rows = $wpdb->get_row ($strSQL, ARRAY_N);

		// pull out shipping/payment details
		$shipping_price = $rows[3];
		$payment_method = $rows[4];

		// grab reserve price
		$reserve_price = $rows[5];

		if ($rows[0] == $auction_id && $rows[1] == 0 && $rows[2] == '') {
			// auction has closed - update winner and price

			// prepare result
			$table_name = $wpdb->prefix . "wpa_bids";

			if ($rows[6] != REVERSE_ENGINE) {
				$strSQL = "SELECT bidder_name, bidder_email, date, current_bid_price FROM $table_name WHERE auction_id=".$auction_id." ORDER BY current_bid_price DESC, bid_type LIMIT 1";
			} else {
				$strSQL = "SELECT bidder_name, bidder_email, date, current_bid_price FROM $table_name WHERE auction_id=".$auction_id." ORDER BY current_bid_price, bid_type LIMIT 1";
			}
			$bidrows = $wpdb->get_row ($strSQL);

			if ($bidrows != '') {  // there is a bid

				// first we have to check if the reserve has been met
				// this applies for reverse auctions too .. because reserve will always be empty
				if ($bidrows->current_bid_price > $reserve_price) {

					$reserve = "Met";
					$winnerdetails = $bidrows->bidder_name . ' (' .$bidrows->bidder_email. ')';

					//update database
					$table_name = $wpdb->prefix . "wpa_auctions";
					$strSQL = "UPDATE $table_name SET winner='$bidrows->bidder_name', winner_email='$bidrows->bidder_email', winning_price = '$bidrows->current_bid_price' WHERE id=" . $auction_id;
					$wpdb->query($strSQL);

					wpa_send_winning_email ( $auction_id );
				}
				else {
					// reserve not met
					$reserve = "NOT MET";
					$winnerdetails = $bidrows->bidder_name . ' (' .$bidrows->bidder_email. ')';

					//update database
					$table_name = $wpdb->prefix . "wpa_auctions";
					$strSQL = "UPDATE $table_name SET winner='$bidrows->bidder_name (Reserve not met)', winning_price = '$bidrows->current_bid_price' WHERE id=" . $auction_id;
					$wpdb->query($strSQL);

					// get details for mail
					$strSQL = "SELECT * FROM $table_name WHERE id=".$auction_id;
					$rows = $wpdb->get_row ($strSQL);

					$emailoptions = get_option('wp_auctions_email');

					$to      = $bidrows->bidder_email;
					$subject = "[".$title."] Auction Closed: ".$rows->name;

					if (@$emailoptions["reserve"] == "") {
						$body   = "You are the top bidder on the following auction on {site_name}.";
						$body  .= "\n\nAuction: {auction_name} for {current_price}";
						$body  .= "\n\nLink: {auction_link}";
						$body  .= "\n\n--------------------------------------------\n";
						$body  .= "Unfortunately your bid was below the reserve price of this auction ({reserve_price}), so it wasn't a successful one.";
						$body  .= "\n\nShould you require any further assistance, please contact me at {contact_email}.";
						$body  .= "\n\n--------------------------------------------\n";

					} else {
						$body = $emailoptions["reserve"];

						// clean up CRLFs
						$body = str_replace("\r\n", "\n", $body);
					}
					// prepare link
					if (strlen($rows->staticpage) > 0) {
						$link  = $rows->staticpage."?auction_id=".$auction_id;
					} else {
						$link  = $landingpage."?auction_to_show=".$auction_id;
					}

					// replace keywords
					$body = str_replace( "{site_name}", get_option('blogname') , $body );
					$body = str_replace( "{auction_name}", $rows->name , $body );
					$body = str_replace( "{auction_link}", $link , $body );
					$body = str_replace( "{payment_details}", $payment , $body );
					$body = str_replace( "{current_price}", $currencycode . $rows->winning_price . "( " . $currencysymbol . $shipping_price . " shipping)", $body );
					$body = str_replace( "{reserve_price}", $currencycode . $rows->reserve_price, $body );
					$body = str_replace( "{contact_email}", get_option('admin_email') , $body );


					// Send the email.
					UTF8_mail($to,$subject,$body);

				}
			} else {
				// there IS not bid

				//update database
				$table_name = $wpdb->prefix . "wpa_auctions";
				$strSQL = "UPDATE $table_name SET winner='No Winner', winning_price = '0' WHERE id=" . $auction_id;
				$wpdb->query($strSQL);

				$winnerdetails = 'No bids';

			}

			// notify site owner if notification requested
			if ($notify != '' && $whennotify != "bidonly") {

				// get details for mail
				$strSQL = "SELECT * FROM $table_name WHERE id=".$auction_id;
				$rows = $wpdb->get_row ($strSQL);

				$to      = $notify;
				$subject = "[".$title."] Auction Closed: ".$rows->name;
				$body   = "Your auction has closed.";
				$body  .= "\n\nReserve: " . $reserve;
				$body  .= "\n\nTop Bid: " . $winnerdetails;

				if (strlen($rows->staticpage) > 0) {
					$body  .= "\n\nLink: " . $rows->staticpage."?auction_id=".$auction_id;
				} else {
					$body  .= "\n\nLink: " . $landingpage."?auction_to_show=".$auction_id;
				}

				if ($winnerdetails != 'No bids') {
					if ($reserve == "NOT MET") {
						$body  .= "\n\nThe top bidder has been sent an email letting them know they've not won.";
					} else {
						switch ($payment_method) {
						case "paypal":
							$body  .= "\n\nThe winner has been sent an email with a PayPal link to complete the transaction";
							break;
						case "bankdetails":
							$body  .= "\n\nThe winner has been sent an email with your bank details and will be remitting payment shortly (reference: ".$auction_id.")";
							break;
						case "mailingaddress":
							$body  .= "\n\nThe winner has been sent an email with your mailing address and requested to quote reference: ".$auction_id;
							break;

						case "custompayment":
							$body  .= "\n\nThe winner has been sent an email with your custom payment instructions and requested to quote reference: ".$auction_id;
							break;
						}
					}
				}

				$body  .= "\n\n--------------------------------------------\n";

				// Send the email.
				UTF8_mail($to,$subject,$body);

			}
		}
	}
}

function wpa_send_winning_email( $auction_id ) {

	global $wpdb;

	$options = get_option('wp_auctions');
	$paypal = $options['paypal'];
	$mailingaddress = $options['mailingaddress'];
	$bankdetails = $options['bankdetails'];
	$custompayment = $options['custompayment'];
	$currencysymbol = $options['currencysymbol'];
	$currencycode = $options['currencycode'];
	$feetype = htmlspecialchars($options['feetype'], ENT_QUOTES);
	$title = $options['title'];
	$landingpage = $options['landingpage'];
	if ($landingpage == "") $landingpage = get_option('siteurl');
	$paymentpage = $options['paymentpage'];

	// make sure we have a numeric auction number
	$auction_id = $auction_id + 0;

	// jump out of auction id is 0
	if ($auction_id != 0 ) {

		// get details for mail
		$table_name = $wpdb->prefix . "wpa_auctions";
		$strSQL = "SELECT * FROM $table_name WHERE id=".$auction_id;
		$rows = $wpdb->get_row ($strSQL);

		$emailoptions = get_option('wp_auctions_email');

		$to      = $rows->winner_email;
		$subject = "[".$title."] Auction Closed: ".$rows->name;

		if (@$emailoptions["win"] == "") {
			$body   = "Congratulations! You have just won the following auction on {site_name}.";
			$body  .= "\n\nAuction: {auction_name} for {current_price}";
			$body  .= "\n\nLink: {auction_link}";
			$body  .= "\n\n--------------------------------------------\n";
			$body  .= "{payment_details}";
			$body  .= "\n\nShould you require any further assistance, please contact me at {contact_email}.";
			$body  .= "\n\n--------------------------------------------\n";

		} else {
			$body = $emailoptions["win"];

			// clean up CRLFs
			$body = str_replace("\r\n", "\n", $body);
		}
		// prepare link
		if (strlen($rows->staticpage) > 0) {
			$link  = $rows->staticpage."?auction_id=".$auction_id;
		} else {
			$link  = $landingpage."?auction_to_show=".$auction_id;
		}

		// prepare payment
		switch ($rows->paymentmethod) {
		case "paypal":
			$payment  = "\n\nYou can pay for the auction by clicking on the link below:";

			if ($paymentpage == '') {

				// pick paypal target
				// current thinking: Payment goes to auction owner. If paypal not supplied, goes to WPA settings
				$paypalaccounttouse = get_the_author_meta( 'paypal', $rows->owner );   // this overrides $paypal
				if ( $paypalaccounttouse == "" ) $paypalaccounttouse = $paypal;

				$payment .= "\n\nhttps://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=".urlencode($paypal)."&item_name=".urlencode($rows->name)."&amount=".urlencode($rows->winning_price+wpa_calculatefee($rows->winning_price))."&shipping=".urlencode($rows->shipping_price)."&no_shipping=0&no_note=1&amp;currency_code=".$currencycode."&lc=GB&bn=PP%2dBuyNowBF&charset=UTF%2d8";
			} else {
				$payment .= "\n\n".$paymentpage."?id=".$auction_id;
			}
			break;
		case "bankdetails":
			$payment  = "\n\nMy banking details are as follows:\n\n";
			$payment .= $bankdetails;
			$payment .= "\n\nPlease submit your payment for ".$currencysymbol.($rows->winning_price+$rows->shipping_price+wpa_calculatefee($rows->winning_price))." using the auction number (".$auction_id.") as a reference";
			break;
		case "mailingaddress":
			$payment  = "\n\nMy postal address is as follows:\n\n";
			$payment .= $mailingaddress;
			$payment .= "\n\nPlease send me a cheque or postal order for ".$currencysymbol.($rows->winning_price+$rows->shipping_price+wpa_calculatefee($rows->winning_price))." quoting the auction number (".$auction_id.") as a reference";
			break;
		case "custompayment":
			$payment  = "\n\nMy payment instructions are follows:\n\n";
			$payment .= $custompayment;
			$payment .= "\n\nPlease remit your payment for ".$currencysymbol.($rows->winning_price+$rows->shipping_price+wpa_calculatefee($rows->winning_price))." quoting the auction number (".$auction_id.") as a reference";
			break;
		}

		// replace keywords
		$body = str_replace( "{site_name}", get_option('blogname') , $body );
		$body = str_replace( "{auction_name}", $rows->name , $body );
		$body = str_replace( "{auction_link}", $link , $body );
		$body = str_replace( "{payment_details}", @$payment , $body );
		$body = str_replace( "{current_price}", $currencycode . $rows->winning_price . ( $rows->shipping_price > 0 ? " (" . $currencycode . $rows->shipping_price . " shipping)" : "" ) . ( $feetype != "" ? " (Fee: " . $currencycode . wpa_calculatefee($rows->winning_price) . ")" : "" ), $body );
		$body = str_replace( "{contact_email}", get_option('admin_email') , $body );

		// Send the email.
		UTF8_mail($to,$subject,$body);
	}
}


function wpa_send_secondchance_email( $auction_id, $bid_id ) {

	global $wpdb;

	$options = get_option('wp_auctions');
	$paypal = $options['paypal'];
	$mailingaddress = $options['mailingaddress'];
	$bankdetails = $options['bankdetails'];
	$custompayment = $options['custompayment'];
	$currencysymbol = $options['currencysymbol'];
	$currencycode = $options['currencycode'];
	$feetype = htmlspecialchars($options['feetype'], ENT_QUOTES);
	$title = $options['title'];
	$landingpage = $options['landingpage'];
	if ($landingpage == "") $landingpage = get_option('siteurl');
	$paymentpage = $options['paymentpage'];

	// make sure we have a numeric auction number
	$auction_id = $auction_id + 0;
	$bid_id = $bid_id + 0;

	// jump out of auction id is 0
	if ($auction_id != 0 && $bid_id != 0) {

		// get details for mail
		$table_name = $wpdb->prefix . "wpa_auctions";
		$strSQL = "SELECT * FROM $table_name WHERE id=".$auction_id;
		$rows = $wpdb->get_row ($strSQL);

		$table_name = $wpdb->prefix . "wpa_bids";
		$strSQL = "SELECT * FROM $table_name WHERE id=".$bid_id;
		$bid_row = $wpdb->get_row ($strSQL);

		$emailoptions = get_option('wp_auctions_email');

		$to      = $bid_row->bidder_email;
		$subject = "[".$title."] Second Chance Offer: ".$rows->name;

		if (@$emailoptions["secondchance"] == "") {
			$body   = "Unfortunately you missed out winning an auction at {site_name}. However you can still purchase the item at the price you were ready to bid!";
			$body  .= "\n\nAuction: {auction_name} for {offer_price}";
			$body  .= "\n\nLink: {auction_link}";
			$body  .= "\n\n--------------------------------------------\n";
			$body  .= "{payment_details}";
			$body  .= "\n\nShould you require any further assistance, please contact me at {contact_email}.";
			$body  .= "\n\n--------------------------------------------\n";

		} else {
			$body = $emailoptions["secondchance"];

			// clean up CRLFs
			$body = str_replace("\r\n", "\n", $body);
		}
		// prepare link
		if (strlen($rows->staticpage) > 0) {
			$link  = $rows->staticpage."?auction_id=".$auction_id;
		} else {
			$link  = $landingpage."?auction_to_show=".$auction_id;
		}

		$offerprice = ($bid_row->max_bid_price+$rows->shipping_price+wpa_calculatefee($bid_row->max_bid_price));

		// prepare payment
		switch ($rows->paymentmethod) {
		case "paypal":
			$payment  = "\n\nYou can pay for the auction by clicking on the link below:";

			if ($paymentpage == '') {

				// pick paypal target
				// current thinking: Payment goes to auction owner. If paypal not supplied, goes to WPA settings
				$paypalaccounttouse = get_the_author_meta( 'paypal', $rows->owner );   // this overrides $paypal
				if ( $paypalaccounttouse == "" ) $paypalaccounttouse = $paypal;

				$payment .= "\n\nhttps://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=".urlencode($paypal)."&item_name=".urlencode($rows->name)."&amount=".urlencode($offerprice)."&shipping=".urlencode($rows->shipping_price)."&no_shipping=0&no_note=1&amp;currency_code=".$currencycode."&lc=GB&bn=PP%2dBuyNowBF&charset=UTF%2d8";
			} else {
				$payment .= "\n\n".$paymentpage."?id=".$auction_id;
			}
			break;
		case "bankdetails":
			$payment  = "\n\nMy banking details are as follows:\n\n";
			$payment .= $bankdetails;
			$payment .= "\n\nPlease submit your payment for ".$currencysymbol.$offerprice." using the auction number (".$auction_id.") as a reference";
			break;
		case "mailingaddress":
			$payment  = "\n\nMy postal address is as follows:\n\n";
			$payment .= $mailingaddress;
			$payment .= "\n\nPlease send me a cheque or postal order for ".$currencysymbol.$offerprice." quoting the auction number (".$auction_id.") as a reference";
			break;
		case "custompayment":
			$payment  = "\n\nMy payment instructions are follows:\n\n";
			$payment .= $custompayment;
			$payment .= "\n\nPlease remit your payment for ".$currencysymbol.$offerprice." quoting the auction number (".$auction_id.") as a reference";
			break;
		}

		// replace keywords
		$body = str_replace( "{site_name}", get_option('blogname') , $body );
		$body = str_replace( "{auction_name}", $rows->name , $body );
		$body = str_replace( "{auction_link}", $link , $body );
		$body = str_replace( "{payment_details}", $payment , $body );
		$body = str_replace( "{offer_price}", $currencycode . ' ' . $bid_row->max_bid_price . ( $rows->shipping_price > 0 ? " (" . $currencycode . $rows->shipping_price . " shipping)" : "" ) . ( $feetype != "" ? " (Fee: " . $currencycode . wpa_calculatefee($bid_row->max_bid_price) . ")" : "" ), $body );
		$body = str_replace( "{contact_email}", get_option('admin_email') , $body );

		// Send the email.
		UTF8_mail($to,$subject,$body);
		
		// update bid record		
		$table_name = $wpdb->prefix . "wpa_bids";
		$sql = "UPDATE ".$table_name." SET second_sent = '".current_time('mysql',"1")."' WHERE id=".$bid_id;
		$wpdb->query($sql);
		
	}
}



function widget_wp_auctions_init() {

	// OCT 2014 - added prophylactic code to ensure this doesn't get called more than once
	
	if ( !function_exists('widget_wp_auctions') ) {
		function widget_wp_auctions($args) {
	
			extract($args);
	
			echo $before_widget;
			docommon_wp_auctions();
			echo $after_widget;
		}

		function widget_wp_auctions_control() {
	
			echo 'Please configure the widget from the Auctions Configuration Screen';
		}

		wp_register_sidebar_widget( 'WP_Auctions', 'WP Auctions', 'widget_wp_auctions', array('description' => 'Add an auction to your website'));
		wp_register_widget_control( 'WP_Auctions', 'WP Auctions', 'widget_wp_auctions_control');
	}
}

function wp_auctions(){

	docommon_wp_auctions();
}

// Post Auction goes here
function dopost_wp_auctions($auction_id) {

	global $wpdb;
	global $BID_WIN, $BID_LOSE, $BIN_WIN, $BID_WIN_REVERSE;

	$options = get_option('wp_auctions');
	$style = $options['style'];
	$currencysymbol = $options['currencysymbol'];
	$title = $options['title'];
	$regonly = $options['regonly'];
	$currencycode = $options['currencycode'];
	$customcontact = $options['customcontact'];
	$countdown = $options['countdown'];
	$custompayment = $options['custompayment'];
	$requesttobid = $options['requesttobid'];
	$hidecustomcontact = $options['hidecustomcontact'];
	$refreshtimeout = $options['refreshtimeout'];
	$anonymizebidder = $options['anonymizebidder'];
	$inpagedisplay = $options['inpagedisplay'];
	$wpa_termsandconditions = $options['termsandconditions'];
	$hideseller = $options['hideseller'];
	$overridelogin = $options['overridelogin'];
	$overridereg = $options['overridereg'];
		
	// ensure regonly is true if RTB is true
	if ($requesttobid == "Yes") $regonly = "Yes";

	if ($customcontact == "") $customcontact = "URL";

	$options = get_option('wp_auctions');

	if (isset($_GET["auction_id"]) && ($_GET['auction_id'] > 0)) {
		$auction_id = intval($_GET['auction_id']);
	}

	// First of all, has a bid just been posted?
	$result = "";
	if (isset($_POST["mode"]) && ($_POST["mode"] == "bid" )) {

		$auction_id = intval($_POST['auction_id']);
		@$bidder_name = htmlspecialchars(strip_tags(stripslashes($_POST['bidder_name'])), ENT_QUOTES);
		@$bidder_email = strip_tags(stripslashes($_POST['bidder_email']));
		@$bidder_url = htmlspecialchars(strip_tags(stripslashes($_POST['bidder_url'])), ENT_QUOTES);
		@$max_bid = $_POST['max_bid'];
		$BIN_amount = $_POST['BIN_Amount'];
		
		if ($max_bid == "") $max_bid = 0; // cater for non-populating when BIN1

		// handle missing fields in modern display
		if (is_user_logged_in()) {
			$current_user = wp_get_current_user();

			if ( $bidder_name == "" ) $bidder_name = $current_user->display_name;
			if ( $bidder_email == "" ) $bidder_email = $current_user->user_email;
			if ( $bidder_url == "" ) $bidder_url = $current_user->user_url;
		}

		$result = wpa_process_bid( $auction_id, $bidder_name, $bidder_email, $bidder_url, $max_bid, $BIN_amount );

	}

	// do some pre-work on whether we need registration or not and what the default settings are
	$needreg = false;
	if (($regonly=="Yes") && !is_user_logged_in()) {
		$needreg = true;
	} else {

		// if the user is logged in .. might as well prepopulate the form
		$defaultname = "";
		$defaultemail = "";
		$defaulturl = "";
		$readonly = false;
		if (is_user_logged_in()) {
			$current_user = wp_get_current_user();

			$defaultname = $current_user->display_name;
			$defaultemail = $current_user->user_email;
			$defaulturl = $current_user->user_url;
			$readonly = true;
		}
	}

	// do prework on need to request
	$needtorequest = false;
	$requeststate = 0;
	if ($requesttobid == "Yes") {
		$needtorequest = true;

		// check if we have a request
		if (is_user_logged_in()) {
			$current_user = wp_get_current_user();

			$bidder_id = $current_user->ID;
		} else {
			$bidder_id = 0;
		}

		$table_name = $wpdb->prefix . "wpa_bidderrequests";
		$strSQL = "SELECT * FROM $table_name WHERE auction_id=".$auction_id." AND bidder_id=".$bidder_id;
		$row = $wpdb->get_row ($strSQL);

		if ($row != null) {
			$requeststate = $row->RTB_Status;
		}
	}

	// select the correct record
	$table_name = $wpdb->prefix . "wpa_auctions";

	// don't have an ID? let's get a random one
	if(!is_numeric($auction_id)) {
		// let's see if we can work out which auction we need from the database
		$strSQL = "SELECT id FROM ".$table_name." WHERE staticpage='".get_permalink()."'";
		//echo "<!-- $strSQL -->";

		$row = $wpdb->get_row ($strSQL);
		$auction_id = $row->id;

		//echo "<!-- Going with $auction_id -->";

	} // else {   echo "<!-- Going with $auction_id -->"; }

	// if we *still* don't have an ID .. let's just pick a random one
	if(!is_numeric($auction_id)) {
		$cond = "'".current_time('mysql',"1")."' < date_end order by rand() limit 1";
	} else {
		$cond = "id=".$auction_id;
	}
	$strSQL = "SELECT id, image_url, extraimage1, extraimage2, extraimage3, name, description, date_end, date_start, duration, BIN_price, start_price, current_price, reserve_price, variable_shipping, shipping_price, shipping_to, shipping_from, paymentmethod, terms, customincrement, owner, staticpage, '".current_time('mysql',"1")."' < date_end AS active, engine, '".current_time('mysql',"1")."' < date_start AS pending FROM ".$table_name." WHERE ".$cond;
	$row = $wpdb->get_row ($strSQL);

	// grab values we need
	if ($row != null) {
		$image_url = $row->image_url;
		$name = $row->name;
		$description = $row->description;
		$end_date = get_date_from_gmt($row->date_end);
		$start_date = get_date_from_gmt($row->date_start);
		$current_price = $row->current_price;
		$BIN_price = $row->BIN_price;
		$start_price = $row->start_price;
		$reserve_price = $row->reserve_price;
		$id = $row->id;
		$terms = $row->terms;
		$variable_shipping = $row->variable_shipping;
		$shipping_price = $row->shipping_price;
		$shipping_to = $row->shipping_to;
		$shipping_from = $row->shipping_from;
		$staticpage = $row->staticpage;
		$active = $row->active;
		$delayed = $row->pending;
		$payment_method = $row->paymentmethod;
		$extraimage = array($row->extraimage1, $row->extraimage2, $row->extraimage3 );
		$engine = $row->engine;
		$customincrement = $row->customincrement;
		$owner = $row->owner;

		// get extra owner details

		$strSQL = "SELECT count(*) FROM $table_name WHERE owner=".$owner;
		$owner_total = $wpdb->get_var ($strSQL);

		$strSQL = "SELECT count(*) FROM $table_name WHERE owner=".$owner." AND '".current_time('mysql',"1")."' < date_end";
		$owner_current = $wpdb->get_var ($strSQL);



		// countdown stuff
		$end_dateGMT = $row->date_end;
		$start_dateGMT = $row->date_start;

		// calculate difference between now and end date .. we'll do this with server timezone
		$today = strtotime("now");
		$auctionend = strtotime($end_dateGMT);
		$secsdiff = $auctionend - $today;

		switch ($countdown) {
		case 0:
			$showcountdown = false;
			break;
		case 999:
			$showcountdown = true;
			break;
		default:
			$showcountdown = ( $secsdiff < $countdown );
		}
	} else {
		// handle no results returned
		$image_url = "";
		$name = "";
		$description = "No auction selected";
		$end_date = "";
		$start_date = "";
		$current_price = "";
		$BIN_price = "";
		$start_price = "";
		$reserve_price = "";
		$id = "";
		$terms = "";
		$variable_shipping = "";
		$shipping_price = "";
		$shipping_to = "";
		$shipping_from = "";
		$staticpage = "";
		$active = "";
		$delayed = "";
		$payment_method = "";
		$extraimage = "";
		$engine = "";
		$customincrement = "";
		$owner = "";

	}

	if ($shipping_to == "") $shipping_to = "n/a";
	if ($shipping_from == "") $shipping_from = "n/a";

	$hasbid = ( $start_price > 0 && $active);
	$hasbin = ( $BIN_price > 0 && $active);

	// always disable BIN if needs approval and doesn't have one
	if ( $needtorequest && $requeststate != RTB_approved) {
		$hasbin = false;
	}

	// engine specific code
	switch ($engine) {
	case 1: // standard
		if ($current_price >= $start_price) {
			$nextbid = $currencysymbol . number_format($current_price + wpa_get_increment($current_price, $customincrement), 2, '.', ',');
		} else {
			$nextbid = $currencysymbol . number_format($start_price, 2, '.', ',');
		}

		$maximumbid_message = __('Enter Your Maximum Bid','wpauctions');
		$bidhigher_message = __('Bid','wpauctions')." " . $nextbid . " " . __('or higher','wpauctions'). " ";
		break;

	case 2: // simple
		if ($current_price >= $start_price) {
			$nextbid = $currencysymbol . number_format($current_price + wpa_get_increment($current_price, $customincrement), 2, '.', ',');
		} else {
			$nextbid = $currencysymbol . number_format($start_price, 2, '.', ',');
		}

		$maximumbid_message = __('Enter Your Bid','wpauctions');
		$bidhigher_message = __('Bid','wpauctions')." " . $nextbid . " " .__('or higher','wpauctions');
		break;

	case 3: // reverse
		if ( $current_price == 0) {
			$nextbid = $currencysymbol . number_format($start_price, 2, '.', ',');
		} else {
			$nextbid = $currencysymbol . number_format($current_price - wpa_get_increment($current_price,$customincrement), 2, '.', ',');
		}
		$maximumbid_message = __('Place Bid [Reverse Auction]','wpauctions');
		$bidhigher_message = __('Bid','wpauctions')." " . $nextbid . " ".__('or lower','wpauctions');
		break;
		
	case 4: // quickbuy
		if ($current_price >= $start_price) {
			$nextbid = $currencysymbol . number_format($current_price + wpa_get_increment($current_price, $customincrement), 2, '.', ',');
			$thisbid = number_format($current_price + wpa_get_increment($current_price, $customincrement), 2, '.', ',');
		} else {
			$nextbid = $currencysymbol . number_format($start_price, 2, '.', ',');
			$thisbid = number_format($start_price, 2, '.', ',');
		}

		$maximumbid_message = __('Click to Bid','wpauctions');
		$bidhigher_message = __('Next Bid','wpauctions')." " . $nextbid;
		break;		
		
	}

	$inreserve = false;
	if ($reserve_price > 0) {
		if ($reserve_price > $current_price) {
			$reservestring = ' [<em>'.__('Not met','wpauctions').'</em>]';
			$inreserve = true;	
		} else
			$reservestring =' [<strong>'.__('Met','wpauctions').'</strong>]';
	} else {
		$reservestring =' [<em>'.__('n/a','wpauctions').'</em>]';
	}

	// get bids
	$table_name = $wpdb->prefix . "wpa_bids";
	if ($engine != REVERSE_ENGINE) {
		$strSQL = "SELECT bidder_name, bidder_email, bidder_url , bidder_wordpress_id ,date,current_bid_price, bid_type FROM $table_name WHERE auction_id=".$auction_id." ORDER BY current_bid_price DESC, bid_type";
	} else {
		$strSQL = "SELECT bidder_name, bidder_email, bidder_url , bidder_wordpress_id, date,current_bid_price, bid_type FROM $table_name WHERE auction_id=".$auction_id." ORDER BY current_bid_price, bid_type";
	}
	$rows = $wpdb->get_results ($strSQL);

	$topbidder = "";
	$lastbiddate = "N/A";
	$firstbiddate = "N/A";

	$numbids = 0;
	foreach ($rows as $bid) {
		$numbids++;
		if ($topbidder == "") {
			$topbidder = anon_bidder_name($bid->bidder_name, $anonymizebidder);
			$lastbiddate = human_time_diff( strtotime(get_date_from_gmt($bid->date)) , current_time('timestamp'));
		}
		$firstbiddate = human_time_diff( strtotime(get_date_from_gmt($bid->date)) , current_time('timestamp')); // keeps overwriting till we get last one
	}

    //////////////////////////////////////////////
    //////// MODERN STYLE STARTS HERE ////////////
    //////////////////////////////////////////////
    
	if ($inpagedisplay == "modern") {

		$p = '';

		$p .= '<section class="wpa-main col-md-12">';

		$p .= '<div id="user-login" class="wpa-login-register">';

		$current_user = wp_get_current_user();
		if ( 0 == $current_user->ID ) {
			$p .= '<p class="wpa-user-status"><a href="'.($overridelogin ? $overridelogin : wp_login_url( get_permalink() )).'" class="label label-info">Login</a> | <a href="'.($overridereg ? $overridereg : wp_registration_url()).'" class="label label-primary">Register</a></p>';
		} else {
			$p .= '<p class="wpa-user-status">'.__('Welcome','wpauctions').', '.$current_user->display_name.'! '.__('You are logged in.','wpauctions').'</p>';
		}
		$p .= '</div><!-- /.wpa-login-register -->';

		$p .= '<section class="wpa-intro clearfix">';

		if ($result != "") {

			// figure out if user isn't logged in
			if ($result == __('Bidder name not supplied','wpauctions')) $result = __('You must log in to bid!','wpauctions');

			$colour = "red";
			if ($result == $BID_WIN || $result == $BIN_WIN) { $colour = "green"; }

			$p .= '<div id="auction-alert" style="background:'.$colour.'; margin: 8px 0 0; padding: 5px; text-align: center; color: #fff;">'.$result.'</div>';


$p .= '<script type="text/javascript">';
$p .= 'jQuery(document).ready(function () {';
$p .= '   jQuery("#auction-alert").delay(15000).fadeOut(300);';
$p .= '});';
$p .= '</script>';


		}
		$p .= '<h2 class="wpa-auction-title">'.$name.'</h2>';

		if (!$active) $p .=  '<div class="wpa-auction-closed-notice"><p>'.__('Auction Closed','wpauctions').'</p></div>';

		$p .= '<div class="wpa-thumbnail-social col-xs-12 col-md-4">';

		$p .= '<ul class="wpa-social">';

		$p .= '</ul>';

		$p .= '<div id="wpa-carousel" class="carousel slide" data-ride="carousel" data-interval="false">';

		$p .= '<div class="carousel-inner">';
		$p .= '<div class="item active">';
		if ($image_url > 0) {
			$p .= '<a href="'.wp_get_attachment_url( $image_url ).'"  class="thickbox"  title="'.$name.'">';
		} else {
			$p .= '      	<a href="#">';
		}

		$p .= '<img src="'.wpa_resize($image_url,150).'" data-zoom-image="'.wp_get_attachment_url($image_url).'" alt="image" id="wpa_image" class="thickbox img-rounded img-responsive" /></a>';
		$p .= '</div>';

		$errors = array_filter($extraimage);
		$noextraimages = (!empty($errors));

		if ($noextraimages != "") {
			for ($i = 0; $i <= 2; $i++) {
				if ($extraimage[$i] != "" ) {
					$p .= '<div class="item">';
					$p .= '<a href="'.wp_get_attachment_url($extraimage[$i]).'" class="thickbox" title="'.$name.'"><img src="'.wpa_resize($extraimage[$i],150).'"  data-zoom-image="'.wp_get_attachment_url($extraimage[$i]).'" alt="image"  id="wpa_image_'.($i + 2).'" class="thickbox img-rounded img-responsive" /></a>';
					$p .= '</div>';
				}
			}
		}

		$p .= '</div><!-- /.carousel-inner -->';

		if ($noextraimages != "") {
			$p .= '<!-- Controls -->';
			$p .= '<a class="left carousel-control" href="#wpa-carousel" data-slide="prev">';
			$p .= '<span class="fa fa-chevron-left"></span>';
			$p .= '</a>';
			$p .= '<a class="right carousel-control" href="#wpa-carousel" data-slide="next">';
			$p .= '<span class="fa fa-chevron-right"></span>';
			$p .= '</a>';
		}
		$p .= '</div><!-- /.carousel -->';

		$p .= '</div><!-- /.wpa-thumbnail -->';

		$p .= '<div class="wpa-bid-area col-xs-12 col-md-8">';
		$p .= '<div id="wpa_notice_div"></div>';
		$p .= '<h4 class="wpa-current-bid text-danger clearfix">';
		if ($active) {
			$p .= '<span id="wpa-liveprice">'.wpa_get_price($current_price,$start_price,$BIN_price,$currencysymbol," ").' </span><a href="javascript:void(0)" onClick="Javascript:wpa_newlayout_ajax_update('.$auction_id.')"><i class="fa fa-refresh"></i></a>';
		} else {
			$p .= ($inreserve ? __('Highest Bid ','wpauctions') : __('Sold for','wpauctions')).': '.$currencysymbol.$current_price;
		}
		$p .= '<a href="#bidstab" class="wpa-bids-count pull-right">['.$numbids.' Bids]</a>';
		$p .= '</h4><!-- /h4 -->';

		$p .= '<p>';
		$p .= '<span class="wpa-reserve">'.__('Reserve','wpauctions').': '.$reservestring.'</span>';
		if ($topbidder != "")
			$p .= '<span class="wpa-winner pull-right">'.($active ? __('Winning','wpauctions') : ($inreserve ? __('Top Bidder','wpauctions') : __('Winner','wpauctions'))) .': '.$topbidder.'</span>';
		$p .= '</p>';


		if ($needtorequest && $requeststate != RTB_approved ) {

			// Request to bid section

			if ( $requeststate == 0 ) {
				$requeststyle = "";
				$responsestyle = "display:none";
			} else {
				$requeststyle = "display:none";
				$responsestyle = "";
			}

			if (is_user_logged_in()) {
				$current_user = wp_get_current_user();

				$username = $current_user->display_name;
				$userID = $current_user->ID;

				$p .= '<p class="wpa-loggedin">'.__('You need to request access to bid on this auction','wpauctions').'</p>';

				$submitfiller = "wpa_request_to_bid ( 'page' );";

				$p .= '     <div class="wpa-request">';
				$p .= '      	<form id="wpa-requestform" action="test">';
				$p .= '          	<fieldset>';
				$p .= '                <p><span class="wpa-approval-name">Your name: </span><strong>'.$username.'</strong></p><div id="wpa-request_pagerequest" style="'.$requeststyle.'">';
				$p .= '                <input id="wpa-request_pageauction_id" type="hidden" value="'.$auction_id.'">';
				$p .= '                <input id="wpa-request_pagebidder_id" type="hidden" value="'.$userID.'">';
				$p .= '                <input type="button" id="wpa-request_pagebutton" value="'.__('Request To Bid','wpauctions').'" onClick="'.$submitfiller.'" />';
				$p .= '                </div><div id="wpa-request_pageresponse" style="'.$responsestyle.'"><p>Your request has been logged</p></div>';
				$p .= '           </fieldset>';
				$p .= '        </form>';

				if ($requeststate == RTB_denied) {
					$p .= '<p class="wpa-loggedin">'.__('Your request to bid on this auction has been <span style="text-decoration: underline;">Denied</span>','wpauctions').'</p>';
				}

				$p .= '     </div><!-- Request access -->  ';

			} else {
				$p .= '<p class="wpa-loggedin">'.__('Bidding for registered & approved users only','wpauctions').'<a href="'.($overridelogin ? $overridelogin : wp_login_url( get_permalink() )).'">'.__('Log in','wpauctions').'</a>'.__(' or ','wpauctions').'<a href="'.($overridereg ? $overridereg : wp_registration_url()).'">'.__('Register','wpauctions').'</a>.</p>';
			}

			// end Request To Bid Section


		} else {



			if ($hasbid && !$delayed) {
				$p .= '<form class="wpa-bid-form" action="'.$staticpage.'#auction-alert" method="POST">';
				$p .= '<div class="input-group">';
				$p .= '<span class="input-group-addon">'.$currencysymbol.' '.$currencycode.'</span>';
				if ($engine != QUICKBUY_ENGINE) {
				    $p .= '<input name="max_bid"  class="form-control" id="prependedInput" type="text" placeholder="'.__('Enter your bid','wpauctions').'">';
				} else {
					$p .= '<input name="max_bid"  class="form-control" id="prependedInput" type="text" value="'.$thisbid.'" readonly>';
				}
				$p .= '<span class="input-group-btn">';
				$p .= '<button class="btn btn-success" type="button" onClick="submit()">'.__('Place Bid','wpauctions').'</button>';
				$p .= '</span>';
				$p .= '</div>';
				$p .= '<input type="hidden" name="mode" value="bid">';
				$p .= '<input type="hidden" name="auction_id" value="'.$auction_id.'">';
				$p .= '<input type="hidden" name="BIN_Amount" value="">';
				$p .= '</form><!-- /form.wpa-bid-form -->';

				if ($engine == QUICKBUY_ENGINE) {
					// add additional disclaimer
					$p .= '<div class="quickbuy-disclaimer"><p>'.__('Clicking "Place Bid" will accept your bid','wpauctions')."</p></div>";	
				}		
				
				
			}
		}

		// pick up logged in user context
		$watchemail = $defaultemail;
		$submitfiller = "wpa_register_watcher ( 'page' );";

		$p .= '<form id="watch-form">';
		$p .= '<input id="wpa-pageemail" type="hidden" value="'.$watchemail.'" />';
		$p .= '<input id="wpa-pageid" type="hidden" value="'.$auction_id.'">';
		$p .= '</form>';

		$p .= '<ul class="wpa-info col-xs-12">';
		if ($active) {
			$p .= '<li class="col-xs-6 wpa-watch-this"><strong><a href="javascript:void(0)" onClick="'.$submitfiller.'">'.__('Watch this auction','wpauctions').'</a></strong></li>';
			$p .= '<li class="col-xs-6 wpa-bid-higher"><em>'.$bidhigher_message.'</em></li>';
		} else {
			$p .= '<li class="col-xs-6 wpa-auction-closed"><strong>'.__('Auction closed','wpauctions').'</a></strong></li>';
			$p .= '<li class="col-xs-6 wpa-bidding-over"><em>'.__('Bidding Over','wpauctions').'</em></li>';
		}
		$p .= '<li class="col-xs-6" id="wpa-firstbiddate"><strong>'.__('First Bid','wpauctions').':</strong> <abbr title="'.$firstbiddate.'">'.$firstbiddate.'</abbr> '.(($firstbiddate == 'N/A') ? '' : __('ago','wpauctions')).'</li>';
		$p .= '<li class="col-xs-6" id="wpa-lastbiddate"><strong>'.__('Last Bid','wpauctions').':</strong> <abbr title="'.$lastbiddate.'">'.$lastbiddate.'</abbr> '.(($lastbiddate == 'N/A') ? '' : __('ago','wpauctions')).'</li>';
		$p .= '<li class="col-xs-6 wpa-shipping-info"><strong>'.__('Shipping','wpauctions').':</strong> '.$shipping_to.'</li>';
		switch ($payment_method) {
		case "paypal":
			$p .= '<li class="col-xs-6 wpa-payment-info-paypal"><strong>'.__('Payment','wpauctions').':</strong> <img src="'.WPA_PLUGIN_STYLE.'/paypal.gif" alt="PayPal" /></li>';
			break;
		case "bankdetails":
			$p .= '<li class="col-xs-6 wpa-payment-info-wire"><strong>'.__('Payment','wpauctions').':</strong> '.__('Wire Transfer','wpauctions').'</li>';
			break;
		case "mailingaddress":
			$p .= '<li class="col-xs-6 wpa-payment-info-cheque"><strong>'.__('Payment','wpauctions').':</strong> '.__('Cheque to be posted','wpauctions').'</li>';
			break;
		case "custompayment":
			$p .= '<li class="col-xs-6 wpa-payment-info-custom"><strong>'.__('Payment','wpauctions').':</strong> '.__('Instructions to follow','wpauctions').'</li>';
			break;
		}

		$p .= '</ul><!-- /ul.wpa-info -->';


		$p .= '</div><!-- /.wpa-bid-area -->';

		if ($hasbin) {
			$p .= '<div class="wpa-buynow-area col-xs-12 col-md-12">';
			$p .= '<form class="wpa-buynow-form" id="wpa-buynow-form" action="'.$staticpage.'#auction-alert" method="POST" onsubmit="return validateBIN()">';
			$p .= '<button class="btn btn-info" type="button" onClick="if(confirm('."'".__('Do you really want to Buy It Now?','wpauctions')."'".')) submit()">'.__('Buy It Now for','wpauctions').' '.$currencysymbol.$BIN_price.'</button>';
			if ($payment_method == "paypal") {
				$p .= '<p>'.__('Pay via PayPal immediately in order to win this auction.','wpauctions').' </p>';
			}
			$p .= '<input type="hidden" name="mode" value="bid">';
			$p .= '<input type="hidden" name="auction_id" value="'.$auction_id.'">';
			$p .= '<input type="hidden" name="BIN_Amount" value="'.$BIN_price.'">';
			$p .= '</form><!-- /form.wpa-buynow-form -->';
			$p .= '</div>';
		}

		$p .= '</section><!-- /.wpa-intro -->';

		$p .= '<section class="wpa-content clearfix">';

		$p .= '<div class="wpa-content-text col-xs-10 col-md-10">';

		$p .= '<div class="wpa-content-countdown">';

		$p .= '<p id="counterwarning" style="color: red;"></p>';
		$p .= '<input type="hidden" id="originaltime" name="originaltime" value="'.wpa_date($end_date).'">';


		if ($delayed) { // future auction
			$p .= '<h5>'.__('This auction is not open yet','wpauctions').'.</h5>';
			$p .= '<strong>'.__('Starting On','wpauctions').':</strong><br /><span>'.wpa_date($start_date).'</span>';
		} else { 

			$p .= '<h5>'.__('Ends','wpauctions').':</h5>';
		
			if ($showcountdown) {		
		
				$p .= '<p><input class="knob days" data-width="50" data-height="50" data-min="0" data-max="365" data-displayPrevious=true data-fgColor="#428bca" data-readOnly="true" data-thickness=".2" value="1">';
				$p .= '<br /> '.__('Days','wpauctions').'</p>';
				$p .= '<p><input class="knob hour" data-width="50" data-height="50" data-min="0" data-max="24" data-displayPrevious=true data-fgColor="#428bca" data-readOnly="true" data-thickness=".2" value="1"><br /> Hours</p>';
				$p .= '<p><input class="knob minute" data-width="50" data-height="50" data-min="0" data-max="60" data-displayPrevious=true data-fgColor="#428bca" data-readOnly="true" data-thickness=".2" value="1"><br /> Minutes</p>';
				$p .= '<p><input class="knob second" data-width="50" data-height="50" data-min="0" data-max="60" data-displayPrevious=true data-fgColor="#428bca" data-readOnly="true" data-thickness=".2" value="0"><br /> Seconds</p>';
		
				// timer runs in user timezone, so need to calculate countdown time and pass this through - we have this in $secsdiff
				
				$p .= '<script type="text/javascript">';
				$p .= 'jQuery(document).ready(function () {';
				$p .= '	var diff = '. $secsdiff.';';
				$p .= '	var d = new Date();';
				$p .= '	d.setSeconds(d.getSeconds() + diff);';
				
				$p .= '	jQuery(".ccounter").ccountdown( d.getFullYear() ,d.getMonth()+1 ,d.getDate() , d.getHours().toString() + ":" + d.getMinutes().toString() + ":" + d.getSeconds().toString());';
				
				$p .= '});';
				
				$p .= '</script>';
				
				
			} else {
					$p .= '<span id="wpa-liveend">'.wpa_date($end_date).'</span>';
			} //showcountdown
		}  // future auction
	
		$p .= '</div><!-- /.wpa-content-countdown -->';	

		$p .= '<h5>'.__('Description','wpauctions').'</h5>';
		$p .= '<ul class="wpa-info col-xs-12">';
		if ($shipping_from != 'n/a') {
			$p .= '<li class="col-xs-6"><strong>'.__('Location','wpauctions').':</strong> '.$shipping_from.'</li>';
		}
		$p .= '</ul><!-- /ul.wpa-info -->';

		$p .= wpautop($description);

		// handle fees
		$fee = wpa_expressfee();

		if ($fee != "") {
			$p .= "<p class='alert alert-warning'>". __('The following fee will be added to this auction: ','wpauctions') . $fee . "</p>";
		}

		$p .= '</div><!-- /.wpa-content-text -->';

		if ($hideseller != 'yes' && $owner) {
			$p .= '<div class="wpa-content-profile col-xs-2 col-md-2">';
			$p .= '<h5>'.__('Seller','wpauctions').'</h5>';

			$seller = get_user_by ( 'id', $owner );
			$p .= '<a href="'.get_author_posts_url($owner).'">'.get_avatar( $owner, 136 ).'</a>';
			$p .= '<p class="profile-bold"><a href="'.get_author_posts_url($owner).'">'.$seller->display_name.'</a></p>';

			$p .= '<p class="profile-italic"><i class="fa fa-star"></i> '.$owner_total.' '.__('total auctions','wpauctions').'</p>';
			$p .= '<p class="profile-italic"><i class="fa fa-gavel"></i> '.$owner_current.' '.__('current auctions','wpauctions').'</p>';
			$p .= '</div><!-- /.wpa-profile -->';
		}

		$p .= '</section><!-- /.wpa-content -->';

		$p .= '<section class="wpa-auction-meta clearfix">';

		$p .= '<h5>'.__('Auction Information','wpauctions').'</h5>';

		$p .= '<ul class="nav nav-tabs">';
		$p .= '<li class="active wpa-bids-navtab"><a href="#bidstab" data-toggle="tab"><i class="fa fa-gavel"></i> '.__('Bids','wpauctions').'</a></li>';

		if (!( $shipping_price == 0 && $shipping_from == 'n/a' && $shipping_to == 'n/a' )) {
			$p .= '<li class="wpa-shipping-navtab"><a href="#shipping" data-toggle="tab"><i class="fa fa-truck"></i> '.__('Shipping','wpauctions').'</a></li>';
		}
		$p .= '<li class="wpa-payment-navtab"><a href="#payment" data-toggle="tab"><i class="fa fa-money"></i> '.__('Payment','wpauctions').'</a></li>';
		$p .= '</ul>';

		$p .= '<div id="myTabContent" class="tab-content">';

		$p .= '<div class="tab-pane active fade in" id="bidstab">';


		if ($start_price > 0) {
			$p .= '<ul>';

			foreach ($rows as $bid) {

				$p .= '<li class="media">';
				if ( $bid->bidder_wordpress_id != "") {
					$p .= '<a class="pull-left" href="'.get_author_posts_url($bid->bidder_wordpress_id).'" rel="nofollow">'.get_avatar( $bid->bidder_email, 45 ).'</a>';
					$p .= '<p><a href="'.get_author_posts_url($bid->bidder_wordpress_id).'" rel="nofollow" data-toggle="tooltip" data-placement="top" title="View profile">'.anon_bidder_name($bid->bidder_name, $anonymizebidder).'</a>';
				} else {
					$p .= '<a class="pull-left">'.get_avatar( $bid->bidder_email, 45 ).'</a>';
					$p .= '<p>'.anon_bidder_name($bid->bidder_name, $anonymizebidder).'</a>';
				}

				$p .= ' '.__('bid','wpauctions').' <strong>'.$currencysymbol.number_format($bid->current_bid_price, 2, '.', ',').'</strong><span>'.wpa_date(get_date_from_gmt($bid->date));
				if ($bid->bid_type == "auto") $p .= ' ['.__('auto','wpauctions').']';
				if ($bid->bid_type == "advance") $p .= ' ['.__('increased max bid','wpauctions').']';
				$p .= '</span></p></li>';
			}

			$p .= '</ul>';
		}

		$p .= '</div><!-- /.tab-pane #bids-tab -->';

		if (!( $shipping_price == 0 && $shipping_from == 'n/a' && $shipping_to == 'n/a' )) {
			$p .= '<div class="tab-pane fade" id="shipping">';
			$p .= '<p><strong>'.__('Shipping','wpauctions').':</strong> ';
			if ($variable_shipping == "" ) {
				if ($shipping_price > 0) {
					$p .= $currencysymbol . number_format($shipping_price, 2, '.', ',').'</p>';
				} else {
					$p .= 'n/a</p>';
				}
			} else {
				$p .= $variable_shipping.'</p>';
			}
			$p .= '<p><strong>'.__('From','wpauctions').':</strong> '.$shipping_from.'</p>';
			$p .= '<p><strong>'.__('To','wpauctions').':</strong> '.$shipping_to.'</p>';

			$p .= '</div>';
		}

		$p .= '<div class="tab-pane fade" id="payment">';

		switch ($payment_method) {
		case "paypal":
			$p .= '              <p class="wpa-post-payment-paypal">'.__('Winner will receive PayPal payment link via email','wpauctions').'.</p>';
			break;
		case "bankdetails":
			$p .= '              <p class="wpa-post-payment-wire">'.__('Winner will receive wire transfer details via email','wpauctions').'.</p>';
			break;
		case "mailingaddress":
			$p .= '              <p class="wpa-post-payment-check">'.__('Winner will receive mailing address via email','wpauctions').'.</p>';
			break;
		case "custompayment":
			$p .= '              <p class="wpa-post-payment-check">'.$custompayment.'</p>';
			break;
		}

		$p .= '</div>';

		$p .= '</div><!-- /.tab-content -->';

		$p .= '</section><!-- /.wpa-auction-meta -->';

		if ( $wpa_termsandconditions != "" ) {
			$p .= '<section id="AuctionTerms" class="wpa-legal">';
			$p .= '<h5>'.__('Terms and Conditions','wpauctions').'</h5>';
			$p .= '<div class="wpa-legal-container" id="accordion">';
			$p .= '<p><a data-toggle="collapse" data-parent="#accordion" href="#collapseTerms">'.__('Click to read our bidding terms.','wpauctions').'</a></p>';

			$p .= '<div id="collapseTerms" class="wpa-collapse in">';
			$p .= $wpa_termsandconditions;
			$p .= '</div>';
			$p .= '</div>';

			$p .= '</section>';
		}
		
		$p .= '</section><!-- /.wpa-main -->';

	} else {
		
		
    ///////////////////////////////////////////////////
    //////// TRADITIONAL STYLE STARTS HERE ////////////
    ///////////////////////////////////////////////////
		
		

		$p = '';

		$p .= '<div class="wpa-post';
		if (!$active) $p .= ' wpa-auction-sold';
		$p .= ' clearfix">';

		$p .= '  <div class="wpa-title clearfix">';
		$p .= '  	<h3>' . $name . '</h3>';
		$p .= '  </div><!-- Title -->';

		$p .= '  <div class="wpa-post-container">';

		$p .= '  	<div class="wpa-post-images clearfix">';

		if ($image_url > 0) {
			$p .= '      	<a href="'.wp_get_attachment_url( $image_url ).'"  class="thickbox"  title="'.$name.'">';
		} else {
			$p .= '      	<a href="#">';
		}
		$p .= '      	 <img src="'.wpa_resize($image_url,150).'" alt="Auction Image" /></a>';

		if ($extraimage != "") {
			for ($i = 0; $i <= 2; $i++) {
				if ($extraimage[$i] != "" ) {
					$p .= '          <a href="'.wp_get_attachment_url($extraimage[$i]).'" title="'.$name.'" class="thickbox"><img src="'.wpa_resize($extraimage[$i],150).'" alt="Auction Image" /></a>';
				}
			}
		}
		$p .= '</div><!-- WPA Top Left -->';
		
		$p .= '<div class="wpa-bidders-area"><!-- WPA Bid Area -->';

		$p .= '<p class="wpa-startingbid"><strong>'.__('Starting Bid','wpauctions').': </strong>'.$currencysymbol . number_format($start_price, 2, '.', ',').'</p>';

		if ($result != "") {
			$colour = "red";
			if ($result == $BID_WIN || $result == $BIN_WIN) { $colour = "green"; }

			$p .= '<div id="auction-alert" style="background:'.$colour.'; margin: 8px 0 0; padding: 5px; text-align: center; color: #fff;">'.$result.'</div>';

$p .= '<script type="text/javascript">';
$p .= 'jQuery(document).ready(function () { ';
$p .= '   jQuery("#auction-alert").delay(3000).fadeOut(300);  ';
$p .= '}); ';
$p .= '</script>';

		}

		//  $p .= '      <p class="wpa-currentbid clearfix"><a href="'.get_permalink().'?auction_id='.$auction_id.'" title="Refresh Bid"><img src="'.WPA_PLUGIN_STYLE.'/refresh.png" alt="Refresh Bid" /></a>';
		$p .= '      <p class="wpa-currentbid clearfix"><a href="javascript:void(0)" onClick="Javascript:wpa_update_price('.$auction_id.')"><img src="'.WPA_PLUGIN_STYLE.'/refresh.png" alt="Refresh Bid" width="20" height="18" /></a>';
		$p .=  '<span id="wpa-liveprice">'.wpa_get_price($current_price,$start_price,$BIN_price,$currencysymbol," ").'</span>';
		$p .= ' <span id="wpa_notice_div"></span>';

		if ($current_price > 0) {
			$p .= '      <span id="wpa-topbidder" class="wpa-topbidder"><strong>'.($inreserve ? __('Top Bidder','wpauctions') : __('Winning','wpauctions')).':</strong> '.$topbidder.'</span></p>';
		} else {
			$p .= '      <span id="wpa-topbidder" class="wpa-topbidder"></span></p>';
		}

		if (!$active) $p .=  '<div class="wpa-auction-closed-notice"><p>'.__('Auction Closed','wpauctions').'</p></div>';

		if ( !$showcountdown ) {
			// Non-countdown
			$p .= '                      <p class="wpa-post-ending"><strong>'.__('Ending On','wpauctions').':</strong> <span>'.wpa_date($end_date).'</span></p>';
		} else {
			// Countdown code
			$p .= '                      <p class="wpa-post-ending"><strong>'.__('Ending In','wpauctions').':</strong><br /><div id="auctionCountdown"></div></p>';


$p .= '<script type="text/javascript"> ';
$p .= 'jQuery(function () { ';

			// keeping everything in GMT should ensure we don't get timezone issues (JS runs in user context, not server)
			$thedate = $end_dateGMT;
			$p .= 'var auctionEnd = new Date(' . mysql2date('Y',$thedate) . ', ' . mysql2date('n',$thedate)-1 . ', ' . mysql2date('j',$thedate) . ', ' . mysql2date('H',$thedate) . ', ' . mysql2date('i',$thedate) . ', ' . mysql2date('s',$thedate) . ');';

	$p .= 'jQuery("#auctionCountdown").countdown({until: auctionEnd, timezone: 0});';
	$p .= 'jQuery("#year").text(auctionEnd.getFullYear());';
$p .= '});';
$p .= '</script>';

		}
		$p .= '</div><!-- WPA Bid Area Ends -->';
		
		$p .= '<div class="wpa-other-refresh clearfix">';
		if ($requesttobid == "Yes") {
			$p .=  '<span id="wpa-otherbidders"><strong>'.__('Approved Bidders','wpauctions').':</strong> '.wpa_getnumberofbidders($auction_id).'</span>';
		}

		if ( $refreshtimeout > 0 ) {
			$p .=  '<div id="wpa-refresh"><span><strong>'.__('Stop auto-refreshing Bids?','wpauctions').'</strong></span> <input type="checkbox" id="wpa-toggle-refresh" name="wpa-toggle-refresh" value="" /></div>';
		}
		$p .= '</div><!-- Closes the Approved Bidders and Auto Refresh Div -->';

		$p .= '      <div class="wpa-tabs clearfix">';
		
		$p .= '<ul><li>';
		
		$p .= '      	<a href="#description" title="'.__('Click here to read the description','wpauctions').'">'.__('Description','wpauctions').'</a>';

		$p .= '</li><li>';

		if ($hasbid) {
			$p .= '          <a href="#bidhere" title="'.__('Click here to Bid on this item','wpauctions').'">'.__('Bid Here','wpauctions').'</a>';
			$p .= '</li><li>';
		}

		if ($hasbin) {
			$p .= '          <a href="#buyitnow" title="'.__('Click here to Buy this item now','wpauctions').'">'.__('Buy it Now','wpauctions').'</a>';
			$p .= '</li><li>';
		}
		
		if ($start_price > 0) {
			$p .= '          <a href="#bids" title="'.__('Click here to view current Bids','wpauctions').'">'.__('Bids','wpauctions').'</a>';
			$p .= '</li><li>';
		}
		
		$p .= '      	<a href="#watch" title="'.__('Click here to Watch this auction','wpauctions').'">'.__('Watch','wpauctions').'</a>';
		$p .= '</li></ul>';
		
		//$p .= '   	</div><!-- WPA Tabs -->';  // moving down

		$p .= '<p class="wpa-refresh-bids-link"><a href="javascript:void(0)" onClick="Javascript:wpa_update_bids('.$auction_id.')">'.__('Update Bids Tab','wpauctions').'</a></p>';

		//$p .= '    	<div class="wpa-tabs-container clearfix">';

		$p .= '      	<div class="wpa-tabs-content wpa-description" id="description">';

		$p .= wpautop($description);

		// handle fees
		$fee = wpa_expressfee();

		if ($fee != "") {
			$p .= "<p class='alert alert-warning'>". __('The following fee will be added to this auction: ','wpauctions') . $fee . "</p>";
		}

		if ($terms != "") {
			$p .= '<p class="wpa-description-aip"><strong>'.__('Terms','wpauctions').':</strong> '.$terms.'</p>';
		}

		$p .= '       	</div><!-- Description -->';

		if ($hasbid) {
			$p .= '          <div class="wpa-tabs-content wpa-bidnow" id="bidhere">';

			if ($needtorequest && $requeststate != RTB_approved ) {

				if ( $requeststate == 0 ) {
					$requeststyle = "";
					$responsestyle = "display:none";
				} else {
					$requeststyle = "display:none";
					$responsestyle = "";
				}

				if (is_user_logged_in()) {
					$current_user = wp_get_current_user();

					$username = $current_user->display_name;
					$userID = $current_user->ID;

					$p .= '<p class="wpa-loggedin">'.__('You need to request access to bid on this auction','wpauctions').'</p>';

					$submitfiller = "wpa_request_to_bid ( 'page' );";

					$p .= '     <div class="wpa-request">';
					$p .= '      	<form id="wpa-requestform" action="test">';
					$p .= '          	<fieldset>';
					$p .= '                <p><span class="wpa-approval-name">Your name: </span><strong>'.$username.'</strong></p><div id="wpa-request_pagerequest" style="'.$requeststyle.'">';
					$p .= '                <input id="wpa-request_pageauction_id" type="hidden" value="'.$auction_id.'">';
					$p .= '                <input id="wpa-request_pagebidder_id" type="hidden" value="'.$userID.'">';
					$p .= '                <input type="button" id="wpa-request_pagebutton" value="'.__('Request To Bid','wpauctions').'" onClick="'.$submitfiller.'" />';
					$p .= '                </div><div id="wpa-request_pageresponse" style="'.$responsestyle.'"><p>Your request has been logged</p></div>';
					$p .= '           </fieldset>';
					$p .= '        </form>';

					if ($requeststate == RTB_denied) {
						$p .= '<p class="wpa-loggedin">'.__('Your request to bid on this auction has been <span style="text-decoration: underline;">Denied</span>','wpauctions').'</p>';
					}

					$p .= '     </div><!-- Request access -->  ';



				} else {
					$p .= '<p class="wpa-loggedin">'.__('Bidding allowed for registered & approved users only','wpauctions').'. <a href="'.($overridelogin ? $overridelogin : wp_login_url( get_permalink() )).'">'.__('Login','wpauctions').'</a>'.__(' or ','wpauctions').'<a href="'.($overridereg ? $overridereg : wp_registration_url()).'">'.__('Register','wpauctions').'</a>.</p>';
				}

			} elseif ($needreg) {
				$p .= '<p class="wpa-loggedin">'.__('Bidding allowed for registered & approved users only','wpauctions').'. <a href="'.($overridelogin ? $overridelogin : wp_login_url( get_permalink() )).'">'.__('Login','wpauctions').'</a>'.__(' or ','wpauctions').'<a href="'.($overridereg ? $overridereg : wp_registration_url()).'">'.__('Register','wpauctions').'</a>.</p>';
			} elseif (!$active) {
				$p .= '              <p class="wpa-loggedin">'.__('This auction is now closed','wpauctions').'.</p>';
			} elseif ($delayed) {
				$p .= '              <p class="wpa-loggedin">'.__('This auction is not open yet','wpauctions').'.</p>';
				if ( !$showcountdown ) {
					// Non-countdown
					$p .= '                      <p class="wpa-post-ending"><strong>'.__('Starting On','wpauctions').':</strong><br /><span>'.$start_date.'</span></p>';
				} else {
					// Countdown code

					$p .= '                      <p class="wpa-post-ending"><strong>'.__('Starting In','wpauctions').':</strong><br /><div id="auctionCountdown2"></div></p>';



$p .= '<script type="text/javascript">';
$p .= 'jQuery(function () {';

		// keeping everything in GMT should ensure we don't get timezone issues (JS runs in user context, not server)
		$thedate = $start_dateGMT;
		$p .= 'var auctionStart = new Date(' . mysql2date('Y',$thedate) . ', ' . mysql2date('n',$thedate)-1 . ', ' . mysql2date('j',$thedate) . ', ' . mysql2date('H',$thedate) . ', ' . mysql2date('i',$thedate) . ', ' . mysql2date('s',$thedate) . ');';
		
	$p .= 'jQuery("#auctionCountdown2").countdown({until: auctionStart, timezone: 0});';
	$p .= 'jQuery("#year").text(auctionStart.getFullYear());';
$p .= '});';
$p .= '</script>';

				}
			} else {
				$p .= '		       <form id="wpa-bidform" action="'.$staticpage.'#auction-alert" method="POST">';
				$p .= '              	<fieldset>';
				$p .= '                  	<p class="wpa-inputfield"><label for="wpa-yourname">'.__('Your Name','wpauctions').'</label>';
				$p .= '                      <input name="bidder_name" '.($readonly=="Yes" ? 'readonly="readonly" ' : '' ).'id="wpa-yourname" type="text" value="'.$defaultname.'" placeholder="'.__('enter your name','wpauctions').'" /></p>';

				$p .= '                      <p class="wpa-inputfield"><label for="wpa-youremail">'.__('Your Email','wpauctions').'</label>';
				$p .= '                      <input name="bidder_email" '.($readonly=="Yes" ? 'readonly="readonly" ' : '' ).'id="wpa-youremail" type="text" value="'.$defaultemail.'" placeholder="'.__('enter your email','wpauctions').'" /></p>';
  
				if ($hidecustomcontact != "Yes") {
					$p .= '                      <p class="wpa-inputfield"><label for="wpa-customfield">'.$customcontact.'</label>';
					$p .= '                      <input name="bidder_url" id="wpa-customfield" type="text" /></p>';
				}

				$p .= '                      <div class="clearfix">';
				$p .= '                      <p class="wpa-maximumbid">'.$maximumbid_message.'<br /><span id="wpa-bidhigher" style="wpa-bidhigher">'.$bidhigher_message.'</span></p>';
				$p .= '                      <p class="wpa-reserve clearfix">'.__('Reserve','wpauctions').':<br /><span>'.$reservestring.'</span></p>';
				$p .= '                      </div>';

				$bidmessage = __('enter your bid','wpauctions');
				$p .= '                      <p class="wpa-inputfield wpa-currency clearfix"><label for="wpa-currency">'.$currencycode.'</label>';
				
				if ($engine != QUICKBUY_ENGINE) {
					$p .= '                      <input name="max_bid" id="wpa-currency" type="text" placeholder="'.$bidmessage.'" /></p>';
				} else {
					$p .= '                      <input name="max_bid" id="wpa-currency" type="text" value="'.$thisbid.'" readonly /></p>';					
				}
				$p .= '                      <input id="wpa-placebid" type="button" value="'.__('Place Bid','wpauctions').'" onClick="submit()" />';


				$p .= '                 	</fieldset>';
				$p .= '<input type="hidden" name="mode" value="bid">';
				$p .= '<input type="hidden" name="auction_id" value="'.$auction_id.'">';
				$p .= '<input type="hidden" name="BIN_Amount" value="">';

				$p .= '             	</form>';
				if ($engine == QUICKBUY_ENGINE) {
					// add additional disclaimer
					$p .= '<div class="quickbuy-disclaimer"><p>'.__('Clicking "Place Bid" will accept your bid','wpauctions')."</p></div>";	
				}	
			}
			$p .= '         	</div><!-- Bid Now -->';
		}

		if ($hasbin) {
			$p .= '         	<div class="wpa-tabs-content wpa-buyitnow" id="buyitnow">';
			if ($needreg) {
				$p .= '          <p class="wpa-loggedin">'.__('Bidding allowed for registered & approved users only','wpauctions').'. <a href="'.($overridelogin ? $overridelogin : wp_login_url( get_permalink() )).'">'.__('Login','wpauctions').'</a>'.__(' or ','wpauctions').'<a href="'.($overridereg ? $overridereg : wp_registration_url()).'">'.__('Register','wpauctions').'</a>.</p>';
			} elseif (!$active) {
				$p .= '              <p class="wpa-loggedin">'.__('This auction is now closed','wpauctions').'.</p>';
			} elseif ($delayed) {
				$p .= '              <p class="wpa-loggedin">'.__('This auction is not open yet','wpauctions').'.</p>';
			} else {
				$p .= '	       	<form id="wpa-buyitnowform" action="'.$staticpage.'#auction-alert" method="POST">';
				$p .= '              	<fieldset>';
				$p .= '                  	<p class="wpa-inputfield"><label for="wpa-yourname">'.__('Your Name','wpauctions').'</label>';
				$p .= '                      <input name="bidder_name" '.($readonly=="Yes" ? 'readonly="readonly" ' : '' ).'id="wpa-yourname" type="text" value="'.$defaultname.'" onblur="if (this.value == \'\') {this.value = \''.$defaultname.'\';}"  onfocus="if (this.value == \''.$defaultname.'\') {this.value = \'\';}" /></p>';

				$p .= '                      <p class="wpa-inputfield"><label for="wpa-youremail">'.__('Your Email','wpauctions').'</label>';
				$p .= '                      <input name="bidder_email" '.($readonly=="Yes" ? 'readonly="readonly" ' : '' ).'id="wpa-youremail" type="text" value="'.$defaultemail.'" onblur="if (this.value == \'\') {this.value = \''.$defaultemail.'\';}"  onfocus="if (this.value == \''.$defaultemail.'\') {this.value = \'\';}" /></p>';

				if ($hidecustomcontact != "Yes") {
					$p .= '                      <p class="wpa-inputfield"><label for="wpa-customfield">'.$customcontact.'</label>';
					$p .= '                      <input name="bidder_url" id="wpa-customfield" type="text" /></p>';
				}

				$p .= '                      <p class="wpa-buythisitem">'.__('Buy This Item Now','wpauctions').'</p>';
				$p .= '                      <p class="wpa-checkemail">'.__('Check your email for details after you have completed the transaction','wpauctions').'</p>';

				$p .= '                      <p class="wpa-inputfield wpa-currency clearfix"><label for="wpa-currencybuyitnow">'.$currencycode.'</label>';
				$p .= '                      <input name="max_bid" id="wpa-currencybuyitnow" type="text" value="'.$BIN_price.'" readonly="readonly" /></p>';

				$p .= '                      <input id="wpa-buyitnowbin" type="button" value="'.__('Buy it Now','wpauctions').'"  onClick="submit()"/>';
				$p .= '                	</fieldset>';
				$p .= '<input type="hidden" name="mode" value="bid">';
				$p .= '<input type="hidden" name="auction_id" value="'.$auction_id.'">';
				$p .= '<input type="hidden" name="BIN_Amount" value="'.$BIN_price.'">';

				$p .= '            	</form>';
			}

			$p .= '       	</div><!-- Buy it Now -->';
		}

		if ($start_price > 0) {
			$p .= '          <div class="wpa-tabs-content wpa-currentbids" id="bids">';
			$p .= '			<ol>';

			foreach ($rows as $bid) {
				$p .= '<li>';
				if ($bid->bidder_url != "" && $customcontact == "URL") {
					// 2013.05.09 mensmaximus
					$p .= '<a href="'.$bid->bidder_url.'" rel="nofollow">'.anon_bidder_name($bid->bidder_name, $anonymizebidder).'</a>';
				} else {
					$p .= anon_bidder_name($bid->bidder_name, $anonymizebidder);
				}
				$p .= ' '.__('bid','wpauctions').' '.$currencysymbol.number_format($bid->current_bid_price, 2, '.', ',').' '.__('on','wpauctions').' '.wpa_date(get_date_from_gmt($bid->date));
				if ($bid->bid_type == "auto") $p .= ' ['.__('auto','wpauctions').']';
				if ($bid->bid_type == "advance") $p .= ' ['.__('increased max bid','wpauctions').']';
				$p .= '</li>';
			}

			$p .= '             	</ol>';
			$p .= '         	</div><!-- Bids -->';
		}

		$p .= '          <div class="wpa-tabs-content wpa-watchtab" id="watch">';
		$p .= '<p>'.__('Enter your email below to get notifications of new bids placed on the above item','wpauctions').'.</p>';

		$watchemail = __('enter your email','wpauctions');
		$submitfiller = "wpa_register_watcher ( 'page' );";
		$onfocusfiller = "if (this.value == '".$watchemail."') {this.value = '';}";
		$onblurfiller = "if (this.value == '') {this.value = '".$watchemail."';}";

		$p .= '            <div class="wpa-watch">';
		$p .= '            	<form id="wpa-form" action="test">';
		$p .= '                	<fieldset>';
		$p .= '                        <label for="wpa-watch-head">'.__('Watch this Auction','wpauctions').'</label>';
		$p .= '                        <input id="wpa-pageemail" type="text" value="'.$watchemail.'" onblur="'.$onblurfiller.'"  onfocus="'.$onfocusfiller.'" title="Check your inbox for details after submitting." />';
		$p .= '                        <input id="wpa-pageid" type="hidden" value="'.$auction_id.'">';
		$p .= '                        <input type="button" value="'.__('Submit','wpauctions').'" onClick="'.$submitfiller.'" />';
		$p .= '                    </fieldset>';
		$p .= '                </form>';
		$p .= '            </div><!-- Watch Auction -->  ';

		$p .= '</div><!-- Watch -->';

		//$p .= '</div>  <!-- WPA Tabs -->';  // <-- we were missing this?


		$p .= '	</div><!-- WPA Tabs Containeer 2 -->';

		$p .= '    	<div class="wpa-post-shipping-payment clearfix">';
		$p .= '      	<div class="wpa-post-shipping">';
		$p .= '          	<h4>'.__('Shipping Details','wpauctions').'</h4>';
		$p .= '              <p><strong>'.__('Shipping','wpauctions').':</strong> ';
		if ($variable_shipping == "" ) {
			if ($shipping_price > 0) {
				$p .= $currencysymbol . number_format($shipping_price, 2, '.', ',').'</p>';
			} else {
				$p .= 'n/a</p>';
			}
		} else {
			$p .= $variable_shipping.'</p>';
		}
		$p .= '              <p><strong>'.__('From','wpauctions').':</strong> '.$shipping_from.'</p>';
		$p .= '              <p><strong>'.__('To','wpauctions').':</strong> '.$shipping_to.'</p>';
		$p .= '        	</div>';

		$p .= '          <div class="wpa-post-payment">';
		$p .= '          	<h4>'.__('Payment Details','wpauctions').'</h4>';

		switch ($payment_method) {
		case "paypal":
			$p .= '              <p class="wpa-post-payment-paypal">'.__('Winner will receive PayPal payment link via email','wpauctions').'.</p>';
			break;
		case "bankdetails":
			$p .= '              <p class="wpa-post-payment-wire">'.__('Winner will receive wire transfer details via email','wpauctions').'.</p>';
			break;
		case "mailingaddress":
			$p .= '              <p class="wpa-post-payment-check">'.__('Winner will receive mailing address via email','wpauctions').'.</p>';
			break;
		case "custompayment":
			$p .= '              <p class="wpa-post-payment-check">'.$custompayment.'</p>';
			break;
		}

		$p .= '         	</div>';
		$p .= '     	</div><!-- WPA Shipping Payment -->';

		$p .= '  </div><!-- WPA Post Container -->    ';  

		$p .= '</div><!-- WP Auctions Post -->';
	}


	return $p;
}

// Sidebar code goes here
function docommon_wp_auctions() {

	global $wpdb;

	$options = get_option('wp_auctions');
	$style = $options['style'];
	$currencysymbol = $options['currencysymbol'];
	$title = $options['title'];
	@$feedback = $options['feedback'];
	$noauction = $options['noauction'];
	$list = $options['list'];
	$otherauctions = $options['otherauctions'];
	$showrss = $options['showrss'];
	$regonly = $options['regonly'];
	$landingpage = $options['landingpage'];
	if ($landingpage == "") $landingpage = get_option('siteurl');
	$anonymizebidder = $options['anonymizebidder'];

	$chunks = explode('<!--more-->', $noauction);
	$chunkno = mt_rand(0, sizeof($chunks) - 1);
	$noauctiontext = $chunks[$chunkno];
	$overridelogin = $options['overridelogin'];
	$overridereg = $options['overridereg'];

	// select a random record
	$table_name = $wpdb->prefix . "wpa_auctions";

	if (isset($_GET["auction_to_show"])) {
		$auction_id = intval($_GET["auction_to_show"]);
	} else {
		$auction_id = "";
	}

	if (isset($_GET["owner"])) {
		$ownercond = intval($_GET["owner"])."=owner AND ";
	} else {
		$ownercond = "";
	}

	if(!is_numeric($auction_id)) {
		$cond = $ownercond . "'".current_time('mysql',"1")."' < date_end AND '".current_time('mysql',"1")."' > date_start order by rand() limit 1";
	} else {
		$cond = "id=".$auction_id;
	}

	$strSQL = "SELECT id, image_url, name, description, date_end, duration, BIN_price, start_price, current_price, reserve_price, staticpage, terms, engine FROM ".$table_name." WHERE ".$cond;
	$row = $wpdb->get_row ($strSQL);

	// grab values we need
	$image_url = $row->image_url;
	$name = $row->name;
	$description = substr(strip_tags($row->description),0,75)."...";
	$end_date = get_date_from_gmt($row->date_end);
	$current_price = $row->current_price;
	$BIN_price = $row->BIN_price;
	$start_price = $row->start_price;
	$reserve_price = $row->reserve_price;
	$id = $row->id;
	$staticpage = $row->staticpage;
	$terms = $row->terms;
	$engine = $row->engine;

	if ($list == "Yes") {

		echo '<!-- Main WP Container Starts -->';

		// cater for no records returned
		if ($id == '') {
			echo '<div id="wp-container">';
			echo '<div style="border: 1px solid #ccc; padding: 5px 2px; margin: 0px !important; background: none !important;">';
			echo ( $noauctiontext );
			echo '</div>';
			echo '</div>';
		} else {
			echo '<div class="wpa-widget clearfix">';
			echo '<div class="wpa-title"><p>'.$title.'</p></div>';
			echo '<div class="wpa-other wpa-other-list">';

			// selected auction first
			echo '<div class="wpa-other-item">';

			echo '<p class="clearfix">';
			if (strlen($staticpage) > 0) {
				echo "<a href='".$staticpage."?auction_id=".$id."'>";
			} else {
				echo '<a href="#" title="Static Page not defined">';
			}
			echo '<img src="'.wpa_resize($image_url,50).'" alt="'.$name.'" /><span>';
			echo "<strong>".$name."</strong>";
			echo "<br />";
			echo wpa_get_price($row->current_price,$row->start_price,$row->BIN_price,$currencysymbol," <br /> ");
			echo "</span></a></p>";

			// select "other" auctions
			$table_name = $wpdb->prefix . "wpa_auctions";

			$strSQL = "SELECT * FROM ".$table_name." WHERE ".$ownercond."'".current_time('mysql',"1")."' < date_end and '".current_time('mysql',"1")."' > date_start and id<>".$id." order by rand()";  // show all other auctions
			$rows = $wpdb->get_results ($strSQL);

			foreach ($rows as $row) {
				echo '<p class="clearfix">';
				if (strlen($row->staticpage) > 0) {
					echo "<a href='".$row->staticpage."?auction_id=".$row->id."'>";
				} else {
					echo '<a href="#" title="Static Page not defined">';
				}
				echo '<img src="'.wpa_resize($row->image_url,50).'" alt="'.$row->name.'" /><span>';
				echo "<strong>".$row->name."</strong>";
				echo "<br />";
				echo wpa_get_price($row->current_price,$row->start_price,$row->BIN_price,$currencysymbol," <br /> ");
				echo "</span></a></p>";
			}

			if ($showrss != "No") {
				echo '<div class="wpa-rss"><a href="'. WPA_PLUGIN_RSS .'"><img src="'. WPA_PLUGIN_STYLE .'/rss.png" alt="RSS" /> '.__('Auctions RSS Feed','wpauctions').'</a></div>';
			}

			echo '</div>';
			echo '</div>';
		}
		echo '<!-- Main WP Container Ends -->';

	} else {

		// cater for no records returned
		if ($id == '') {
?>

<!--WP-Auction - Sidebar Presentation Section -->
<div class="wpa-widget clearfix">

  <?php if ($noauctiontext != '') { ?>
  <div style="border: 1px solid #ccc; padding: 5px 2px; margin: 0px !important; background: none !important;">
      <?php echo $noauctiontext ?>
  </div>

  <?php } else { //noauctiontext is blank ?>
    <div class="wpa-title"><p><?php echo $title ?></p></div>

    <div class="wpa-body">
    	<div class="wpa-featured">
      		<h3><?php _e("No auctions found",'wpauctions'); ?></h3>
            <img src="<?php echo wpa_resize($image_url,125) ?>" width="125" height="125" />
        	<p class="wpa-widgetdescription"><?php _e("Sorry, we seem to have sold out of everything we had!",'wpauctions'); ?></p>
    	</div>
	</div><!-- Main WP Container Ends -->
  <?php } ?>
</div>
<!--WP-Auction - End -->
<?php
		} else {

			// select "other" auctions
			$table_name = $wpdb->prefix . "wpa_auctions";

			$thelimit = "";
			if ($otherauctions != 'all' && $otherauctions > 0) {
				$thelimit = " limit ".$otherauctions;
			}

			$strSQL = "SELECT *  FROM ".$table_name." WHERE '".current_time('mysql',"1")."' < date_end and '".current_time('mysql',"1")."' > date_start and id<>".$id." order by rand()".$thelimit;
			$rows = $wpdb->get_results ($strSQL);

			// prepare auction link
			if (strlen($staticpage) > 0) {
				$auctionlink = '<a href="'.$staticpage.'?auction_id='.$id.'" title="Bid Now">';
			} else {
				$auctionlink = '<a href="#" title="Static Page not defined">';
			}
?>
<!-- WP Auctions Widget -->

<div class="wpa-widget clearfix">

    <div class="wpa-title">
    	<p><?php echo $title ?></p>
    </div><!-- Title -->

    <div class="wpa-body">
    	<div class="wpa-featured">
	        <h3><?php echo $name; ?></h3>
            <?php echo $auctionlink; ?><img src="<?php echo wpa_resize($image_url,125); ?>" alt="<?php echo $name; ?>" /></a>

<?php
			// get top bidder
			$table_name = $wpdb->prefix . "wpa_bids";

			if ($engine != REVERSE_ENGINE) {
				$strSQL = "SELECT * FROM $table_name WHERE auction_id=".$id." ORDER BY current_bid_price DESC, bid_type LIMIT 1";
			} else {
				$strSQL = "SELECT * FROM $table_name WHERE auction_id=".$id." ORDER BY current_bid_price, bid_type LIMIT 1";
			}
			$current = $wpdb->get_row ($strSQL);

			if (($current)) {

				$topbidder = anon_bidder_name($current->bidder_name, $anonymizebidder);

				echo '<p class="wpa-currentbid">'.__('Current Bid','wpauctions').'<br>'. $currencysymbol.number_format($current->current_bid_price, 2, '.', ',').'</p>';
				echo '<p class="wpa-winning">'.__('By','wpauctions').': '.$topbidder.'</p>';

			} else {
				echo '<p class="wpa-currentbid">'. wpa_get_price($current_price,$start_price,$BIN_price,$currencysymbol," <br /> ").'</p>';
			}


			if ($reserve_price > 0) {
				if ($reserve_price > $current_price)
					echo '<p class="wpa-reserve">'.__('Reserve Price','wpauctions').': '.__('Not Met','wpauctions').'</p>';
				else
					echo '<p class="wpa-reserve">'.__('Reserve Price','wpauctions').': '.__('Met','wpauctions').'</p>';

			}
?>

	          <?php if (($regonly=="Yes") && !is_user_logged_in()) {  ?>
	             <p class="wpa-loggedin"><?php _e('Bidding allowed for registered users only.','wpauctions'); ?> <a href="<?php echo ($overridelogin ? $overridelogin : wp_login_url( get_permalink() )) ?>"><?php _e('Login','wpauctions'); ?></a> <?php _e('or','wpauctions'); ?> <a href="<?php echo ($overridereg ? $overridereg : wp_registration_url()) ?>"><?php _e('Register','wpauctions'); ?></a>.</p>
            <?php } ?>

            <div class="wpa-widgetdescription"><?php echo $description; ?><?php echo $auctionlink; ?><?php _e('read more','wpauctions'); ?> &rsaquo;</a></div>
            <?php if ($terms != "") { ?>
              <p class="wpa-category-sidebar"><strong><?php _e('Category:','wpauctions'); ?> </strong><?php echo $terms; ?></p>
            <?php } ?>

            <?php if ($start_price > 0): ?>
            <p class="wpa-bidnow"><?php echo $auctionlink; ?><?php _e('Bid Now:','wpauctions'); ?></a></p>
            <?php endif ?>
            <p class="wpa-endtime"><?php _e('Ending','wpauctions'); ?>: <br><?php echo wpa_date($end_date) ?></p>
            <?php if ($BIN_price > 0): ?>
            <p class="wpa-bin"><?php echo $auctionlink; ?><?php _e('Buy it Now','wpauctions'); ?><br /><?php echo $currencysymbol.number_format($BIN_price, 2, '.', ',') ?></a></p>
            <?php endif ?>

            <div class="wpa-watch">
            	<form id="wpa-form" action="test">
                	<fieldset>
                        <label for="wpa-watch-head"><?php _e('Watch This Auction','wpauctions'); ?></label>
                        <input id="wpa-sidebaremail" type="text" value="<?php _e('enter your email','wpauctions'); ?>" onblur="if (this.value == '') {this.value = '<?php _e('enter your email','wpauctions'); ?>';}"  onfocus="if (this.value == '<?php _e('enter your email','wpauctions'); ?>') {this.value = '';}" title="<?php _e('Check your inbox for details after submitting','wpauctions'); ?>." />
                        <input id="wpa-sidebarid" type="hidden" value="<?php echo $id; ?>">
                        <input type="button" value="<?php _e('Submit','wpauctions'); ?>" onClick="wpa_register_watcher ( 'sidebar' );" />
                    </fieldset>
                </form>
            </div><!-- Watch Auction -->

        </div><!-- Featured -->

	<?php if (!empty($rows)): ?>
        <div id="wpa-other">
        	<h4 class="wpa-other-titles"><?php _e('Other Auctions','wpauctions'); ?></h4>
        	<div class="wpa-other-item">

      <?php foreach ($rows as $row) {
				echo '<p class="clearfix">';
				if (strlen($row->staticpage) > 0) {
					echo "<a href='".$row->staticpage."?auction_id=".$row->id."'>";
				} else {
					echo "<a href='".$landingpage."?auction_to_show=".$row->id."'>";
				}
				echo '<img src="'.wpa_resize($row->image_url,50).'" alt="'.$row->name.'" />';
				echo "<strong>".$row->name."</strong>";
				echo "<br />";
				echo wpa_get_price($row->current_price,$row->start_price,$row->BIN_price,$currencysymbol," <br /> ");
				echo "</a></p>";
			} ?>
            </div>
        </div>
   <?php endif; ?>

<?php
			if ($showrss != "No") {
				echo '<div class="wpa-rss wpa-rss-alt"><a href="'. WPA_PLUGIN_RSS .'"><img src="'. WPA_PLUGIN_STYLE .'/rss.png" alt="RSS" /> '.__('Auctions RSS Feed','wpauctions').'</a></div>';
			}
?>

    </div><!-- WP Auctions Body -->

</div>

<!-- WP Auctions Widget -->

<?php

		}

		// hook to terminate auction if needed (not strictly correct, but more efficient if it's here)
		check_auction_end($id);

	}

}

// perf improvement .. only load admin code if we're in admin :)
if (is_admin()) {
	include 'wpa_admin.php';
}



// style header - Load CSS and LightBox Javascript

function wpa_enqueue_scripts() {

	$options = get_option('wp_auctions');
	@$overridestyle = $options['overridestyle'];
	@$inpagedisplay = $options['inpagedisplay'];


	if ($inpagedisplay == "modern") {

		wp_enqueue_script('bootstrap', WPA_PLUGIN_URL . '/js/wpa-bootstrap.js', array('jquery') );
		wp_enqueue_script('fitvid', WPA_PLUGIN_URL . '/js/fitvid.js', array('jquery') );
		wp_enqueue_script('knob', WPA_PLUGIN_URL . '/js/jquery.knob.js', array('jquery') );
		wp_enqueue_script('ccountdown', WPA_PLUGIN_URL . '/js/jquery.ccountdown.js', array('jquery') );
		wp_enqueue_script('WPAinit', WPA_PLUGIN_URL . '/js/init.js', array('jquery') );
		wp_enqueue_script('WPAmodern', WPA_PLUGIN_URL . '/js/modern.js', array('jquery') );

		wp_enqueue_style('WPAbaseCSS', WPA_PLUGIN_URL . '/style/wpauctions.css' );
		wp_enqueue_style('bootstrapCSS', WPA_PLUGIN_URL . '/style/bootstrap.css' );
		wp_enqueue_style('fontawesome', '//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css' );
		wp_enqueue_style('WPAmodernCSS', WPA_PLUGIN_URL . '/style/modern_style.css' );

		//

	} else {
		// enqueue scripts
		wp_enqueue_script('countdown', WPA_PLUGIN_URL . '/js/jquery.countdown.min.js', array('jquery') );

		// enqueue styles
		wp_enqueue_style('WPAbaseCSS', WPA_PLUGIN_URL . '/style/wpauctions.css' );
		wp_enqueue_style('WPAcountdownCSS', WPA_PLUGIN_URL . '/js/jquery.countdown.css' );		
		
	}

	// common
	wp_enqueue_script('thickbox');
	wp_enqueue_style('thickbox');
	wp_enqueue_script('wp_auction_AJAX', WPA_PLUGIN_URL . "/wp_auctionsjs.php", array('jquery') );
	// wp_enqueue_style('WPAcustomCSS', WPA_PLUGIN_URL . '/style/wpauctions.php' );
	wp_enqueue_script('jquery-ui-tabs');
	wp_enqueue_style('jquery_ui_css', 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css' );

	if ($overridestyle != "") {
		wp_enqueue_style('WPAoverideCSS', $overridestyle );
	}

}

// add shortcode support to allow user to insert auctions in posts or pages
// we also have a 2nd shortcode to support indirect payments
// and a 3rd shortcode to show an auction list
add_shortcode('wpauction', 'insertAuction');
add_shortcode('wpapayment', 'insertPaymentPage');
add_shortcode('wpadisplay', 'insertAuctionDisplay');

function insertAuctionDisplay ( $attr) {
	extract(shortcode_atts(array(
			), $attr));

	global $wpdb;

	$options = get_option('wp_auctions');
	$style = $options['style'];
	$currencysymbol = $options['currencysymbol'];
	$title = $options['title'];
	$feedback = $options['feedback'];
	$noauction = $options['noauction'];
	$otherauctions = $options['otherauctions'];
	$showrss = $options['showrss'];
	$regonly = $options['regonly'];
	$landingpage = $options['landingpage'];
	if ($landingpage == "") $landingpage = get_option('siteurl');
	$anonymizebidder = $options['anonymizebidder'];

	$chunks = explode('<!--more-->', $noauction);
	$chunkno = mt_rand(0, sizeof($chunks) - 1);
	$noauctiontext = $chunks[$chunkno];

	// select a random record
	$table_name = $wpdb->prefix . "wpa_auctions";
	
	$content = "";

	if (isset($_GET["owner"])) {
		$ownercond = intval($_GET["owner"])."=owner AND ";


		$content .= '<!-- Main WP Container Starts -->';

		// select "other" auctions
		$table_name = $wpdb->prefix . "wpa_auctions";

		$strSQL = "SELECT * FROM ".$table_name." WHERE ".$ownercond."'".current_time('mysql',"1")."' < date_end and '".current_time('mysql',"1")."' > date_start order by rand()";  // show all other auctions
		$rows = $wpdb->get_results ($strSQL);

		// cater for no records returned
		if (!$rows) {
			$content .=  '<div id="wp-container">';
			$content .=  '<div style="border: 1px solid #ccc; padding: 5px 2px; margin: 0px !important; background: none !important;">';
			$content .=  ( $noauctiontext );
			$content .=  '</div>';
			$content .=  '</div>';
		} else {
			$content .=  '<div class="wpa-widget clearfix">';
			$content .=  '<div class="wpa-title"><p>'.$title.'</p></div>';
			$content .=  '<div class="wpa-other wpa-other-list">';

			// selected auction first
			$content .=  '<div class="wpa-other-item">';

			foreach ($rows as $row) {
				$content .=  '<p class="clearfix">';
				if (strlen($row->staticpage) > 0) {
					$content .=  "<a href='".$row->staticpage."?auction_id=".$row->id."'>";
				} else {
					$content .=  '<a href="#" title="Static Page Not Defined">';
				}
				$content .=  '<img src="'.wpa_resize($row->image_url,50).'" alt="'.$row->name.'" /><span>';
				$content .=  "<strong>".$row->name."</strong>";
				$content .=  "<br />";
				$content .=  wpa_get_price($row->current_price,$row->start_price,$row->BIN_price,$currencysymbol," <br /> ");
				$content .=  "</span></a></p>";
			}

			if ($showrss != "No") {
				$content .=  '<div class="wpa-rss"><a href="'. WPA_PLUGIN_RSS .'"><img src="'. WPA_PLUGIN_STYLE .'/rss.png" alt="RSS" /> '.__('Auctions RSS Feed','wpauctions').'</a></div>';
			}

			$content .=  '</div>';
			$content .=  '</div>';
		}
		$content .=  '<!-- Main WP Container Ends -->';

	} else {

		// ask which user's auctions we want to display

		global $wp;
		$current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );

		$table_name = $wpdb->prefix . "wpa_auctions";
		$strSQL = "SELECT DISTINCT owner FROM ".$table_name." WHERE '".current_time('mysql',"1")."' < date_end and '".current_time('mysql',"1")."' > date_start order by rand()";  // pick out oweners of active auctions
		$rows = $wpdb->get_results ($strSQL);

		foreach ($rows as $row) {
			//echo "User: ". $row->owner;

			// get extra owner details
			if ( $row->owner > 0 ) {

				$strSQL = "SELECT count(*) FROM $table_name WHERE owner=".$row->owner;
				$owner_total = $wpdb->get_var ($strSQL);
	
				$strSQL = "SELECT count(*) FROM $table_name WHERE owner=".$row->owner." AND '".current_time('mysql',"1")."' < date_end";
				$owner_current = $wpdb->get_var ($strSQL);
	
				$content .=  '<div class="wpa-content-profile col-xs-2 col-md-2">';
				$content .=  '<h5>'.__('Seller','wpauctions').'</h5>';
	
				$this_url = add_query_arg( 'owner', $row->owner , $current_url );
	
				$seller = get_user_by ( 'id', $row->owner );
				$content .=  '<a href="'.$this_url.'">'.get_avatar( $row->owner, 136 ).'</a>';
				$content .=  '<p class="profile-bold"><a href="'.get_author_posts_url($row->owner).'">'.$seller->display_name.'</a></p>';
	
				$content .=  '<p class="profile-italic"><i class="fa fa-star"></i> '.$owner_total.' '.__('total auctions','wpauctions').'</p>';
				$content .=  '<p class="profile-italic"><i class="fa fa-gavel"></i> '.$owner_current.' '.__('current auctions','wpauctions').'</p>';
				$content .=  '</div><!-- /.wpa-profile -->';
			}

			//echo "<br>";
		}

	}

	return $content;
}


function insertAuction ( $attr) {
	extract(shortcode_atts(array(
				'id' => 1
			), $attr));

	$content = dopost_wp_auctions($id);

	return $content;
}

function insertPaymentPage ( $attr) {
	extract(shortcode_atts(array(
			), $attr));

	global $wpdb;
	$options = get_option('wp_auctions');
	$paypal = $options['paypal'];
	$currencysymbol = $options['currencysymbol'];
	$currencycode = $options['currencycode'];
	$feetype = htmlspecialchars($options['feetype'], ENT_QUOTES);

	if (isset($_GET["id"])) {

		$auction_id = intval($_GET["id"]);

		$cond = "id=".intval($auction_id);

		$table_name = $wpdb->prefix . "wpa_auctions";
		$strSQL = "SELECT id, image_url, name, description, date_end, duration, BIN_price, winning_price, start_price, shipping_price, current_price, reserve_price, staticpage, terms, engine, owner FROM ".$table_name." WHERE ".$cond;
		$row = $wpdb->get_row ($strSQL);

		if ($row != null) {
			// grab values we need
			$image_url = $row->image_url;
			$name = $row->name;
			$description = substr(strip_tags($row->description),0,75)."...";
			$end_date = get_date_from_gmt($row->date_end);
			$winning_price = $row->winning_price + wpa_calculatefee($row->winning_price);
			$shipping_price = $row->shipping_price;
			$id = $row->id;
			$terms = $row->terms;
			$end_dateGMT = $row->date_end;
			$owner = $row->owner;

			// calculate difference between now and end date .. we'll do this with server timezone
			$today = strtotime("now");
			$auctionend = strtotime($end_dateGMT);

			// decide payment recipient
			// current thinking: Payment goes to auction owner. If paypal not supplied, goes to WPA settings
			$paypalaccounttouse = get_the_author_meta( 'paypal', $owner );   // this overrides $paypal
			if ( $paypalaccounttouse == "" ) $paypalaccounttouse = $paypal;

			if ( $auctionend < $today ) {

				$content .= '<h1>'.$name.'</h1>';
				$content .= '<div style="float:right"><img src="'.wpa_resize($image_url,50).'" alt="'.$name.'" /></div>';
				$content .= '<p>'.$description.'</p>';
				$content .= '<strong>Winning Price: </strong>'.$currencysymbol.number_format($winning_price, 2, '.', ',').'</br>';
				if ($shipping_price > 0)
					$content .= '<strong>Shipping Price: </strong>'.$currencysymbol.number_format($shipping_price, 2, '.', ',').'</br>';

				$content .= '<strong>Payment going to : </strong>'.$paypalaccounttouse.'</br>';

				$content .= '<br/><p>Please use the PayPal button below to pay for this auction:</p>';
				$content .= '<form action="https://www.paypal.com/cgi-bin/webscr" method="post">';

				$content .= '<!-- Identify your business so that you can collect the payments. -->';
				$content .= '<input type="hidden" name="business" value="'.$paypalaccounttouse.'">';

				$content .= '<!-- Specify a Buy Now button. -->';
				$content .= '<input type="hidden" name="cmd" value="_xclick">';

				$content .= '<!-- Specify details about the item that buyers will purchase. -->';
				$content .= '<input type="hidden" name="item_name" value="'.$name.'">';
				$content .= '<input type="hidden" name="amount" value="'.$winning_price.'">';
				$content .= '<input type="hidden" name="shipping" value="'.$shipping_price.'">';
				$content .= '<input type="hidden" name="currency_code" value="'.$currencycode.'">';

				$content .= '<!-- Display the payment button. -->';
				$content .= '<input type="image" name="submit" border="0" src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_paynow_107x26.png" alt="PayPal - The safer, easier way to pay online">';
				$content .= '<img alt="" border="0" width="1" height="1" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" >';

				$content .= '</form>';



			} else {
				$content = "Auction not finished yet";
			}

		} else {
			$content = "Unable to locate auction";
		}
	} else {
		$content = "No Auction specified";
	}


	return $content;
}


function insertAuctionSelector() {

	global $wpdb;
	$table_name = $wpdb->prefix . "wpa_auctions";
	$strSQL = "SELECT id, name, image_url FROM $table_name WHERE '".current_time('mysql',"1")."' < date_end ORDER BY date_end DESC";
	$rows = $wpdb->get_results ($strSQL);

?>
   <table class="form-table">
      <tr valign="top">
         <th scope="row"><label for="WPA_Admin_id"><?php _e('Select an auction','wpauctions'); ?></label></th>
         <td>

	<?php if (is_array($rows)): ?>
        <select name="WPA_Admin[id]" id="WPA_Admin_id" style="width:95%;">
		       <?php foreach ($rows as $row) {
			echo '<option value="'.$row->id.'">'.$row->name.'</option>';
		} ?>
         </select>
         <br>(<?php _e('You can only have one auction per Page or Post','wpauctions'); ?>)
  <?php else:
		echo _e('Please create some auctions first','wpauctions');
	endif;
?>

         </td>

         <td>
         	<p class="submit">
      			<input type="button" onclick="return WPA_Setup.sendToEditor(this.form);" value="Insert and Bind Auction" />
            </p>
         </td>
      </tr>
      <tr>
      <td colspan="3">
      <p><em><?php _e('Tip: Use the &lt;!--more--&gt; tag from the editor to separate content and auction forms for your archive and search pages. If you show more than one bid form per page the bids will not be accepted.','wpauctions'); ?></em></p>
      </td>
      </tr>
   </table>

<?php
}


// Add Toolbar Menus
function wpa_custom_toolbar() {
	global $wp_admin_bar;

	$args = array(
		'id'     => 'wpa-parent-menu',
		'title' => __('WP Auctions', 'wpauctions' ),
		'title'  => __( 'WP Auctions', 'wpauctions' ),
	);
	$wp_admin_bar->add_menu( $args );

	$args = array(
		'id'     => 'wpa-child-menu',
		'parent' => 'wpa-parent-menu',
		'title'  => __( 'New Auction', 'wpauctions' ),
		'href'   => admin_url( 'admin.php?page=wp-auctions-add' ),
	);
	$wp_admin_bar->add_menu( $args );

	$args = array(
		'id'     => 'wpa-child-menu2',
		'parent' => 'wpa-parent-menu',
		'title'  => __( 'Current Auctions', 'wpauctions' ),
		'href'   => admin_url( 'admin.php?page=wp-auctions-manage' ),
	);
	$wp_admin_bar->add_menu( $args );

	$args = array(
		'id'     => 'wpa-child-menu3',
		'parent' => 'wpa-parent-menu',
		'title'  => __( 'Closed Auctions', 'wpauctions' ),
		'href'   => admin_url( 'admin.php?page=wp-auctions-manage-closed' ),
	);
	$wp_admin_bar->add_menu( $args );

}

// Hook into the 'wp_before_admin_bar_render' action
add_action( 'wp_before_admin_bar_render', 'wpa_custom_toolbar', 999 );



function wpa_adminWPHead() {
	if ($GLOBALS['editing']) {
		wp_enqueue_script('WPA_Admin', WPA_PLUGIN_URL . '/wp_aAdminjs.js', array('jquery'), '1.0.0' );
	}
}

add_action('wp_ajax_bind_auction', 'wpa_bind_auction');

function wpa_bind_auction() {
	global $wpdb;

	$this_auction = intval( $_POST['auction'] );
	$this_post = intval( $_POST['post'] );

	if ($this_post > 0 and $this_auction > 0) {
		$table_name = $wpdb->prefix . "wpa_auctions";
		$sql = "UPDATE ".$table_name." SET staticpage = '".get_permalink($this_post)."' WHERE id=".$this_auction;
		$wpdb->query($sql);

		$returnval = 'Done';
	} else {
		$returnval = 'Unable to figure out what to do';
	}

	echo $returnval;
	die();
}

function wpa_admin_scripts() {
	wp_enqueue_script( 'formbuilder', WPA_PLUGIN_URL . '/js/jquery.formbuilder.js', array('jquery','jquery-ui-core') , 1.0, true );
	wp_enqueue_script( 'jquery-ui-datetimepicker', WPA_PLUGIN_URL . '/js/jquery-ui-timepicker-addon.js', array('jquery-ui-datepicker','jquery-ui-slider') , 0.1, true );
    //wp_enqueue_script( 'jquery-ui-datetimepicker', '//cdn.jsdelivr.net/jquery.ui.timepicker.addon/1.4.5/jquery-ui-timepicker-addon.min.js', array('jquery-ui-datepicker','jquery-ui-slider') , 0.1, true );
   
   wp_enqueue_media();
   wp_enqueue_script( 'custom-header' );
}

function wpap_admin_styles() {
	wp_enqueue_style('jquery-style', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/smoothness/jquery-ui.css');
	wp_enqueue_style('jquery-formbuilder', WPA_PLUGIN_URL . '/js/jquery.formbuilder.css');
	//wp_enqueue_style( 'jquery-ui-datetimepicker', WPA_PLUGIN_URL . '/js/timepicker.custom.css' );
	wp_enqueue_style( 'jquery-ui-datetimepicker', WPA_PLUGIN_URL . '/js/jquery-ui-timepicker-addon.css' );
	
}

function wpa_design_scripts() {
	wp_enqueue_script('farbtastic');
}

function wpa_design_styles() {
	wp_enqueue_style( 'farbtastic' );
}


function wp_auctions_adminmenu(){


	// add new top level menu page
	$menu = add_menu_page ('WP Auctions', 'WP Auctions' , 'create_auction' , WPA_PLUGIN_NAME , 'wp_auctions_welcome', WPA_PLUGIN_STYLE."/wpa.png" );

	// add submenus
	$submenu_new = add_submenu_page (WPA_PLUGIN_NAME, __('New Auction','wpauctions'), __('New Auction','wpauctions'), 'create_auction' , 'wp-auctions-add', 'wp_auctions_add' );
	$submenu_current = add_submenu_page (WPA_PLUGIN_NAME, __('Current Auctions','wpauctions'), __('Current Auctions','wpauctions'), 'create_auction' , 'wp-auctions-manage', 'wp_auctions_manage' );
	$submenu_closed = add_submenu_page (WPA_PLUGIN_NAME, __('Closed Auctions','wpauctions'), __('Closed Auctions','wpauctions'), 'create_auction' , 'wp-auctions-manage-closed', 'wp_auctions_manage' );
	$submenu_bidders = add_submenu_page (WPA_PLUGIN_NAME, __('Manage Bidders','wpauctions'), __('Manage Bidders','wpauctions'), 'install_plugins' , 'wp-manage-bidders', 'wp_manage_bidders' );
	$submenu_categories = add_submenu_page (WPA_PLUGIN_NAME, __('Auction Categories','wpauctions'), __('Auction Categories','wpauctions'), 'install_plugins' , 'edit-tags.php?taxonomy=auction_category' );
	$submenu_settings = add_submenu_page (WPA_PLUGIN_NAME, __('Auction Settings','wpauctions'), __('Auction Settings','wpauctions'), 'install_plugins' , 'wp-auctions-settings', 'wp_auctions_settings' );
	$submenu_design = add_submenu_page (WPA_PLUGIN_NAME, __('Design Settings','wpauctions'), __('Design Settings','wpauctions'), 'install_plugins' , 'wp-auctions-design', 'wp_auctions_design' );
	$submenu_email = add_submenu_page (WPA_PLUGIN_NAME, __('Email Settings','wpauctions'), __('Email Settings','wpauctions'), 'install_plugins' , 'wp-auctions-email', 'wp_auctions_email' );

	// add scripts
	add_action ( 'admin_print_scripts-'.$submenu_bidders, 'wp_manage_bidders_head');

	add_action ( 'admin_print_scripts-'.$submenu_design, 'wpa_design_scripts');
	add_action ( 'admin_print_styles-'.$submenu_design, 'wpa_design_styles');

	add_action ( 'admin_print_scripts-'.$submenu_new, 'wpa_admin_scripts');
	add_action ( 'admin_print_styles-'.$submenu_new, 'wpap_admin_styles');

	// add meta boxes
	add_meta_box('WPA_Admin', __('Insert Auction','wpauctions'), 'insertAuctionSelector', 'post', 'normal', 'high');
	add_meta_box('WPA_Admin', __('Insert Auction','wpauctions'), 'insertAuctionSelector', 'page', 'normal', 'high');

}

function wpa_init()
{

	// Add new taxonomy, make it hierarchical (like categories)
	if (!taxonomy_exists('auction_category')) {
		$labels = array(
			'name' => _x( 'Auction Categories', 'taxonomy general name','wpauctions' ),
			'singular_name' => _x( 'Auction Category', 'taxonomy singular name','wpauctions' ),
			'search_items' =>  __( 'Search Auction Categories','wpauctions' ),
			'all_items' => __( 'All Auction Categories','wpauctions' ),
			'parent_item' => __( 'Parent Auction Category','wpauctions' ),
			'parent_item_colon' => __( 'Parent Auction Category:','wpauctions' ),
			'edit_item' => __( 'Edit Auction Category','wpauctions' ),
			'update_item' => __( 'Update Auction Category','wpauctions' ),
			'add_new_item' => __( 'Add New Auction Category','wpauctions' ),
			'new_item_name' => __( 'New Auction Category Name','wpauctions' ),
			'menu_name' => __( 'Auction Category','wpauctions' ),
		);
	
		register_taxonomy('auction_category',array('auctions'), array(
				'hierarchical' => false,
				'labels' => $labels,
				'show_ui' => true,
				'show_tagcloud' => true,
				'query_var' => true,
				'rewrite' => false,
				'show_in_nav_menus' => true,
			));
	}

	// define thumbnail sizes
	add_image_size( 'WPA_thumbnail', 50, 50, true );
	add_image_size( 'WPA_widget', 125, 125, true );
	add_image_size( 'WPA_page', 150, 150, true );
	add_image_size( 'WPA_popup', 1200, 1004, true );

	// after the page reloads, print them out
	if (!isset($_COOKIE['wpacolorcookieone'])) {
		$options = get_option('wp_auctions_design');

		$auctioncolorone = htmlspecialchars($options['auctioncolorone'] ?? "", ENT_QUOTES);
		$auctioncolortwo = htmlspecialchars($options['auctioncolortwo'] ?? "", ENT_QUOTES);
		$auctioncolorthree = htmlspecialchars($options['auctioncolorthree'] ?? "", ENT_QUOTES);
		$auctioncolorfour = htmlspecialchars($options['auctioncolorfour'] ?? "", ENT_QUOTES);
		$auctioncolorfive = htmlspecialchars($options['auctioncolorfive'] ?? "", ENT_QUOTES);

		setcookie("wpacolorcookieone", $auctioncolorone );
		setcookie("wpacolorcookietwo", $auctioncolortwo );
		setcookie("wpacolorcookiethree", $auctioncolorthree );
		setcookie("wpacolorcookiefour", $auctioncolorfour );
		setcookie("wpacolorcookiefive", $auctioncolorfive );

	}

}

add_filter('admin_print_scripts', 'wpa_adminWPHead');

add_action('wp_enqueue_scripts', 'wpa_enqueue_scripts');
add_action('widgets_init', 'widget_wp_auctions_init');
add_action('admin_menu','wp_auctions_adminmenu',1);
add_action('activate_'.plugin_basename(__FILE__), 'wp_auctions_install');
add_action('deactivate_'.plugin_basename(__FILE__), 'wp_auctions_uninstall');
add_action('wpa_daily_check', 'close_expired_auctions');
add_action('init', 'wpa_init', 0 );

?>