//Some useful constants
const
 //Script types
 stMovies = 0;
 stPeople = 1; 
 stPoster = 2;
  
 //Script modes
 smSearch   = 0; 
 smNormal   = 1;
 //Custom modes
 smEp = 2;
 //smCredits  = 2;
 smStudio   = 3;
 smPoster   = 4;
 smFinished = 5;
  
 //Parse results
 prError    = 0; 
 prFinished = 1;
 prList     = 2;
 prListImage= 3;
 prDownload = 4;
  
 //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.3';  
 SCRIPT_NAME    = 'Anime News Network';
 SCRIPT_DESC    = '[EN] Get movie information from ANN';
 SCRIPT_LANG    = $09; // English
 SCRIPT_TYPE    = stMovies;
// author - AcM 
 
 BASE_URL    = 'http://www.animenewsnetwork.com';
 RATING_NAME = 'ANN';
 
 SEARCH_STR  = 'http://www.animenewsnetwork.com/encyclopedia/search/name?q=%s';
 
 CODE_PAGE   = 65001; //Use 0 for Autodetect 
 
 //OPTIONS
 DOWNLOAD_POSTER = False;
 DOWNLOAD_EPISODES = True;
 DOWNLOAD_STUDIO = True;
 DOWNLOAD_CONNECTIONS = False;
 DOWNLOAD_AUTHOR_INSTEAD_OF_PRODUCER = False;

//Global variables 
var
 ELI : Integer;
 Mode : Byte;
 ExtraLinks : array [smNormal..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 GetBaseURL : AnsiString;
begin
 Result := BASE_URL;
end;

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

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

function GetScriptType : Byte; 
begin
 Result := SCRIPT_TYPE;
end;

function GetCurrentMode : Byte; 
begin
 Result := Mode;
end;

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


procedure ParseEpisodes(HTML : String);
var
 P, curPos, EndPos, R, T, F, N, D: Integer;
 S, Day, Tname, Oname: String;
begin
 P := 1;
 //Studio

  curPos := Pos('episode-list', HTML);
 if curPos > 0 then begin 

   curPos := PosFrom('episode-list', HTML, curPos);
   EndPos := PosFrom('You can contribute information to this page', HTML, curPos);
 T := PosFrom ( '<TR>', HTML, curPos);
 N := PrevPos ('<TD CLASS=n>', HTML, EndPos);
 D := StrToInt (TextBetween(HTML, '<TD CLASS=n>','.</TD>', false, N));

  while   (P < D) or (P = D)  do begin
  T := PosFrom( '<TR>', HTML, curPos);
  curPos := PosFrom( '<TD CLASS=d>', HTML, T);
  R := PosFrom ('</TR>', HTML , T);
  S:= Copy (HTML, T, R - T);

F := Pos ('<TR>', S);
Day:= TextBetween (S, '<DIV>', '</DIV>', false, F);

F := Pos ('<TD VALIGN="top">', S);
if F>0 then
Tname:= TextBetween (S, '<DIV>', '</DIV>', false, F);

F := Pos ('<DIV CLASS=j>', S);
if F>0 then
Oname:= TextBetween (S, '<DIV>', '</DIV>', false, F);

If (Tname = '') then 
	Tname := Day; 

 AddEpisode (Tname, Oname, Day, '', '', '', FloatToStr(P));
 P := P+1;
end;

end;
end;

procedure ParseMovie(MovieURL : String; HTML : String);
var
 curPos, EndPos, P,  curPos1, curPos2, curPos3 : Integer;
 Tmp, URL, Name, TransName, Role, EPT, OP, EN : String;
 
 OrigTitleFound : Boolean;
begin

 AddFieldValue(mfURL, MovieURL); 

 curPos :=  Pos('<h1 id="page_header">', HTML);
 EndPos := Pos('</h1>', HTML);
  if (EndPos > 0) AND (curPos > 0) AND (curPos < EndPos) then begin
  AddFieldValue(mfOrigTitle, RemoveTags(Copy(HTML, curPos, EndPos - curPos), false));
  AddFieldValue(mfTitle, RemoveTags(Copy(HTML, curPos, EndPos - curPos), false)); 
  OrigTitleFound := True;

EPT := RemoveTags(Copy(HTML, curPos, EndPos - curPos), false);
EndPos:=1;
EPT := TextBetween (EPT, '(', ')' , false,  EndPos );
AddFieldValueXML('category',  EPT);


 end else
  OrigTitleFound := False;  

 // What is
 curPos := Pos('<SMALL>[ ', HTML); 
 if curPos > 0 then begin
 AddFieldValueXML('tagline', TextBetween (HTML, '[', ']', false, curPos)); 
 end; 

//Other titles
 curPos := PosFrom('Alternative title', HTML, EndPos);
 EndPos := curPos;
  Tmp := HTMLValues(HTML, '</strong>', 'Genres',
			       '<DIV CLASS="tab">', '</DIV>', 
			       #13#10, curPos);
				   
   //Write first to Original title field
  if not OrigTitleFound then begin
   P := Pos(#13#10, Tmp);
   if P < 1 then
    P := Length(Tmp) + 1;
   AddFieldValue(mfOrigTitle, Copy(Tmp, 1, P - 1));  
   Delete(Tmp, 1, P + 1);
  end;    

  //Write all other titles to Aka field
  AddFieldValue(mfAka, Tmp);  

 //Poster URL
 if DOWNLOAD_POSTER then begin
  curPos := Pos('thumbnails/fit200x200/', HTML);
  if curPos > 0 then begin 
   curPos := PosFrom('thumbnails/fit200x200/', HTML, curPos) + Length('thumbnails/fit200x200/');
   EndPos := PosFrom('''', HTML, curPos);

   ExtraLinks[smPoster] := 'http://www.animenewsnetwork.com/thumbnails/fit200x200/' + Copy(HTML, curPos, EndPos - curPos);
  end;
 end; 


 //Genre
 curPos := Pos('Genre', HTML);
 EndPos := curPos;
 AddFieldValue(mfGenre, HTMLValues2(HTML, 
                             'Genres', '</div>',
			                 'class="discreet"', '</a>', 
			                 ', ', EndPos));		

 //Tags (Themes)
 curPos := Pos('<strong>Themes:</strong>', HTML);
 EndPos := curPos;
  AddFieldValueXML ('tags', HTMLValues2(HTML, 
                             '<strong>Themes:</strong>', '</div>',
			                 'class="discreet"', '</a>', 
			                 ', ', EndPos));		

 //Description 
curPos := Pos('<strong>Plot Summary:</strong>', HTML);
if curPos > 0 then begin
EndPos := curPos;
AddFieldValue(mfDescription, TextBetween(HTML, '<SPAN>', '</SPAN>', false, EndPos)); 
end;
 

 //Rating
 curPos := Pos('Bayesian estimate', HTML);
 if curPos > 0 then begin
  curPos := curPos + Length('Bayesian estimate:</B>');
  EndPos := PosFrom('(', HTML, curPos);
   AddFieldValue(mfRating, Trim(HTMLToText(Copy(HTML, curPos, EndPos - curPos))));
 end;	

 //Year
 curPos := Pos('Vintage', HTML); 
 if curPos > 0 then begin
	 if PosFrom ('-', HTML, curPos) < PosFrom('">', HTML, curPos) then
		AddFieldValue(mfYear, TextBetween (HTML, '>', '-', true, curPos))
	else
		AddFieldValue(mfYear, TextBetween (HTML, '">', '<', true, curPos))
 end; 

 //Songs 
curPos := Pos('<STRONG>Opening Theme:</STRONG>', HTML);
if curPos > 0 then begin
EndPos := curPos;
OP := 'Opening Theme:' + '<br>' + HTMLValues (HTML, '<STRONG>Opening Theme:</STRONG>', '<STRONG>', '<DIV CLASS="tab">', '</DIV>', '<br>', EndPos) ;
End;

curPos := Pos('<STRONG>Ending Theme:</STRONG> ', HTML);
if curPos > 0 then begin
EndPos := curPos;
EN := 'Ending Theme:' + '<br>' + HTMLValues (HTML, '<STRONG>Ending Theme:</STRONG> ', '<STRONG>', '<DIV CLASS="tab">', '</DIV>', '<br>', EndPos);


//AddFieldValueXML ('comment', OP+ '<br>'+ '<br>'+EN);
AddCustomFieldValueByName ('Дополнительно:', OP+ '<br>'+ '<br>'+EN);
End;


 //Writers

curPos := Pos('<B>Script</B>', HTML);
 if curPos > 0 then begin 

  EndPos := curPos; 
  curPos := PosFrom('people.php?id=', HTML, EndPos);
  curPos1 := PosFrom('ENTAB', HTML, EndPos)
 while curPos < curPos1 do begin
   EndPos := PosFrom('">', HTML, curPos);
 URL := BASE_URL + '/people.php?id=' + TextBetween(HTML,  '=', '">', false, curPos);
      TransName := TextBetween(HTML,  '">', '</a>', false, curPos);
 curPos := PosFrom('people.php?id', HTML, EndPos);
AddMoviePerson(TransName, TransName, '', URL, ctWriters);
  end;
  end;

 curPos := Pos('Screenplay', HTML);
 if curPos > 0 then begin 
  EndPos := curPos; 
  curPos := PosFrom('people.php?id=', HTML, EndPos);
  curPos1 := PosFrom('ENTAB', HTML, EndPos)
 while curPos < curPos1 do begin
  
   EndPos := PosFrom('">', HTML, curPos);
 URL := BASE_URL + '/people.php?id=' + TextBetween(HTML,  '=', '">', false, curPos);
      TransName := TextBetween(HTML,  '">', '</a>', false, curPos);
 curPos := PosFrom('people.php?id', HTML, EndPos);
AddMoviePerson(TransName, TransName, '', URL, ctWriters);
  end;
end;

 //Directors
curPos := Pos('<b>Director</b>', HTML);
 if curPos > 0 then begin 
  EndPos := curPos; 
  curPos := PosFrom('people.php?id=', HTML, EndPos);
  curPos1 := PosFrom('ENTAB', HTML, EndPos)
 while curPos < curPos1 do begin
  
   EndPos := PosFrom('">', HTML, curPos);
 URL := BASE_URL + '/people.php?id=' + TextBetween(HTML,  '=', '">', false, curPos);
      TransName := TextBetween(HTML,  '">', '</a>', false, curPos);
 curPos := PosFrom('people.php?id', HTML, EndPos);
AddMoviePerson(TransName, TransName, '', URL, ctDirectors);
  end;
end;

 //Producer
curPos := Pos('Producer', HTML);
 if curPos > 0 then begin 
  EndPos := curPos; 
  curPos := PosFrom('people.php?id=', HTML, EndPos);
  curPos1 := PosFrom('ENTAB', HTML, EndPos)
 while curPos < curPos1 do begin
  
   EndPos := PosFrom('">', HTML, curPos);
 URL := BASE_URL + '/people.php?id=' + TextBetween(HTML,  '=', '">', false, curPos);
      TransName := TextBetween(HTML,  '">', '</a>', false, curPos);
 curPos := PosFrom('people.php?id', HTML, EndPos);
AddMoviePerson(TransName, TransName, '', URL, ctProducers);
  end;
end;

 //Composers
curPos := Pos('Music', HTML);
 if curPos > 0 then begin 
  EndPos := curPos; 
  curPos := PosFrom('people.php?id=', HTML, EndPos);
  curPos1 := PosFrom('ENTAB', HTML, EndPos)
 while curPos < curPos1 do begin
  
   EndPos := PosFrom('">', HTML, curPos);
 URL := BASE_URL + '/people.php?id=' + TextBetween(HTML,  '=', '">', false, curPos);
      TransName := TextBetween(HTML,  '">', '</a>', false, curPos);
 curPos := PosFrom('people.php?id', HTML, EndPos);
AddMoviePerson(TransName, TransName, '', URL, ctComposers);
  end;
end;


 //Seiyu
curPos := Pos('<i>as</i>', HTML);
 if curPos > 0 then begin 
curPos := Pos('Japanese cast', HTML);
EndPos  := curPos;
curPos1 := PosFrom('<i>as</i>', HTML, EndPos)

 while curPos < curPos1 do begin
  curPos2 := curPos;
  curPos := PosFrom('people.php?id=', HTML, EndPos);
 URL := BASE_URL + '/people.php?id=' + TextBetween(HTML,  '=', '">', false, curPos);
  EndPos := curPos; 
  end;

curPos := PrevPos('people.php?id=', HTML, curPos2);
  EndPos := curPos; 
  curPos1 := Pos('Japanese companies', HTML);
  curPos3 :=  PrevPos('people.php?id=', HTML, curPos1);
  curPos := PosFrom('people.php?id=', HTML, EndPos);
 while curPos < curPos3 do begin
   EndPos := PosFrom('">', HTML, curPos);
URL := BASE_URL + '/people.php?id=' + TextBetween(HTML,  '=', '">', false, curPos);
TransName := TextBetween(HTML,  '">', '</a>', false, curPos);
Role := TextBetween(HTML,  '<b>', '</b>', false, curPos);
 curPos := PosFrom('people.php?id', HTML, EndPos)
 AddMoviePerson(Name, TransName, Role, URL, ctActors);
end;
EndPos := PosFrom('">', HTML, curPos);
URL := BASE_URL + '/people.php?id=' + TextBetween(HTML,  '=', '">', false, curPos);
TransName := TextBetween(HTML,  '">', '</a>', false, curPos);
Role := TextBetween(HTML,  '<b>', '</b>', false, curPos);
 curPos := PosFrom('people.php?id', HTML, EndPos)
 AddMoviePerson(Name, TransName, Role, URL, ctActors);
end;



 //Companies
curPos := Pos('<b>Animation Production</b>', HTML);
 if curPos > 0 then begin 
  EndPos := curPos; 
  curPos := PosFrom('company.php?id=', HTML, EndPos);
  curPos1 := PosFrom('ENTAB', HTML, EndPos)
 while curPos < curPos1 do begin
  
   EndPos := PosFrom('">', HTML, curPos);
      TransName := TextBetween(HTML,  '">', '</a>', false, curPos);
 curPos := PosFrom('company.php?id', HTML, EndPos);
AddFieldValue(mfStudio, TransName);
  end;
end;

curPos := Pos('<b>Production</b>', HTML);
 if curPos > 0 then begin 
  EndPos := curPos; 
  curPos := PosFrom('company.php?id=', HTML, EndPos);
  curPos1 := PosFrom('ENTAB', HTML, EndPos)
 while curPos < curPos1 do begin
  
   EndPos := PosFrom('">', HTML, curPos);
      TransName := TextBetween(HTML,  '">', '</a>', false, curPos);
 curPos := PosFrom('company.php?id', HTML, EndPos);
AddFieldValue(mfStudio, TransName);
  end;
end;

 // EpLink
 if DOWNLOAD_EPISODES then begin

  EndPos := Pos('Episode titles', HTML);
  if EndPos > 0 then begin
   curPos :=  PosFrom('/encyclopedia/anime.php?id=', HTML, EndPos);
   EndPos := PosFrom('"', HTML, curPos);
   ExtraLinks[smEp] := BASE_URL + Copy(HTML, curPos, EndPos - curPos);
  end else 
   EndPos := 1;  
 end; 
end;


procedure ParseSearchResults(HTML : String);
var
 curPos, EndPos, P : Integer;
 Title, URL : String;
begin  
 curPos := Pos('<head>', HTML);
 if curPos < 1 then
  Exit;
  
 curPos := PosFrom('/encyclopedia/anime.php?id=', HTML, curPos);  
 EndPos := curPos; 
 P := PosFrom('Privacy policy</a>', HTML, EndPos);
 while (curPos > 0) AND ((P < 1) OR (curPos < P)) do begin
  EndPos := PosFrom('">', HTML, curPos);
  URL := BASE_URL + Copy(HTML, curPos, EndPos - curPos);
  
  curPos := PosFrom('>', HTML, EndPos) + 1;
  
  EndPos := PosFrom('</a>', HTML, curPos);
  Title := Copy(HTML, curPos, EndPos - curPos);

  AddSearchResult(HTMLToText (RemoveTags(Title, true)), '', '', URL, '');
  curPos := PosFrom('/encyclopedia/anime.php?id=', HTML, EndPos); 
  P := PosFrom('Privacy policy</a>', HTML, EndPos);
 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;
var
 P, P2 : Integer;
begin 
 if Pos('<title>Search', HTML) > 0 then begin  
  ParseSearchResults(HTML);
  Result := prList; 
  Exit;
 end else  
 if Pos('did not match any documents', HTML) > 0 then begin
  Result := prError;
  Exit;
 end else 
 if Pos('<strong>Genres:</strong>', HTML) > 0 then
  ParseMovie(URL, HTML)
 else

 if Pos('Go back to', HTML) > 0 then
  ParseEpisodes(HTML)
 else

 if Pos('<meta http-equiv=''Refresh''', HTML) > 0 then begin 
  P := Pos('url=', HTML) + 4; 
  P2 := PosFrom('''', HTML, P);
  Mode := smNormal;
  ExtraLinks[Mode] := BASE_URL + Copy(HTML, P, P2 - P);
  Result := prDownload;
  Exit;
//  AddSearchResult('', '', '', BASE_URL + Copy(HTML, P, P2 - P), '');
  
//  Result := prList;
  Exit; 
 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.
