 //This version of script is for use with PVD versions 0.9.9.5 and above!!!
 //derived from allmovie template
(*
 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;
 stPeople = 1; 
 stPoster = 2;
  
 //Script modes
 smSearch     = 0; 
 smNormal     = 1;
 //smCast       = 2;
 //smReview     = 3;
 //smCredits    = 4;
 smAward      = 2;
 smPrePoster  = 3;
 smPoster     = 4;
 smFinished   = 5;
 
 //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.6'; 
 SCRIPT_NAME    = 'mymovies.it';
 SCRIPT_DESC    = '[IT] Get movie information from Mymovies.it';
 SCRIPT_LANG    = $09; //English
 SCRIPT_TYPE    = stMovies;
 
 BASE_URL    = 'http://www.mymovies.it';
 RATING_NAME = 'mymovies';
 
 SEARCH_STR  = 'http://www.google.it/cse?q=%s&cx=partner-pub-1699801751737986%3Ax7j961-1g3m&cof=FORID%3A9&ie=ISO-8859-1&sa=Cerca&ad=w9&num=10&rurl=http%3A%2F%2Fwww.mymovies.it%2Fdatabase%2Fricercalibera%2Fdefault.asp%3Fq%3D%s%26cx%3Dpartner-pub-1699801751737986%253Ax7j961-1g3m%26cof%3DFORID%253A9%26ie%3DISO-8859-1%26sa%3DCerca';

 
 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, intParsed : Integer;
 Mode : Byte;
 ExtraLinks : array [smAward..smPoster] of String;
 
//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
  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, EndPos : Integer;
 strDescription : String;
begin
 curPos := Pos('<div id="recensione">', HTML);
 
 if curPos < 1 then
  Exit;
  
 LogMessage('Parsing review...');  
  
 //Review          
  
 EndPos := PosFrom('</p>', HTML, curPos);
 curPos := PrevPos('<img style="', HTML, EndPos);
 curPos := PosFrom('</a>', HTML, curPos);
 
//if curPos < Pos('<div id="recensione">', HTML) then 
//  curPos := PrevPos('<p>', HTML, EndPos);
  

 curPos := curPos + 4;
 strDescription := Trim(HTMLToText(Copy(HTML, curPos, EndPos - curPos)));
 strDescription := StringReplace(strDescription, '<i>', '', true, false, false);
 strDescription := StringReplace(strDescription, '</i>','', true, false, false);
 strDescription := StringReplace(strDescription, '</a>','', true, false, false);
 strDescription := StringReplace(strDescription, '<em>','', true, false, false);
 strDescription := StringReplace(strDescription, '</em>','', true, false, false);
 strDescription := StringReplace(strDescription, '<a href ="',' ', true, false, false);
 strDescription := StringReplace(strDescription, '">',' ', true, false, false);
 
 
 if Trim(strDescription) <> '' then begin
	 AddFieldValue(mfDescription, Trim(strDescription)); 
	 LogMessage('Recensione: '+  strDescription);  
 end;
end;

procedure ParseCast(HTML : String);
var
 curPos, EndPos : Integer;
 Name, Role, URL : String;
begin
 curPos := Pos('Con <a href=', HTML);
if curPos < 1 then
  Exit;
  
 LogMessage('Parsing cast...'); 
  
 //Actors              
 EndPos := curPos; 
 curPos := PosFrom('"', HTML, curPos);
 while (curPos > 0) AND (curPos < PosFrom('</a></div>', HTML, EndPos))  do begin
  curPos := curPos + Length('"');
  EndPos := PosFrom('">', HTML, curPos);
   
  URL := Trim(Copy(HTML, curPos, EndPos - curPos));
   
  curPos := EndPos + 2;
  EndPos := PosFrom('</a>', HTML, curPos);
   
  Name := Copy(HTML, curPos, EndPos - curPos); 
  Role := '';  
  curPos := EndPos;
   
  AddMoviePerson(Name, '', Role, URL, ctActors);
  //LogMessage('Actor:' + URL + ' ' + Name);
  curPos := PosFrom('<a href="', HTML, curPos);
  if curPos > PosFrom('Titolo originale', HTML, EndPos) then
   Exit;
 end;
end;

procedure ParseAward(HTML : String);
var
 curPos, EndPos, intTable : Integer;
 strAnno : String;
 strAward : String;
 boolWin : Boolean;
begin
	   curPos := 1;
	   while ( curPos > 0) do begin
	   		curPos := PosFrom('<table style="width:100%;" cellpadding="0" cellspacing="0" border="0">', HTML, curPos);
			LogMessage('Posizione table:' + IntToStr(curPos));
			if (curPos > 0) then begin
			    intTable := curPos;
				curPos := curPos + 1;
			    boolWin := true;
			    curPos := PosFrom('<img alt="', HTML, curPos);
			    curPos := curPos + 10;
			    EndPos := PosFrom('"', HTML, curPos + 10 );
			    LogMessage('Parsing Award:' + Trim(Copy(HTML, curPos , EndPos - curPos)));
			    strAward := RemoveTags(Trim(Copy(HTML, curPos, EndPos - curPos)), false);
			    strAnno  := Copy(strAward, length(strAward) - 4 , length(strAward));
			end;
			while (curPos > 0) do begin
					  EndPos := PosFrom('</div>', HTML, curPos);
					  curPos := PrevPos ('align="absmiddle" />', HTML, EndPos) + 20;
					  if curPos < intTable then begin
					  	curPos := PosFrom('<table style="width:100%;" cellpadding="0" cellspacing="0" border="0">', HTML, EndPos);
						break;
					  end;
					  AddAward(Trim(strAward), RemoveTags(Trim(Copy(HTML, curPos , EndPos - curPos)),false) , '', '', strAnno, boolWin);
					  LogMessage('Parsing Award:' + Trim(Copy(HTML, curPos , EndPos - curPos)));
					  if PrevPos('<table style="width:100%;" cellpadding="0" cellspacing="0" border="0">', HTML, curPos) <> intTable then begin
							curPos := PrevPos('<table style="width:100%;" cellpadding="0" cellspacing="0" border="0">', HTML, curPos);
							LogMessage('Posizione table:' + IntToStr(curPos));
							break;
					  end;
					  curPos := PosFrom('http://www.mymovies.it/biografia/img/premio.gif" align="absmiddle" />', HTML, EndPos);
			end;
	   end;
end;
	 
procedure ParsePoster(HTML : String);
var
 curPos, EndPos : Integer;
begin
  //Poster

 curPos := Pos('alt="Locandina italiana', HTML);
 EndPos := PosFrom('" />', HTML, curPos);
 curPos := PrevPos('"', HTML, EndPos);


 if curPos > 0 then begin
   curPos := curPos + 1;
   ExtraLinks[smPoster] := Trim(Copy(HTML, curPos, EndPos - curPos));
   if Pos('noimage', ExtraLinks[smPoster]) > 0 then
     ExtraLinks[smPoster] := '';
   LogMessage('Parsing poster...' + ExtraLinks[smPoster]);
 end;
end;

procedure ParseMovie(MovieURL : String; HTML : String);
var
 curPos, EndPos : Integer;
 Name, URL, Title  : String;
begin
 LogMessage('Parsing movie...'); 
 intParsed := 0;



 //Title 
 curPos := Pos('Titolo originale', HTML); 
 if curPos > 0 then begin
   curPos := curPos + Length('Titolo originale');
   EndPos := PosFrom('<strong>', HTML, curPos);
   Title := StringReplace(Trim(Copy(HTML, curPos, EndPos - curPos)), '<em>' , '',false,false,false);
   Title := StringReplace(Title, '</em>' , '',false,false,false);
	   AddFieldValue(mfOrigTitle, Title ); 
	   LogMessage('Original Title:' + Title);
 end
 else
 begin
   curPos := Pos('<h1 style="margin-bottom:3px;">', HTML);
   curPos := curPos + Length('<h1 style="margin-bottom:3px;">');
   EndPos := PosFrom('</h1>', HTML, curPos);
   AddFieldValue(mfOrigTitle, Trim(Copy(HTML, curPos, EndPos - curPos)) ); 
   LogMessage('Original Title:' + Trim(Copy(HTML, curPos, EndPos - curPos)));
 end;
 
//Director
 curPos := PosFrom('Un film di <a href=', HTML, EndPos);
 if curPos > 0 then begin
  EndPos := curPos;
  curPos := PosFrom('"', HTML, curPos);
  while (curPos > 0) AND (curPos < PosFrom('Con <a', HTML, EndPos)) do begin
   curPos := curPos + Length('"');
   EndPos := PosFrom('">', HTML, curPos);
   
   URL := Trim(Copy(HTML, curPos, EndPos - curPos));
   
   curPos := EndPos + 2;
   EndPos := PosFrom('</a>', HTML, curPos);
   
   Name := Trim(Copy(HTML, curPos, EndPos - curPos)); 
   
   AddMoviePerson(Name, '', '', URL, ctDirectors);
   LogMessage('Director:' + URL + ' ' + Name);

   curPos := PosFrom('<a href="', HTML, curPos);
  end;
 end else
 curPos := EndPos;    
 
 //Get URL
 EndPos := PosFrom('">Recensione &raquo;</a>', HTML, curPos);
 if EndPos > 0 then begin
  curPos := PrevPos('<a href="', HTML, EndPos);
  EndPos := PosFrom('"', HTML, curPos);
  AddFieldValue(mfURL, Copy(HTML, curPos + 9, EndPos - curPos - 9));
 end else
  AddFieldValue(mfURL, MovieURL);

 //Poster
 curPos := Pos('http://www.mymovies.it/poster/?id=', HTML);
 if curPos > 0 then begin
  curPos := curPos + Length('http://www.mymovies.it/poster/?id=');
  EndPos := PosFrom('"', HTML, curPos);
  ExtraLinks[smPrePoster] := 'http://www.mymovies.it/poster/0/?id=' + Trim(Copy(HTML, curPos, EndPos - curPos));
  LogMessage('PrePoster:' + ExtraLinks[smPrePoster] );
 end;

 //Get Award URL
 
 curPos := Pos('http://www.mymovies.it/dizionario/premi.asp?', HTML);
 if curPos > 0 then begin
  EndPos := PosFrom('">', HTML, curPos) ;
  ExtraLinks[smAward] := Trim(Copy(HTML, curPos, EndPos - curPos ));
  LogMessage('Award Link:' + Copy(HTML, curPos, EndPos - curPos ));
 end; 


 //Genre
 curPos := Pos('<a title="Film', HTML);
 if curPos > 0 then begin
	 CurPos := CurPos + Length('<a title="Film')
	 EndPos := PosFrom('"', HTML, curPos);
	 AddFieldValue(mfGenre, UpperCase(Copy(HTML, curPos , 2)) + Copy(HTML, curPos + 2, EndPos - curPos - 2) ); 
	 LogMessage('Genre:' + UpperCase(Copy(HTML, curPos , 2)) + Copy(HTML, curPos + 2, EndPos - curPos - 2) );  
 end ;

 //Duration 
 EndPos := PosFrom('min.', HTML,CurPos);
 if EndPos > 0 then begin
	 curPos := EndPos - 4
	 AddFieldValue(mfDuration, Trim(Copy(HTML, curPos, EndPos - curPos))); 
	 LogMessage('Duration:' + Trim(Copy(HTML, curPos, EndPos - curPos))); 
	 curPos := EndPos;
 end ;
 
 //Country
 curPos := PosFrom('-', HTML, curPos); 
 if curPos > 0 then begin
  curPos := curPos + 1
  EndPos := PosFrom('<strong>', HTML, curPos); 
  AddFieldValue(mfCountry, Trim(Copy(HTML, curPos , Endpos - curPos ))); 
  LogMessage('Country: ' + Trim(Copy(HTML, curPos , Endpos - curPos )));
 end else
 
  
 //Year
 curPos := PosFrom('www.mymovies.it/film/?anno=', HTML, curPos); 
 if curPos > 0 then begin
  curPos := curPos + Length('www.mymovies.it/film/?anno=')
  curPos := PosFrom('">', HTML, curPos) + 2;
  EndPos := PosFrom('</', HTML, curPos);
  AddFieldValue(mfYear, Trim(Copy(HTML, curPos , Endpos - curPos ))); 
  LogMessage('Anno: ' + Trim(Copy(HTML, curPos , Endpos - curPos )));
 end else

 //Rating

 curPos := Pos('http://www.mymovies.it/v7/img/mymonetro_incassi_sopra.png', HTML);
 curPos := PosFrom('margin:0px 11px 7px 11px">', HTML, curPos);
 if curPos > 0 then begin
  curPos := curPos + 26;
  EndPos := PosFrom('<', HTML, curPos);
  AddFieldValue(mfRating, FloatToStr(StrToFloat(Copy(HTML, curPos, EndPos - curPos)) * 2));  
  LogMessage('Rating:' + FloatToStr(StrToFloat(Copy(HTML, curPos, EndPos - curPos)) * 2));
 end else 
  curPos := EndPos;
end;

procedure ParseSearchResults(HTML : String);
var
 intInitPos, curPos, EndPos : Integer;
 Title, Year, URL : String;
begin
 curPos := Pos('Ricerca personalizzata', HTML);
  if curPos < 1 then
  Exit;
  
 LogMessage('Parsing search results...');  

 intInitPos := curPos

 curPos := PosFrom('<a href="http://www.mymovies.it/dizionario/recensione.asp?', HTML, curPos); 

 if curPos = 0 then curPos := PosFrom('<a href="http://www.mymovies.it/film/', HTML, intInitPos ); 

 while curPos > 0 do begin
  EndPos := PosFrom('>', HTML, curPos);
  URL := Copy(HTML, curPos + 16, EndPos - curPos - 37);
  
  curPos := EndPos + 1;
  
  EndPos := PosFrom('(', HTML, curPos);
	

  Title := Copy(HTML, curPos, EndPos - curPos);
  Title := StringReplace(Title, '<em>' , '',true,false,false)
  Title := StringReplace(Title, '</em>', '',true,false,false)
  Title := StringReplace(Title, '<b>', '',true,false,false)  
  Title := StringReplace(Title, '</b>', '',true,false,false)  
  
  if Length(Title) > 80 then Title := Copy(Title, 1, 80);
  
  curPos := PosFrom('(', HTML, curPos);
  curPos := curPos + 1;
  EndPos := PosFrom(')', HTML, curPos);
  
  Year := Copy(HTML, curPos, EndPos - curPos);
  
  AddSearchResult(Title, '', Year, URL, '');
 
  curPos := PosFrom('<a href="http://www.mymovies.it/dizionario/recensione.asp?', 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
   LogMessage('Extralinks:' + IntToStr(I) );
   Result := I;
   Break;
  end;
end;

function ParsePage(HTML : String; URL : AnsiString) : Cardinal;
begin
 HTML := HTMLToText(HTML);

 if Pos('Risultati', HTML) > 0 then begin
  ParseSearchResults(HTML);
  Result := prList; 
  Exit;
 end else
 if Pos('<title>Premi e Nomination',HTML) <= 0 then begin
  if intParsed = 0 then begin
	  ParseReview(HTML);
	  ParseMovie(URL, HTML);
	  ParseCast(HTML);
	  intParsed := 1;
  end;
  if Pos('<title>Poster', HTML) > 0 then begin
   ParsePoster(HTML);
   end;
 end
 else if Pos('<title>Premi e Nomination',HTML) > 0 then begin
  ParseAward(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.
