const
	script_name='dvdempire';
	language='English';
	version=20;
	author='Alex';
	MinProgramBuild=6000;
	Dbg = false;
	PCount = 12;
var
	DownloadMovieBigCover, DownloadMovieShortCast, DownloadMovieFullCast, 
	DownloadMovieBigDescription, DownloadMovieComments, 
	DownloadMovieStudios,	DownloadMovieAwards, DownloadMovieEarnings, 
	DownloadMovieAdditionalInfo, DownloadMovieSeasonsList, DownloadMovieTechnicalInfo: boolean;
	MaxShotsCount: integer;

	title, MovieName, year, director, name, character, BasicURL, country, description, salary: string;
	movie_code, movie_site_url, title_code, imdb_code: string;
	code: string;
	duration: integer;
	imdb_rating: single;
	front_cover_url, cover_code, back_cover_url: string;
	posters_exists, boxes_exists, screenshots_exists: boolean;
	original_title, mpaa, mpaa_rating: string;
	prefixes: array [1..PCount] of string;
	awards: string;
	resolution, barcode, aspect_ratio, features, media_format, video_codec: string;
	duration_min: integer;
	//subtitles, AudioTracks: array of string;
	//SubtitlesCount, AudioTracksCount: integer;
	RequestParameters: TStringList;
	
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..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 MovieSearch: integer;
var
	i, j, ii, jj, TitlesCount: integer;
	s, s2, s3, year, original_title, description, small_cover: string;
begin
	s:='';
	TitlesCount:=0;
	
	i:=pos('<strong>0</strong> Matches Found', all);
	if (all='') or (i>0) then
		// Movie not found!
	else 
	begin
		i:=pos('</strong> Matches Found',all);
		if i>0 then begin
			delete(all, 1, i);
			ii:=Pos('<div class="item', all);
			while ii > 0 do begin
				jj:=MyPos('</div>', all, ii+1);
				if jj>0 then begin
					s3 := copy(all,ii,jj-ii);
					
					//title
					title := GetStr(s3, '<p class="title">', '</p>');
					title_code := ParseString(title, ' href="/(\d+)', 1);
					title := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(title)));
					
					//cover
					small_cover := GetStr(s3, '<img src="', '"');
					
					//year
					year := ParseString(s3, '- year: (\d+)', 1);
					
					//studio (instead of original title)
					s := GetStr(s3, ' itemprop="brand">', '</a>');
					original_title := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
					
					//description
					description := '';
					s := GetStr(s3, '<p class="cast">', '</p>');
					i := Pos('<a ', s);
					while i > 0 do begin
						s2 := GetStr(s, '<a ', '/a>');
						s2 := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(GetStr(s2, '>', '<'))));
						if s2 <> '' then
							description := description + s2 + ', ';
						delete(s, 1, i);
						i := Pos('<a ', s);
					end;
					if description <> '' then
						description := copy(description, 1, length(description) - 2);
					
					if (title <> '') and (title_code <> '') then begin
						TitlesCount := TitlesCount + 1;
						SetSearchResult2(title, title_code, year, original_title, description, small_cover);
					end;
					
					delete(all, 1, jj);
					ii := Pos('<div class="item', all);
				end;
			end;
		end;
	end;
	result:=TitlesCount;
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, 'iso-8859-1');
	if ABarcode <> '' then begin
		url := format('http://www.dvdempire.com/allsearch/search?pageSize=50&exactMatch=%s&q=%s&sort=title', [ABarcode, ABarcode]);
	end
	else
		url:=format('http://www.dvdempire.com/allsearch/search?pageSize=50&exactMatch=%s&q=%s&sort=title', [MovieName, 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
	if images_only then
		result:=format('http://www.dvdempire.com/Exec/v4_item.asp?item_id=%s', [code])
	else
		result:=format('http://www.dvdempire.com/Exec/v4_item.asp?item_id=%s', [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 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 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;

//Parse Audio Tracks to Movienizer's format
function ParseAudioTrack(s: string): string; //Need redaction
begin
	result:=s;
	if Pos(':', s)>0 then
		result := ReplaceStr(s, ':', '', -1);
	if Pos('Dolby Digital Stereo', s)>0	then
		result := ReplaceStr(result, 'Dolby Digital Stereo', 'AC3 2 ch', -1)
	else if Pos('Dolby Digital 5.1 EX', s)>0 then
		result := ReplaceStr(result, 'Dolby Digital 5.1 EX' , 'DD-EX 5.1', -1)
	else if Pos('Dolby Digital 5.1', s)>0 then
		result := ReplaceStr(result, 'Dolby Digital 5.1' , 'AC3 5 ch', -1)
	else if Pos('(Theatrical only)', s)>0 then
		result := ReplaceStr(result, '(Theatrical only)' , '', -1)
	else if Pos('Dolby Digital 2.0', s)>0 then
		result := ReplaceStr(result, 'Dolby Digital 2.0' , 'AC3 2 ch', -1)
	//else if Pos('Dolby Digital Surround', s)>0 then
		//result := ReplaceStr(result, 'Dolby Digital Surround' , 'AC3 2 ch', -1)
	else if Pos('DTS 5.1', s)>0 then
		result := ReplaceStr(result, 'DTS 5.1' , 'DTS 5 ch', -1)
end;

//get movie info
function GetInfo(url: string; images_only: boolean): string;
const
	title_junk=['edition', 'screen', 'lenticular', 'feature', 'director''s'];
var
	s, s2, s3, s4, keyword: string;
	i, j, k: integer;
begin
	result:='';
	BasicURL:=url;
	all:=DownloadURL(url, False, RequestParameters);
	if all='-1' then
		result:='-1'
	else
		result:=all;

	imdb_code:='';
	
	title := GetStr(all, '<h1>', '</h1>');
	title := RemoveTags(title);
	
	//remove garbage
	i := Pos('(', title);
	if i>0 then begin
		delete(title, i, length(title) + 1);
	end;
	i := Pos(' - ', title);
	if i>0 then begin
		s := copy(title, i, length(title) - i + 1);
		for k := 0 to length(title_junk) - 1 do begin
			if (Pos(title_junk[k], LowerCase(s))>0) then
				delete(title, i, length(title) - i + 1);
		end;		
	end;
	i := Pos(':', title);
	if i>0 then begin
		s := copy(title, i, length(title) - i + 1);
		for k := 0 to length(title_junk) - 1 do begin
			if (Pos(title_junk[k], LowerCase(s))>0) then begin
				title := copy(title, 1, i-1);
			end;
		end;
	end;

	title := DecodeHTML(title);
	title := MovePrefixLeft(title);
	title := ClearExtraBlankCharacters(title);
	if title='' then
		exit;

	movie_code:=ParseString(BasicURL, 'http://www.dvdempire.com/Exec/v4_item.asp\?item_id=(\d+)', 1);
	movie_site_url:=GetMovieSiteURL(movie_code);

	//movie year
	year:=ParseString(all, '<strong>Production Year</strong> (\d+)', 1);

	//mpaa
	mpaa:='';
	mpaa_rating:='';
	i:=pos('<strong>Rating</strong>', all);
	if i>0 then begin
		j:=MyPos('<br/>', all, i+1);
		if j>0 then begin
			s2:=copy(all, i, j-i);
			delete(s2, 1, 23);
			s2 := ClearExtraBlankCharacters(RemoveTags(s2));
			if s2<>'' then
				mpaa:=s2;
		end;
	end;


	//plot
	description := GetStr(all, '<h2>Synopsis</h2>', '</div>');
	i := Pos('<i>PLEASE NOTE:', description);
	if i>0 then begin
		j := MyPos('</i>', description, i+1);
		delete(description, i, j-i);
	end;
	description := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(description)));

	//directors
	s2 := GetStr(all, '<h3>Director</h3>', '</ul>');
	if s2 <> '' then begin
		i := Pos('<li', s2);
		while i>0 do begin
			s3 := GetStr(s2, '<li', '</li>');
			name := ClearExtraBlankCharacters(DecodeHTML(RemoveTags('<' + s3)));
			code := ParseString(s3, ' href=".*?(\d+)/director', 1);
			if name <> '' then
				SetPersonName(name, '', 1, code);
			delete(s2, 1, i);
			i := Pos('<li', s2);
		end;
	end;
	
	
	//actors
	s2 := GetStr(all, '<h3>Cast</h3>', '</ul>');
	if s2 <> '' then begin
		i := Pos('<li', s2);
		while i>0 do begin
			s3 := GetStr(s2, '<li', '</li>');
			name := ClearExtraBlankCharacters(DecodeHTML(RemoveTags('<' + s3)));
			code := ParseString(s3, ' href=".*?(\d+)/cast', 1);
			if name <> '' then
				SetPersonName(name, '', 3, code);
			delete(s2, 1, i);
			i := Pos('<li', s2);
		end;
	end;
	
	//imdb rating
	imdb_rating:=0;

	//movie duration (minutes)
	s2:=GetStr(all, '<strong>Length</strong>', '<br/>');
	s3 := ParseString(s2, '^(\d+) hrs', 1);
	s4 := ParseString(s2, '(\d+) mins', 1);
	duration:=0;
	try
		if s4<>'' then
			duration:=StrToInt(s4);
		if s3 <> '' then
			duration := duration + StrToInt(s3)*60
	except
	end;

		
	//movie image
	cover_code := '';
	s2 := GetStr(all, '<div id="Boxcover">', '</div>');
	front_cover_url := GetStr(s2, ' href="', '"');
	back_cover_url := '';
	i := Pos('View Back', s2);
	if i>0 then begin
		j := Pos('</a>', s2);
		delete(s2, 1, j);
		back_cover_url := GetStr(s2, '<a href="', '"');
	end;

	//movie genres
	s2 := GetStr(all, '<h2>Categories</h2>', '</p>');
	i := Pos('<a ', s2);
	while i>0 do begin
		s3 := GetStr(s2, '<a ', '/a>');
		s3 := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(GetStr(s3, '>', '<'))));
		if s3 <> '' then
			SetGenre(s3);
		delete(s2, 1, i);
		i := Pos('<a ', s2);
	end;
	
	//Studio
	if DownloadMovieStudios then begin
		i := Pos('<strong>Studio', all);
		if i>0 then begin
			i := MyPos('</strong>', all, i+1);
			j := MyPos('</a>', all, i+1);
			s := copy(all, i, j-i);
			s := RemoveTags(s);
			s := DecodeHTML(s);
			s := ClearExtraBlankCharacters(s);
			SetStudio(s);
		end;
	end;

	//technical info
	resolution:='';
	barcode:='';
	aspect_ratio:='';
	features:='';
	duration_min:=0;
	//SubtitlesCount:=0;
	//AudioTracksCount:=0;
	media_format:='';
	video_codec:='';
	if DownloadMovieTechnicalInfo then begin

		//barcode
		s2:='<strong>UPC Code</strong>';
		i:=pos(s2, all);
		if i>0 then begin
			j:=MyPos('<br />', all, i+length(s2));
			if j>0 then begin
				s3:=copy(all, i+length(s2), j-i-length(s2));
				s3 := ClearExtraBlankCharacters(RemoveTags(s3));
				//ShowMessage('='+s3+'=');
				barcode:=s3;
			end;
		end;

		//AspectRatio
		s2 := GetStr(all, '<strong>Video</strong><br />', '<br />');
		s2 := ClearExtraBlankCharacters(RemoveTags(s2));
		aspect_ratio := GetStr(s2, ' ', ' ');
		
		//features
		s2 := GetStr(all, '<h3>Features</h3>', '</p>');
		s2 := ReplaceStr(s2, '<br />', #13#10, -1);
		features := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s2)));
		if Pos('features not specified', LowerCase(features))>0 then
			features := '';

		//Subtitles
		s2 := GetStr(all, '<strong>Subtitles</strong>', '<br');
		s2 := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s2)));
		i := Pos(', ', s2);
		while i > 0 do begin
			s3 := copy(s2, 1, i-1);
			delete(s2, 1, i + 1);
			SetSubtitle(s3);
			i := Pos(', ', s2);
		end;
		i := Pos(' and ', s2);
		if i > 0 then begin
			s3 := copy(s2, 1, i-1);
			SetSubtitle(s3);
			delete(s2, 1, i+4);
		end;
		if s2 <> '' then
			SetSubtitle(s2);
		

		//Audio tracks
		s2 := GetStr(all, '<strong>Audio</strong><br />', '</div>');
		i := Pos('<br />', s2);
		while i>0 do begin
			s3 := copy(s2, 1, i-1);
			s3 := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s3)));
			s3 := ParseAudioTrack(s3);
			SetAudioTrack(s3);
			delete(s2, 1, i+5);
			i := Pos('<br />', s2);
		end;

		//Media format
		s2:='<span class=''fontsmall3''><b><nobr>&nbsp;/&nbsp; ';
		i:=pos(s2, all);
		if i>0 then begin
			j:=MyPos('</a></b></nobr></span>', all, i+1);
			if j>0 then begin
				s2:='<a href=';
				i:=MyPos(s2, all, i+1);
				if i>0 then begin
					s3:=copy(all, i, j-i);
					s2:=ClearExtraXCharacters(RemoveTags(s3));
					if s2='DVD-Video' then
						s2:='DVD';
					media_format:=s2;
					//ShowMessage('='+s2+'=');
				end;
			end;
		end;

		//duration
		duration_min:=duration;

		//video codec
		//video_codec:='test';
	end;

	posters_exists:=false;
end;

//returned images links
procedure GetImages;
var
	front_cover_url_back: string;
begin
	if front_cover_url <> '' then
		SetImageName('', front_cover_url, '', 1);
	if back_cover_url <> '' then
		SetImageName('', back_cover_url, '', 2);
end;

//returned link to front cover
function GetFrontCoverURL: string;
var
	res, all, url, s, s2, s3, amazon_url: string;
	i, j: integer;
	front_cover_url_big: string;
begin
	res:=front_cover_url;
	if front_cover_url<>'' then
		SetImageName('', front_cover_url, '', 1);
	result:=res;
end;

//get screenshots
procedure GetScreenshots(url: string);
var
	i, j, frames_count: integer;
	all, s, img_url: string;
begin
	all:=DownloadURL(url);
	frames_count:=0;
	j:=0;
	i:=pos(format('http://cdn3a.dvdempire.org/gen/screenshots/%s_%da.jpg', [movie_code, j]), all);
	while (i>0) and (frames_count<MaxShotsCount) do begin
		img_url:=format('http://cdn3a.dvdempire.org/gen/screenshots/%s_%db.jpg', [movie_code, j]);
		SetImageName('', img_url, '', 3);
		j:=j+1;
		frames_count:=frames_count+1;
		i:=MyPos(format('http://cdn3a.dvdempire.org/gen/screenshots/%s_%da.jpg', [movie_code, j]), all, i+1);
	end;
end;

//get posters
procedure GetPosters(url: string);
var
	i, j: integer;
	all, s: string;
begin
	all:=DownloadURL(url);
	i:=pos('http://posters.imdb.com/', all);
	while i>0 do begin
		j:=MyPos('"', all, i+1);
		if j>0 then begin
			s:=copy(all, i, j-i);
			SetImageName('', s, '', 4);
		end;
		i:=MyPos('http://posters.imdb.com/', all, i+1);
	end;
end;

//get movie site url
function GetMovieSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:='http://www.dvdempire.com/Exec/v4_item.asp?item_id='+code;
end;

//get person site url
function GetPersonSiteURL(code: string): string;
begin
	result:='';
end;

begin

DownloadMovieTechnicalInfo:=false;

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';

  RequestParameters := TStringList.Create();
  RequestParameters.Add('Host=www.dvdempire.com');
  RequestParameters.Add('AcceptLanguage=en-US');
  RequestParameters.Add('Connection=Close'); 
  RequestParameters.Add('useragent=Mozilla/5.0');

end.