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

  //Types
  TWIDEARRAY : array of String

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

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

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

//Some useful constants
const
 //Script types
 stMovies = 0;
//riga 50
 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;
//riga 100
 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.6'; 
 SCRIPT_NAME    = 'Ibs.it';
 SCRIPT_DESC    = '[IT] Get movie information from Ibs.it';
 SCRIPT_LANG    = $09; //English
 SCRIPT_TYPE    = stMovies;
 
 BASE_URL    = 'http://www.ibs.it';
 RATING_NAME = 'Ibs';
 
 SEARCH_STR  = 'http://www.ibs.it/ser/serfat.asp?site=dvd&xy=%s';
 
 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 String;
//riga 150
//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
 //if Mode = smSearch then
 // Result := dmPOST
 //else
//riga 200
  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 ParseReview(HTML : String);
var
 curPos : Integer;
begin
 curPos := Pos('IBS - Ricerca nei dvd', 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 : String);
var
 curPos, EndPos : Integer;
 Name, Role, URL : String;

begin
 curPos := Pos('Principali interpreti', HTML);
 if curPos < 1 then
  Exit;
 LogMessage('Pasrsing cast...'); 

 //Actors              
 curPos := PosFrom('<a href="/dvd-film/attore', HTML, curPos);
//riga 250
 while (curPos > 0) AND (curPos < PosFrom('prezzo<', HTML, EndPos)) do begin
  EndPos := PosFrom('">', HTML, curPos);
  URL := BASE_URL + Copy(HTML, curPos + 9, EndPos - curPos - 9);
  curPos := EndPos + 2;
  EndPos := PosFrom('</a>', HTML, curPos);
  Name := Copy(HTML, curPos, EndPos - curPos); 
  Role := '';  
  AddMoviePerson(Name, '', Role, URL, ctActors);
  if curPos > 0 then 
   curPos := PosFrom('<a href="/dvd-film/attore', HTML, curPos)
  else
   Exit;  
 end;
end;

procedure ParseMovie(MovieURL : String; HTML : String);
var
 curPos, EndPos : Integer;
 Name, URL : String;
begin
 LogMessage('Pasrsing movie...'); 
 
 //Title 
 curPos := Pos('>Titolo<', HTML);
 if curPos > 0 then begin
  EndPos := PosFrom('</td></tr>', HTML, curPos);
  AddFieldValue(mfTitle, Copy(HTML, curPos+63, EndPos - curPos-63)); 
  LogMessage('Title:' + Copy(HTML, curPos+63, EndPos - curPos-63));
 end;
 curPos := Pos('>Titolo o', HTML);
 if curPos > 0 then begin
  EndPos := PosFrom('</td></tr>', HTML, curPos);
  AddFieldValue(mfOrigTitle, Copy(HTML, curPos+61, EndPos - curPos-61)); 
  LogMessage('OrigTitle:' + Copy(HTML, curPos+61, EndPos - curPos-61));
 end;

 //Country
 curPos := Pos('Anno<', HTML);
 if curPos > 0 then begin
  curPos := curPos + 30;
  EndPos := PosFrom(', ', HTML, curPos);
  LogMessage('paese: pos='+ IntToStr(curPos)+' endpos='+IntToStr(EndPos));
  AddFieldValue(mfCountry, Copy(HTML, curPos, EndPos - curPos));
  LogMessage('Paese:' + Copy(HTML, curPos, EndPos - curPos));
 
  //Year
  EndPos := PosFrom('</td>', HTML, curPos);
  curPos := EndPos - 4; 
  LogMessage('anno: pos='+ IntToStr(curPos)+' endpos='+IntToStr(EndPos));
  AddFieldValue(mfYear, Copy(HTML, curPos, 4)); 
  LogMessage('Year:' + Copy(HTML, curPos, 4));
 end;
//riga 300
 //Director
 curPos := Pos('>Regia<', HTML);
 if curPos > 0 then begin
  curPos := Posfrom('href=', HTML, curPos);
  while (curPos > 0) AND (curPos < PosFrom('Principali interpreti', HTML, EndPos)) do begin
   EndPos := PosFrom('">', HTML, curPos);
   URL := BASE_URL + Copy(HTML, curPos+6, EndPos - curPos-6);
   curPos := EndPos + 2;
   EndPos := PosFrom('</a>', HTML, curPos);
   Name := Copy(HTML, curPos, EndPos - curPos); 
   AddMoviePerson(Name, '', '', URL, ctDirectors);
   curPos := PosFrom('href=', HTML, curPos);
  end;
 end;

 //Genre
 curPos := Pos('Genere</b></td><td valign="top">', HTML);
 if curPos > 0 then begin
  CurPos := CurPos + Length('Genere</b></td><td valign="top">')
  EndPos := PosFrom('</td>', HTML, curPos);
  AddFieldValue(mfGenre, Copy(HTML, curPos, EndPos - curPos) ); 
  LogMessage('Genre:' + Copy(HTML, curPos, EndPos - curPos) );  
 end ;
						 							 
 //Duration 
 curPos := Pos('Dati tecnici</b></td><td valign="top">', HTML);
 if curPos > 0 then begin
  EndPos := PosFrom(' min.', HTML, curPos);
  AddFieldValue(mfDuration, Copy(HTML, curPos+38, EndPos - curPos-38)); 
  LogMessage('Duration:' + Copy(HTML, curPos+38, EndPos - curPos-38));
 end;
  
 //Get URL 
 EndPos := Pos('" content="index,follow">', HTML);
 if EndPos > 0 then begin
  curPos := PrevPos('" href="', HTML, EndPos);
  EndPos := Pos('">', HTML);
  AddFieldValue(mfURL, Copy(HTML, curPos + 8, EndPos - curPos - 8));
 end else
  AddFieldValue(mfURL, MovieURL);
  
 //Poster
 curPos := Pos('<link rel="image_src" href="', HTML);
 if curPos > 0 then begin
  curPos := curPos + Length('<link rel="image_src" href="');
  EndPos := PosFrom('"', HTML, curPos);
//riga 350
  ExtraLinks[smPoster] := Copy(HTML, curPos, EndPos - curPos);
  if Pos('noimage', ExtraLinks[smPoster]) > 0 then
   ExtraLinks[smPoster] := '';
 end;
 
 //Description
 curPos := Pos('Descrizione', HTML);
 if curPos > 0 then 
 AddFieldValue(mfDescription, TextBetween(HTML, '<span class="tcorpotesto">', '</span><p>', True, curPos)); 

end;

procedure ParseSearchResults(HTML : String);
var
 curPos, EndPos : Integer;
 Title, Year, URL : String;

begin
 curPos := Pos('<title>IBS - Ricerca', HTML);
 if curPos < 1 then
  Exit;
  
 LogMessage('Parsing search results...');  
  
 curPos := PosFrom('href="http://www.ibs.it/dvd-film/', HTML, curPos); 
 while curPos > 0 do begin
  EndPos := PosFrom('">', HTML, curPos);
  URL := Copy(HTML, curPos + 6, EndPos - curPos - 6);
  curPos := PosFrom('<b>', HTML, curPos);   
  EndPos := PosFrom('</b>', HTML, curPos);
  Title := Copy(HTML, curPos +3, EndPos - curPos -3);
  Year := ''
  AddSearchResult(Title, '', Year, URL, '');
  curPos := PosFrom('href="http://www.ibs.it/dvd-film/', HTML, curPos); 
 end;
end;

function NextMode(curMode : Integer) : Integer;
//riga 400
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
 HTML := HTMLToText(HTML);

 if Pos('<title>IBS - Ricerca', HTML) > 0 then begin
  ParseSearchResults(HTML);
  Result := prList; 
  Exit;
 end else
 if Pos('name="de', HTML) > 0 then begin
  ParseMovie(URL, HTML);
  ParseCast(HTML);
 end;
 
 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.
