const
	script_name='ozon';
	language='Russian';
	version=12;
	author='Alex';
	MinProgramBuild=5500;
	PCount = 12;
var
	DownloadPersonBiography, DownloadPersonAdditionalInfo: boolean;
	MaxPhotosCount: integer;

	persons_count: integer;
	persons: array of string;
	imdb_codes: array of 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..PCount] of string;
	person_height: integer;

function GetSearchURLbyName(PersonName: string): string;
var
	url: string;
begin
	url:=format('http://www.ozon.ru/?context=search&text=%s&type=person', [PersonName]);
	url:=ReplaceStr(url, ' ', '+', -1);
	result:=url;
end;

//Download search results from URL
function DownloadSearchURL(url: string): integer;
begin
	all:=DownloadURL(url);
	if all='-1' then
		result:=-1
	else
		result:=PersonSearch;
end;

function PersonSearch: integer;
var
	i, j: integer;
	url, person, code, s, s2, s3, small_photo: string;
begin
	persons_count:=0;
	
	i:=pos('Ничего не найдено', all);

	if (all='') or (i>0) then
		// Person not found!
	else 
	begin
		i := pos('<div class="SearchResults">', all);
		if i>0 then begin
			j := MyPos('<script', all, i+1);
			s := copy(all, i, j-i);
			i := Pos('<div class="Persona">', s);
			while i>0 do begin
				j := MyPos('</div>', s, i+1);
				s2 := copy(s, i, j-i);
				code := ParseString(s2, '<a href="/context/detail/id/(\d+)/"', 1);
				small_photo := ParseString(s2, '/multimedia/person_photo/(.*?).jpg" title', 1);
				if small_photo<>'' then
					small_photo := 'http://mmedia.ozon.ru/multimedia/person_photo/' + small_photo + '.jpg';
				person := RemoveTags(s2);
				person := DecodeHTML(person);
				person := ClearExtraBlankCharacters(person);
				if person <> '' then begin
					SetSearchResult2(person, code, '', '', '', small_photo);
					Inc(persons_count);
				end;
				delete(s, 1, j);
				i := Pos('<div class="Persona">', s);
			end;
		end;
	end;
	result:=persons_count;
end;

function GetPersonURL(code: string; images_only: boolean): string;
begin
	result:=format('http://www.ozon.ru/context/detail/id/%s/', [code])
end;

function GetStr(str: String; s1: String; s2: String): String;
var
  I: Integer;
  J: Integer;
begin
  // Вырезает кусок строки между s1 и s2
	Result := '';
	I := Pos(LowerCase(s1), LowerCase(str));
	if I > 0 then
	begin
		J := MyPos(LowerCase(s2), LowerCase(str), I + Length(s1));
		if J > 0 then
  		Result := Copy(str, I + Length(s1), J - I - Length(s1));
	end;
end;

//returned images links
procedure GetImages;
var
	temp, s, img_url: String;
	img_cnt: Integer;
begin
	img_cnt := 0;
	temp := GetStr(all, 'var model = {"Picture":', '}');
	while (img_cnt < MaxPhotosCount) and (Pos('person_photo/', temp)>0) do begin
		s := GetStr(temp, 'person_photo/', '"');
		if s <> '' then begin
			img_url := 'http://static.ozone.ru/multimedia/person_photo/' + s;
			SetImageName('', img_url, '', 6);
			img_cnt := img_cnt + 1;
		end;
		delete(temp, 1, Pos('person_photo/', temp));
	end;
end;

function SavePhoto(url, FileName: string): boolean;
var
	fs: TFileStream;
	s: string;
begin
	s:=DownloadURL(url);
	if (length(s)>0) and (s<>'-1') then begin
		try
			fs:=TFileStream.Create(FileName, fmCreate);
			fs.Write(s, Length(s));
			fs.Free;
			result:=true;
		except
			result:=false;
		end;
	end
	else
		result:=false;
end;

function MovePrefixLeft(name: string): string;
var
	i, j: integer;
begin
	// replace "The", "A", "An"... to the left
	for j:=1 to PCount do
	begin
		i:=pos(', '+Prefixes[j], name);
		if i>0 then
			if (i = length(name)-length(Prefixes[j])-1) or
			(length(name) >= i+2+length(Prefixes[j])) and (name[i+2+length(Prefixes[j])]=':') then
			begin
				if Prefixes[j][length(Prefixes[j])] = '''' then
					name := Prefixes[j] + copy(name, 1, i-1) + copy(name, i+length(Prefixes[j])+2, length(name)-i-length(Prefixes[j])-2+1)
				else
					name := Prefixes[j]+' ' + copy(name, 1, i-1) + copy(name, i+length(Prefixes[j])+2, length(name)-i-length(Prefixes[j])-2+1);
				break;
			end;
	end;
	Result := name;
end;

function ClearBrackets(name: string): string;
var
	i: integer;
begin
	// clear word in brackets at the end of name
	i := pos(' (', name);
	if i>0 then
		name := copy(name, 1, i-1);
	Result := name;
end;

function ClearExtraQuotes(name: string): string;
begin
// Clears extra quotes «"»
	if length(name)>0 then
		if (name[1]='"') and (name[length(name)]='"') then
			name := copy(name,2,length(name)-2);
	{if (name[1]='''') and (name[length(name)]='''') then
		name := copy(name,2,length(name)-2);}
	Result := name;
end;


function GetInfo(url: string; images_only: boolean): string;
var
	day, month, year, original_title, s, s2, s3, temp: string;
	i, j, k: integer;
begin
	result:='';
	BasicURL:=url;

	imdb_code := '';
	person_code := ParseString(url, 'http://www.ozon.ru/context/detail/id/(\d+)/', 1);;
	person_site_url:=GetPersonSiteURL(person_code);

	all := DownloadURL(url);
	{//если требуется авторизация
	if GetResponseCode=403 then begin
		SiteLogin;
		all:=DownloadURL(url);
	end;}
	if all='-1' then
		result := '-1'
	else
		result := all;

	person := GetStr(all, '<h1', '/h1>');
	person := GetStr(person, '>', '<');
	i:=pos(' (', person);
	if i>0 then
		person := copy(person, 1, i-1);
	i:=Pos('. ', person);
	if i>0 then
		person := copy(person, 1, i-1);
	person := DecodeHTML(person);
	person := ClearExtraBlankCharacters(person);
	
	//кусок с настоящим именем, датой рождения и т.п.
	temp := GetStr(all, '<div class="product-detail">', '</div>');
	
	s := GetStr(temp, '<p>', '</p>');
	//проверяем, не является ли строка информацией о рождении
	if (Pos(',', s) = 0) and (ParseString(s, '(\d+)', 1) = '') then begin
		//original name
		original_name := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(original_name)));
		delete(temp, 1, Pos('</p>', temp));
	end;
	
	//birth date and place
	birthplace := '';
	birth_date := '';
	death_date := '';
	s := GetStr(temp, '<p>', '</p>');
	i := Pos(',', s);
	if i>0 then begin
		birthplace := copy(s, 1, i-1);
		birthplace := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(birthplace)));
		delete(s, 1, i);
		s := ClearExtraBlankCharacters(s);
		s2 := '';
		i := Pos('-', s);
		if i>0 then begin
			s2 := copy(s, i+1, length(s)-i);
			delete(s, i, length(s)-i+1);
		end;
		day := ParseString(s, '^(\d+).', 1);
		month := ParseString(s, '^\d+.(\d+).', 1);
		year := ParseString(s, '^\d+.\d+.(\d+)', 1);
		if (day<>'') and (month<>'') and (year<>'') then
			birth_date := month + '/' + day + '/' + year;
		if s2<>'' then begin
			day := ParseString(s2, '^(\d+).', 1);
			month := ParseString(s2, '^\d+.(\d+).', 1);
			year := ParseString(s2, '^\d+.\d+.(\d+)', 1);
			if (day<>'') and (month<>'') and (year<>'') then
				death_date := month + '/' + day + '/' + year;
		end;
	end;

	//biography
	if DownloadPersonBiography then
	begin
		temp := GetStr(all, 'Биографическая справка:', '<span class="pseudo-href">');
		biography := GetStr(temp, 'class="techDescription">', '<span');
		delete(temp, 1, Pos('<span', temp));
		s := GetStr(temp, 'class="techDescription">', '</div>');
		biography := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(biography)));
		s := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
		if s <> '' then
			biography := biography + ' ' + s;
	end;
	
end;

function ClearExtraBlankCharacters(text: string): string;
begin
	// Clear all extra blank charackters
	while (length(text) > 0) and (ord(text[1]) in [1..32]) do
		delete(text, 1, 1);
	while (length(text) > 0) and (ord(text[length(text)]) in [1..32]) do
		delete(text, length(text), 1);
	Result := text;
end;
	
//get movie site url
function GetMovieSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:='http://www.ozon.ru/context/detail/id/'+code+'/';
end;

//get person site url
function GetPersonSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:=format('http://www.ozon.ru/context/detail/id/%s/', [code]);
end;


//иногда требуется логин на сайт
procedure SiteLogin;
var
	url, all: string;
begin
	url:='http://www.kinopoisk.ru/level/30/?shop_user[login]=tester&shop_user[pass]=rbyj&shop_user[mem]=true';	
	url:=ReplaceStr(url, ' ', '+', -1);
	all:=DownloadURL(url);
end;


begin
monthes[1]:='января';
monthes[2]:='февраля';
monthes[3]:='марта';
monthes[4]:='апреля';
monthes[5]:='мая';
monthes[6]:='июня';
monthes[7]:='июля';
monthes[8]:='августа';
monthes[9]:='сентября';
monthes[10]:='октября';
monthes[11]:='ноября';
monthes[12]:='декабря';

prefixes[1]:='The';
prefixes[2]:='A';
prefixes[3]:='An';
prefixes[4]:='La';
prefixes[5]:='Les';
prefixes[6]:='Des';
prefixes[7]:='L''';
prefixes[8]:='Un';
prefixes[9]:='El';
prefixes[10]:='Il';
prefixes[11]:='Le';
prefixes[12]:='Uno';

end.