const
	script_name='adorocinema';
	language='Brazilian Portuguese';
	version=3;
	author='Vlad';
	MinProgramBuild=5500;
	PCount = 12;
	//MAX_PHOTOS_COUNT = 3;
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, birthplace, birth_name, salary, height, original_name, death_date, person_site_url: string;
	photo_url: string;
	monthes: array [1..12] of string;
	prefixes: array [1..PCount] of string;
	movie_html: string;
	person_height: integer;
	FotoURL: string;
	
const
	main_photo_resizer='/rx_160_214';
	photo_resizer='/c_100_100';

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

function GetSearchURLbyName(PersonName: string): string;
var
	url: string;
begin
	PersonName := EncodeURL(PersonName);
	url:=format('http://www.adorocinema.com/busca/?q=%s', [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
	url, s, s2, temp, small_photo, code, name, description: string;
	i, j, k: integer;
begin
	persons_count:=0;
	s:='';
	s := GetStr(all, 'Personalidades</h2>', '</table>');
	if s = '' then
		s := GetStr(all, 'Personalidades'#10'</h2>', '</table>');
	if (s = '') then
	//person not found
	else begin
		i:=pos('<tr>', s);
		while i>0 do begin
			temp:=GetStr(s, '<tr>', '</tr>');
			name := GetStr(temp, '<div>', '</a>');
			name := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(name)));
			code := GetStr(temp, ' href=''/personalidades/personalidade-', '/');
			small_photo := GetStr(temp, 'src=''', '''');
			if (Pos('empty', small_photo)>0) then
				small_photo := '';
			s2 := GetStr(temp, '<span class="fs11">', '</span>');
			description := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s2)));
			if name<>'' then begin
				SetSearchResult2(name, code, '', '', description, small_photo);
				persons_count := persons_count + 1;
			end;
			delete(s, 1, i);
			i:=pos('<tr>', s);
		end;
	end;
	result:=persons_count;
end;

function GetPersonURL(code: string; images_only: boolean): string;
begin
		result:='http://www.adorocinema.com/personalidades/personalidade-'+code+'/';
end;

procedure GetPhotos(img_cnt: Integer);
var
	s, temp, s2, img_url: String;
	i, k: Integer;
begin
	s := GetHTMLPageContentFromRequest(FotoURL);
	temp := GetStr(s, 'Fotos promocionais'#10'</h2>', '</ul>');
	i := Pos('<li', temp);
	while (i>0) and (MaxPhotosCount > img_cnt) do begin
		s2 := GetStr(temp, '<li', '</li>');
		img_url := GetStr(s2, 'src":"', '"');
		k := Pos(photo_resizer, img_url);
		if k>0 then
			delete(img_url, k, length(photo_resizer));
		if img_url<>'' then begin
			Inc(img_cnt);
			SetImageName('', img_url, '', 6);
		end;
		delete(temp, 1, i);
		i := Pos('<li', temp);
	end;
end;


//returnes images links
procedure GetImages;
var
	img_cnt: Integer;
begin
	img_cnt := 0;
	if photo_url<>'' then begin
		SetImageName('', photo_url, '', 6);
		img_cnt := 1;
	end;
	if MaxPhotosCount > img_cnt then
		GetPhotos(img_cnt);
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);
	Result := name;
end;

procedure ExtractMovies(text: string; mode: integer);
var
	i: Integer;
	s, s2, temp, year, character, title, code: String;
begin
	temp := GetStr(text, '<tbody>', '</tbody>');
	s := GetStr(temp, '<tr>', '</tr>');
	while s <> '' do begin
		year := GetStr(s, '<td', '</td>');
		year := ParseString(year, '(\d+)', 1);
		delete(s, 1, Pos('</td>', s));
		s2 := GetStr(s, '<td', '</td>');
		code := GetStr(s2, 'href="/filmes/filme-', '/"');
		title := ClearExtraBlankCharacters(DecodeHTML(RemoveTags('<' + s2)));
		character := '';
		if (mode = 3) then begin
			delete(s, 1, Pos('</td>', s));
			character := GetStr(s, '<td', '</td>');
			character := ClearExtraBlankCharacters(DecodeHTML(RemoveTags('<' + character)));
			if character = '-' then
				character :=  '';
		end;
		if (title <> '') then
			SetMovieName(title, character, mode, code, year);
		delete(temp, 1, Pos('</tr>', temp));
		s := GetStr(temp, '<tr>', '</tr>');
	end;
end;

function GetInfo(url: string; images_only: boolean): string;
var
	s, s2, s3, s4, day, month, year: string;
	i, j, k, l, mode: integer;
	filmo_page: boolean;
	temp, filmo_url, bio_url, title, code, character: string;
begin
	result:='';
	BasicURL:=url;
	person_code:=ParseString(url, '(\d+)/$', 1);
	person_site_url:=GetPersonSiteURL(person_code);
	all:=DownloadURL(url);
	if all='-1' then
		result:='-1'
	else
		result:=all;
		
	//download filmography
	filmo_url := '';
	i := Pos('/filmografia/', all);
	if i>0 then begin
		filmo_url := url + 'filmografia/';
		AddRequestForHTMLPageContent(filmo_url, False);
	end;
	
	//download biography
	bio_url := '';
	i := Pos('/biografia/', all);
	if i>0 then begin
		bio_url := url + 'biografia/';
		AddRequestForHTMLPageContent(bio_url, False);
	end;
	
	FotoURL := '';
	i := Pos('/fotos/', all);
	if (MaxPhotosCount>1) and (i>0) then begin
		FotoURL := url + 'fotos/';
		AddRequestForHTMLPageContent(FotoURL, False);
	end;
		
	//name
	person := GetStr(all, '<h1', '</h1>');
	person := RemoveTags('<' + person);
	person := ClearExtraBlankCharacters(DecodeHTML(person));
	
	original_name := '';
	s := GetStr(all, 'Nome verdadeiro</', '</div>');
	if s <> '' then
		original_name := ClearExtraBlankCharacters(DecodeHTML(RemoveTags('<' + s)));
	
	//birth
	birth_date := '';
	temp := GetStr(all, 'Nascimento</', '</li>');
	s := GetStr(temp, '<span', '</span>');
	s := ClearExtraBlankCharacters(DecodeHTML(RemoveTags('<' + s)));
	day := ParseString(s, '^(\d+) ', 1);
	month := ParseString(s, 'de (.*?) de', 1);
	year := ParseString(s, 'de (\d+)$', 1);
	i := 12;
	while (i>0) and (LowerCase(month)<>LowerCase(monthes[i])) do
		i := i - 1;
	if (i>0) and (day <> '') and (year <> '') then
		birth_date := Format('%d/%s/%s', [i, day, year]);
	i := Pos('<span', temp);
	if i>0 then
		delete(temp, 1, i-1);
	birthplace := ParseString(temp, '</span>(.*?)$', 1);
	birthplace := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(birthplace)));
	i := Pos('em ', birthplace);
	if i=1 then
		delete(birthplace, 1, 3);
	i := Pos('(', birthplace);
	if i = 1 then
		delete(birthplace, 1, 1);
	i := Pos(')', birthplace);
	if i = length(birthplace) then
		delete(birthplace, i, 1);
		
	//death date
	death_date := '';
	temp := GetStr(all, 'Falecimento</', '</p>');
	s := GetStr(temp, '<span', '</span>');
	s := ClearExtraBlankCharacters(DecodeHTML(RemoveTags('<' + s)));
	day := ParseString(s, '^(\d+) ', 1);
	month := ParseString(s, 'de (.*?) de', 1);
	year := ParseString(s, 'de (\d+)$', 1);
	i := 12;
	while (i>0) and (LowerCase(month)<>LowerCase(monthes[i])) do
		i := i - 1;
	if (i>0) and (day <> '') and (year <> '') then
		death_date := Format('%d/%s/%s', [i, day, year]);
		
	//biography
	temp := GetHTMLPageContentFromRequest(bio_url);
	temp := GetStr(temp, 'Biografia'#10'</h2', '<div class="breaker"');
	s := GetStr(temp, '<p>', '</p>');
	s := ReplaceStr(s, '<br />', #13#10, -1);
	if Pos('<style>', s)>0 then
		s := '';
	biography := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
	if biography = '' then begin
		i := Pos('</p>', temp);
		delete(temp, 1, i);
		s := GetStr(temp, '<p>', '</p>');
		s := ReplaceStr(s, '<br />', #13#10, -1);
		biography := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
	end;

	//photo
	photo_url := GetStr(all, '<link rel="image_src" href="', '"');
	i := Pos(main_photo_resizer, photo_url);
	if i>0 then
		delete(photo_url, i, length(main_photo_resizer));
	if Pos('empty', photo_url) > 0 then
		photo_url := '';
		
	//filmography
	if (filmo_url <> '') then begin
		temp := GetHTMLPageContentFromRequest(filmo_url);
		i := Pos('Atores</h2>', temp);
		if i = 0 then
			i := Pos('Atriz</h2>', temp);
		if i>0 then begin
			j := MyPos('</table>', temp, i+1);
			ExtractMovies(copy(temp, i, j-i), 3);
		end;
		i := Pos('Direção</h2>', temp);
		if i>0 then begin
			j := MyPos('</table>', temp, i+1);
			ExtractMovies(copy(temp, i, j-i), 1);
		end;
		i := Pos('Roteiro</h2>', temp);
		if i>0 then begin
			j := MyPos('</table>', temp, i+1);
			ExtractMovies(copy(temp, i, j-i), 2);
		end;
	end;	

end;

	
//get movie site url
function GetMovieSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:='http://www.adorocinema.com/filmes/filme-'+code+'/';
end;

//get person site url
function GetPersonSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:='http://www.adorocinema.com/personalidades/personalidade-'+code+'/';
end;

begin

	monthes[1]:='janeiro';
	monthes[2]:='fevereiro';
	monthes[3]:='março';
	monthes[4]:='Abril';
	monthes[5]:='Maio';
	monthes[6]:='Junho';
	monthes[7]:='Julho';
	monthes[8]:='Agosto';
	monthes[9]:='Setembro';
	monthes[10]:='Outubro';
	monthes[11]:='Novembro';
	monthes[12]:='Dezembro';

	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.