const
	script_name='FilmAffinity';
	language='Spanish';
	version=16;
	author='Vlad';
	MinProgramBuild=6000;
	PCount = 12;
	//MaxPicturesCount = 3;
var
	DownloadMovieBigCover, DownloadMovieShortCast, DownloadMovieFullCast, 
	DownloadMovieBigDescription, DownloadMovieComments,
	DownloadMovieStudios,	DownloadMovieAwards, DownloadMovieEarnings, 
	DownloadMovieAdditionalInfo, DownloadMovieSeasonsList: boolean;
	MaxShotsCount, MaxPostersCount, MaxBackdropsCount: integer;
	MaxTrailersCount: Integer;
	DownloadSeasonsCovers: Boolean;
	DownloadEpisodesCovers: Boolean;
	DownloadedPersonPhotosForMovie: Integer;

	title, MovieName, s, s2, s3, s4, year, director, name, character, BasicURL, country, description, salary: string;
	movie_code, movie_site_url, title_code, imdb_code, awards: 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;
	imdb_rating, rating: double;
	front_cover_url: string;
	posters_exists, ask_amazon: boolean;
	original_title, mpaa, mpaa_rating: string;
	prefixes: array [1..PCount] of string;
	resolution, barcode, aspect_ratio, features, media_format, video_codec: string;
	SequenceName: String;
	SequenceNumber: Integer;

function MovieSearch: integer;
var
	i, j, k, l: integer;
	title, original_title, small_cover, description, year, s3: string;
begin
	s:='';
	titles_count:=0;
	i:=pos('squeda de', all);
	j:=MyPos('- FilmAffinity</title>', all, i+1);
	//if the search is forwarded to the details page
	if (i=0) or (j=0) then begin
		i:=pos('movie_id=', all);
		j:=MyPos('"', all, i+9);
		title_code:=copy(all, i+9, j-i-9);
		if title_code<>'' then begin
			title := GetStr(all, '<h1>', '</h1>');
			titles_count:=1;
			SetSearchResult(title, title_code);
		end;
	end;

	i:=pos('Resultados', all);
	if i>0 then begin
		j:=MyPos('Si no encuentras', all, i+1);
		if j>0 then
			s:=copy(all, i, j-i);
	end;

	if (s='') or (pos('<b>0 resultados', all)>0) then
	//movie not found

	else begin         
	  i := pos('a href="/es/film',s);
	  s := copy(s,i,length(s));
	  i := 1;
	  j := Pos('</td></tr></table></div>', s);
	  if j = 0 then
		j := Pos('</div></div>', s);
	  while j>0 do begin
			
			s2:=copy(s, i, j-i);
					
			title_code:=ParseString(s2, ' href="/es/film(\d+).html', 1);
			title := GetStr(s2, ' class="mc-title"', '</td>');
			if title = '' then
				title := GetStr(s2, ' class="mc-title"', '</div>');
			year := GetStr(title, '</a>', '<');
			year := ParseString(year, '(\d+)', 1);
			title:=GetStr(title, '>', '</a>');
			title:=DecodeHTML(RemoveTags(title));
			title:=ClearExtraSpaces(title);
			//original title - none
			original_title := '';
			//small cover
			small_cover := GetStr(s2, ' src="', '"');
			if small_cover = '' then begin
				small_cover := ParseString(s2, '<img src="http:\/\/pics\.filmaffinity\.com\/(.*?)" ', 1);
				if small_cover <> '' then
					small_cover := 'http://pics.filmaffinity.com/' + small_cover;
			end;
				
			//director
			original_title := GetStr(s2, ' class="mc-director">', '</table>');
			if original_title = '' then
				original_title := GetStr(s2, ' class="mc-director">', '</div>');
			original_title := RemoveTags(DecodeHTML(original_title));
			
			//cast
			description := GetStr(s2, 'class="mc-cast">', '</div>');
			description := RemoveTags(DecodeHTML(description));
			
			if (title <> '') and (title_code <> '') then begin
				titles_count:=titles_count+1;
				SetSearchResult2(title, title_code, year, original_title, description, small_cover);
			end;
		    delete(s, 1, j+4);
			i:=Pos('a href="/es/film', s);
			j:=MyPos('</td></tr></table></div>', s, i+1);
			if j = 0 then
				j := MyPos('</div></div>', s, i + 1);
	  end;
	end;
	result:=titles_count;

end;

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;

//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, AYear, ABarcode: string): string;
var
	url: string;
begin
	MovieName := EncodeURL(MovieName, 'ISO-8859-1');
	url:=format('http://www.filmaffinity.com/es/search.php?stext=%s&stype=title', [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:=format('http://www.filmaffinity.com/es/film%s.html', [code])
end;

//returned link to front cover
function GetAmazonImages: string;
var
	res, all, url, s, s2, s3, amazon_url: string;
	i, j: integer;
begin
	s:=original_title;
	url:=format('http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&SubscriptionId=0J0N83PT9M72BYH98YR2&Operation=ItemSearch&Keywords=%s&SearchIndex=Video&ResponseGroup=Request,Images,Tracks,ItemAttributes', [original_title]);	
	url:=ReplaceStr(url, ' ', '+', -1);
	all:=DownloadURL(url);
	//search image by title
	amazon_url:='';
	i:=pos('<Item>', all);
	while (i>0) and (amazon_url='') 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);
			s3:=DecodeHTML(s3);
			if s3<>'' then 
			begin
				//if title=s3 then begin //!!!
				if pos(UpperCase(original_title), UpperCase(s3))=1 then 
				begin
					amazon_url:=ParseString(s2, '<LargeImage><URL>(.*?)</URL>', 1);
				end;
			end;
		end;
		i:=MyPos('<Item>', all, i+1);
	end;
	if amazon_url<>'' then begin
		SetImageName('', amazon_url, '', 1);
		res:=amazon_url;
	end;
	result:=res;
end;

//save front cover to file
function SaveFrontCover(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 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;

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;


function GetInfo(url: string; images_only: boolean): string;
var 
	keyword, s, s2, s3, plot_outline: string;
	i, j, k: integer;
begin
	result:='';
	BasicURL:=url;
	all:=DownloadURL(url);
	if all='-1' then
		result:='-1'
	else
		result:=all;

	movie_code:=ParseString(url, 'http://www.filmaffinity.com/es/film(\d+).html', 1);
	movie_site_url:=GetMovieSiteURL(movie_code);

	//movie title
	title:=ParseString(all, '<title>(.*?) \(', 1);
	title:=RemoveTags(title);
	title:=DecodeHTML(title);
	title:=ClearExtraSpaces(title);
	title := ClearExtraQuotes(title);
	title := MovePrefixLeft(title);
	if title='' then exit;

	//original title
	s := GetStr(all, 'tulo original', '</dd>');
	s := RemoveTags(s);
	s := DecodeHTML(s);
	s := ClearExtraBlankCharacters(s);
	SequenceNumber := 0;
	SequenceName := '';
	i := Pos(' (', s);
	if i > 0 then begin
		s2 := copy(s, i+2, length(s)-i-2);
		s3 := ParseString(s2, '(\d+)', 1);
		if s3 <> '' then begin
			SequenceName := ParseString(s2, '^(.*?) \d+', 1);
			try
				SequenceNumber := StrToInt(s3);
			except
			end;
		end;
		delete(s, i, length(s)-i+1);
	end;
	original_title := s;
	
	//year
	year := ParseString(all, '<title>.*?\((\d+)\)', 1);

	//duration, minutes
	duration:=0;
	s := GetStr(all, 'Duraci&oacute;n</dt>', '</dd>');
	s := RemoveTags(s);
	s := ClearExtraBlankCharacters(s);
	s2:=ParseString(s, '^(\d+) min.', 1);
	if s2 = '' then
		s2 := ParseString(s, '^(\d+)', 1);
	if s2<>'' then
		try
			duration:=StrToInt(s2);
		except
		end;

	//directors
	s := GetStr(all, 'Director</dt>', '</dd>');
	i := Pos('<a href=', s);
	while i>0 do begin
		s2 := GetStr(s, '<a href', '/a>');
		s2 := GetStr(s2, '>', '<');
		name := ClearExtraBlankCharacters(DecodeHTML(s2));
		j := Pos('(', name);
		if j > 0 then begin
			delete(name, j, length(name)-j+1);
			name := ClearExtraBlankCharacters(name);
		end;
		if name <> '' then
			SetPersonName(name, '', 1, '');
		delete(s, 1, i);
		i := Pos('<a href=', s);
	end;
	
	//writers
	s := GetStr(all, 'Gui&oacute;n</dt>', '</dd>');
	s := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
	i := Pos(' (', s);
	if i>0 then begin
		j := MyPos(')', s, i+1);
		if j = length(s) then
			delete(s, i, length(s) - i + 2);
	end;
	repeat
		s2 := '';
		i := Pos(', ', s);
		j := Pos(' & ', s);
		if (j > 0) and ((j < i) or (i = 0)) then begin
			s2 := copy(s, j+3, length(s));
			delete(s, j, length(s));
			i := 0;
		end;
		if i > 0 then begin
			s2 := copy(s, i+2, length(s)-i);
			delete(s, i, length(s)-i+1);
		end;
		j := Pos(' (', s);
		if j > 0 then
			delete(s, j, length(s)-j+2);
		if s <> '' then
			SetPersonName(s, '', 2, '');
		s := s2;
	until s = '';
	
	//actors
	s := GetStr(all, 'Reparto</dt>', '</dd>');
	i := Pos('<a href', s);
	while i>0 do begin
		s2 := GetStr(s, '<a href', '/a>');
		name := ClearExtraBlankCharacters(DecodeHTML(GetStr(s2, '>', '<')));
		if name <> '' then
			SetPersonName(name, '', 3, '');
		delete(s, 1, i);
		i := Pos('<a href', s);
	end;
	
	//composers
	s := GetStr(all, 'M&uacute;sica</dt>', '</dd>');
	s := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
	i := Pos(' (', s);
	if i>0 then begin
		j := MyPos(')', s, i+1);
		if j = length(s) then
			delete(s, i, length(s) - i + 2);
	end;
	repeat
		s2 := '';
		i := Pos(', ', s);
		if i > 0 then begin
			s2 := copy(s, i+2, length(s)-i);
			delete(s, i, length(s)-i+1);
		end;
		j := Pos(' (', s);
		if j > 0 then
			delete(s, j, length(s)-j+2);
		if s <> '' then
			SetPersonName(s, '', 4, '');
		s := s2;
	until i = 0;

	//image
	// small image
	i:=pos('http://www.filmaffinity.com/imgs/movies/full', all);
	if i > 0 then
		s:=copy(all, i, 58);
	// big image
	i:=pos('<a class="lightbox" href="', all);
	if (i>0) then begin
	   j:=MyPos('" title="', all, i);
	   s:=copy(all, i+26,j-i-26);
	end;
	if s = '' then begin
		s := GetStr(all, '<div id="movie-main-image-container">', '</div>');
		s := GetStr(s, ' src="', '"');
	end;
	front_cover_url:=s;

	//description
	s := GetStr(all, '<dt>Sinopsis</dt>', '</dd>');
	description := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
	
	
	//studios
	if DownloadMovieStudios then begin
		s := GetStr(all, 'Productora</dt>', '</dd>');
		s := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
		i := Pos(';', s);
		if i>0 then
			delete(s, 1, i);
		i := Pos('. Productor:', s);
		if i>0 then
			delete(s, i, length(s)-i+1);
		repeat
			s2 := '';
			i := Pos(' / ', s);
			j := Pos('. Distribuida por', s);
			if (j > 0) and ((j < i) or (i = 0)) then begin
				s2 := copy(s, j + 18, length(s));
				delete(s, j, length(s));
				i := 0;
			end;
			if i > 0 then begin
				s2 := copy(s, i+2, length(s)-i);
				delete(s, i, length(s)-i+1);
			end;
			j := Pos(' (', s);
			if j > 0 then
				delete(s, j, length(s)-j+2);
			if s <> '' then
				SetStudio(s);
			s := s2;
		until s = '';	
	end;
	
	if DownloadMovieAwards then begin
		//premios
		s := GetStr(all, 'Premios</dt>', '</dd>');
		awards := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
	end;
	
	//genres
	s := GetStr(all, 'G&eacute;neros</dt>', '</dd>');
	if s = '' then
		s := GetStr(all, 'G&eacute;nero</dt>', '</dd>');
	i := Pos('<a href', s);
	while i>0 do begin
		s2 := GetStr(s, '<a href', '/a>');
		name := ClearExtraBlankCharacters(DecodeHTML(GetStr(s2, '>', '<')));
		if name <> '' then
			SetGenre(name);
		delete(s, 1, i);
		i := Pos('<a href', s);
	end;
	
	//country
	name:=ParseString(all, '<img src="/imgs/countries/.*?" title="(.*?)" border="0"', 1);
	setCountry(name);
	
	// Valoracion
	s := GetStr(all, '<div id="movie-rat-avg"', '</div>');
	if s <> '' then
		s := ClearExtraBlankCharacters(DecodeHTML(RemoveTags('<' + s)));
    try
      rating:=StrToFloat(s);
	except
	end;
	
  // Trailers
(*  i:= pos('<a href="/es/evideos.php?movie_id=',all);
  if i>0 then begin
     j:= MyPos('">Trailers', all, i);
     s:= copy(all, i+9, j-i-9);
     s:= 'http://www.filmaffinity.com' + s;
     all:=DownloadURL(s);
     i:= pos('<div id="divec1" style="padding: 4px;">', all);
     if i>0 then begin
        i:= MyPos('value="http://', all, i);
        j:= MyPos('"></param>', all, i);
        s:= copy(all, i+14, j-i-14);
        description:= description + '<br><a href="link:' + s + '">Ver trailer online</a>';
     end;
  end; 
*)
end;

//returned images links
procedure GetImages;
begin
	if front_cover_url<>'' then
		SetImageName('', front_cover_url, '', 1);
end;

//get movie site url
function GetMovieSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:='http://www.filmaffinity.com/es/film'+code+'.html';
end;

//get person site url
function GetPersonSiteURL(code: string): string;
begin
	result:='';
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.