(*
 Additional types and functions that can be used in scripts:

  //Types
  TWIDEARRAY : array of WideString

  //Field functions
  procedure AddSearchResult(Title1, Title2, Year, URL, PreviewURL : WideString)
  procedure AddFieldValue(AField: Integer; AValue : WideString)
  procedure AddMoviePerson(Name, TransName, Role, URL : WideString; AType : Byte)
  procedure AddPersonMovie(Title, OrigTitle, Role, Year, URL : WideString; AType : Byte)
  procedure AddAward(Event, Award, Category, Recipient, Year: WideString; const Won : Boolean)
  procedure AddConnection(Title, OrigTitle, Category, URL, Year: WideString)
  procedure AddEpisode(Title, OrigTitle, Description, URL, Year, Season, Episode : WideString)
  
  //String functions
  function Pos(Substr : WideString; Str: WideString): Integer
  function PosFrom(const SubStr, Str : WideString; FromIndex : Integer) : Integer
  function LastPos(const SubStr, Str : WideString) : Integer
  function PrevPos(const SubStr, Str : WideString; APos : Integer) : Integer
  function RemoveTags(AText : WideString; doLineBreaks : Boolean) : WideString
  function ExplodeString(AText : WideString; var Items : TWideArray; Delimiters : WideString) : Integer
  function Copy(S: WideString; Index, Count: Integer): WideString
  procedure Delete(var S: WideString; Index, Count: Integer)
  procedure Insert(Source: WideString; var Dest: WideString; Index: Integer)
  function Length(S: WideString): Integer
  function Trim(S: WideString): WideString
  function CompareText(S1, S2: WideString): Integer
  function CompareStr(S1, S2: WideString): Integer
  function UpperCase(S: WideString): WideString
  function LowerCase(S: WideString): WideString
  function StringReplace(S, OldPattern, NewPattern: WideString; ReplaceAll : Boolean; IgnoreCase : Boolean; WholeWord: Boolean): WideString
  function StrToInt(const S: WideString): Integer
  function IntToStr(const Value: Integer): WideString
  function StrToFloat(const S: WideString): Extended
  function FloatToStr(const Value: Extended): WideString

  function HTMLValues(const HTML : WideString; ABegin, AEnd, ItemBegin, ItemEnd : WideString; ValDelim : WideString; var Pos : Integer) : WideString
  function HTMLValues2(const HTML : WideString; ABegin, AEnd, ItemBegin, ItemEnd : WideString; ValDelim : WideString; var Pos : Integer) : WideString
  function TextBetween(const HTML : WideString; ABegin, AEnd : WideString; doLineBreaks : Boolean; var Pos : Integer) : WideString
  function HTMLToText(const HTML : WideString) : WideString

  procedure ShowMessage(const Msg, Head : WideString)
*)

//Some useful constants
const
 //Script types
 stMovies = 0;
 stPeople = 1; 
 stPoster = 2;
  
 //Script modes
 smSearch   = 0; 
 smNormal   = 1;
 smCast     = 2;
 smReview   = 3;
 smCredits  = 4;
 smPoster   = 5;
 smFinished = 6;
  
 //Parse results
 prError     = 0; 
 prFinished  = 1;
 prList      = 2;
 prListImage = 3;
 prDownload  = 4;
 
 //Download methods
 dmGET  = 0;
 dmPOST = 1;
 
 //Prefix modes
 pmNone   = 0;
 pmEnd    = 1;
 pmBegin  = 2;
 pmRemove = 3; 
  
 //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;
  
 //Credits types
 ctActors    = 0;
 ctDirectors = 1;
 ctWriters   = 2;
 ctComposers = 3;
 ctProducers = 4;
  
 //Script data 
 SCRIPT_VERSION = '0.1.0.5'; 
 SCRIPT_NAME    = 'AllMovie.com';
 SCRIPT_DESC    = '[EN] Get movie information from Allmovie.com';
 SCRIPT_LANG    = $09; //English
 SCRIPT_TYPE    = stMovies;
 
 BASE_URL    = 'http://www.allmovie.com';
 RATING_NAME = 'AllMovie';
 
 SEARCH_STR  = 'http://www.allmovie.com/search/work/%s/results';
 
 CODE_PAGE   = 65001; //Use 0 for Autodetect 

 //OPTIONS
 GET_THEMES  = True; //Set to False if you do not want Themes in Category field 
 GET_REVIEW  = True; 
 GET_CREDITS = True;
 
 //Custom field names to use
 IMPORTANCE_FIELD     = 'High Historical Importance'; 
 ARTQUALITY_FIELD     = 'High Artistic Quality';
 CREDITS_FIELD        = 'Production Credits'; 
 REVIEW_FIELD         = 'Review';
 HIGHBUDGET_FIELD     = 'High Budget';
 HIGHPRODUCTION_FIELD = 'High Production Value';
 CULT_FIELD           = 'Cult Film';

//Global variables 
var
 ELI : Integer;
 Mode : Byte;
 ExtraLinks : array [smCast..smPoster] of WideString;

//Functions 
function GetScriptVersion : WideString;
begin
 Result := SCRIPT_VERSION;
end; 
 
function GetScriptName : WideString;
begin
 Result :=  SCRIPT_NAME;
end;

function GetScriptDesc : WideString;
begin
 Result := SCRIPT_DESC;
end;

function GetRatingName : WideString;
begin
 Result := RATING_NAME;
end;

function GetScriptLang: Cardinal;
begin
 Result := SCRIPT_LANG;
end;

function GetCodePage : Cardinal;
begin
 Result := CODE_PAGE;
end;

function GetBaseURL : String;
begin
 Result := BASE_URL;
end;

function GetDownloadURL : String;
begin
 if (Mode = smSearch) then
  Result := SEARCH_STR
 else
  Result := ExtraLinks[Mode]; 
end;

function GetDownloadMethod : Byte;
begin
 //if Mode = smSearch then
 // Result := dmPOST
 //else
  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 ParseCredits(HTML : WideString);
var
 curPos, EndPos : Integer;
 TmpStr : WideString;
  Name, Role, URL : WideString;
begin
 curPos := Pos('<div id="results-table">', HTML);
 if curPos < 1 then
  Exit;
  
 LogMessage('Pasrsing credits...');  
 
 TmpStr := '';
  
 EndPos := curPos; 
 curPos := PosFrom('allmovie.com/artist/', HTML, curPos);
 while (curPos > 0) AND (curPos < PosFrom('</table>', HTML, EndPos)) do begin
  EndPos := PosFrom('">', HTML, curPos);
   
  URL := Copy(HTML, curPos, EndPos - curPos);
   
  curPos := EndPos + 2;
  EndPos := PosFrom('</a>', HTML, curPos);
   
  Name := Copy(HTML, curPos, EndPos - curPos); 
  
  curPos := PosFrom('<em>', HTML, EndPos);
  if curPos > 0 then begin 
   curPos := curPos + 4;
   EndPos := PosFrom('</em>', HTML, curPos);
  
   Role := Trim(Copy(HTML, curPos, EndPos - curPos));
  end else begin
   Role := '';  
   curPos := EndPos;
  end; 
   
  if TmpStr <> '' then
   TmpStr := TmpStr + #13;  
  if URL <> '' then 
   TmpStr := TmpStr + '<link url="' + URL + '">';
  TmpStr := TmpStr + Name;
  if Role <> '' then
   TmpStr := TmpStr + ' - ' + Role;
  if URL <> '' then 
   TmpStr := TmpStr + '</link>';

  if curPos > 0 then 
   curPos := PosFrom('allmovie.com/artist/', HTML, curPos)
  else
   Exit;  
 end;
  
 AddCustomFieldValueByName(CREDITS_FIELD, TmpStr); 
end;

procedure ParseReview(HTML : WideString);
var
 curPos : Integer;
begin
 curPos := Pos('<div id="results-table">', HTML);
 if curPos < 1 then
  Exit;
  
 LogMessage('Pasrsing review...');  
  
 //Review             
 curPos := PosFrom('<td align="left" class="title">Review</td>', HTML, curPos); 
 AddCustomFieldValueByName(REVIEW_FIELD, TextBetween(HTML, '<td colspan="2"><p>', '</p></td>', True, curPos));
end;

procedure ParseCast(HTML : WideString);
var
 curPos, EndPos : Integer;
 Name, Role, URL : WideString;
begin
 curPos := Pos('<div id="results-table">', HTML);
 if curPos < 1 then
  Exit;
  
 LogMessage('Pasrsing cast...'); 
  
 //Actors              
 EndPos := curPos; 
 curPos := PosFrom('allmovie.com/artist/', HTML, curPos);
 while (curPos > 0) AND (curPos < PosFrom('</table>', HTML, EndPos)) do begin
  EndPos := PosFrom('">', HTML, curPos);
   
  URL := Copy(HTML, curPos, EndPos - curPos);
   
  curPos := EndPos + 2;
  EndPos := PosFrom('</a>', HTML, curPos);
   
  Name := Copy(HTML, curPos, EndPos - curPos); 
  
  curPos := PosFrom('<em>', HTML, EndPos);
  if curPos > 0 then begin 
   curPos := curPos + 4;
   EndPos := PosFrom('</em>', HTML, curPos);
  
   Role := Trim(Copy(HTML, curPos, EndPos - curPos));
  end else begin
   Role := '';  
   curPos := EndPos;
  end; 
   
  AddMoviePerson(Name, '', Role, URL, ctActors);

  if curPos > 0 then 
   curPos := PosFrom('allmovie.com/artist/', HTML, curPos)
  else
   Exit;  
 end;
end;

procedure ParseMovie(MovieURL : WideString; HTML : WideString);
var
 curPos, EndPos : Integer;
 Name, URL, TmpStr : WideString;
begin
 LogMessage('Pasrsing movie...'); 
 
 //Get URL
 EndPos := Pos('">Overview</a>', HTML);
 if EndPos > 0 then begin
  curPos := PrevPos('<a href="', HTML, EndPos);
  AddFieldValue(mfURL, Copy(HTML, curPos + 9, EndPos - curPos - 9));
 end else
  AddFieldValue(mfURL, MovieURL);
  
 //Get Review URL
 if GET_REVIEW then begin
  EndPos := Pos('">Review</a>', HTML);
  if EndPos > 0 then begin
   curPos := PrevPos('<a href="', HTML, EndPos);
   ExtraLinks[smReview] := Copy(HTML, curPos + 9, EndPos - curPos - 9);
  end;  
 end; 
 
 //Get Cast URL
 EndPos := Pos('">Cast</a>', HTML);
 if EndPos > 0 then begin
  curPos := PrevPos('<a href="', HTML, EndPos);
  ExtraLinks[smCast] := Copy(HTML, curPos + 9, EndPos - curPos - 9);
 end; 
 
 //Get Credits URL
 if GET_CREDITS then begin
  EndPos := Pos('">Production Credits</a>', HTML);
  if EndPos > 0 then begin
   curPos := PrevPos('<a href="', HTML, EndPos);
   ExtraLinks[smCredits] := Copy(HTML, curPos + 9, EndPos - curPos - 9);
  end; 
 end; 
  
 //Title 
 curPos := Pos('<span class="title">', HTML) + Length('<span class="title">'); 
 EndPos := PosFrom('</span>', HTML, curPos);
 
 AddFieldValue(mfTitle, Copy(HTML, curPos, EndPos - curPos)); 
 LogMessage('Title:' + Copy(HTML, curPos, EndPos - curPos));
 
 //Poster
 curPos := PosFrom('<tr><td valign="top"><img src="', HTML, EndPos);
 if curPos > 0 then begin
  curPos := curPos + Length('<tr><td valign="top"><img src="');
  EndPos := PosFrom('"', HTML, curPos);
  
  ExtraLinks[smPoster] := Copy(HTML, curPos, EndPos - curPos);
  if Pos('noimage', ExtraLinks[smPoster]) > 0 then
   ExtraLinks[smPoster] := '';
 end;
 
 //Year
 curPos := PosFrom('allmovie.com/explore/year/', HTML, EndPos); 
 if curPos < PosFrom('min.', HTML, EndPos) then begin
  EndPos := PosFrom('">', HTML, curPos);
 
  AddFieldValue(mfYear, Copy(HTML, curPos + Length('allmovie.com/explore/year/'), 4)); 
  
  LogMessage('Year:' + Copy(HTML, curPos + Length('allmovie.com/explore/year/'), 4));
  
  EndPos := EndPos + 1;
 end else
  EndPos := PosFrom('">', HTML, curPos) + 1;
 
 //Duration 
 curPos := PosFrom('">', HTML, EndPos) + 2;
 EndPos := PosFrom(' ', HTML, curPos);
 
 AddFieldValue(mfDuration, Copy(HTML, curPos, EndPos - curPos)); 
 
 LogMessage('Duration:' + Copy(HTML, curPos, EndPos - curPos));
 
 //Rating
 curPos := PosFrom('<img src="/img/st_r', HTML, EndPos);
 if curPos > 0 then begin
  curPos := PosFrom('alt="', HTML, curPos) + 5;
  EndPos := PosFrom(' ', HTML, curPos);
  
  AddFieldValue(mfRating, FloatToStr(StrToFloat(Copy(HTML, curPos, EndPos - curPos)) * 2));  
  
  LogMessage('Rating:' + Copy(HTML, curPos, EndPos - curPos));
 end else 
  curPos := EndPos;
  
 curPos := PosFrom('<span>Attributes</span>', HTML, EndPos); 
 if curPos > 0 then begin
  curPos := curPos + Length('<span>Attributes</span>');
  EndPos := PosFrom('</table>', HTML, curPos);  
  
  TmpStr := RemoveTags(Copy(HTML, curPos, EndPos - curPos), False);
  if PosFrom('High Historical Importance', TmpStr, 1) > 0 then
   AddCustomFieldValueByName(IMPORTANCE_FIELD, '-1'); 
   
  if PosFrom('High Artistic Quality', TmpStr, 1) > 0 then
   AddCustomFieldValueByName(ARTQUALITY_FIELD, '-1'); 
   
  if PosFrom('High Budget', TmpStr, 1) > 0 then
   AddCustomFieldValueByName(HIGHBUDGET_FIELD, '-1');  
   
  if PosFrom('High Production Values', TmpStr, 1) > 0 then
   AddCustomFieldValueByName(HIGHPRODUCTION_FIELD, '-1');

  if PosFrom('Cult Film', TmpStr, 1) > 0 then
   AddCustomFieldValueByName(CULT_FIELD, '-1');   
   
  LogMessage('Custom:' + TmpStr); 
 end else
  curPos := EndPos;
 
 //Country
  AddFieldValue(mfCountry, HTMLValues2(HTML, 
                             '<span>Countries</span>', '</table>',
    	                     'allmovie.com/explore/country/', '</a>', 
	    	                 ', ', EndPos));  
 
 EndPos := PosFrom('class="formed-sub"', HTML, curPos); //if no countries found set EndPos to the right position			
 
 //MPAA 
 if Pos('MPAA Rating', HTML) > 0 then begin
  curPos := PosFrom('">', HTML, EndPos) + 2;
  EndPos := PosFrom('</td>', HTML, curPos);
 
  AddFieldValue(mfMPAA, Copy(HTML, curPos, EndPos - curPos)); 
 
  LogMessage('MPAA:' + Copy(HTML, curPos, EndPos - curPos)); 
 end; 
 
 //Aka
 AddFieldValue(mfAka, TextBetween(HTML, '<span>AKA</span>', '</table>', True, curPos));							 
  
 //Director
 curPos := PosFrom('<span>Director</span>', HTML, EndPos);
 if curPos > 0 then begin
  EndPos := curPos;
  curPos := PosFrom('allmovie.com/artist/', HTML, curPos);
  while (curPos > 0) AND (curPos < PosFrom('</table>', HTML, EndPos)) do begin
   curPos := curPos + Length('allmovie.com/artist/');
   EndPos := PosFrom('">', HTML, curPos);
   
   URL := 'http://www.allmovie.com/artist/' + Copy(HTML, curPos, EndPos - curPos);
   
   curPos := EndPos + 2;
   EndPos := PosFrom('</a>', HTML, curPos);
   
   Name := Copy(HTML, curPos, EndPos - curPos); 
   
   AddMoviePerson(Name, '', '', URL, ctDirectors);

   curPos := PosFrom('allmovie.com/artist/', HTML, curPos);
  end;
 end else
 curPos := EndPos; 

 //Genre
 AddFieldValue(mfGenre, HTMLValues(HTML, 
                             '<span>Genres</span>', '</table>',
			                 '<li>', '</li>', 
			                 ', ', EndPos));							 							 
  
 //Tags 
 AddFieldValue(mfTags, HTMLValues(HTML, 
                             '<span>Keywords</span>', '</table>',
			                 '<li>', '</li>', 
			                 ', ', EndPos));
							 
 //Themes (Category) 
 if GET_THEMES then
  AddFieldValue(mfCategory, HTMLValues(HTML, 
                             '<span>Themes</span>', '</table>',
			                 '<li>', '</li>', 
			                 ', ', EndPos));

 //Box office							 
 curPos := PosFrom('<span>Box office</span>', HTML, EndPos);	
 if curPos > 0 then begin
  curPos := PosFrom('<li>', HTML, curPos) + 5;
  EndPos := PosFrom('</li>', HTML, curPos); 
  
  TmpStr := Copy(HTML, curPos, EndPos - curPos);
  curPos := Pos('/', TmpStr);
  if curPos > 0 then
   Delete(TmpStr, curPos, Length(TmpStr) - curPos);
  curPos := Pos(':', TmpStr);
  if curPos > 0 then
   Delete(TmpStr, curPos, Length(TmpStr) - curPos); 
  AddFieldValueXML('money', TmpStr); 
  
  LogMessage('Box office:' + TmpStr); 
 end; 
  
 //Studio
 AddFieldValue(mfStudio, HTMLValues2(HTML, 
                             '<span>Produced by</span>', '</table>',
			                 '<a href="', '</a>', 
			                 ', ', EndPos)); 
  
 //Description
 curPos := PosFrom('<td align="left" class="title">Plot Synopsis</td>', HTML, EndPos); 
 AddFieldValue(mfDescription, TextBetween(HTML, '<td colspan="2"><p>', '</p></td>', True, curPos)); 
end;

procedure ParseSearchResults(HTML : WideString);
var
 curPos, EndPos : Integer;
 Title, Year, URL : WideString;
begin
 curPos := Pos('<div id="results-table">', HTML);
 if curPos < 1 then
  Exit;
  
 LogMessage('Parsing search results...');  
  
 curPos := PosFrom('<a href="http://www.allmovie.com/work/', HTML, curPos); 
 while curPos > 0 do begin
  EndPos := PosFrom('">', HTML, curPos);
  URL := Copy(HTML, curPos + 9, EndPos - curPos - 9);
  
  curPos := EndPos + 2;
  
  EndPos := PosFrom('</a>', HTML, curPos);
  Title := Copy(HTML, curPos, EndPos - curPos);
  
  curPos := PosFrom('style="width: 70px;">', HTML, curPos);
  curPos := curPos + Length('style="width: 70px;">');
  EndPos := PosFrom('</td>', HTML, curPos);
  
  Year := Copy(HTML, curPos, EndPos - curPos);
  
  AddSearchResult(Title, '', Year, URL, '');
 
  curPos := PosFrom('<a href="http://www.allmovie.com/work/', HTML, curPos); 
 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 : WideString; URL : String) : Cardinal;
begin
 HTML := HTMLToText(HTML);

 if Pos('Search Results for:', HTML) > 0 then begin
  ParseSearchResults(HTML);
  Result := prList; 
  Exit;
 end else
 if Pos('> Overview - AllMovie</title>', HTML) > 0 then
  ParseMovie(URL, HTML)
 else
 if Pos('> Review - AllMovie</title>', HTML) > 0 then
  ParseReview(HTML)
 else 
 if Pos('> Cast - AllMovie</title>', HTML) > 0 then
  ParseCast(HTML)
 else
 if Pos('> Production Credits - AllMovie</title>', HTML) > 0 then
  ParseCredits(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.