// DEBUG          = True;  True turns on message logging.  You have to be in debug mode to view the log.
// MAXIMUM_SIZE_X = 600;    Maximum width of the image.  Smaller images won't be upscaled.
// MAXIMUM_SIZE_Y = 0;      Maximum height of the image. Smaller images won't be upscaled.
//                          ...If you want images to fit with a maximum width AND height,
//                          ...set MAXIMUM_SIZE_X to the same value as MAXIMUM_SIZE_Y
// SILENT_MODE    = False;  True allows the FIRST IMAGE FOUND to be loaded.

const

 stMovies       = 0;
 stPeople       = 1;
 stPoster       = 2;

 smSearch       = 0;
 smNormal       = 1;
 smPage         = 2;
 smGallery      = 3;

 prError        = 0;
 prFinished     = 1;
 prList         = 2;
 prListImage    = 3;
 prDownload     = 4;

 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;

 pfPID          = 0;
 pfName         = 1;
 pfTransName    = 2;
 pfAltNames     = 3;
 pfBirthday     = 4;
 pfDeath        = 5;
 pfBirthplace   = 6;
 pfURL          = 7;
 pfRating       = 8;
 pfDateAdded    = 9;
 pfModDate      = 10;
 pfBio          = 11;
 pfComment      = 12;
 pfBookmark     = 13;
 pfVisible      = 14;
 pfGenres       = 15;
 pfAge          = 16;
 pfFilmography  = 17;
 pfCareer       = 18;
 pfAwards       = 19;
 pfPhoto        = 20;
 pfImageList    = 21;

 ctActors       = 0;
 ctDirectors    = 1;
 ctWriters      = 2;
 ctComposers    = 3;
 ctProducers    = 4;

 mlInfo         = 0;
 mlGood         = 1;
 mlWarn         = 2;
 mlFail         = 3;

 SCRIPT_VERSION = '0.1.0.2';
 SCRIPT_NAME    = 'ImdbImage';
 SCRIPT_DESC    = '[ENG] IMDB - Images Only - Large Database - Large Images';
 SCRIPT_LANG    = $09;
 SCRIPT_TYPE    = stPeople;

 BASE_URL       = 'http://imdb.com';
 RATING_NAME    = 'IMDB.com';
 SEARCH_STR     = 'http://www.imdb.com/find?s=nm&q=%s+photo';
 CODE_PAGE      = 0;

 DEBUG          = False;
 MAXIMUM_SIZE_X = 600;
 MAXIMUM_SIZE_Y = 600;
 SILENT_MODE    = False;

var
 Mode      : Byte;
 Name      : string;
 LinkCount : Integer;
 LinkIndex : Integer;
 Links     : TWideArray;
 PersonUrl : string;
 Pages     : Integer;
 PageUrl   : string;

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 TFFReplace(Hay:String; Needle:String; Replace:String):String;

begin;
   Result :=  StringReplace(Hay,Needle,Replace,True,False,False);
end;

procedure Msg(MessageText:String; Level:Integer );
var
   Prefix : String;
begin;
 if ( Level = mlInfo ) then
    Prefix := '  '
 else
 if ( Level = mlGood ) then
    Prefix := '. '
 else
 if ( Level = mlWarn ) then
    Prefix := '- '
 else
    Prefix := '* ';

 if DEBUG then
    LogMessage( Prefix + MessageText );
end;

function GetDownloadURL : AnsiString;

begin

 Msg('-------- GetDownloadUrl Starting',mlGood);
 if ( PersonUrl = '' ) then begin;
    LinkCount := ExplodeString(GetFieldValue(pfURL),Links,' ');

    for LinkIndex := 0 to LinkCount-1 do begin;
        if ((Pos('imdb.com',Links[LinkIndex]) > 0) and (PersonUrl = '')) then begin;
           PersonUrl := Links[LinkIndex] + '/mediaindex';
           PersonUrl := TFFReplace( PersonUrl,'//mediaindex','/mediaindex');
           Msg('PersonUrl has been set to ' + PersonUrl,mlGood);
           continue;
        end;
    end;
    Mode := smNormal;
    Msg('Mode now set to smNormal',mlGood);
 end;

 if (Mode = smSearch) then
    Result := SEARCH_STR
 else
 if (Mode = smPage) then
    Result := PageUrl
 else
    Result := PersonUrl;

 Msg('-------- GetDownloadUrl completed Result: ' + Result,mlGood);

end;

function IsImage( FilePath:string )  : Boolean;
var
   Extension, Ext_List : string;
   Ext_Pos : Integer;
begin;

   Ext_List  := ' jpg jpeg gif png bmp ';

   Ext_Pos   := LastPos('.', FilePath);
   Extension := LowerCase(Copy(FilePath, Ext_pos+1, Length(FilePath) - (Ext_Pos-1)));

   if ( Pos( ' ' + Extension + ' ', Ext_List ) > 0 ) then begin;
      Result := True
      Msg('IsImage Result: Image file found',mlGood);
   end
   else begin;
      Result := False;
      Msg('IsImage Result: ('+ Extension + ') Not an image file extension',mlGood);
   end;
end;

function SelectImageSize : String;
var
   X, Y, XY : String;
begin;

   X  := '_SX' + IntToStr(MAXIMUM_SIZE_X);
   Y  := '_SY' + IntToStr(MAXIMUM_SIZE_Y);

   Result := X + Y

   Msg('-------- SelectImageSize completed Result: ' + Result,mlGood);

end;

function ParsePages(HTML: String; URL : AnsiString ) : Integer;
var
   curPos,PCount, ValidCount : Integer;
   Temp          : string;
   PList         : TWideArray;
begin;

   ValidCount := 0;
   curPos := Pos( 'page_list">', HTML );
   Pages  := 1;
   if (curPos > 0 ) then begin;
      Msg('Parsing Page Count', mlInfo);
      Temp  := TextBetween(HTML, '>', '</span>', True, curPos);
      Msg(Temp, mlInfo);
      Pages := ExplodeString(Temp,PList,' ') - 1;

      for PCount := 0 to Pages do begin;
          if ( StrToInt(PList[PCount]) > 0) then
             Inc(ValidCount);
          end;

      Pages := ValidCount;
      end;

   Msg('Number of image pages: ' + IntToStr(Pages), mlInfo);

   if ( Pages > 1 ) then
      for PCount := 1 to Result do begin;
         PageUrl := PersonUrl + '?page=' + IntToStr(PCount) + '&ipage=load';
         AddSearchResult('Image Page #'+IntToStr(PCount),'','', PageUrl, '');
     end;

   Result := Pages;
end;

function ParseGallery(HTML : String; URL : AnsiString ) : Integer;
var
 curPos, EndPos, LCount, capStart, capEnd, imageStart, imageEnd : Integer;
 PLink, TLink, gUrl, ImageSize, Caption : string;
 done : Boolean;

begin

 EndPos    := 1;
 LCount    := 0;
 done      := False;
 name      := GetFieldValue(pfName);
 caption   := '';

 ImageSize := SelectImageSize();

 gUrl      := 'http://ia.media-imdb.com/images'; 
 imageStart:= Pos('class="media_index_thumb_list"', HTML);
 imageEnd := PosFrom('</div>', HTML, imageStart);
	curPos    := PosFrom('title="',HTML,imageStart);

 Msg('------ ParseGallery starting',mlInfo);

 if ( not SILENT_MODE ) then
    Pages := ParsePages(HTML,URL);

	if (curPos < 1) then
		Msg('No image links found',mlFail )
	else

 while ( not done) do begin

   capStart := curPos+7;
   capEnd   := PosFrom('"', HTML, capStart);
   caption  := Copy(HTML, capStart, CapEnd-CapStart) + '>';

   curPos := PosFrom('src="', HTML, curPos)+5;
   endPos := PosFrom('"', HTML, curPos);
   PLink  := trim(Copy(HTML, curPos, EndPos - curPos));

   if (IsImage(PLink)) then begin;
      Inc(LCount);
      if (Pos(',',PLink) > 0 ) then
         PLink := Copy(PLink, 1, Pos(',',PLink) -1 ) + '.jpg';

      TLink := PLink;
      PLink := Copy(Tlink,1,LastPos('.',TLink)-1);                       // clear Extension
      PLink := Copy(Plink,1,LastPos('.',PLink)) + ImageSize + '.jpg';    // Set Image Parameters
//      PLink := TFFReplace(PLink,'.jpg', ImageSize) + '.jpg';
      Msg( 'Plink -----------' + TLink,mlInfo);

      if (SILENT_MODE) then begin
         AddSearchResult(name,'','', PLink, TLink);
         done := True;
         end
      else
         AddSearchResult('','','', PLink, TLink);
      Msg( Caption + '-----------' + PLink,mlInfo);
   end

   else
      msg('Link is not an image: ' + PLink, mlInfo);

	curPos    := PosFrom('title="',HTML,EndPos);
	if (curPos=0) or (curPos>imageEnd) then
	begin
		Msg('All image files have been processed',mlInfo);
		done := true;
	end;
 end;

 Result := LCount;
 Mode   := smGallery;

 Msg('   ParseGallery completed ' + IntToStr(Result) + ') Images found. ',mlInfo);

end;

function ParsePage(HTML : String; URL : AnsiString): Cardinal;
var
   RVal : Integer;
begin

   if ((Pos('/mediaindex',URL) > 0)) then begin;
      if ((Pos('&ipage=load',URL) > 0) and (Mode <> smPage)) then begin;
         PageUrl := URL;
         Result  := prDownLoad;
         Mode    := smPage;
      end
      else begin;
         RVal := ParseGallery(HTML,URL);

         if (RVal > 0 ) then
            Result := prList
         else
            Result := prFinished;
      end;
   end

   else
   if (Mode = smGallery) then begin;
      Result := prFinished;
   end

   else begin;
      AddSearchResult('',GetFieldValue(pfName),'',PersonUrl,'');
      Result := prDownload;
   end;

 Msg('  ParsePage completed with Result (' + IntToStr(Result) + ')', mlInfo );

end;

begin
 Mode      := smSearch;
 PersonUrl := '';
 Pages     := 0;

end.
