const
	script_name='Blu-ray';
	language='English';
	version=17;
	author='BlackStream/Vlad';
	MinProgramBuild=4100;
	Dbg =false;
	PCount = 0;
var
	DownloadMovieBigCover, DownloadMovieShortCast, DownloadMovieFullCast, 
	DownloadMovieBigDescription, DownloadMovieComments, 
	DownloadMovieStudios,	DownloadMovieAwards, DownloadMovieEarnings, 
	DownloadMovieAdditionalInfo, DownloadMovieSeasonsList, DownloadMovieTechnicalInfo: boolean;
	MaxShotsCount, MaxPostersCount: integer;
	TitlesCount: 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, rating: double;
	back_cover_url, front_cover_url: string;
	posters_exists, boxes_exists, screenshots_exists: boolean;
	original_title, mpaa, mpaa_rating: string;
	awards: string;
	resolution, barcode, aspect_ratio, features, media_format, video_codec: string;
	duration_min: integer;
	//SubtitlesCount, AudioTracksCount: integer;

//debug function
function DbgMsg(msg: string): boolean;
begin
	result := true;
	if Dbg then ShowMessage('='+msg+'=') 
	else result := false;
end;

	
function MovieSearch: integer;
var
	i, ii, j, jj, TitlesCount: integer;
	x, xx: integer;
	s, s2, temp, small_cover, year, description, original_title: string;
begin
	s:='';
	TitlesCount:=0;
	i := Pos('<link rel="canonical" href="http://www.blu-ray.com/movies/', all);
	if i > 0 then begin
		j := MyPos('">', all, i+1);
		jj := length('<link rel="canonical" href="http://www.blu-ray.com/movies/');
		title_code := copy(all, i + jj, j-i-jj);
		if title_code<>'' then begin
			SetSearchResult('title', title_code);
			TitlesCount := 1;
		end;
	end;
	i:=pos('Sorry, your search for', all);
	if (all='') or (i>0) then
		// Movie not found!
	else 
	begin
		i:=pos('<h2 class="noline">Search movies (', all);
		if i>0 then
		begin
			temp:=copy(all, i, length(all)-i);
			temp:=RemoveEndLines(temp);
			ii:=Pos('<td width="14"> </td>', temp);
			if ii>0 then 
				temp:=copy(temp,1,ii);
		end;
		
		i := Pos('<tr>', temp);
		while i>0 do begin
			j := MyPos('</tr>', temp, i+1);
			s := copy(temp, i, j-i);
			title := ParseString(s, '<h3>(.*?)</h3>', 1);
			title := DecodeHTML(title);
			title := ReplaceStr(title, ' Blu-ray', '', -1);
			title_code := ParseString(s, '<a href="http://www.blu-ray.com/movies/(.*?)/">', 1);
			small_cover := ParseString(s, 'src="http://images.*?.bluray.com/movies/covers/(.*?).jpg"', 1);
			if small_cover<>'' then
				small_cover := 'http://images.blu-ray.com/movies/covers/' + small_cover + '.jpg';
				
			year := '';
			original_title := ParseString(s, '<br><a href="http://www.blu-ray.com/movies/.*?">(.*?)</a><br>', 1);
			original_title := DecodeHTML(original_title);
			description := ParseString(s, '<small style="color: #666666">(.*?)</small><br>', 1);
			description := RemoveTags(description);
			description := DecodeHTML(description);
			description := ClearExtraBlankCharacters(description);
			
			if title <> '' then begin
				SetSearchResult2(title, title_code, year, original_title, description, small_cover);
				TitlesCount := TitlesCount + 1;
			end;
			delete(temp, 1, j);
			i := Pos('<tr>', temp);
		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, AYear, ABarcode: string): string;
var 
	url: string;
begin
	url:='http://www.blu-ray.com/search/?quicksearch=1&section=bluraymovies&quicksearch_keyword='+MovieName+'&sortby=popularity';
	result:=ReplaceStr(url, ' ', '+', -1);
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;

//url to selected movie page
function GetMovieURL(code: string; images_only: boolean): string;
begin
	result:=format('http://www.blu-ray.com/movies/%s', [code]);
	//title_code := code;
	movie_site_url := result;
end;

//get movie site url
function GetMovieSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:='http://www.blu-ray.com/movies/'+code;
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', 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 5.1 EX', s)>0 then
		result := ReplaceStr(result, 'Dolby Digital 5.1 EX' , 'DD-EX 5.1', -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;
var
	temp, x, s, s2, url2: string;
	i, j, ii, jj, cl, k, l: integer;	
	flReview: boolean;
	function StrClear(Str: string): string;  //string clear function
	begin
		result := RemoveTags(Str);
		result := DecodeHTML(result);
		result := ClearExtraXCharacters(result);
	end;
	
begin
	result := '';
	BasicURL := url; 
	all := DownloadURL(url);
	if all='-1' then
		result := '-1'
	else
		result := all;
	imdb_code := '';
	original_title := '';
	title := '';
	//get movie fix title
	i := Pos('<title>', all);
	if i>0 then 
	begin
		j := MyPos('</title>', all, i+1);
		//ShowMEssage(j);
		if j>0 then 
		begin
			title := copy(all, i+7, j-i-7);
			i := Pos(' Blu-ray', title);
			if i>0 then
			begin
				s := copy(title, 1, i-1);
				title := s;
			end;	
		end;
		s2 := '</h3>&nbsp;(';
		i := pos(s2, all);
		if i>0 then begin
			j := MyPos(')', all, i+1);
			if j>0 then
				year := copy(all, i+length(s2), j-i-length(s2));
		end;
	end;
	//SHowMessage(title);

	//get movie code
	movie_code := ParseString(BasicUrl+'/', 'http://www.blu-ray.com/movies/(.+)/', 1);
	//ger movie site url
	movie_site_url := GetMovieSiteURL(movie_code);

	//get movie site rating
	rating:=0;
	i := Pos('Overall', all);
	if i>0 then
	begin
		i := MyPos('<img src=', all, i+1);
		if i>0 then 
		begin
			i := MyPos('alt="', all, i+1);
			if i>0 then 
			begin
				j := MyPos(' of', all, i+1);
				if j>0 then 
				begin
					s := copy(all, i, j-i);
					s := ParseString(s, 'alt="(.+)', 1);
					s := ClearExtraSpaces(s);

					if length(s)>0 then begin
						i := pos('.', s);
						if i>0 then
							s[i] := DecimalSeparator;
						try
							rating := StrToFloat(s);
						except
						end;
					end;
				end;
			end;	
		end;
	end;		
	//technical info
	resolution := '';
	barcode := '';
	aspect_ratio := '';
	features := '';
	duration_min := 0;
	//SubtitlesCount := 0;
	//AudioTracksCount := 0;
	media_format := 'Blu-ray';
	video_codec := '';
	
(*	//countries 
	i := Pos('</h2><img src="http://images.blu-ray.com/flags/', all);
	if i>0 then begin
		i := MyPos('title="', all, i+1);
		j := MyPos('"', all, i+7);
		s := copy(all, i+7, j-i-7);
		if s<>'' then
			SetCountry(s);
	end;
*)	
	//get movie techmical info
	if DownloadMovieTechnicalInfo then
	begin
		//get video codec
		i := Pos('Video codec: ', all);
		if i>0 then
		begin
			j := MyPos('<br>', all, i+1);
			if j>0 then
			begin
				s := copy(all, i+13,j-i-13);
				video_codec := s;
			end;
		end;	
		//get video resolution
		i := Pos('Video resolution: ', all);
		if i>0 then
		begin
			j := MyPos('<br>', all, i+1);
			if j>0 then
			begin
				s := copy(all, i+18,j-i-18);
				resolution := s;
			end;
		end;	
		//get aspect ratio
		i := Pos('spect ratio: ', all);
		if i>0 then
		begin
			j := MyPos('<br>', all, i+1);
			if j>0 then
			begin
				s := copy(all, i+13,j-i-13);
				aspect_ratio := s;
			end;
		end;	
		//get audiotracks
		s2 := '<div id="longaudio" style="display: none">';
		i := Pos(s2, all);
		if i>0 then
		begin
			j := MyPos(' <a href="', all, i+1);
			if j>0 then
			begin
				x := copy(all, i+length(s2), j-i-length(s2));
				x:=ReplaceStr(x, '<br>', #10, -1)+#10;
				i:=0;
				j := 0;
				repeat
					i := j;
					j := MyPos(#10, x, i+1);
					if j>0 then
					begin
						s := copy(x, i, j-i);
						s := RemoveEndLines(s);
						if s[1]=' ' then
							Delete(s, 1, 1);
						if (s<>'') and (s<>' ') then
						begin
							s := ParseAudioTrack(s);
							SetAudioTrack(s);
							//inc(AudioTracksCount);
						end;	
					end;	
				until (j=0);
			end;
		end;
		//get subtitles
		s2 := '<div id="longsubs" style="display:none">';
		i := Pos(s2, all);
		if i>0 then
		begin
			j := MyPos(' <a href="', all, i+1);
			if j>0 then
			begin
				s := copy(all, i+length(s2), j-i-length(s2));
				s :=  ReplaceStr(s, ', ', #10, -1);
				s := ClearExtraXCharacters(s);
				s := s+#10;
				repeat
					j := Pos(#10, s);
					if j>0 then
					begin
						s2 := copy(s, 1, j-1);
						SetSubtitle(s2);
					end;	
					delete(s, 1, j)	;
				until (j=0);
			end;	
		end;	
		//get dvd featrues
		i := Pos('<span class="subheading">Discs</span>', all);
		if i>0 then
		begin
			j := MyPos('</td>', all, i+1);
			if j>0 then
			begin
				s := copy(all, i, j-i);
				s := ReplaceStr(s, '<span class="subheading">Discs</span>', '', -1);
				s :=  ReplaceStr(s, #10, '', -1);
				s :=  ReplaceStr(s, '<br>', #13#10, -1);
				s := ClearExtraXCharacters(s);
				s := RemoveTags(s);
				features := s;
			end;
		end;
	end;
	//get other information
	i := Pos('<span class="subheading" style="color: #666666">'+#10, all);
	if i>0 then
	begin
		j := MyPos('</span><br><br>', all, i+1);
		if j>0 then 
		begin
			s := copy(all, i, j-i);
			s := ReplaceStr(s, '<span class="subheading" style="color: #666666">'+#10, '', -1);
			s := RemoveTags(s);
	//get movie studio		
			i := Pos(' |',s);
			if i>0 then
			begin
				x := copy(s, 1, i-1);
				j := Pos(' / ', x);
				while j > 0 do begin
					s2 := copy(x, 1, j-1);
					s2 := ClearExtraBlankCharacters(DecodeHTML(s2));
					SetStudio(s2);
					delete(x, 1, j+2);
					j := Pos(' / ', x);
				end;
				SetStudio(x);
			end;	
	//movie duration (minutes)
			x := ParseString(s, '(\d+) min', 1);
			if x<>'' then
			try
				duration := StrToInt(x);
				if DownloadMovieTechnicalInfo then 
					duration_min := duration;
			except
			end;	
	//movie rating MPAA
			x := ParseString(s, 'Rated (.+)', 1);
			i := Pos(' |', x);
			if i>0 then
			begin
				x := copy(x, 1, i-1);
				mpaa := x;
				//mpaa_rating := x; |  ???			
			end;	
		end;
	end;
	//get movie director
	i := Pos('<br>Director', all);
	if i>0 then begin
		j := MyPos('<br>', all, i+1);
		s := copy(all, i, j-i);
		i := Pos('<a href', s);
		while i>0 do begin
			j := MyPos('</a>', s, i+1);
			s2 := copy(s, i, j-i);
			name := RemoveTags(s2);
			name := DecodeHTML(name);
			code :=	ParseString(s2, 'nameid=(\d+)">', 1);
			if name<>'' then
				SetPersonName(name, '', 1, code);
			delete(s, 1, j);
			i := Pos('<a href', s);
		end;		
	end;	
	//get movie actors
	name := '';
	code := '';
	i := pos('<br>Starring:', all);
	if i>0 then
	begin
		if j>0 then
		begin
			j := MyPos(#10, all, i+1);
			s := copy(all, i+14, j-i-14);
			if i>0 then 
			begin
				i := 0;
				j := 0;
				repeat
					i := j;
					j := MyPos(',', s, j+1);
					if j>0 then
					begin
						if i = 0 then
							x := copy(s, i, j-1)
						else
							x := copy(s, i+1, j-i-1);	
						code :=	ParseString(x, 'href="http://www.blu-ray.com/.*?/(\d+)/"', 1);
						name := ParseString(x, 'href="http://www.blu-ray.com/.*?>(.*?)</a>', 1);
						name := RemoveTags(name);
						if name<>'' then
							SetPersonName(name, '', 3, code);
					end;
				until (j=0);
			end;
		end;
	end;
	//get genre list
	k := 0;
	s := GetStr(all, '<h3>Movie appeal', '</table>');
	while (Pos('<tr ', s)>0) do begin
		s2 := GetStr(s, '<tr', '</tr>');
		s2 := GetStr(s2, '>', '</td>');
		s2 := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s2)));
		if s2<>'' then
			SetGenre(s2);
		delete(s, 1, Pos('<tr ', s));
	end;
	
	//get movie descriptions
	i := Pos('Blu-ray Review</h2><br>', all);
	if (i>0) and DownloadMovieBigDescription then begin
		s := '';
		i := MyPos('</small><br><br>', all, i+1);
		j := MyPos('<br><br><br>', all, i+1);
		s := copy(all, i, j-i);
		k := Pos('<center>', s);
		while k>0 do begin
			l := MyPos('</center>', s, k+1);
			delete(s, k, l-k+9);
			k := Pos('<center>', s);
		end;
	end;
	s := ReplaceStr(s, '<br><br>', 'breaks_here', -1);
	s := ReplaceStr(s, #10, '', -1);
	s := RemoveTags(s);
	s := DecodeHTML(s);
	s := ClearExtraBlankCharacters(s);
	if Pos('breaks_here', s) = 1 then
		delete(s, 1, 11);
	s := ReplaceStr(s, 'breaks_here', '<br><br>', -1);
	description := s;
	
	//get front and back covers url
	i := 0;
	i:=Pos('/', movie_code);
	if i>0 then
	begin
		x:=copy(movie_code, i+1, length(movie_code)-1);
		i := Pos('/', x);
		if i>0 then
			Delete(x, i, 1);
		s := '.static-bluray.com/movies/covers/'+x+'_medium.jpg';
		back_cover_url := '.static-bluray.com/movies/covers/'+x+'_back.jpg';
		if Pos(back_cover_url, all)=0 then 
			back_cover_url := ''
		else
			back_cover_url := 'http://images' + back_cover_url;
		s2 := '.static-bluray.com/movies/covers/'+x+'_small.jpg';
		if DownloadMovieBigCover then begin
			front_cover_url := '.static-bluray.com/movies/covers/'+x+'_front.jpg';
			if Pos(front_cover_url, all) = 0 then
				front_cover_url := '.static-bluray.com/movies/covers/'+x+'_large.jpg';
		end
		else
			front_cover_url := '.static-bluray.com/movies/covers/'+x+'_medium.jpg';
		if (Pos(s2, all) = 0) and (Pos(s, all) = 0) and (Pos(front_cover_url, all) = 0) then
			front_cover_url := ''
		else
			front_cover_url := 'http://images' + front_cover_url;
	end;		
end;

//returned images links
procedure GetImages;
	var
	c, i, j: integer;
	image_url, s, s2, x: string;
begin
	if front_cover_url<>'' then
		SetImageName('', front_cover_url, '', 1);
	if DownloadMovieBigCover then	
		if back_cover_url<>'' then
			SetImageName('', back_cover_url, '', 2);	
	
		c := 0;
		i := Pos('.static-bluray.com/reviews/', all);
		while (i>0) and (c < MaxShotsCount) do begin
			j := MyPos('"', all, i+15);
			s2 := copy(all, i-20, j-i+20);
			c := c + 1;
			image_url := ParseString(s2, 'src="(.*?)_tn.jpg', 1);
			if image_url = '' then
				image_url := ParseString(s2, 'src="(.*?).jpg', 1);
			SetImageName('', image_url+'_large.jpg', '', 3);
			delete(all, 1, j);
			i := Pos('.static-bluray.com/reviews/', all);
		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;

//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 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 person site url
function GetPersonSiteURL(code: string): string;
begin
    result:=format('http://www.blu-ray.com/small/%s/', [code]);
end;

begin

end.