const
	script_name='kino-teatr';
	language='Russian';
	version=20;
	author='BlackStream';
	MinProgramBuild=5500;
	Dbg = false;
	PCount = 12;
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;
	t_code, my_code, code: string;
	duration: integer;
	imdb_rating: single;
	rating: string;
	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;
	prefixes: array [1..PCount] of string;
	shots_url, posters_url : string;
	
	
//debug function
function DbgMsg(msg: string): boolean;
begin
	result := true;
	if Dbg then ShowMessage('='+msg+'=') 
	else result := false;
end;

function MovieSearch: integer;
var
	jj, i, j, k, l, TitlesCount: integer;
	s, s2, temp: string;
	original_title, year, description, small_cover, code: string;
begin
	i := Pos('<strong>результат поиска</strong>', all);
	if i>0 then
	begin
		j := MyPos('</td></tr></table', all, i+1);
		if j>0 then
		begin
			s := copy(all, i, j-i);
			j := 0;
			i := Pos('<h3 align=left>', s);
			if i = 0 then
				i := Pos('<div itemscope', s);
			while i>0 do begin
				j := MyPos('<div class="hr">', s, i+1);
				if j = 0 then
					j := MyPos('<div class="separator">', s, i+1);
				if j = 0 then
					j := length(s) + 1;
				s2 := copy(s, i, j-i);
				//title
				title := GetStr(s2, '<strong itemprop="name">', '</strong>');
				//title_code
				temp := GetStr(s2, '<a href="', '>');
				code := ParseString(temp, '/movie/.*?(\d+)/annot/" title', 1);
				//again title
				title := RemoveTags(title);
				title := DecodeHTML(title);	
				
				//year
				year := GetStr(s2, '>Год: ', '</p>');
				year := ClearExtraBlankCharacters(RemoveTags(year));
				//original title
				original_title := '';
				k := Pos(' / ', s2);
				if k>0 then begin
					l := MyPos('</a>', s2, k+1);
					original_title := copy(s2, k+3, l-k-3);
					original_title := RemoveTags(original_title);
					original_title := DecodeHTML(original_title);
				end;
				//description
				description := GetStr(s2, '<p itemprop="description">', '</p>');
				description := RemoveTags(description);
				description := DecodeHTML(description);
				//small cover
				small_cover := GetStr(s2, '<img src="', '"');
				if (small_cover <> '') and (small_cover <> '/img/poster.gif') then
					small_cover := 'http://www.kino-teatr.ru' + small_cover
				else
					small_cover := '';
				if title <> '' then begin
					Inc(TitlesCount);
					SetSearchResult2(title, code, year, original_title, description, small_cover);
				end;
				delete(s, 1, j);
				i := Pos('<h3 align=left>', s);
				if i = 0 then
					i := Pos('<div itemscope', s);
			end;
		end;
	end;
	result := TitlesCount;
end;

//Get search URL by movie name
function GetSearchURLbyName(MovieName, AYear, ABarcode: string): string;
var 
	url: string;
	i, j: integer;
begin
	url := 'http://www.kino-teatr.ru/search/?text='+MovieName+'&movie=1&acter=0&submit=submit';
(*	all := DownloadURLWithReferer(url, 'post');
	i := Pos('По вашему запросу ничего не обнаружено...', all);
	if not(i>0) then
	begin
		i := Pos('<a href="/search/', all);
		if i>0 then
		begin
			j := MyPos('/">', all, i+1);
			if j>0 then
				result := 'http://www.kino-teatr.ru'+copy(all, i+9, j-i-9);
		end;
	end
	else
	result := '-1';
*)
	result := url;
end;

//Download search results from URL
function DownloadSearchURL(url: string): integer;
begin
	all:=DownloadURLWithReferer(url, 'post');
	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:='http://www.kino-teatr.ru/kino/movie/'+code+'/annot/';
	//title_code := code;
	movie_site_url := result;
end;

//parse function
function GetStr(str: String; s1: String; s2: String): String;
var
  I: Integer;
  J: Integer;
begin
  // Вырезает кусок строки между s1 и s2
	Result := '';
	I := Pos(LowerCase(s1), LowerCase(str));
	if I > 0 then
	begin
		J := MyPos(LowerCase(s2), LowerCase(str), I + Length(s1));
		if J > 0 then
  		Result := Copy(str, I + Length(s1), J - I - Length(s1));
	end;
end;

//get movie site url
function GetMovieSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:='http://www.kino-teatr.ru/kino/movie/'+code+'/annot/';
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;

//get person site url
function GetPersonSiteURL(code: string): string;
begin
	result:='http://www.kino-teatr.ru/kino/acter/'+code+'/';
end;

//modify original title to standart
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 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 info
function GetInfo(url: string; images_only: boolean): string;
var
	temp, x, s, s3, url2, s2, roll, descr: string;
	i, j, ii, jj, cl, season, episode: integer;	
	flTitr: boolean;
	EpisodeDescription, EpisodeTitle, seasonnr, episodenr, CastURL, small_photo, cast_page, EpisodeURL, episode_page: String;

	procedure GetPeople(temp, f1, f2: string; role: byte);
	var
			s2:string;
			i, j, k: integer;
	begin
			s2 := f1;
			i := Pos(s2, temp);
			if i>0 then 
				j := MyPos('</p>', temp, i+1)
			else	s2 := f2;	
			i := Pos(s2, temp);
			if i>0 then
			begin
				j := MyPos('</p>', temp, i+1);
				if j>0 then
				begin
					s := copy(temp, i+length(s2), j-i-length(s2)+7);
					s := s+', ';
				end;
				repeat	
					j := MyPos(', ', s, 1);
					if j>0 then 
					begin
						s2 := copy(s, 1, j-1);
						Delete(s, 1, j+1);
						name := removetags(s2);
						code := ParseString(s2, '\/(\d+)\/', 1);
						if Pos(' (', name)>0 then
						begin
							s3 := GetStr(name, ' (', ')');
							name :=ReplaceStr(name, ' ('+s3+')', '', -1);
						end;
						k := Pos('<', name);
						if k>0 then
							delete(name, k, length(name)-k+1);
						if name<>'' then
							SetPersonName(name, '', role, code);
					end;
				until (j=0);
			end;	
	end;
begin
	CastURL := '';
	EpisodeURL := '';
	shots_url := '';
	posters_url := '';
	result := '';
	BasicURL := url; 
	i := Pos('/annot', BasicURL);
	if i>0 then
		delete(BasicURL, i, length(BasicURL) - i + 1);
	all := DownloadURL(url);
	if all='-1' then
		result := '-1'
	else
		result := all;
	imdb_code := '';
	movie_code := ParseString(url, '\/(\d+)\/', 1);
	movie_site_url := GetMovieSiteURL(movie_code);
	my_code := ParseString(all, '<option value="(.+)/'+movie_code+'/annot/"', 1);
	my_code := my_code+'/'+movie_code+'/annot/';
	t_code := ParseString(all, '<option value="/kino/movie/(.+)/'+movie_code+'/annot/"', 1);
	t_code := t_code+'/'+movie_code+'/annot/';
	front_cover_url := 'http://kino-teatr.ru/movie/poster/'+movie_code+'.jpg';
	original_title := '';
	title := '';
	s2 := '<h3><strong>информация о фильме';
	i := Pos(s2, all);
	if i>0 then begin
		if DownloadMovieFullCast and (Pos(movie_code + '/titr', all)>0) then begin
			CastURL := ReplaceStr(url, 'annot', 'titr', -1);
			AddRequestForHTMLPageContent(CastURL, False);
		end;
		if DownloadMovieSeasonsList and (Pos(movie_code + '/series', all)>0) then begin
			EpisodeURL := ReplaceStr(url, 'annot', 'series', -1);
			AddRequestForHTMLPageContent(EpisodeURL, False);
		end;
		if (MaxShotsCount > 0) and (Pos(movie_code + '/foto', all)>0) then begin
			shots_url := ReplaceStr(url, 'annot', 'foto', -1);
			AddRequestForHTMLPageContent(shots_url, False);
		end;
		if (MaxPostersCount > 0) and (Pos(movie_code + '/poster', all)>0) then begin
			posters_url := ReplaceStr(url, 'annot', 'poster', -1);
			AddRequestForHTMLPageContent(posters_url, False);
		end;
		j := MyPos('</td></tr></table>', all, i+1);
		if j>0 then begin
			temp := copy(all, i+length(s2), j-i-length(s2));
			//get title		
			s := ParseString(temp, '<h2 align="left">(.+)</h2>', 1);
			s := copy(s, 1, length(s));
			i := Pos(' / ', s);
			if i>0 then begin
				title := copy(s, 1, i-1);
				title := RemoveTags(title);
				Delete(s, 1, i+2);
				s := MovePrefixLeft(s);
				s := RemoveTags(s);
				original_title := DecodeHTML(s);
			end
			else begin
				title := s;
				title := RemoveTags(title);
				title := DecodeHTML(title);
			end;
			//get year <p>Год: <span class="red">2008</span></p>
			year := GetStr(temp, '<p>Год: ', '</p>');
			year := ClearExtraBlankCharacters(RemoveTags(year));
			year := ParseString(year, '^(\d+)', 1);
			//get director or directors
			GetPeople(temp, ' align="left">Режиссеры: ', ' align="left">Режиссер: ', 1);					
			//get writer or writers
			GetPeople(temp, ' align="left">Сценарист: ', ' align="left">Сценаристы: ', 2);			
			//get compositor or compositors
			GetPeople(temp, ' align="left">Композитор: ', ' align="left">Композиторы: ', 4);			
			//get actors
			flTitr := false;
			if DownloadMovieFullCast then begin
				cast_page := GetHTMLPageContentFromRequest(CastURL);
				cast_page := GetStr(cast_page, '<h3><strong>актеры и роли</strong></h3>', '<div class="separator">');
				i := Pos('<tr itemprop="actors"', cast_page);
				if i>0 then
					flTitr := True;
				while i>0 do begin
					delete(cast_page, 1, i-1);
					j := Pos('</tr>', cast_page);
					s := copy(cast_page, 1, j-1);
					small_photo := GetStr(s, '<img src="', '"');
					if (small_photo<>'') and (small_photo<>'/img/pv.gif') then begin
						small_photo := ReplaceStr(small_photo, 'pv_', '', -1);
						small_photo := 'http://www.kino-teatr.ru' + small_photo;
					end
					else
						small_photo := '';
					s2 := GetStr(s, '<a href="', '"');
					code := ParseString(s2, '\/(\d+)\/bio', 1);
					if code = '' then
						code := ParseString(s2, '\/(\d+)\/works', 1);
					name := DecodeHTML(RemoveTags(GetStr(s, '<strong itemprop="name">', '</strong>')));
					if name = '' then
						name := DecodeHTML(RemoveTags(GetStr(s, ' itemprop="name">', '</strong>')));
					roll := DecodeHTML(RemoveTags(GetStr(s, 'class="comment"><strong>', '</strong>')));
					if name<>'' then
						SetPersonName(name, roll, 3, code, small_photo);
					delete(cast_page, 1, j);
					i := Pos('<tr itemprop="actors"', cast_page);
				end;
			end;
			if not (DownloadMovieFullCast or flTitr) then begin
				GetPeople(temp, '<p class="titr">Актеры: ', 'class="titr">Актеры: ', 3);
			end;
			//get description
			s := GetStr(temp, '<p itemprop="description">', '</p>');
			s :=  ClearExtraXCharacters(s);
			s := RemoveTags(s);
			s := DecodeHTML(s);
			description := s;
			//get genres
			s2 := GetStr(temp, '<p align="left">Жанр: ', '</p>');
			s2 := RemoveTags(s2);
			repeat
				j := Pos(', ', s2);
				if j>0 then begin
					s := copy(s2, 1, j-1);
					delete(s2, 1, j+1);
					if s<>'' then
						SetGenre(s);
				end
				else if s2<>'' then
					SetGenre(s2);
			until (j = 0);
			//get country
			s := GetStr(temp, '<p align="left">Страна: ', '</p>');
			s := RemoveTags(s);
			repeat
				j := Pos(', ', s);
				if j>0 then begin
					s2 := copy(s, 1, j-1);
					delete(s, 1, j+1);
					if s2<>'' then
						SetCountry(s2);
				end
				else if s<>'' then
					SetCountry(s);
			until (j=0);
			//get studios
			s := GetStr(temp, '<p align="left">Производство: ', '</p>');
			s := RemoveTags(s);
			if s<>'' then
				s := s + ', ';
			repeat
				j := Pos(', ', s);
				if j>0 then	begin
					s2 := copy(s, 1, j-1);
					Delete(s, 1, j+1);
					s2 := DecodeHTML(s2);
					if Pos(' по заказу', s2)>0 then
						s2 := copy(s2, 1, Pos(' по заказу', s2)-1);
					if s2[1]='"' then
						s2 := copy(s2, 2, length(s2)-2);
					if s2 = 'Киностудия СТВ,Ленфильм' then begin
						SetStudio('СТВ');
						SetStudio('Ленфильм');
					end
						else SetStudio(s2);
				end;
			until (j=0);
			
			
			//get awards
			if DownloadMovieAwards then begin
				s := GetStr(temp, '<strong>награды, номинации, фестивали</strong>', '</span>');
				s := DecodeHTML(s);
				awards := RemoveTags(s);
				i := Pos('Сайт:', awards);
				if i>0 then
					delete(awards, i, length(awards) - i + 1);
			end;
			
			//box office
			if DownloadMovieEarnings then begin
				s := GetStr(all, '<strong>бокс-офис</strong>', '</table>');
				s := ReplaceStr(s, '<div class="separator">', #13#10, -1);
				s := ReplaceStr(s, ':', ': ', -1);
				s := RemoveTags(s);
				s := DecodeHTML(s);
				salary := ClearExtraBlankCharacters(s);
			end;
			
		end;
		
		//серии
		if DownloadMovieSeasonsList then begin
			episode_page := GetHTMLPageContentFromRequest(EpisodeURL);
			i := Pos('<div itemprop="episodes"', episode_page);
			while i>0 do begin
				delete(episode_page, 1, i);
				i := Pos('</div>', episode_page);
				temp := copy(episode_page, 1, i-1);
				s := GetStr(temp, '<strong itemprop="episodeNumber">', '</strong>');
				s2 := ParseString(s, '(\d+)', 1);
				episode := 1;
				try
					episode := StrToInt(s2);
				except
				end;
				EpisodeTitle := GetStr(temp, '<strong itemprop="name">', '</strong>');
				EpisodeTitle := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(EpisodeTitle)));
				EpisodeDescription := GetStr(temp, '<p itemprop="description">', '</p>');
				j := Pos('<a ', EpisodeDescription);
				if j>0 then
					delete(EpisodeDescription, j, length(EpisodeDescription)-j+1);
				EpisodeDescription := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(EpisodeDescription)));
				if EpisodeTitle <> '' then
					SetEpisode(1, episode, EpisodeTitle, EpisodeDescription, '', '');
				delete(episode_page, 1, i);
				i := Pos('<div itemprop="episodes"', episode_page);
			end;
		end;

	end;
end;

function GetTextBetween(fromStr, str1, str2: string): string;
var
	i, j: integer;
begin
	Result := '';
	if str1 = '' then
		i := 1
	else
		i := pos(str1, fromStr);
	if str2 = '' then
		j := Length(fromStr) + 1
	else
		j := MyPos(str2, fromStr, i+length(str1));
	if (i>0)and(j>0) then begin
		i := i + length(str1);
		Result := copy(fromStr, i, j-i);
	end;
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);
	i := pos(' [', name);
	if i>0 then
		name := copy(name, 1, i-1);
	Result := name;
end;

function GetFrontCoverURL2: string;
var
	res, all, url, s, s2, s3, amazon_url: string;
	i, j, frames_count, k: integer;
	item_url: string;
	image_data, image_height, image_width, image_url: string;
	frame_urls: array [1..100] of string;
	int_year: Word;
	year_prew, year_next, title: string;
	valid_year: boolean;
begin
	title:=original_title;
	res:=front_cover_url;
	amazon_url:='';
	if DownloadMovieBigCover then begin
  	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
  	frames_count := 0;
  	i:=pos('<Item>', all);
  	if year<>'' then begin
  		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 := GetTextBetween(s2, '<Title>', '</Title>');
  				s3 := ClearBrackets(s3);
  				s3 := DecodeHTML(s3);
  				if s3<>'' then 
  				begin
  					if (UpperCase(title) = UpperCase(s3)) then
  					begin
  						valid_year := true;
  						if pos('<TheatricalReleaseDate>', s2) > 0 then
  						begin
  							int_year := StrToInt(year);
  							year_prew := IntToStr(int_year - 1);
  							year_next := IntToStr(int_year + 1);
  							valid_year := false;
  							valid_year := pos('<TheatricalReleaseDate>'+year, s2) > 0;
  							valid_year := valid_year or (pos('<TheatricalReleaseDate>'+year_prew, s2) > 0);
  							valid_year := valid_year or (pos('<TheatricalReleaseDate>'+year_next, s2) > 0);						
  							year_prew := IntToStr(int_year - 2);
  							year_next := IntToStr(int_year + 2);
  							valid_year := valid_year or (pos('<TheatricalReleaseDate>'+year_prew, s2) > 0);
  							valid_year := valid_year or (pos('<TheatricalReleaseDate>'+year_next, s2) > 0);						
  						end;
  						if valid_year then
  						begin
  							s := '';
  							frames_count := 0;
  							repeat
  								image_data := GetTextBetween(s2, '<LargeImage>', '</LargeImage>');
  								image_url := GetTextBetween(image_data, '<URL>', '</URL>');
  								image_height := GetTextBetween(image_data, '<Height','</Height>');
  								image_height := GetTextBetween(image_height, '>','');
  								image_width := GetTextBetween(image_data, '<Width','</Width>');
  								image_width := GetTextBetween(image_width, '>','');
  								try
  									if (image_height <> '0') and ((StrToInt(image_width) / StrToInt(image_height)) > 1.2) then 
  									begin
  										for k := 1 to frames_count do
  											if frame_urls[k] = image_url then break;
  										if (frames_count = 0) or (frame_urls[k] <> image_url) then begin
  											frames_count := frames_count + 1;
  											frame_urls[frames_count] := image_url;
  										end;
  									end
  									else if amazon_url = '' then
  										amazon_url := image_url;
  								except
  									//Wrong XML format!
  								end;
  								delete(s2, 1, 25 + length(image_data));
  							until (image_data = '') or (frames_count = MaxShotsCount);
  						end;
  					end; //if
  				end; //if
  			end; //if
  			delete(all, 1, j);
  			i := Pos('<Item>', all);
  		end; //while
  	end; //if year<>''
	end;

	if amazon_url<>'' then   // front-cover from amazon
		SetImageName('', amazon_url, '', 1);
	if front_cover_url<>'' then // front-cover from movie site
		SetImageName('', front_cover_url, '', 1);
	Result:=amazon_url;
	//Showmessage(title);
end;

procedure GetPosters;
var
	i, j, img_cnt: Integer;
	temp, s: String;
begin
	img_cnt := 0;
	temp := GetHTMLPageContentFromRequest(posters_url);
	i := Pos('<h3><strong>постеры фильма</strong></h3>', temp);
	if i>0 then
		delete(temp, 1, i);
	i := Pos('<img src="/movie/poster/', temp);
	while (i>0) and (img_cnt < MaxPostersCount) do begin
		delete(temp, 1, i-1);
		i := Pos('" ', temp);
		s := copy(temp, 11, i-11);
		s := ReplaceStr(s, '/pv_', '/', -1);
		s := 'http://www.kino-teatr.ru'+s;
		SetImageName('', s, '', 4);
		delete(temp, 1, i);
		img_cnt := img_cnt + 1;
		i := Pos('<img src="/movie/poster/', temp);		
	end;
end;

//returned images links
procedure GetImages;
var
	url, temp, s, front_cover_url_back: string;
	c, i, j, img_cnt, page: integer;
begin
	GetFrontCoverURL2;
	if MaxPostersCount > 0 then
		GetPosters;
	img_cnt := 0;
	if MaxShotsCount > 0 then begin
		temp := GetHTMLPageContentFromRequest(shots_url);
		i := Pos('<img src="/movie/kadr/', temp);
		while (i>0) and (img_cnt < MaxShotsCount) do begin
			delete(temp, 1, i-1);
			i := Pos('" ', temp);
			s := copy(temp, 11, i-11);
			s := ReplaceStr(s, '/pv_', '/', -1);
			s := 'http://www.kino-teatr.ru'+s;
			SetImageName('', s, '', 3);
			delete(temp, 1, i);
			img_cnt := img_cnt + 1;
			i := Pos('<img src="/movie/kadr/', temp);
		end;
	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.