const
 script_name='animator';
 language='Russian';
 version=5;
 author='BlackStream';
 MinProgramBuild=5500;
 
 PERSON_DIRECTOR = 1;
 PERSON_WRITER   = 2;
 PERSON_ACTOR    = 3;
 PERSON_COMPOSER = 4;
 IMAGE_PHOTO = 6;

var
	DownloadPersonBiography, DownloadPersonAdditionalInfo: boolean;
	MaxPhotosCount: integer;
	persons_count: integer;
	persons: array of string;
	imdb_codes: array of string;
	url_fix: string;
	imdb_code, person_code: string;
	name, code, year, description: string;
	person, BasicURL, biography, trivia, character, birth_date, death_date, birthplace, birth_name, salary, height, original_name, person_site_url: string;
	photo_url: string;
	monthes: array [1..12] of string;
	prefixes: array [1..13] of string;
	person_height: integer;
	is_photos_present: boolean;
	BaseImageURL: string;
	
//==================================================================================================
//  Вспомогательные функции
//==================================================================================================
function GetStr(str, s1, s2: string): string;
	var
		i, j: integer;
begin
	result := '';
	i := Pos(s1, str);
	if i>0 then
	begin
		j := MyPos(s2, str, i+1);
		if j>0 then
		begin
			result := copy(str, i+length(s1), j-i-length(s1));
		end;
	end;
end;

function LowerTitle(str :string): string;
	var
	s: string;
begin
	s := str;
	result := lowercase(s);
	Delete(result, 1, 1);
	Delete(s, 2, Length(s));
	result := s+result;
end;

//==================================================================================================
//  Экспортируемые из скрипта функции
//==================================================================================================

//==================================================================================================
//  01. Формирование URL для поиска актёра на сайте по названию
//==================================================================================================
function GetSearchURLbyName(Name: string): string;
var 
	url: string;
	i, j: integer;
begin
	Name := ReplaceStr(Name, ' ', '+', -1);
	if Name<>'' then
		Result:=Format('http://animator.ru/db/?p=search&SearchMask=2&text=%s', [Name])
	else
		result := '-1';
end;

function DownloadSearchURL(url: string): Integer;
begin          
	all := DownloadURL(url);
	if (all<>'-1') and (GetResponseCode=200)
	then   Result:=SelectActor
	else   Result:=-1
end;

function SelectActor: Integer;
var
	i, j: integer;
	s, s2, temp: string;
	Actor, Code : string; 
begin
	Result:=0;
	Result:=0;
	s2 :=  '<br>'+#10+'Ничего не найдено';
	if Pos(s2, all)>0 then
	exit;
	s2 := '<br><br>'+#10+'Найдено';
	temp := GetStr(all, s2, '<br><br>'+#10+'</DIV>');
	if temp<>'' then 
	begin
		i := Pos('<br><br>', temp);
		Delete(temp, 1, i+7);
		temp:=ReplaceStr(temp, '<br><br>', #13#10, -1);
		repeat
			j := Pos(#13#10, temp);
			if j>0 then
			begin
				s := copy(temp, 1, j-1);
				Delete(temp, 1, j+2);
				s := ReplaceStr(s, '| Биография', '', -1);
				Actor := GetStr(s,'Персоналии | ', #10+'</a>');
				Code := ParseString(s, 'pid=(\d+)', 1);
				if (Actor<>'') and (Code<>'') then
				begin
					SetSearchResult(Actor, Code);
					inc(result);
				end;
			end;
		until (j=0);
	end;
end;	

//==================================================================================================
//  04. Формирование URL с информацией об актёре по коду актёра в формате сайта 
//==================================================================================================
function GetPersonURL(Code: string; Images_Only: Boolean): string;
begin
	if Code<>''	then
		Result:='http://www.animator.ru/db/?p=show_person&pid='+Code+'&sp=0' //2
	else   Result:=''
end; 

 function GetPersonSiteURL(Code: string): string;
begin
	if Code<>''	then 
		Result:='http://www.animator.ru/db/?p=show_person&pid='+Code
	else   Result:=''
end;

//==================================================================================================
//  05. Получение данных по фильму по URL
//==================================================================================================
function GetInfo(URL: string; Images_Only: Boolean): string;
	var
		s, s2, temp: string;
		Movie, Role, Code, Year: string;
		i, j, jj: Integer;
		flNs, flWorks: boolean;
	function FormatDate (Str: string): string;
		var
		 day, year, month: string;
		 j,i: integer;
		 
	begin
		i := Pos('.', Str);
		j := MyPos('.', Str, i+1);
		day := copy(Str, 1, i-1);
		month := copy(Str, i+1, j-i-1);
		year := copy(Str, j+1, length(Str));
		result := format('%s/%s/%s', [month,day, year]);
	end;
	procedure GetFilms(temp: string; mode: byte);
		var
			s, s2: string;
			i, j: integer;
			code, year, movie: string;
	begin
		case mode of
			1: s := GetStr(temp, '<font class=ProffInHeader>режиссер</font>', '<br></td></tr>');
			2: s := GetStr(temp, '<font class=ProffInHeader>сценарист</font>', '<br></td></tr>');
			3: s := GetStr(temp, '<font class=ProffInHeader>озвучивал(а) роли</font>', '<br></td></tr>');
			4: s := GetStr(temp, '<font class=ProffInHeader>композитор</font>', '<br></td></tr>');
		end;	
		s := ReplaceStr(s, #10, '', -1);
		s := ReplaceStr(s, '<br>', #13#10, -1);
		s := s+#13#10;
		j := 0;
		repeat
			j := Pos(#13#10, s);
			role := '';
			s2 := copy(s, 1, j-1);
			Delete(s, 1, j);
			if Pos('> - ', s2) then
			 role := copy(s2, Pos('> - ', s2)+4, length(s2));
			if Pos('<font class=ProffInHeader>', s2)>0 then j := 0;
			code := GetStr(s2, 'showFilm(', ')');
			movie := GetStr(s2, '«', '»');
			movie := LowerTitle(movie);
			year := ParseString(s2, '\((\d+)\)</span>', 1);
			if (movie<>'') and (code<>'') then
				SetMovieName(Movie, role, mode, Code, year);
		until (j=0);
	end;
begin
	Result:=DownloadURL(URL);
	if (Result='-1') or (GetResponseCode<>200) then
	exit;
	all := Result;
	original_name := '';
	Person_Code := ParseString(url, 'pid=(\d+)', 1);;
	person_site_url:=GetPersonSiteURL(Person_Code);
	s := GetStr(all, '<div class="PersonName">', '</div>');
	if s='' then
		s := GetStr(all, '<tr><td align="left" class="PersonName">', '</td></tr>');
	s := ReplaceStr(s, '<br>', ' ', -1);
	Person := s;
	s := GetStr(all, '<img src="/db/../person_photo', '" alt');
	if s<>'' then 
		BaseImageURL:='http://animator.ru/person_photo'+s;
	s := GetStr(all, '<div class="PersonComments" style="font-weight:normal;padding-top:10px">', '</div>');
	if s='' then
		s := GetStr(all, '<tr><td align="left" class="PersonComments" style="font-weight:normal;padding-top:10px">', '</td></tr>');
	s := DecodeHTML(s);
	i := Pos(' – ', s); 
	if i>0 then 
	begin
		s2 := copy(s, 1, i-1);
		Delete(s, 1, i+1);
		birth_date := FormatDate(s2);
		death_date := FormatDate(s);
	end	
	else
	begin
		s := FormatDate(s);
		birth_date := s;
	end;	
	if DownloadPersonBiography then
	begin
		temp := DownloadURL('http://www.animator.ru/db/?p=show_person&pid='+Person_Code+'&sp=1');
		s := GetStr(temp, '<tr><td align="left" class="PersonComments" style="padding-top:10">', '</td></tr>');
		if s<>'' then
		begin
			s := ReplaceStr(s, '<br><br>', '<br>', -1);
			s := DecodeHTML(s);
			s := ClearExtraXCharacters(s);
			i := Pos('<small>', s);
			if i>0 then
			s := copy(s, 1, i-1);
			biography := RemoveTags(s);
		end;
	end;
	
	s := GetStr(all, '<font class=ProffInHeader>сценарист</font>', '<br></td></tr>');
	s := ReplaceStr(s, #10, '', -1);
	s := ReplaceStr(s, '<br>', #13#10, -1);
	s := s+#13#10;
	if DownloadPersonAdditionalInfo then
	begin
		temp := DownloadURL('http://www.animator.ru/db/?p=show_person&pid='+Person_Code+'&sp=2');
		for i:=1  to 4 do
			GetFilms(temp, i);
	end
	else
	for i:=1  to 4 do
		GetFilms(all, i);
end;

//==================================================================================================
//  06. Загрузка картинок
//==================================================================================================
procedure GetImages;
	var
		temp, s: string;
		c: Integer;
		url: string;
		i, j: integer;
		flPhoto: boolean;
begin
	c := 0;
	if BaseImageURL<>'' then
		SetImageName('', BaseImageURL, '', IMAGE_PHOTO);
	if Pos('<AREA ID="snb3"', all)>0 then
	begin
		temp := DownloadURL('http://www.animator.ru/db/?p=show_person&pid='+Person_Code+'&sp=3'); 
		if temp='-1'then 
		exit;
		i :=1;
		while (c<>MaxPhotosCount) and (i>0)  do
		begin
			i := Pos('src="/db/../photo', temp);
			if i>0 then
			begin
				s := GetStr(temp, 'src="/db/../photo', '" alt');
				url := 'http://www.animator.ru/photo'+s; 
				SetImageName('', url, '', 6);
			end;
			Delete(temp, 1, i+20);
		end;	
	end;
end;

//==================================================================================================
//  07. Сохранение картинки по ее URL в выбранный файл
//==================================================================================================
function SavePhoto(URL, FileName: string): Boolean;
	var
		Stream: TFileStream;
		Temp  : string;
begin          
	Temp:=DownloadURL(URL);
	if (Length(Temp)>0) and (Temp<>'-1') and (GetResponseCode=200)
	then   try
				Stream:=TFileStream.Create(FileName, fmCreate);
    			Stream.Write(Temp, Length(Temp));
    			Stream.Free;
					Result:=True;
	        except
				Result:=False
	        end
	else   Result:=False
end;

//==================================================================================================
//  Получение ссылки на страницу фильма по коду в формате сайта
//==================================================================================================
function GetMovieSiteURL(Code: string): string;
begin
	if Code<>''	then 
		result:='http://animator.ru/db/?p=show_film&fid='+code
	else   Result:=''
end;

begin
end.