(*	
SCRIPT INFO:

---------------------------------------------

SCRIPT:		Amazon_poster Script 
AUTHOR:			Ivek23
VERSION:		0.0.3
DATE:			26/11/2014
UPDATE:			24/12/2015

---------------------------------------------

*)

//SCRIPT BEGINS HERE...

//Some useful constants

const
 pauseBeforeLoad = 0; // Pause before loading (in millisecond)

//Script types
	stMovies		= 0;
	stPeople		= 1;
	stPoster		= 2;
	
//Script modes
	smSearch		= 0;
	smNormal		= 1;
	smCast		    = 2;
	smReview		= 3;
	smCredits		= 4;
	smPoster1		= 5;
	smPoster2		= 6;
	smPoster3		= 7;
	smPoster		= 8;
	smFinished	    = 9;
	
//Parse results
	prError			= 0;
	prFinished		= 1;
	prList			= 2;
	prListImage		= 3;
	prDownload		= 4;
	
//Prefix modes
	pmNone			= 0;
	pmEnd			= 1;
	pmBegin			= 2;
	pmRemove		= 3;
	
//Download methods
	dmGET			= 0;
	dmPOST			= 1;
	
//Movie fields
	mfURL			= 0;
	mfTitle			= 1;
	mfOrigTitle		= 2;
	mfAka			= 3;
	mfYear			= 4;
	mfGenre			= 5;
	mfCategory		= 6;
	mfCountry		= 7;
	mfStudio		= 8;
	mfMPAA			= 9;
	mfRating		= 10;	
	mfTags			= 11;
	mfTagline		= 12;
	mfDescription	= 13;
	mfDuration		= 14;
	mfFeatures		= 15;
	
//People fields
    pfURL        	= 0;
	pfName       	= 1;
	pfTransName  	= 2;
	pfAltNames   	= 3;
	pfBirthday   	= 4;
	pfBirthplace 	= 5;
	pfGenre      	= 6;
	pfBio        	= 7;
	pfDeathDate  	= 8;  
	pfComment    	= 9;
	pfBookmark   	= 10;
	pfPid        	= 11; 
	pfCareer     	= 12; 
	
//Credits types
	ctActors		= 0;
	ctDirectors		= 1;
	ctWriters		= 2;
	ctComposers		= 3;
	ctProducers		= 4;
	
//Script data
	SCRIPT_VERSION = '0.0.3';
	SCRIPT_NAME    = 'Amazon_poster Script';
	SCRIPT_DESC    = '[EN] Get Movie Poster from Amazon.com';
	SCRIPT_LANG		= $09; //English
	SCRIPT_TYPE		= stMovies;
  
	BASE_URL		= 'http://www.amazon.com/';
	RATING_NAME		= 'Amazon.com';
//	SEARCH_STR		= '';
//	SEARCH_STR		= 'http://www.amazon.com/exec/obidos/search-handle-url/index=dvd&field-keywords=%s';
//	SEARCH_STR		= 'http://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Ddvd&field-keywords=%s';
	SEARCH_STR		= 'http://www.amazon.com/gp/search?ie=UTF8&keywords=%s&tag=persvidedata-20&index=dvd&linkCode=ur2&camp=1789&creative=9325';
	CODE_PAGE		= 65001;	//Use 0 for Autodetect
  
//User Options
	GET_THEMES	= True;	//Set to False to ensure ~mfCategory~ not added even if 'Overwrite fields' setting allows
    GET_POSTER  = False; //Set to False or True

//Global variables
var
ELI, I : Integer;
Mode : Byte;
MovieName : String;
ExtraLinks : array [smCast..smPoster] of String;
TabMovieName, TabNumber : TwideArray;

//Functions
function GetScriptVersion : String;
begin
	Result := SCRIPT_VERSION;
end;

function GetScriptName : String;
begin
	Result :=  SCRIPT_NAME;
end;

function GetScriptDesc : String;
begin
	Result := SCRIPT_DESC;
end;

function GetRatingName : String;
begin
	Result := RATING_NAME;
end;

function GetScriptLang: Cardinal;
begin
	Result := SCRIPT_LANG;
end;

function GetCodePage : Cardinal;
begin
	Result := CODE_PAGE;
end;

function GetBaseURL : AnsiString;
begin
	Result := BASE_URL;
end;

function GetDownloadURL : AnsiString;
begin
	if (Mode = smSearch) then
		Result := SEARCH_STR
	else
		Result := ExtraLinks[Mode];
end;



function GetDownloadMethod : Byte;
begin
	Result := dmGET;
end;

function GetPrefixMode : Byte;
begin
	Result := pmBegin;
end;

function GetScriptType : Byte;
begin
	Result := SCRIPT_TYPE;
end;

function GetCurrentMode : Byte;
begin
	Result := Mode;
end;

procedure ParseMovie(MovieURL : String; HTML : String);
var
	curPos, endPos : Integer;
	TmpStr : String;
begin

//Get ~mfURL~ or ~URL~
//endPos := Pos('" />', HTML);
//if endPos > 0 then begin
//	curPos := PrevPos('" href="', HTML, endPos);
//	AddFieldValue(mfURL, BASE_URL + Copy(HTML, curPos + 8, endPos - curPos -8));
//end else
//AddFieldValue(mfURL, MovieURL);
//AddCustomFieldValueByName('Url-DVD Amazon', '<link url="' + MovieURL + '">' + MovieURL + '</link>');
  
//~Poster~  for Amazon Instant Video
curPos := Pos('<div id="dv-dp-left-content">', HTML);
  EndPos := curPos;
curPos := Pos('<div class="dp-left-meta js-hide-on-play">', HTML);
  EndPos := curPos;
	curPos := PosFrom('<img alt="" src="http://ecx.images-amazon.com/images/', HTML, EndPos)+17;
	EndPos := PosFrom('._SX200_QL80_.jpg" width="200"', HTML, curPos)+17;
	ExtraLinks[smPoster1] := Copy(HTML, curPos, endPos - curPos);
	ExtraLinks[smPoster1] := StringReplace(ExtraLinks[smPoster1], '._SX200_QL80_.jpg', '.jpg', True, True, False);

//~Poster~
curPos := Pos('<meta property ="og:image" content= "http://ecx.images-amazon.com/images/', HTML);
if curPos > 0 then begin
	endPos := PosFrom('"/>', HTML, curPos);
	ExtraLinks[smPoster] := Copy(HTML, curPos+37, EndPos - curPos-37);
 end;
  
//~Poster~
curPos := Pos('<div id="leftCol" class="leftCol">', HTML);
  EndPos := curPos;
curPos := Pos('<div id="imageBlock_feature_div" class="feature" data-feature-name="imageBlock">', HTML);
  EndPos := curPos;
	curPos := PosFrom('<img alt="" src="http://ecx.images-amazon.com/images/', HTML, EndPos)+17;
	EndPos := PosFrom('._SX38_SY50_CR,0,0,38,50_.jpg">', HTML, curPos)+29;
	ExtraLinks[smPoster2] := Copy(HTML, curPos, endPos - curPos);
	ExtraLinks[smPoster2] := StringReplace(ExtraLinks[smPoster2], '._SX38_SY50_CR,0,0,38,50_.jpg', '.jpg', True, True, False);
	
end;


procedure ParseSearchResults(HTML : String);
var
	curPos, endPos: Integer;
	Title, URL, Preview : String;
begin
  //List of other site number where search page :
  TabNumber := ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
  
//	curPos := Pos('<div id="rightContainerATF">', HTML);
	curPos := Pos('<div id="rightResultsATF">', HTML);
	if curPos < 1 then
		Exit;
				
LogMessage('Parsing search results...');

	curPos  := PosFrom('" src="', HTML, curPos);
	endPos  := PosFrom('" onload="viewCompleteImageLoaded', HTML, curPos);
	Preview := Copy(HTML, curPos+7, endPos - curPos-7);
	
//curPos := PosFrom('" href="http://www.amazon.com/', HTML, curPos);
curPos := PosFrom('" href="http://www.', HTML, curPos);
while curPos > 0 do begin
	endPos	:= PosFrom('/ref=sr_1_', HTML, curPos);
//	endPos	:= PosFrom('"><h2 class="a-size-medium a-color-null s-inline s-access-title a-text-normal">', HTML, curPos);
	URL		:= Copy(HTML, curPos+8, endPos - curPos-8);

	curPos	:= PosFrom('<h2 class="a-size-medium a-color-null s-inline s-access-title a-text-normal">', HTML, curPos)+77;
	endPos	:= PosFrom('</h2></a>', HTML, curPos);
	Title	:= Trim(Copy(HTML, curPos, endPos - curPos)); 	
//	Title	:= RemoveTags(Trim(Copy(HTML, curPos, endPos - curPos)), false); 
	
//	AddSearchResult(Title, '', '', URL, '');
	AddSearchResult(Title, '', '', URL, Preview);

	curPos  := PosFrom('" src="', HTML, curPos);
	endPos  := PosFrom('" onload="viewCompleteImageLoaded', HTML, curPos);
	Preview := Copy(HTML, curPos+7, endPos - curPos-7);

//	curPos := PosFrom('" href="http://www.amazon.com/', HTML, curPos);
	curPos := PosFrom('" href="http://www.', HTML, curPos);
 end;

//Get Name of movie to search :                
    MovieName := GetFieldValue(2);
    Explodestring(MovieName,TabMovieName,#32);
    MovieName := #43;
    For I:=low(TabMovieName) to High(TabMovieName) do
    Begin
    MovieName := MovieName + TabMovieName[I] + #43;
    end;	
//Add Links to Page with other sites in TabNumber:
    For I := Low(TabNumber) to High(TabNumber) do
    Begin
	URL := 'http://www.amazon.com/s/ref=sr_pg_' + TabNumber[I] + '?rh=i%3Advd%2Ck%3A'+MovieName+'&page=' + TabNumber[I] + '&keywords='+MovieName;
	AddSearchResult('Search in '+MovieName+' on Amazon.com',TabNumber[I],'',URL,'');
   end;

end;

function NextMode(curMode : Integer) : Integer;
var
	I : Integer;
begin
Result := smFinished;
if curMode < Low(ExtraLinks) - 1 then
	curMode := Low(ExtraLinks) - 1;

for I := curMode + 1 to High(ExtraLinks) do
	if ExtraLinks[I] <> '' then begin
		Result := I;
		Break;
	end;
end;

function ParsePage(HTML : String; URL : AnsiString) : Cardinal;
begin
 Wait (pauseBeforeLoad);
 
HTML := HTMLToText(HTML);
HTML := StringReplace (HTML, 'http://amazon.com', 'http://www.amazon.com', True, True, False);

if Pos(': Movies '+#38+' TV', HTML) > 0 then begin
	ParseSearchResults(HTML);
	Result := prList;
	Exit;
	
end else 
if Pos('<title>Amazon.com:', HTML) > 0 then
	ParseMovie(URL, HTML)
else
if Pos(': Movies '+#38+' TV</title>', HTML) > 0 then
	ParseMovie(URL, HTML)
else
if Pos(':Amazon</title>', HTML) > 0 then
	ParseMovie(URL, HTML)
else
if Pos(': Amazon Instant Video</title>', HTML) > 0 then
	ParseMovie(URL, HTML)
else
if Pos(': Amazon Digital Services , Inc.</title>', HTML) > 0 then
	ParseMovie(URL, HTML)
else
if Pos(',Warner Bros" />', HTML) > 0 then
	ParseMovie(URL, HTML)
else
if Pos('<title>Amazon.com - ', HTML) > 0 then
	ParseMovie(URL, HTML)
else
if Pos('<title>', HTML) > 0 then
	ParseMovie(URL, HTML);

Mode := NextMode(Mode);
if Mode <> smFinished then
	Result := prDownload
else
	Result := prFinished;
end;

begin
Mode := smSearch;
for ELI := Low(ExtraLinks) to High(ExtraLinks) do
	ExtraLinks[ELI] := '';
end.