const
	script_name='moviemeter';
	language='Dutch';
	version=11;
	author='Vlad';
	MinProgramBuild=6000;
	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;
	resolution, barcode, aspect_ratio, features, media_format, video_codec: string;

function MovieSearch: integer;
var
	i, j, k, l: integer;
	title: string;
begin
	//all:=DownloadURL('http://www.moviemeter.nl/film/searchresults#results');
	s:='';
	titles_count:=0;
	i:=Pos('<a name="results">', all);
	//if we are forwarded directly to a movie's page
	if i=0 then begin
		title:=ParseString(all, '<title>(.*?) - MovieMeter.nl</title>', 1);
		title_code:=ParseString(all, '<li><a href="http://www.moviemeter.nl/film/(\d+)/info/"', 1);
		if title<>'' then begin
			titles_count:=titles_count+1;
			SetSearchResult(title, title_code);
		end;
	end

	//otherwise check seach results
	else begin		
		i:=pos('<a name="results">', all);
		if i>0 then begin
			j:=MyPos('</p></div></div>', all, i+1);
			if j>0 then
				s:=copy(all, i, j-i);
		end;
		if (s='') or (pos('Er zijn geen films, regisseurs', all)>0) then
			//Movie not found
		else begin
			i := pos('<a href="http://www.moviemeter.nl/film/',s);
			while i>0 do begin
				titles_count:=titles_count+1;
				SetLength(titles, titles_count);
				j := MyPos('</div>', s, i+1);
				s2 := copy(s, i, j-i);
				title_code:=ParseString(s2, '<a href="http://www.moviemeter.nl/film/(\d+)"', 1);
				title:=RemoveTags(s2);
				title:=DecodeHTML(title);
				
				while (length(title)>0) and (title[1]=' ') do
					delete(title, 1, 1);
				titles[titles_count-1]:=title_code;
				SetSearchResult(title, title_code);
				delete(s, 1, j+5);
				i:=pos('<a href="http://www.moviemeter.nl/film/', s);
			end;
		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, AYear, ABarcode: string): string;
var
	url: string;
begin
	MovieName := EncodeURL(MovieName, 'ISO-8859-1');
	url:=format('http://www.moviemeter.nl/film/search/%s', [MovieName]);
	//url:=ReplaceStr(url, ' ', '+', -1);
	result:=url;
end;

//Download search results from URL
function DownloadSearchURL(url: string): integer;
begin
	all:=DownloadURL(url);
	all := DownloadURL('http://www.moviemeter.nl/film/searchresults#results');
	if all='-1' then
		result:=-1
	else begin
		result:=MovieSearch;
	end;
end;

function GetMovieURL(code: string; images_only: boolean): string;
begin
		result:=format('http://www.moviemeter.nl/film/%s', [code]);
end;

//returned link to front cover
function GetAmazonImages: string;
var
	res, all, url, s, s2, s3, amazon_url: string;
	i, j: integer;
begin
	//discard info in brackets
	s:=title;
	url:=format('http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&SubscriptionId=0J0N83PT9M72BYH98YR2&Operation=ItemSearch&Keywords=%s&SearchIndex=Video&ResponseGroup=Request,Images,Tracks,ItemAttributes', [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(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 GetInfo(url: string; images_only: boolean): string;
var 
	keyword, s, s2, s3: string;
	i, j, k, frames_count: integer;
begin
	result:='';
	all:=DownloadURL(url);
	if all='-1' then
		result:='-1'
	else
		result:=all;

	movie_code:=ParseString(url, 'http://www.moviemeter.nl/film/(\d+)$', 1);
	movie_site_url:=GetMovieSiteURL(movie_code);
	//movie title
	title:=ParseString(all, '<title>(.*?) \(\d+\) - MovieMeter.nl</title>', 1);
	title:=DecodeHTML(title);
	title:=ClearExtraSpaces(title);
	title:=MovePrefixLeft(title);

	if title='' then
		exit;
		
	//original title
		
	//year
	year:=ParseString(all, '<title>.*? \((\d+)\) - MovieMeter.nl</title>', 1);
	
	//copy the part with movie details
	i:=Pos('<div id="film_info" class="film_info">', all);
	if i>0 then begin
		j:=MyPos('<div class="price_compare">', all, i+1);
		if j = 0 then
			j := MyPos('<div id="menu">', all, i+1);
		s:=copy(all, i, j-i);		
		j := Pos('</script>', s);
		while j>0 do begin
			delete(s, 1, j+8);
			j := Pos('</script>', s);
		end;
	end;
	
	//countries
	j:=Pos('<br />', s);
	s2:=copy(s, 1, j-1);
	s2:=RemoveTags(s2);
	i:=Pos(' /', s2);
	while i>0 do begin
		s3:=copy(s2, 1, i-1);
		s3 := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s3)));
		if s3<>'' then
			SetCountry(s3);
		delete(s2, 1, i+2);
		i:=Pos(' /', s2);
	end;
	s2 := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s2)));
	if s2<>'' then
		SetCountry(s2);
		
		
	//Genres
	i:=MyPos('<br />', s, j+1);
	s2:=copy(s, j+6, i-j-6);
	j:=Pos(' /', s2);
	while j>0 do begin
		s3:=copy(s2, 1, j-1);
		s3 := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s3)));
		if s3<>'' then
			SetGenre(s3);
		delete(s2, 1, j+2);
		j:=Pos(' /', s2);
	end;
	s2 := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s2)));
	if s2<>'' then
		SetGenre(s2);
		

	
	//duration
	s2:=ParseString(s, '<div style="max-width: 416px;">(\d+) minuten', 1);
	try
		duration:=StrToInt(s2)
	except
	end;
	
	//directors
	s2:=ParseString(s, 'geregisseerd door (.*?)<br />', 1);
	if s2<>'' then begin
		i:=Pos('<a href="http://www.moviemeter.nl/director/', s2);
		while i>0 do begin
			j:=MyPos('</a>', s2, i+1);
			s3:=copy(s2, i, j-i);
			name:=DecodeHTML(RemoveTags(s3));
			name := ClearExtraBlankCharacters(name);
			code:=ParseString(s3, '<a href="http://www.moviemeter.nl/director/(\d+)"', 1);
			if name<>'' then
				SetPersonName(name, '', 1, code);
			delete(s2, 1, j+4);
			i:=Pos('<a href="http://www.moviemeter.nl/director/', s2);
		end;
	end;
	
	//actors
	s2:=ParseString(s, '<br />met (.*?)<br />', 1);
	if s2<>'' then begin
		i:=Pos(',', s2);
		while i>0 do begin
			name:=copy(s2, 1, i-1);
			name := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(name)));
			if name<>'' then
				SetPersonName(name, '', 3, '');
			delete(s2, 1, i+1);
			i:=Pos(',', s2);
		end;
		i:=Pos(' en ', s2);
		if i>0 then begin
			name:=copy(s2, 1, i-1);
			name := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(name)));
			if name<>'' then
				SetPersonName(name, '', 3, '');
			delete(s2, 1, i+3);
		end;
		s2 := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s2)));
		if s2<>'' then
			SetPersonName(s2, '', 3, '');
		
	end;
	
	//description
	description := GetStr(all, 'itemprop="description">', '</');
	description := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(description)));
	
	//front cover
	s2:=ParseString(all, 'id="poster" class="poster" src="http://www.moviemeter.nl/images/covers/(.*?).jpg"', 1);
	if s2<>'' then
		front_cover_url:='http://www.moviemeter.nl/images/covers/' + s2 + '.jpg';
		
	//imdb code
	imdb_code:=ParseString(all, '<a href="http://www.imdb.com/title/tt(\d+)/"', 1);
	
	//imdb rating
	s2:=ParseString(all, '>IMDb \((.*?) \/', 1);
	if s2<>'' then begin
		i:=pos(',', s2);
		if i>0 then
			s2[i]:=DecimalSeparator;
		try
			imdb_rating:=StrToFloat(s2);
		except
		end;
	end;
	
	//site rating
	s2 := GetStr(all, ' itemprop="average"', '/span>');
	s2 := GetStr(s2, '>', '<');
	if s2 <> '' then begin
		i:=pos(',', s2);
		if i>0 then
			s2[i]:=DecimalSeparator;
		try
			rating:=StrToFloat(s2);
		except
		end;
	end;
	
	//age rating
	mpaa := '';
	s2 := GetStr(all, '<div id="rating_icons">', '</div>');
	if s2 <> '' then begin
		s3 := GetStr(s2, ' alt="', ' jaar');
		if s3 <> '' then
			mpaa := ClearExtraBlankCharacters(s3);
	end;

end;

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

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

//get person site url
function GetPersonSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:='http://www.moviemeter.nl/director/'+code;
end;

function ClearExtraBlankCharacters(text: string): string;
begin
	// Clear all extra blank charackters
	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 GetStr(str: String; s1: String; s2: String): String;
var
  I: Integer;
  J: Integer;
begin
	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;

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.