const
	script_name='HKMDB';
	language='English';
	version=5;
	author='Vlad';
	MinProgramBuild=4007;
	PCount = 12;
	//MaxPicturesCount = 3;
var
	DownloadMovieBigCover, DownloadMovieShortCast, DownloadMovieFullCast, 
	DownloadMovieBigDescription, DownloadMovieComments,
	DownloadMovieStudios,	DownloadMovieAwards, DownloadMovieEarnings, 
	DownloadMovieAdditionalInfo, DownloadMovieSeasonsList: boolean;
	MaxShotsCount, MaxPostersCount: integer;

	title, MovieName, s, s2, s3, s4, year, director, name, character, BasicURL, country, description, salary: 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: 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: integer;
	title, code, year: string;
begin
	s:='';
	titles_count:=0;
	//forwarded to the movie page
	i := Pos('<TITLE>', all);
	if i>0 then begin
		code := ParseString(all, '<A HREF="/db/images/edit/add.mhtml\?caller_mode=movie\&caller_id=(\d+)\&display_set=eng">', 1);
		SetSearchResult('title', code);
		result := 1;
		exit;
	end;
	i:=pos('<H3>Films</H3>', all);
	if i>0 then begin
		j:=MyPos('</TABLE></CENTER>', all, i+1);
		if j>0 then
			s:=copy(all, i+3, j-i-4);
	end;
	if (s='') or (pos('Nothing matched your search', all)>0) then
		//Movie not found
	else begin
	  i := pos('<TABLE ',s);
	  s := copy(s,i+3,length(s));
	  
	  i:=Pos('<TR>', s);
	  while i>0 do begin			
			j:=MyPos('</TR>', s, i+1);
			s2 := copy(s, i, j-i);
			
			code:=ParseString(s2, '<a href="/db/movies/view.mhtml\?id=(\d+)\&display_set=eng">', 1);

			
			title:=ParseString(s2, 'display_set=eng"> (.*?) \/ <\/a>', 1);
			title:=DecodeHTML(title);
			title:=ClearExtraSpaces(title);
			
			year := ParseString(s2, '\((\d+)\)', 1);

			if title<>'' then begin
				titles_count:=titles_count+1;
				SetSearchResult(title + ' (' + year + ')', code);
			end;
			delete(s, 1, j+5);
			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, AYear, ABarcode: string): string;
var
	url: string;
begin
	url:=format('http://hkmdb.com/db/search/simple_search_results.mhtml?display_set=eng&search_for=movies&search_string=%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:=format('http://hkmdb.com/db/movies/view.mhtml?id=%s&display_set=eng', [code]);
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;

procedure ExtractStudios(i: Integer);
var
	s2, s3: String;
	j, k, l : Integer;
begin
	j := MyPos('<TD COLSPAN="2"', all, i+1);
	s2 := copy(all, i+25, j-i-25);
	i := Pos('<A HREF', s2);
	while i>0 do begin
		j := MyPos('</A>', s2, i+1);
		s3 := copy(s2, i, j-i);
		s3 := RemoveTags(s3);
		s3 := DecodeHTML(s3);
		//remove Hong Kong from distributors
		k := Pos('(Hong Kong)', s3);
		if k>0 then
			delete(s3, k, 11);
		s3 := ClearExtraBlankCharacters(s3);
		if s3<>'' then
			SetStudio(s3);
		delete(s2, 1, j);
		i := Pos('<A HREF', s2);
	end;
end;


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

	movie_code:=ParseString(url, 'http://hkmdb.com/db/movies/view.mhtml\?id=(\d+)\&display_set=eng',1);
	movie_site_url:=GetMovieSiteURL(movie_code);
	
	//movie title
	title:=ParseString(all, '<TITLE>(.*?) \(\d+\)</TITLE>', 1);
	title:=RemoveTags(title);
	title:=DecodeHTML(title);
	title:=ClearExtraSpaces(title);
	title := ClearExtraQuotes(title);
	title := MovePrefixLeft(title);
	original_title := '';
	if title='' then
		exit;
	
	//year
	year := ParseString(all, '<TITLE>.*? \((\d+)\)</TITLE>', 1);
	
	//country
	s2 := ParseString(all, 'Country: (.*?)'#10, 1);
	s2 := DecodeHTML(s2);
	s2 := ClearExtraSpaces(s2);
	if s2<>'' then
		SetCountry(s2);

	//movie genres
	i := Pos('<b><font size="-1">Genre', all);
	if i>0 then begin
		j := MyPos('</font></b>', all, i+1);
		s2 := copy(all, i+26, j-i-26);
		i := Pos('&nbsp;', s2);
		while i>0 do begin
			s3 := copy(s2, 1, i-1);
			s3 := DecodeHTML(s3);
			s3 := ClearExtraBlankCharacters(s3);
			if s3<>'' then
				SetGenre(s3);
			delete(s2, 1, i+5);
			i := Pos('&nbsp;', s2);
		end;
	end;
	
	//alias
	i:=pos('>Alias: ', all);
	if i=0 then begin
		i := Pos('>Alt title: ', all);
		if i = 0 then
			i := Pos('>Alt Title: ', all);
		if i>0 then
			i := i + 4;
	end;
	if i>0 then begin
		j := MyPos('</TABLE>', all, i+1);
		s := copy(all, i, j-i);
		i := 1;
		while i>0 do begin
			j := MyPos('<', s, i+1);
			s2 := copy(s, i+8, j-i-8);
			s2 := DecodeHTML(s2);
			description := description + 'AKA: ' + s2 + '<br>';
			delete(s, 1, j);
			i:=pos('>Alias: ', s);
			if i=0 then begin
				i := Pos('>alt title: ', LowerCase(s));
				if i>0 then
					i := i + 4;
			end;
		end;
		//description := description + '<br>';
	end;
	
	//description
	i:=pos('<p class="hft-paras">', all);
	if i>0 then begin
		j := MyPos('[', all, i+1);
		if j = 0 then
			j := MyPos('</p>', all, i+1);
		s2 := copy(all, i, j-i);
		s2 := RemoveTags(s2);
		s2 := DecodeHTML(s2);
		if (s2 <> '') and (description <> '') then
			description := description + '<br>' + s2
		else
			description := description + s2;
	end;
	
	//theatrical run
	i := Pos('Theatrical Run:', all);
	if i=0 then
		i := Pos('Release Date:', all);
	if i>0 then begin
		j := MyPos(#10, all, i+1);
		s2 := copy(all, i, j-i);
		s2 := DecodeHTML(s2);
		if (s2 <> '') and (description <> '') then
			description := description + '<br>';
		if (s2 <> '') then
			description := description + s2;
	end;
	
	//age certification
	i := Pos('Rating:', all);
	if i>0 then begin
		j := MyPos(' (', all, i+1);
		s2 := copy(all, i+7, j-i-7);
		s2 := DecodeHTML(s2);
		mpaa := ClearExtraBlankCharacters(s2);
	end;
	
	//movie image
	s2:=ParseString(all, '<IMG SRC="/db/images/movies/(.*?)t.jpg" ',1);
	if s2 <> '' then
		front_cover_url:=format('http://hkmdb.com/db/images/movies/%sb.jpg',[s2]);
		
	//box office
	salary := ParseString(all, 'Box Office: (.*?)</font></b>', 1);

	//directors
	i:=pos('<B>Director', all);
	if i>0 then begin
		j:=MyPos('</TABLE>', all, i+1);
		s:=copy(all, i, j-i);
		i := Pos('<A HREF="/db/people/', s);
		while i>0 do begin
			j := MyPos('</A>', s, i+1);
			s2:=copy(s, i, j-i);
			name := RemoveTags(s2);
			name := DecodeHTML(name);
			k := Pos(' (', name);
			if k>0 then
				delete(name, k, length(name) - k + 1);
			name := ClearExtraBlankCharacters(name);
			code:=ParseString(s2,'<A HREF="/db/people/view.mhtml\?id=(\d+)\&display_set=eng">', 1);
			if name<>'' then
				setPersonName(name, '', 1, code);
			delete(s, 1, i);
			i:=MyPos('<A HREF="/db/people/', s, i+1);
		end;
	end;

	//writers
	i:=pos('<B>Script', all);
	if i>0 then begin
		j:=MyPos('</TABLE>', all, i+1);
		s:=copy(all, i, j-i);
		i := Pos('<A HREF="/db/people/', s);
		while i>0 do begin
			j := MyPos('</A>', s, i+1);
			s2:=copy(s, i, j-i);
			name := RemoveTags(s2);
			name := DecodeHTML(name);
			k := Pos(' (', name);
			if k>0 then
				delete(name, k, length(name) - k + 1);
			name := ClearExtraBlankCharacters(name);
			code:=ParseString(s2,'<A HREF="/db/people/view.mhtml\?id=(\d+)\&display_set=eng">', 1);
			if name<>'' then
				setPersonName(name, '', 2, code);
			delete(s, 1, i);
			i := Pos('<A HREF="/db/people/', s);
		end;
	end;

	//actors
	i:=pos('<b>Cast</b>', all);
	if i>0 then begin
		j:=MyPos('</TABLE>', all, i+1);
		s:=copy(all, i, j-i);
		i := Pos('<TR>', s);
		while i>0 do begin
			j := MyPos('</TR>', s, i+1);
			s2:=copy(s, i, j-i);
			//character
			character := '';
			k := Pos('<TD NOWRAP>', s2);
			if k>0 then begin
				k := MyPos('<TD>', s2, k+1);
				l := MyPos('</TD>', s2, k+1);
				character := copy(s2, k+4, l-k-4);
				character := DecodeHTML(character);
			end;
			code := ParseString(s2, '<A HREF="/db/people/view.mhtml\?id=(\d+)&display_set=eng">', 1);
			name := ParseString(s2, 'display_set=eng">(.*?)<\/A>', 1);
			name := DecodeHTML(name);
			k := Pos(' (', name);
			if k>0 then
				delete(name, k, length(name) - k + 1);
			if name<>'' then
				SetPersonName(name, character, 3, code);
			delete(s, 1, j);
			i := Pos('<TR>', s);
		end;
	end;
	
	//composers
	i := Pos('<b>Composer</b>', all);
	if i>0 then begin
		j:=MyPos('<TD COLSPAN="2"', all, i+1);
		s:=copy(all, i, j-i);
		i := Pos('<a href="/db/people/', s);
		while i>0 do begin
			j := MyPos('</a>', s, i+1);
			s2:=copy(s, i, j-i);
			name := RemoveTags(s2);
			name := DecodeHTML(name);
			k := Pos(' (', name);
			if k>0 then
				delete(name, k, length(name) - k + 1);
			name := ClearExtraBlankCharacters(name);
			code:=ParseString(s2,'<a href="/db/people/view.mhtml\?id=(\d+)\&display_set=eng">', 1);
			if name<>'' then
				setPersonName(name, '', 4, code);
			delete(s, 1, i);
			i := Pos('<a href="/db/people/', s);
		end;
	end;

	
	//studios
	if DownloadMovieStudios then begin
		i := Pos('<B>Production Compan', all);
		if i>0 then
			ExtractStudios(i);
		i := Pos('<B>Filming Compan', all);
		if i>0 then
			ExtractStudios(i);
		i := Pos('<B>Distributor', all);
		if i>0 then
			ExtractStudios(i);
	end;

end;

//returned images links
procedure GetImages;
var
	image_cnt, i, j: Integer;
	url, s, s2: String;
begin
	if front_cover_url<>'' then
		SetImageName('', front_cover_url, '', 1);
	image_cnt := 0;
	if MaxShotsCount>0 then begin
		url := format('http://hkmdb.com/db/movies/images.mhtml?id=%s&display_set=eng', [movie_code]);
		s := DownloadURL(url);
		i := Pos('<IMG SRC="/db/images/', s);
		while (image_cnt < MaxShotsCount) and (i>0) do begin
			j := MyPos('"', s, i+10);
			s2 := copy(s, i+10, j-i-10);
			if s2<>'' then begin
				s2 := ReplaceStr(s2, 't.jpg', 'b.jpg', -1);
				SetImageName('', 'http://hkmdb.com' + s2, '', 3);
				image_cnt := image_cnt + 1;
			end;
			delete(s, i, j-i);
			i := Pos('<IMG SRC="/db/images/', s);
		end;
	end;
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;

//get movie site url
function GetMovieSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:='http://hkmdb.com/db/movies/view.mhtml?id='+code+'&display_set=eng';
end;

//get person url
function GetPersonSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:=format('http://hkmdb.com/db/people/view.mhtml?id=%s&display_set=eng', [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.