const
	script_name='adorocinema';
	language='Brazilian Portuguese';
	version=16;
	author='Vlad';
	MinProgramBuild=5500;
	PCount = 12;
	//MaxPicturesCount = 3;
var
	title, MovieName, s, s2, s3, s4, year, director, name, character, BasicURL, country, description, salary, awards: String;
	episodes, movie_code, movie_site_url, title_code, imdb_code: string;
	titles: array of string;
	titles_count: integer;
	i, j: integer;
	director_code, code: string;
	directors, writers, actors, characters, genres, imdb_codes: array of string;
	duration: integer;
	rating, imdb_rating: double;
	front_cover_url: string;
	posters_exists, ask_amazon: boolean;
	original_title, mpaa, mpaa_rating: string;
	prefixes: array [1..PCount] of string;
	DownloadMovieBigCover, DownloadMovieFullCast: Boolean; 
	DownloadMovieBigDescription, DownloadMovieComments: Boolean; 
	DownloadMovieStudios, DownloadMovieAwards, DownloadMovieEarnings: Boolean; 
	DownloadMovieAdditionalInfo, DownloadMovieSeasonsList: Boolean; 
	MaxShotsCount, MaxPostersCount: integer;
	resolution, barcode, aspect_ratio, features, media_format, video_codec: string;
	FotoURL: String;
	
const
	medium_photo_resizer='/r_120_160';
	small_photo_resizer='/r_60_80';
	front_cover_resizer='/r_160_240';

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;
	
function MovieSearch: integer;
var
	i, j, k, l: integer;
	temp, s2, title, year, description, original_title, small_cover: string;
begin
	s:='';
	titles_count:=0;
	s := GetStr(all, 'Filmes</h2>', '</table>');
	if s = '' then
		s := GetStr(all, 'Filmes'#10'</h2>', '</table>');
	if (s = '') then
	//movie not found
	else begin
		i:=pos('<tr>', s);
		while i>0 do begin
			temp:=GetStr(s, '<tr>', '</tr>');
			title := GetStr(temp, '<div>', '</a>');
			title := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(title)));
			title_code := GetStr(temp, ' href=''/filmes/filme-', '/');
			small_cover := GetStr(temp, 'src=''', '''');
			if (Pos('emptysearchposter', small_cover)>0) then
				small_cover := '';
			original_title := GetStr(temp, '</b>', '<br');
			original_title := DecodeHTML(GetStr(original_title, '(', ')'));
			s2 := GetStr(temp, '<span', '<div>');
			year := GetStr(s2, '">', '<br');
			year := ParseString(year, '(\d+)', 1);
			j := Pos('<br />', s2);
			if j>0 then
				delete(s2, 1, j-1);
			s2 := ReplaceStr(s2, '<br />', #13#10, -1);
			description := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s2)));
			if title<>'' then begin
				SetSearchResult2(title, title_code, year, original_title, description, small_cover);
				titles_count := titles_count + 1;
			end;
			delete(s, 1, i);
			i:=pos('<tr>', s);
		end;
	end;
	result:=titles_count;
end;

//get  movie name by barcode(UPC-12)
function GetMovieNameByUPC(barcode: string): string;
var
	url, all, s2, s3, res: string;
	i, j: integer;
begin
	res:='';
	url:=format('http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&SubscriptionId=0J0N83PT9M72BYH98YR2&Operation=ItemSearch&Keywords=%s&SearchIndex=Video&ResponseGroup=Request,Images,Tracks,ItemAttributes', [barcode]);	
	url:=ReplaceStr(url, ' ', '+', -1);
	all:=DownloadURL(url);
	//search image by title
	i:=pos('<Item>', all);
	while (i>0) and (res='') do begin
		j:=MyPos('</Item>', all, i+1);
		if j>0 then begin
			s2:=copy(all, i, j-i);
			s3:=ParseString(s2, '<Title>(.*?) \(.*\)</Title>', 1);
			if s3='' then
				s3:=ParseString(s2, '<Title>(.*?)</Title>', 1);
			if s3<>'' then
				res:=s3;
		end;
		i:=MyPos('<Item>', all, i+1);
	end;
	i:=pos('[', res);
	if i>0 then begin
		j:=MyPos(']', res, i+1);
		if j>0 then
			delete(res, i, j-i+1);
	end;
	result:=res;
end;

//Get search URL by movie name
function GetSearchURLbyName(MovieName: string; AYear: string; ABarcode: String): string;
var
	url: string;
begin
	MovieName := EncodeURL(MovieName, 'utf-8');
	url:=format('http://www.adorocinema.com/busca/?q=%s', [MovieName]);
	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:=MovieSearch;
end;

function GetMovieURL(code: string; images_only: boolean): string;
begin
	result:='http://www.adorocinema.com/filmes/filme-'+code+'/';
end;


//save front cover to file
function SaveFrontCover(url, FileName: string): boolean;
var
	fs: TFileStream;
	s, referer: string;
	i: integer;
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 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 ExtractPeople(text: String; mode: Integer);
var
	s, temp, name, character, code, photo: String;
	i, k: Integer;
begin
	i := Pos('<li', text);
	while i>0 do begin
		s := GetStr(text, '<li', '</li>');
		name := RemoveTags(GetStr(s, 'itemprop="name">', '</'));
		if name = '' then begin
			name := GetStr(s, '<p>', '</');
			if name <> '' then
				name := RemoveTags('<' + name);
		end;
		name := ClearExtraBlankCharacters(DecodeHTML(name));
		code := ParseString(s, ' href="/personalidades/personalidade-(\d+)/', 1);
		photo := GetStr(s, 'src=''', '''');
		k := Pos(medium_photo_resizer, photo);
		if k>0 then
			delete(photo, k, length(medium_photo_resizer));
		if Pos('empty', photo)>0 then
			photo := '';
		character := '';
		if mode = 3 then begin
			character := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(GetStr(s, 'Personagem: ', '</p>'))));
		end;
		if (name <> '') then
			SetPersonName(name, character, mode, code, photo);
		delete(text, 1, i);
		i := Pos('<li', text);
	end;
	temp := GetStr(text, '<table class="table_02">', '</table>');
	//alternative
	i := Pos('<tr', temp);
	while i>0 do begin
		s := GetStr(temp, '<tr', '</tr>');
		character := GetStr(s, '<td>', '</td>');
		character := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(character)));
		delete(s, 1, Pos('</td>', s));
		name := GetStr(s, '<td>', '</td>');
		code := ParseString(name, ' href="/personalidades/personalidade-(\d+)', 1);
		name := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(name)));
		photo := GetStr(s, 'src=''', '''');
		k := Pos(small_photo_resizer, photo);
		if k>0 then
			delete(photo, k, length(small_photo_resizer));
		if Pos('empty', photo)>0 then
			photo := '';
		if mode <> 3 then
			character := '';
		if (name <> '') then
			SetPersonName(name, character, mode, code, photo);
		delete(temp, 1, i);
		i := Pos('<tr', temp);
	end;
end;

function GetInfo(url: string; images_only: boolean): string;
var 
	keyword, s, s2, s3, plot_outline, shot, shot_prefix, shot_ext, sh, sm, st, sa, sr, TmpAll, sc: string;
	i, j, k, frames_count, sb, se: integer;
	actors: boolean;
	name, character, code, temp, cast_url, cast_page, small_photo: String;
begin
	result:='';
	all:=DownloadURL(url);
	if all='-1' then
		result:='-1'
	else
		result:=all;
		
	cast_url := '';
	if DownloadMovieFullCast and (Pos('/creditos/', all)>0) then begin
		cast_url := url + 'creditos/';
		AddRequestForHTMLPageContent(cast_url, False);
	end;
	
	FotoURL := '';
	if ((MaxShotsCount > 0) or (MaxPostersCount > 0)) and (Pos('/fotos/', all)>0) then begin
		FotoURL := url + 'fotos/';
		AddRequestForHTMLPageContent(FotoURL, False);
	end;


	movie_code:=ParseString(url, 'http://www.adorocinema.com/filmes/filme-(\d+)/',1);
	movie_site_url:=GetMovieSiteURL(movie_code);
	//movie title
	i := Pos('<title>', all);
	j := MyPos(' - ', all, i+1);
	title := copy(all, i+7, j-i-7);
	title := ClearExtraBlankCharacters(DecodeHTML(title));
	if title='' then exit;

	//original title
	original_title := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(GetStr(all, 'Título original', '</td>'))));
	if (original_title = '') then
		original_title := title;

	//genres
	temp := GetStr(all, 'Gênero</span>', '</div>');
	temp := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(temp)));
	while (temp <> '') do begin
		i := Pos(',', temp);
		if i = 0 then
			i := Length(temp) + 1;
		s := copy(temp, 1, i-1);
		s := ClearExtraBlankCharacters(s);
		if s <> '' then
			SetGenre(s);
		delete(temp, 1, i);
	end;

	//duration
	duration:=0;
	temp := GetStr(all, '<span itemprop="duration"', '</span>');
	temp := ClearExtraBlankCharacters(RemoveTags('<' + temp));
	sm := ParseString(temp, '(\d+)min', 1);
	sh := ParseString(temp, '^(\d+)h', 1);
	i := 0;
	if (sm <> '') then begin
		try 
			Duration := StrToInt(sm);
			i := StrToInt(sh);
		except
		end;
		if i > 0 then
			Duration := Duration + i*60;
	end;

	//countries
	temp := GetStr(all, 'Nacionalidade </span>', '</div>');
	temp := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(temp)));
	while (temp <> '') do begin
		i := Pos(',', temp);
		if i = 0 then
			i := Length(temp) + 1;
		s := copy(temp, 1, i-1);
		s := ClearExtraBlankCharacters(s);
		if s <> '' then
			SetCountry(s);
		delete(temp, 1, i);
	end;

	//Year
	temp := GetStr(all, 'Ano de produção</th>', '</td>');
	temp := RemoveTags(temp);
	year := ParseString(temp, '(\d+)', 1);
	
	//synopsis
	temp := GetStr(all, 'itemprop="description">', '</p>');
	description := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(temp)));
	
	//front cover
	temp := GetStr(all, '<div class="poster">', '</div>');
	front_cover_url := GetStr(temp, ' src=''', '''');
	i := Pos(front_cover_resizer, front_cover_url);
	if i>0 then
		delete(front_cover_url, i, length(front_cover_resizer));
	if Pos('empty', front_cover_url) > 0 then
		front_cover_url := '';
		
	//Orçamento
	salary := '';
	if DownloadMovieAdditionalInfo then begin
		temp := GetStr(all, 'Orçamento</th>', '</td>');
		temp := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(temp)));
		if temp <> '-' then
			salary := 'Orçamento: ' + temp;
	end;
	
	//site visitors rating
	rating := 0;
	temp := GetStr(all, 'Leitores'#10'</a>', '</div>');
	temp := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(temp)));
	i := pos(',', temp);
	if i > 0 then
		temp[i]:=DecimalSeparator;
	try
		rating:=StrToFloat(temp);
	except
	end;
	
	//studios
	if DownloadMovieStudios then begin
		temp := GetStr(all, 'Distribuidor</th>', '</td>');
		temp := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(temp)));
		while (temp <> '') do begin
			i := Pos(',', temp);
			if i = 0 then
				i := Length(temp) + 1;
			s := copy(temp, 1, i-1);
			s := ClearExtraBlankCharacters(s);
			if (s <> '') and (s <> '-') then
				SetStudio(s);
			delete(temp, 1, i);
		end;
	end;
	
	
	//cast and crew
	if cast_url <> '' then begin
		cast_page := GetHTMLPageContentFromRequest(cast_url);
		//directors
		i := Pos('Diretores'#10'</h2>', cast_page);
		if i>0 then begin
			j := MyPos('<div class="sep_', cast_page, i+1);
			s := copy(cast_page, i, j-i);
			ExtractPeople(s, 1);
		end;
		//actors
		i := Pos('Atores e atrizes'#10'</h2>', cast_page);
		if i>0 then begin
			j := MyPos('<div class="sep_', cast_page, i+1);
			s := copy(cast_page, i, j-i);
			ExtractPeople(s, 3);
		end
		else begin
			i := Pos('Dubladores (vozes originais)', cast_page);
			if i>0 then begin
				j := MyPos('<div class="sep_', cast_page, i+1);
				s := copy(cast_page, i, j-i);
				ExtractPeople(s, 3);
			end;
		end;
		//screenplay
		i := Pos('Roteiro'#10'</h2>', cast_page);
		if i>0 then begin
			j := MyPos('<div class="sep_', cast_page, i+1);
			s := copy(cast_page, i, j-i);
			ExtractPeople(s, 2);
		end;
	end
	else begin
		//directors
		temp := GetStr(all, 'Dirigido por</span>', '</li>');
		i := Pos('itemprop="director"', temp);
		while i > 0 do begin
			s := GetStr(temp, 'itemprop="director"', '</span>');
			name := ClearExtraBlankCharacters(DecodeHTML(RemoveTags('<' + s)));
			code := ParseString(s, ' href="/personalidades/personalidade-(\d+)', 1);
			if name <> '' then
				SetPersonName(name, '', 1, code);
			delete(temp, 1, i);
			i := Pos('itemprop="director"', temp);
		end;
		//actors
		temp := GetStr(all, 'Elenco</span>', '</ul>');
		i := Pos('<li', temp);
		while i>0 do begin
			s := GetStr(temp, '<li', '</li>');
			name := GetStr(s, 'itemprop="name">', '</');
			name := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(name)));
			code := ParseString(s, ' href="/personalidades/personalidade-(\d+)', 1);
			character := GetStr(s, 'Personagem:', '</');
			character := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(character)));
			small_photo := GetStr(s, 'src=''', '''');
			k := Pos(medium_photo_resizer, small_photo);
			if k>0 then
				delete(small_photo, k, length(medium_photo_resizer));
			if Pos('empty', small_photo)>0 then
				small_photo := '';
			if name <> '' then
				SetPersonName(name, character, 3, code, small_photo);
			delete(temp, 1, i);
			i := Pos('<li', temp);
		end;
	end;
	

end;

procedure ExtractImages(text: String; mode, max_cnt: Integer);
var
	i, k, img_cnt: Integer;
	s, img_url: String;
const
	resizer = '/c_100_100';
begin
	img_cnt := 0;
	i := Pos('<li', text);
	while (i>0) and (img_cnt < max_cnt) do begin
		s := GetStr(text, '<li', '</li>');
		img_url := GetStr(s, ' src=''', '''');
		k := Pos(resizer, img_url);
		if k>0 then
			delete(img_url, k, length(resizer));
		if img_url <> '' then begin
			SetImageName('', img_url, '', mode);
			Inc(img_cnt);
		end;
		delete(text, 1, i);
		i := Pos('<li', text);
	end;
end;

//returned images links
procedure GetImages;
var
	i, j, image_count, mode, poster_count: integer;
	s, s2, temp: string;
begin
	if front_cover_url <> '' then
		SetImageName('', front_cover_url, '', 1);
	if FotoURL <> '' then begin
		temp := GetHTMLPageContentFromRequest(FotoURL);
		if MaxPostersCount > 0 then begin
			s := GetStr(temp, 'Posters'#10'</h2>', '</ul>');
			ExtractImages(s, 4, MaxPostersCount);
		end;
		if MaxShotsCount > 0 then begin
			s := GetStr(temp, 'Fotos do filme'#10'</h2>', '</ul>');
			ExtractImages(s, 3, MaxShotsCount);
		end;
	end;
end;

function ClearExtraBlankCharacters(text: string): string;
begin
	// Clear all extra blank characters
	while (length(text) > 0) and (ord(text[1]) in [1..20, 32]) do
		delete(text, 1, 1);
	while (length(text) > 0) and (ord(text[length(text)]) in [1..20, 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.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

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.