# $Id: //ncom_2_4/stores/farm/lib/BORD.pm#17 $

package BORD;
use LWP::UserAgent;
use HTTP::Request::Common;
use lib "/ncom/stores/farm/lib";
use FarmAgent;
use AMZN;
use strict;

sub link {
	my ($isbn) = shift;

	return AMZN::link( $isbn ) . &get_sid;
}

# Borders is now actually just a co-branded Amazon.
# We have to get an SID from tbe borders.com page so
# that we can then get an amazon title details with the
# same sid.  This is the only way to get title details on
# borders that exhibits whatever special behavior amazon
# wants borders to have.

sub get_sid {
	my ($res, $ua, $sid, $url);
	my $timeout = shift;
	
	$ua = LWP::UserAgent->new();
	$ua->timeout( ($timeout || 30) );
	$ua->agent( FarmAgent::agent() );

	$res = $ua->request( GET "http://www.borders.com" );
	if ($res->is_success) {
		$url = $res->as_string;
		# Print the borders main page.
		if ($url =~ m/session-id=([^-]+-[^-]+-[^;]+);/) {
			$sid = '/' . $1; 
		} else {
			$sid = '';
		}
	} else {
		$sid = '';
	}

	return $sid;
}

sub name {
	my ( $pretty ) = shift;
	return "Borders" if ( $pretty eq "pretty" );
	return "Borders.com";
}

sub pf_link {
	my ($isbn) = shift;
	my ($link) = 'http://www.pricefarmer.com/cgi-bin/link?site=bord&isbn=' . $isbn;
	return $link;
}

sub affiliate_link {
	my($isbn) = shift;
	#my($link) = 'http://click.linksynergy.com/fs-bin/stat?id=r3zLqM3SHkg&offerid=6424';
	#$link .= '&type=2&subid=&url=http%253A//search.borders.com/fcgi-bin/';
	#$link .= 'db2www/search/search.d2w/Details%253Fcode%253D' . $isbn;
	#$link .= '%2526mediaType%253DBook%2526searchType%253DISBNUPC%2526prodid%253D';
	#my ( $link ) = 'http://search.borders.com/fcgi-bin/db2www/search/search.d2w/Details?code=' . $isbn;
	# $link       .= '$mediaType=Book&searchType=ISBNUPC&prodID=';

	return &link($isbn);
}

sub avail {
	my ($days) = shift;
	my $avail;

	if ($days == 3) {
		$avail = "2-3 days";
	} elsif ($days == 1) {
		$avail = "24 hours";
	} elsif ($days == 14) {
		$avail = "1-2 weeks";
	} elsif ($days == 41) {
		$avail = "1-6 weeks";
	} elsif ($days == 42) {
		$avail = "4-6 weeks";
	} elsif ($days == 800) {
		$avail = "Advance order";
	} elsif ($days == 900) {
		$avail = "N/A";
	} elsif ($days == 1000) {
		$avail = "N/A";
	} else {
		$avail = $days . " days";
	}
	return $avail;	
}

sub fetch {
	my ($isbn, $master_list_price, $timeout ) = @_;
	my (@res);
	
	# We'll just use the amazon fetch.
	if ($isbn) {
		@res = AMZN::fetch( $isbn . &get_sid($timeout), $master_list_price, $timeout);
	}
	
	return ( 'bord', $isbn, splice( @res, 2, 8 ) );
}

1;
