const
	script_name='kinopoisk';
	language='Russian';
	version=191;
	author='Alex';
	MinProgramBuild=6200;
	PCount = 14;
	EMPTY_PERSON_IMAGE_URL = 'http://st.kinopoisk.ru/images/no-poster.gif';
	
	//default settings
	DL_TMDB_POSTERS = 1;
	DL_TMDB_BACKDROPS = 0;
	DL_TVDB_DESCRIPTIONS = 0;
	DL_TVDB_EPISODES = 1;
	DL_TVDB_ENG_DESC = 0;
	DL_TVDB_POSTERS = 1;
	DL_TVDB_FANART = 0;
	NO_SMALL_COVER = 1;
	NEVER_USE_AMAZON = 0;
	NO_AMAZON_COVER_IF_BIG_AVAILABLE = 1;
	ALWAYS_USE_AMAZON = 0;
	DL_BIG_KINOPOISK_COVER = 1;

var
	DownloadMovieBigCover, DownloadMovieShortCast, DownloadMovieFullCast, 
	DownloadMovieBigDescription, DownloadMovieComments, 
	DownloadMovieStudios,	DownloadMovieAwards, DownloadMovieEarnings, 
	DownloadMovieAdditionalInfo, DownloadMovieSeasonsList: boolean;
	DownloadMovieLinks: Boolean;
	NoVideosInSeries: Boolean;
	MaxShotsCount, MaxPostersCount: integer;
	// Fade: flags for download seasons/episodes covers 
	DownloadSeasonsCovers: Boolean;
	DownloadEpisodesCovers: Boolean;
	// 10.11.2010
	MaxTrailersCount, MaxBackdropsCount: Integer;
	DownloadedPersonPhotosForMovie: Integer;
	title, MovieName, MovieYear, year, director, name, character, BasicURL, country, description, salary, awards, media_type: string;
	movie_code, movie_site_url, title_code{?}, imdb_code: string;
	titles_count: integer;
	director_code, code: string;
	directors_count, writers_count, actors_count, genres_count: integer;
	duration: integer;
	Tagline: string;  
	imdb_rating, rating: double;
	front_cover_url: string;
	posters_exists: boolean;
	original_title, mpaa, mpaa_rating: string;
	prefixes: array [1..PCount] of string;
	is_frames_present, is_posters_present, flEpisodes, last_time, EpisodesDownloading, PostersDownloading, BackdropsDownloading, ShotsDownloading: boolean;
	f: TForm;
	b: TButton;
	edUserName, edPassword, edURL: TEdit;
	labCaption, labCaption2, labUserName, labPassword: TLabel;
	monthes: array [1..12] of string;

	resolution, barcode, aspect_ratio, features, media_format, video_codec: string;
	duration_min: integer;
	subtitles, AudioTracks: array of string;
	SubtitlesCount, AudioTracksCount: integer;
	flUseTMDB: boolean;
	tmdb_code, tvdb_code: string;
	UseTMDBPosters, UseTMDBSnapshots, DownloadTVDBEpisodeDescriptions, DownloadTVDBEpisodes, DownloadTVDBEnglishDesc, DownloadSeasonPosters, DownloadEpisodeImages, UseTVDBPosters, UseTVDBFanart: integer;
	flEpisodesTitle, FoundBigKinopoiskPoster, TVDBNotFound, TVDBDecided: boolean;
	TickCount: Cardinal;

	GlobalMyPos: string;
	RequestParameters, EpisodeURLs: TStringList;  
	LatinTitle: String;

function MyPosGlobal(const SubStr: string; Offset: Cardinal = 1): Integer;
var
  I,X: Integer;
  Len, LenSubStr: Integer;
begin
  if Offset = 1 then
    Result := Pos(SubStr, GlobalMyPos)
  else
  begin
    I := Offset;
    LenSubStr := Length(SubStr);
    Len := Length(GlobalMyPos) - LenSubStr + 1;
    while I <= Len do
    begin
      if GlobalMyPos[I] = SubStr[1] then
      begin
        X := 1;
        while (X < LenSubStr) and (GlobalMyPos[I + X] = SubStr[X + 1]) do
          Inc(X);
        if (X = LenSubStr) then
        begin
          Result := I;
          exit;
        end;
      end;
      Inc(I);
    end;
    Result := 0;
  end;
end;


function RemoveAllBadChars(text: String): String;
var
	i: Integer;
begin
	i := 0;
	while i<=Length(text) do begin
		if ord(text[i]) in [1..20] then
			delete(text, i, 1)
		else
			i := i + 1;
	end;
	result := text;
end;

function MovieSearch: integer;
var
	i, j, ii, jj, k, l: integer;
	title, code, year, description, small_cover, original_title, s, s2: string;
begin
  TickCount := 0;//GetTickCount();
	titles_count:=0;
	//один результат, загружается страница фильма
	if not(pos('<title>Результаты поиска', all)>0) then begin
		code:=ParseString(all, 'id_film = (\d+); </script>', 1);
		if code <> '' then begin
			SetSearchResult('title', code);
			titles_count:=1;
		end;
	end
	else begin

		i:=pos('К сожалению, по вашему запросу ничего не найдено', all);
		if (all='') or (i>0) then
			//Фильм не найден!
		else 
		begin
			i:=pos('<title>Результаты поиска',all);
			if i>0 then
			begin
				s:='';
				i:=pos('<p class="pic"><a href="', all);
				while (i>0) do begin
					j := MyPos('</div>', all, i+1);
					s := copy(all, i, j-i);
					code:=ParseString(s, '<p class="pic"><a href="/level/1/film/(\d+)/', 1);
					if code = '' then
						code:=ParseString(s, '<p class="pic"><a href="http://www.kinopoisk.ru/level/1/film/(\d+)/', 1);
					title:=ParseString(s, '<p class="name">(.*?)</a> <span', 1);
					if title = '' then
						title := ParseString(s, '<p class="name">(.*?)</a>', 1);
					title:=RemoveTags(title);
					title:=DecodeHTML(title);
					title:=ClearExtraSpaces(title);

					year := ParseString(s, '<span class="year">(\d+)</span></p>', 1);
					
					original_title := '';
					k := Pos('<span class="gray">', s);
					if k>0 then begin
						l := MyPos('</span>', s, k+1);
						s2 := copy(s, k, l-k);
						original_title := ParseString(s2, '"gray">(.*?), \d+ мин', 1);
						original_title := DecodeHTML(original_title);
					end;
					
					
					small_cover := ParseString(s, 'title="/images/(.*?)" alt="', 1);
					if (small_cover <> '') and (Pos('no-poster', small_cover)=0) then
						small_cover := 'http://www.kinopoisk.ru/images/' + small_cover;
					
					description := '';
					if l>0 then begin
						delete(s, 1, l-1);
						description := RemoveTags(s);
						description := DecodeHTML(description);
						description:=ReplaceStr(description, #10, ' ', -1);
						description := ClearExtraSpaces(description);
						description := RemoveAllBadChars(description);
					end;

					titles_count:=titles_count+1;
					SetSearchResult2(title, code, year, original_title, description, small_cover);
					delete(all, 1, j);
					if MovieYear = '' then
						i:=pos('<p class="pic"><a href="', all)
					else
						i:=0;
				end;
			end
			else
			begin
				i:=pos('<title>',all);
				j:=pos('</title>',all);
				if (i>0)and(j>0) then
				begin
					i:=i+7;
					title := copy(all,i,j-i);
					title := DecodeHTML(title);
					title := RemoveTags(title);
					title := ClearExtraSpaces(title);
					i := Pos('/level/111/film/',all);
					if i>0 then
					begin
						i := i + 16;
						j := MyPos('/',all,i+1);
						code := copy(all,i,j-i);
					end;
					
					titles_count := titles_count + 1;
					SetSearchResult(title, code);
				end;
			end;
			{}
		end;
	end;
	result:=titles_count;
end;


function GetPersonURL(code: string; images_only: boolean): string;
begin
	if images_only then
		result:=format('http://www.kinopoisk.ru/level/1/film/%s/', [code])
	else
		result:=format('http://www.kinopoisk.ru/level/1/film/%s/', [code])
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;
	result:=res;
end;

//Get search URL by movie name
function GetSearchURLbyName(MovieName, AYear, ABarcode: string): string;
var
	url: string;
begin
	MovieYear := AYear;
	MovieName := ClearExtraBlankCharacters(MovieName);
	//MovieName:=ReplaceStr(MovieName, ' ', '+', -1);	
	MovieName := EncodeURL(MovieName, 'WINDOWS-1251');
	url:=format('http://www.kinopoisk.ru/index.php?level=7&from=forma&result=adv&m_act%%5Bfrom%%5D=forma&m_act%%5Bwhat%%5D=content&m_act%%5Bfind%%5D=%s&m_act%%5Bcountry%%5D=&m_act%%5Byear%%5D=%s&m_act%%5Bgenre%%5D=&m_act%%5Bcontent_find%%5D=&m_act%%5Bfilm%%5D=&m_act%%5Bsex%%5D=', [MovieName, AYear]);
	result:=url;
end;

//Download search results from URL
function DownloadSearchURL(url: string): integer;
begin
	//all:=DownloadURL(url);
	//all:=DownloadURLWithReferer(url, 'http://s.kinopoisk.ru');
  TickCount := 0;//GetTickCount();
	all:=DownloadURLWithReferer(url, 'http://s.kinopoisk.ru/index.php', True, RequestParameters);
	//SaveLog(all);
	if pos('Если вы видите эту страницу', all)>0 then
		all:=DownloadURL(url, True, RequestParameters);

	//если требуется авторизация
	if GetResponseCode=403 then
  begin
		SiteLogin;
		all:=DownloadURL(url, True, RequestParameters);
	end;

	if all='-1' then
		result:=-1
	else
		result:=MovieSearch;
end;

function GetMovieURL(code: string; images_only: boolean): string;
begin
	result := format('http://www.kinopoisk.ru/level/1/film/%s/', [code]);
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 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 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);
    all := GetHTMLPageContentFromRequest(url);
    TickCount := 0;//GetTickCount();
  	//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)) or (flEpisodes) then
  					begin
  						valid_year := true;
  						if (pos('ReleaseDate>', s2) > 0) and (not flEpisodes) then
  						begin
  							int_year := StrToInt(year);
  							year_prew := IntToStr(int_year - 1);
  							year_next := IntToStr(int_year + 1);
  							valid_year := false;
  							valid_year := pos('ReleaseDate>'+year, s2) > 0;
  							valid_year := valid_year or (pos('ReleaseDate>'+year_prew, s2) > 0);
  							valid_year := valid_year or (pos('ReleaseDate>'+year_next, s2) > 0);						
  							year_prew := IntToStr(int_year - 2);
  							year_next := IntToStr(int_year + 2);
  							valid_year := valid_year or (pos('ReleaseDate>'+year_prew, s2) > 0);
  							valid_year := valid_year or (pos('ReleaseDate>'+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);
	Result:=amazon_url;
end;

//save front cover to file
function SaveFrontCover(url, FileName: string): boolean;
var
	fs: TFileStream;
	s, referer: string;
	i: integer;
begin
	i := length(url);
	repeat dec(i) until (i=0)or(url[i] = '/');
	if i=0 then 
		exit;
	referer := copy(url, 1, i);

	//referer:='post';

	s := DownloadURLWithReferer(url, referer, False, RequestParameters);
	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 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 RemoveCharacter(text: string; char_code: integer): string;
var
	i: integer;
begin
	i:=length(text);
	while i>0 do begin
		if (ord(text[i])=char_code) then
			delete(text, i, 1);
		i:=i-1;
	end;
	Result:=text;
end;

function ReplaceTagWithChar(text, html_tag: string; char_code: integer): string;
var
	i, j: integer;
begin
	j:=0;
	i:=Pos(html_tag, text);
	while i>j do begin
		text[i]:= Chr(char_code);
		text[i+1]:='<';
		j:=i;
		i:=MyPos(html_tag, text, i+1);
	end;
	Result:=text;
end;

function GetPersonImageURL(ACode: string): string;
begin
	if RegReadInteger('KinopoiskDlBiggerPhoto', 1) = 1 then
		Result := Format('http://st3.kinopoisk.ru/images/actor_iphone/iphone360_%s.jpg', [ACode])
	else
		Result := Format('http://st3.kinopoisk.ru/images/actor/%s.jpg', [ACode]);
end;

procedure ExtractPeopleFull(text: string; mode: integer);
var
	i, j, k, pic_cnt, added_persons_cnt: Integer;
	s2, name, code, character, picture_url: string;
begin
	pic_cnt := 0;
	added_persons_cnt := 0;
	i := Pos('<div class="actorInfo"', text);
	while (i>0) and (added_persons_cnt < MaxPersonsCount) do begin
		j:=MyPos('<div class="clear"></div>', text, i+1);
		s2:=copy(text, i, j-i);
		code := ParseString(s2, '<a href="/level/4/people/(\d+)/', 1);
		if code = '' then
			code := ParseString(s2, '<a href="/name/(\d+)/', 1);
		name := GetStr(s2, '<div class="name">', '</a>');
		name := DecodeHTML(RemoveTags(name));
		if (mode <> 3) and (pic_cnt > 0) or (Pos('/images/no-poster.gif', s2) > 0) then
			picture_url := ''
		else begin
			picture_url := GetPersonImageURL(code);
			pic_cnt := pic_cnt + 1;
		end;
		character := '';
		if mode = 3 then begin
			character := GetStr(s2, '>... ', '<');
			character := RemoveTags(character);
			character := DecodeHTML(character);
			character := ClearExtraSpaces(character);
			k := Pos(' (', character);
			if k>0 then
				delete(character, k, length(character)-k+1);
			if character<>'' then
				if character[length(character)] = ',' then
					delete(character,length(character),1);
		end;
		if name<>'' then begin
			SetPersonName(name, character, mode, code, picture_url);
			Inc(added_persons_cnt);
		end;
		delete(text, 1, i);
		i := Pos('<div class="actorInfo"', text);
	end;
end;

procedure ExtractPeople(text: string; mode: integer);
var
	i, j, pic_cnt, added_persons_cnt: Integer;
	s2, name, code, picture_url: string;
begin
	pic_cnt := 0;
	added_persons_cnt := 0;
	i := Pos('<a href="/level/4/people/', text);
	if i = 0 then
		i := Pos('<a href="/name/', text);
	while (i>0) and (added_persons_cnt < MaxPersonsCount) do begin
		j:=MyPos('</a>', text, i+1);
		s2:=copy(text, i, j-i);
		code := ParseString(s2, '<a href="/level/4/people/(\d+)/', 1);
		if code = '' then
			code := ParseString(s2, '<a href="/name/(\d+)/', 1);
		name := DecodeHTML(RemoveTags(s2));
		if (mode <> 3) and (pic_cnt > 0) then
			picture_url := ''
		else begin
			picture_url := GetPersonImageURL(code);
			pic_cnt := pic_cnt + 1;
		end;
		if name<>'' then begin
			SetPersonName(name, '', mode, code, picture_url);
			Inc(added_persons_cnt);
		end;
		delete(text, 1, j);
		i := Pos('<a href="/level/4/people/', text);
		if i = 0 then
			i := Pos('<a href="/name/', text);
	end;
end;

procedure ShowTickCount(ADesc: string);
begin
  TickCount := 0;//GetTickCount();
end;


function ParsePersonImageURLFromPersonInfo(APersonInfo: string): string;
const
  NOCOVER_TEMPLATE = 'no-poster';
  TITLE_TEMPLATE_SEARCH = 'title="';
  IMAGE_TEMPLATE_SEARCH = TITLE_TEMPLATE_SEARCH + '/images/';
var
  PosStart: integer;
  PosEnd: integer;
begin
  Result := '';
  PosStart := Pos(IMAGE_TEMPLATE_SEARCH, APersonInfo);
  PosEnd := MyPos('"', APersonInfo, PosStart + Length(IMAGE_TEMPLATE_SEARCH));
  if ((PosStart > 0) and
      (PosEnd > 0)) then
  begin
    PosStart := PosStart + Length(TITLE_TEMPLATE_SEARCH);
    Result := Copy(APersonInfo, PosStart, PosEnd - PosStart);
    if (Pos('no-poster', Result) > 0) then
      Result := '';
  end;
  // recieve real URL to image
  if (Result <> '') then
    Result := Format('http://st3.kinopoisk.ru%s', [Result]);
end;

function ExtractAwards(text: String): String;
var
	i, j: Integer;
	s, temp, name, status, subj: String;
begin
	name := GetStr(text, '<b><a href="/awards/', '</b>');
	name := GetStr(name, '>', '<');
	name := DecodeHTML(name);
	Result := name;
	i := Pos('<tr><td class="news" style="padding: 10px; color:', text);
	while i>0 do begin
		s := GetStr(text, '<tr><td class="news" style="padding: 10px; color:', '</tr>');
		delete(text, 1, i);
		i := Pos('<tr><td class="news" style="padding: 10px; color:', text);
		status := RemoveTags(DecodeHTML(GetStr(s, '<b>', '</td>')));
		Result := Result + '<br>' + status;
		j := Pos('<li class="trivia">', text);
		subj := '';
		while (j > 0) and ((j < i) or (i = 0)) do begin
			temp := GetStr(text, '<li class="trivia">', '</li>');
			temp := ClearExtraBlankCharacters(DecodeHTML(RemoveSpacesInText(RemoveTags(temp))));
			temp := ReplaceStr(temp, #10, '', -1);
			if (temp <> '') and (subj <> '') then
				subj := subj + '<br>';
			subj := subj + temp;
			delete(text, 1, j);
			j := Pos('<li class="trivia">', text);
			i := Pos('<tr><td class="news" style="padding: 10px; color:', text);
		end;
		if subj <> '' then
			Result := Result + '<br>' + subj;
	end;
end;

function GetInfo(url: string; images_only: boolean): string;
var
	s, s2, s3, keyword, money: string;
	i, j, kol, season, episode, k, k2, pic_cnt: integer;
	AirDate, EpisodeTitle, EpisodeIMDB, EpisodeDescription, day, month, ayear, picture_url, temp: string;
	awards_exist, backdrops_exist: boolean;
  TrailerURL: string;
  RefererURL: string;
  ImageURL, TempURL, TriviaURL: string;
  ActorsURL: string;
  sl: TStringList;
const
	MyQuotes = ['»', '«'];
begin
	TickCount := 0;//GetTickCount();
	LatinTitle := '';
	result:='';
	TVDBNotFound := False;
	if DownloadTVDBEpisodes = 1 then
		TVDBDecided := False
	else
		TVDBDecided := True;
	
	EpisodeURLs := TStringList.Create;
	UseTMDBSnapshots:=RegReadInteger('KinopoiskUseTmdbBackdrops', DL_TMDB_BACKDROPS);
	UseTVDBFanart:=RegReadInteger('KinopoiskUseTvdbFanart', DL_TVDB_FANART);

	flEpisodesTitle:=false;
	EpisodesDownloading := False;
	movie_code := ParseString(url, 'http://www.kinopoisk.ru/level/1/film/(\d+)/', 1);
	movie_site_url:=GetMovieSiteURL(movie_code);
	// Fade - add requests for multi-thread downloading
	RefererURL := 'http://www.kinopoisk.ru/level/1/film/' + movie_code + '/';
	
	TriviaURL := 'http://www.kinopoisk.ru/handler_info.php?obj_type=film&obj_id=' + movie_code;

  if (DownloadMovieFullCast) then
  begin
    ActorsURL := 'http://www.kinopoisk.ru/film/'+movie_code+'/cast/?start_list=30000';
    AddRequestForHTMLPageContent(ActorsURL, True, RefererURL);
    //AddRequestForHTMLPageContent('http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/director/', True, ActorsURL);
    //AddRequestForHTMLPageContent('http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/composer/', True, ActorsURL);
    //AddRequestForHTMLPageContent('http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/writer/', True, ActorsURL);
  end;

	if DownloadMovieStudios then
    AddRequestForHTMLPageContent('http://www.kinopoisk.ru/level/91/film/'+movie_code+'/', True, RefererURL);
  if DownloadMovieAwards then
    AddRequestForHTMLPageContent('http://www.kinopoisk.ru/level/94/film/'+movie_code+'/', True, RefererURL);
  if (MaxTrailersCount > 0) then
    AddRequestForHTMLPageContent('http://www.kinopoisk.ru/film/'+movie_code+'/video/', True, RefererURL);

	

	//SiteLogin;
	//all:=DownloadURL(url);

	//all:=DownloadURLWithReferer(url, 'http://s.kinopoisk.ru');
	all:=DownloadURLWithReferer(url, 'http://s.kinopoisk.ru/index.php', True, RequestParameters);

	//SaveLog(all);

	if pos('Если вы видите эту страницу', all)>0 then
		all:=DownloadURL(url+'sr/1/', True, RequestParameters);

	//если требуется авторизация
	if GetResponseCode=403 then begin
		SiteLogin;
		all:=DownloadURL(url, True, RequestParameters);
	end;
	if all='-1' then begin
		result:='-1';
		exit;
	end
	else
		result:=all;
	imdb_code := '';
	
   // movies links
	if (DownloadMovieLinks) and (Pos('film/' + movie_code + '/other', all) > 0) then
		AddRequestForHTMLPageContent('http://www.kinopoisk.ru/level/90/film/'+movie_code+'/', True, RefererURL);
 
	//if (DownloadMovieAdditionalInfo) and (pos('Знаете ли вы, что...</td>', all)>0) then
		//AddRequestForHTMLPageContent(TriviaURL, True, RefererURL, '', RequestParameters);

	is_frames_present := false;
	if (pos('level/13/film/' + movie_code, all) > 0) or (Pos('film/' + movie_code + '/stills/', all) > 0) then
		is_frames_present := true;

	//16.05.10
	is_posters_present := false;
	if (pos('level/17/film/' + movie_code, all) > 0) or (Pos('film/' + movie_code + '/posters/', all) > 0) then
		is_posters_present := true;
		
	//backdrops kinopoisk
	backdrops_exist := false;
	if (pos('level/12/film/' + movie_code, all) > 0) or (pos('film/' + movie_code + '/wall/', all) > 0) then
		backdrops_exist := True;
	if not backdrops_exist then begin
		UseTMDBSnapshots := 1;
		UseTVDBFanart := 1;
	end;

	//movie year
	i := Pos('>год</b>',all);
	if i=0 then
		i := Pos('>год</td>',all);
	if i>0 then
	begin
		i := i + 4;
		k := MyPos('</a>', all, i+1);
		j := MyPos('</li>',all,i+1);
		if (k>0) and (k<j) then
			j:=k;
		s := copy(all,i,j-i);
		i:=pos('&nbsp;', s);
		if i>0 then
			s:=copy(s, 1, i-1);
		year := RemoveTags(s);
		year:=ClearExtraSpaces(year);
		year:=ClearExtraBlankCharacters(year);
	end;
	
	//Определяем, есть ли страница наград
	if (pos('href="/level/94/film/', all)>0) or (Pos('film/' + movie_code + '/awards/', all) > 0) then
		awards_exist := true;
	
	//movie title
	title:=ParseString(all, '<title>(.*)</title>', 1);
	title:=RemoveTags(title);
	title:=DecodeHTML(title);
	title:=ClearExtraSpaces(title);
	title:=ClearExtraQuotes(title);

	if pos('КиноПоиск.ru', title)>0 then begin
		title:='';
		exit;
	end;

	i:=pos('<span style="color: #666; font-size: 13px"', all);
	if i>0 then begin
		j:=MyPos('</span>', all, i+1);
		if j>0 then begin
			original_title:=copy(all, i+43, j-i-43);
			original_title := '<' + original_title;
			original_title:=RemoveTags(original_title);
			original_title:=DecodeHTML(original_title);
			original_title:=ClearExtraSpaces(original_title);
			if original_title <> '' then
				if original_title[length(original_title)]='.' then
					delete(original_title,length(original_title),1);
		end;
	end;
	if original_title = '' then
		original_title := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(GetStr(all, 'itemprop="alternativeHeadline">', '</'))));

  // 08.01.2013. Add condition to avoid AV from FastScript
	if (Length(title) > 0) and (title[1]='"') and (title[length(title)]='"') then
		title := copy(title,2,length(title)-2);
	if title='' then
		exit;

	s := GetStr(all, '<h1 ', '</h1>');
	// тип фильма
	media_type := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(GetStr(s, '<span>', '<'))));
	if media_type <> '' then begin
		s2 := GetStr(media_type, '(', ')');
		if s2 = '' then begin
			if Pos('(', media_type) = 1 then
				delete(media_type, 1, 1);
		end
		else
			media_type := s2;
	end;
	if (pos('(сериал', s)>0) or (pos('(мини-сериал', all)>0) then
		flEpisodesTitle:=true;

	if (pos('/level/44/film/', all)>0) or (Pos('/film/' + movie_code + '/episodes/', all) > 0) then
		flEpisodes:=true
	else
		flEpisodes:=false;
		
	if (flEpisodes or flEpisodesTitle) and DownloadMovieFullCast then begin
		AddRequestForHTMLPageContent('http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/director/', True, ActorsURL);
		AddRequestForHTMLPageContent('http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/composer/', True, ActorsURL);
		AddRequestForHTMLPageContent('http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/writer/', True, ActorsURL);
	end;
		
  if DownloadMovieSeasonsList and flEpisodes then
    AddRequestForHTMLPageContent('http://www.kinopoisk.ru/level/44/film/'+movie_code+'/', True, RefererURL);
	
	if (MaxPostersCount > 0) and (is_posters_present or ((UseTVDBPosters=1) and (flEpisodes or flEpisodesTitle)) or ((UseTMDBPosters=1) and not (flEpisodes or flEpisodesTitle))) then
		PostersDownloading := True;
	if (MaxShotsCount > 0) and is_frames_present then
		ShotsDownloading := True;
	if (MaxBackdropsCount > 0) and (backdrops_exist or ((UseTVDBFanart=1) and (flEpisodes or flEpisodesTitle)) or ((UseTMDBSnapshots=1) and not (flEpisodes or flEpisodesTitle))) then
		BackdropsDownloading := True;
 
	//если сериал, и одна из опций для сериала выбрана для thetvdb, ищем на thetvdb
	if (flEpisodesTitle or flEpisodes) and ((DownloadTVDBEpisodes = 1) or ((UseTVDBPosters=1) and (MaxPostersCount>0)) 
	or ((UseTVDBFanart=1) and (MaxBackdropsCount>0))) then begin
		if DownloadTVDBEpisodes = 1 then
			EpisodesDownloading := True;
//		if original_title <> '' then
//			s := original_title
//		else
			s := EncodeURL(title, 'utf-8');
		TempURL := format('http://www.thetvdb.com/index.php?seriesname=%s&fieldlocation=1&language=&genre=&year=%s&network=&zap2it_id=&tvcom_id=&imdb_id=&order=translation&searching=Search&tab=advancedsearch', [s, year]);
		TempURL := ReplaceStr(TempURL, ' ', '+', -1);
		AddRequestForHTMLPageContent(TempURL, False, '', 'OnTVDBMainPageLoaded');
	end;

  // TMDB images
	if ((UseTMDBPosters=1) and (MaxPostersCount > 0)) or ((UseTMDBSnapshots=1) and (MaxBackdropsCount > 0)) then begin
		if (original_title<>'') and (not flEpisodes) then begin
			TempURL := format('http://www.themoviedb.org/search/movie?query=%s&movie_page=&movie_collection_page=&person_page=&company_page=&keyword_page=&active=0', [original_title]);
			TempURL := ReplaceStr(TempURL, ' ', '+', -1);
			AddRequestForHTMLPageContent(TempURL, False, '', 'OnITDBLoaded');
		end
		else begin
			if (UseTMDBPosters = 1) then
				PostersDownloading := False;
			if (UseTMDBSnapshots = 1) then
				BackdropsDownloading := False;
		end;
	end;

  // Amazon image content
	if ((RegReadInteger('KinopoiskNeverAmazon', NEVER_USE_AMAZON) = 0) and
      (DownloadMovieBigCover)) then begin
		ImageURL := format('http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&SubscriptionId=0J0N83PT9M72BYH98YR2&Operation=ItemSearch&Keywords=%s&SearchIndex=Video&ResponseGroup=Request,Images,Tracks,ItemAttributes,ItemIds,EditorialReview,BrowseNodes', [original_title]);
		ImageURL:=ReplaceStr(ImageURL, ' ', '+', -1);
		AddRequestForHTMLPageContent(ImageURL, False);
	end;

  // kinopoisk posters
  if (is_posters_present) then begin
	//если сериал и загрузка постеров с thetvdb выключена, или не сериал и загрузка постеров с themoviedb выключена
	if ((flEpisodes or flEpisodesTitle) and (UseTVDBPosters = 0)) or ((not (flEpisodes or flEpisodesTitle)) and (UseTMDBPosters=0)) then begin
		TempUrl := 'http://www.kinopoisk.ru/level/17/film/' + movie_code + '/';
		AddRequestForHTMLPageContent(TempUrl, True, RefererURL, 'ParseKinopoiskPosters');
	end;
  end;

  // kinopoisk frames
	if (is_frames_present) and (MaxShotsCount>0) then begin
		//ImageUrl := 'http://www.kinopoisk.ru/level/13/film/' + movie_code + '/';
		ImageUrl := 'http://www.kinopoisk.ru/film/' + movie_code + '/stills/';
		AddRequestForHTMLPageContent(ImageUrl, True, RefererURL, 'ParseKinopoiskShots');
	end;

	//kinopoisk backdrops
	if (backdrops_exist) and (MaxBackdropsCount>0) then begin
		if ((flEpisodes or flEpisodesTitle) and (UseTVDBFanart = 0)) or ((not (flEpisodes or flEpisodesTitle)) and (UseTMDBSnapshots=0)) then begin
			// TempURL := 'http://www.kinopoisk.ru/level/12/film/' + movie_code + '/';
      TempURL := 'http://www.kinopoisk.ru/wall/film/' + movie_code + '/';
			AddRequestForHTMLPageContent(TempURL, True, RefererURL, 'ParseKinopoiskBackdrops');
		end;
	end;


	//imdb rating
	imdb_rating:=0;
	i:=pos('IMDb: ', all);
	if i>0 then begin
		j:=MyPos(' ', all, i+7);
		if j>0 then begin
			s2:=copy(all, i, j-i);
			delete(s2, 1, 6);
			s2:=copy(s2, 1, 3);
			if s2<>'' then begin
				i:=pos('.', s2);
				if i>0 then
					s2[i]:=DecimalSeparator;
				try
					imdb_rating:=StrToFloat(s2);
				except
				end;
			end;
		end;
	end;

	//kinopoisk rating
	rating:=0;
	s2 := '<span class="rating_ball">';
	i := pos(s2, all);
	if i>0 then begin
		j := MyPos('</span>', all, i+1);		
		if j>0 then begin
				s2:=copy(all, i+length(s2), j-i-length(s2));
				s2 := RemoveTags(s2);
				s2 := DecodeHTML(s2);
				s2 := ClearExtraBlankCharacters(s2);
				if length(s2)>0 then begin
					i:=pos('.', s2);
					if i>0 then
						s2[i]:=DecimalSeparator;
					try
						rating:=StrToFloat(s2);
					except
					end;
				end;
		end;
	end;

	//mpaa
	mpaa:='';
	mpaa_rating:='';
	i:=pos('рейтинг MPAA', all);
	if i>0 then begin
		j:=MyPos('</a>', all, i+1);
		if j>0 then begin
			s2:=copy(all, i+12, j-i-12);
			i:=pos('ейтинг ', s2);
			if i>0 then begin
				j:=MyPos('"', s2, i+1);
				if j<=0 then
					j:=MyPos('''', s2, i+1);
				if j>0 then begin
					s2:=copy(s2, i+7, j-i-7);
					if s2<>'' then
						mpaa:=s2;
				end;
			end;

		end;
	end;

	//movie image
	front_cover_url := '';
	FoundBigKinopoiskPoster := False;
	i := pos('/images/film_big/'+movie_code+'.', all);
	if (i>0) and (RegReadInteger('KinopoiskBigCover', 1) = 1) then begin
		FoundBigKinopoiskPoster := True;
	end;
	i := Pos('/images/film/'+movie_code+'.', all);
	if i = 0 then
		i := Pos('/images/film_iphone/iphone360_' + movie_code, all);
	if i > 0 then
	begin
		j := MyPos('"',all,i+1);
		s2 := copy(all,i,j-i);
		i := Pos('''', s2);
		if i>0 then
			delete(s2, i, length(s2)-i+1);
		front_cover_url := 'http://www.kinopoisk.ru' + s2;
	end;

	//movie duration (minutes)
	s2 := ParseString(all, '<td class="time" id="runtime">(\d+) мин.', 1);
	if s2 = '' then
		s2:=ParseString(all, 'время</b>.*?(\d+?) мин', 1);
	duration:=0;
	if s2<>'' then
		try
			duration:=StrToInt(s2);
		except
		end;

	//movie genres
	s2:=ParseString(all, 'жанр</b>(.*?)</li>', 1);
	if s2='' then
		s2:=ParseString(all, 'жанр</td>(.*?)</tr>', 1);
	if length(s2)>0 then begin
		i:=pos('</a>', s2);
		while i>0 do begin
			s3:=copy(s2, 1, i+3);
			name:=ParseString(s3, '/m_act%5Bgenre%5D.*?>(.*?)</a>', 1);
			if name<>'' then begin
				genres_count:=genres_count+1;
				SetGenre(name);
			end;
			delete(s2, 1, i+3);
			i:=pos('</a>', s2);
		end;
	end;

	//movie countries
	s2:=ParseString(all, 'страна</b>(.*?)</li>', 1);
	if s2='' then
		s2:=ParseString(all, 'страна</td>(.*?)</tr>', 1);
	if length(s2)>0 then begin
		i:=pos('</a>', s2);
		while i>0 do begin
			s3:=copy(s2, 1, i+3);
			name:=ParseString(s3, '/m_act%5Bcountry%5D.*?>(.*?)</a>', 1);
			if name<>'' then begin
				SetCountry(name);
			end;
			delete(s2, 1, i+3);
			i:=pos('</a>', s2);
		end;
	end;
	

  // Fade - parse tagline for movie 
  s2 := ParseString(all, 'слоган</td>(.*?)</td></tr>', 1);
  TagLine := '';
	if length(s2)>0 then
  begin
    // remove tags and extra characters from tagline
    TagLine := DecodeHTML(s2);
    TagLine := ClearExtraSpaces(TagLine);
    TagLine := RemoveTags(TagLine);
    TagLine := ClearExtraCharacters(TagLine);
    TagLine := ClearExtraSpaces(TagLine);
	TagLine := ClearExtraQuotes(TagLine);
	//remove quotes
	for i := 0 to length(MyQuotes) - 1 do begin
		j := Pos(MyQuotes[i], TagLine);
		if j > 0 then
			delete(TagLine, j, 1);
	end;
	//too few characters
	if Length(TagLine) < 3 then
		TagLine := '';
  end;

	if (pos('href="/level/17/film/'+movie_code+'/"', all)>0) or (Pos('film/' + movie_code + '/posters/', all) > 0) then
		posters_exists:=true
	else
		posters_exists:=false;		
		
	if not images_only then
	begin
	//movie plot
		//s2 := '<tr><td colspan=3 style="padding:10px;padding-left:20px;" class="news">';
		s2:='<tr><td colspan=3 style="padding: 10px 10px 20px 20px" class="news">';
		i := pos(s2, all);
		if i>0 then
		begin
			i := i + length(s2);
			j := MyPos('</td></tr>',all,i+1);
			if (i>0)and(j>0) then
			begin
				description:=copy(all,i,j-i);
				description:=DecodeHTML(description);
				description:=ClearExtraSpaces(description);
				description:=ReplaceStr(description, '</p>', #10, -1);
				description:=ReplaceStr(description, '<br>', #10, -1);
				description:=RemoveTags(description);
				description:=ClearExtraCharacters(description);
				description:=ClearExtraSpaces(description);
				description:=ReplaceStr(description, #10, '<br>', -1);
			end;
		end;
	end;

	// Знаете ли Вы, что...
	i:=pos('Знаете ли вы, что...</', all);
	if i>0 then begin
		s := GetStr(all, '<ul class="trivia', '</ul>');
		temp := '';
		j := Pos('<li class="trivia', s);
		while j > 0 do begin
			s2 := GetStr(s, '<li class="trivia', '</li>');
			if s2 <> '' then
				s2 := ClearExtraBlankCharacters(DecodeHTML(RemoveTags('<' + s2)));
			if (temp <> '') and (s2 <> '') then
				temp := temp + #13#10#13#10;
			temp := temp + s2;
			delete(s, 1, j);
			j := Pos('<li class="trivia', s);
		end;
		description := description +ReplaceStr('t', 't', #13#10#13#10, -1) +'Знаете ли Вы, что... :'+ReplaceStr('t', 't', #13#10, -1) + temp;
	end;


	//budget and box office
	money := '';
	s := '';
	if DownloadMovieEarnings then begin
		i := Pos('>бюджет</b>',all);
		if i=0 then
			i := Pos('>бюджет</td>',all);
		if i>0 then
		begin
			i := i + 7;
			k := MyPos('</td>', all, i+1);
			j := MyPos('</li>',all,i+1);
			if (k>0) and (k<j) then
				j:=k;
			s := copy(all,i,j-i);
			s := DecodeHTML(s);
			s := RemoveTags(s);
			s := ClearExtraSpaces(s);
			s := ClearExtraXCharacters(s);
			s := 'Бюджет: ' + s + '<br>';

			money := money + s;
		end;
		i := Pos('>сборы в России</td>',all);
		if i=0 then
			i := Pos('>сборы в России</b>',all);
		if i>0 then
		begin
			i := i + 15;
			k := MyPos('</a>', all, i+1);
			j := MyPos('</div>',all,i+1);
			if (k>0) and (k<j) then
				j:=k;
			s := copy(all,i,j-i);
			s := DecodeHTML(s);
			s := RemoveTags(s);
			s := ClearExtraSpaces(s);
			s := ClearExtraXCharacters(s);
			s := 'Cборы в России: ' + s + '<br>';
			money := money + s;
		end;
		i := Pos('>сборы в США</b>',all);
		if i=0 then
			i := Pos('>сборы в США</td>',all);
		if i>0 then
		begin
			i := i + 12;
			k := MyPos('</a>', all, i+1);
			j := MyPos('</div>',all,i+1);
			if (k>0) and (k<j) then
				j:=k;
			s := copy(all,i,j-i);
			s := DecodeHTML(s);
			s := RemoveTags(s);
			s := ClearExtraSpaces(s);
			s := ClearExtraXCharacters(s);
			s := 'Cборы в США: ' + s + '<br>';
			money := money + s;
		end;
		i := Pos('>сборы в мире</b>',all);
		if i=0 then
			i := Pos('>сборы в мире</td>',all);
		if i>0 then
		begin
			i := i + 13;
			k := MyPos('</a>', all, i+1);
			j := MyPos('</div>',all,i+1);
			if (k>0) and (k<j) then
				j:=k;
			s := copy(all,i,j-i);
			s := DecodeHTML(s);
			s := RemoveTags(s);
			s := ClearExtraSpaces(s);
			s := ClearExtraXCharacters(s);
			s := 'Cборы в мире: ' + s; // + '<br>';
			money := money + s;
		end;
		
		if length(money)>4 then
			salary:=money;
	end;

	// New page for getting full information about creators
	if DownloadMovieFullCast then begin
    {AddRequestForHTMLPageContent('http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/Producer/', True, RefererURL);
    AddRequestForHTMLPageContent('http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/composer/', True, RefererURL);
    AddRequestForHTMLPageContent('http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/writer/', True, RefererURL);}

		//5.03.11
		//all:=DownloadURL(url);

		//all:=DownloadURLWithReferer(url, 'http://www.kinopoisk.ru/level/1/film/'+movie_code+'/');}
		//url := 'http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/director/';
		all := GetHTMLPageContentFromRequest(ActorsURL);

		//movie directors
		i:=pos('Режиссеры</div>', all);
		if i<=0 then
			i:=pos('Режиссер</div>', all);
		if i>0 then	begin
			kol:=0;
			//i:=MyPos('<tr><td colspan=3><br /></td></tr>', all, i+1);
			j:=MyPos('<a name="', all, i+1);
			if j = 0 then
				 j := MyPos('<table', all, i+1);
			if j = 0 then
				j := Length(all);
			if (i>0)and(j>0) then begin
				s2 := copy(all, i, j-i);
				//ShowMessage(s2);
				ExtractPeopleFull(s2, 1);
			end;
		end
		else begin
			s2 := GetHTMLPageContentFromRequest('http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/director/');
			ExtractPeopleFull(s2, 1);
		end;

		//url := 'http://www.kinopoisk.ru/level/19/film/'+movie_code+'/';
		//all := GetHTMLPageContentFromRequest(url);
		//movie cast
		i:=pos('Актеры</div>', all);
		if i = 0 then
			i := Pos('Актер</div>', all);
		if i = 0 then
			i := Pos('Актриса</div>', all);
		if i>0 then
		begin
			//i:=MyPos('<tr><td colspan=3><br /></td></tr>', all, i+1);
			j:=MyPos('<a name="', all, i+1);
			if j = 0 then
				 j := MyPos('<table', all, i+1);
			if j = 0 then
				j := Length(all);
			if (i>0)and(j>0) then begin
				s2 := copy(all, i, j-i);
				ExtractPeopleFull(s2, 3);
			end;
		end;

		//url := 'http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/writer/';
		//all := GetHTMLPageContentFromRequest(url);
		//movie writers
		i:=pos('Сценаристы</div>', all);
		if i = 0 then
			i:=pos('Сценарист</div>', all);
		if i>0 then begin
			kol:=0;
			//i:=MyPos('<tr><td colspan=3><br /></td></tr>', all, i+1);
			j:=MyPos('<a name="', all, i+1);
			if j = 0 then
				 j := MyPos('<table', all, i+1);
			if j = 0 then
				j := Length(all);
			if (i>0)and(j>0) then begin
				s2 := copy(all, i, j-i);
				ExtractPeopleFull(s2, 2);
			end;
		end
		else begin
			s2 := GetHTMLPageContentFromRequest('http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/writer/');
			ExtractPeopleFull(s2, 2);
		end;

		//movie composers
		//url := 'http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/composer/';
		//all := GetHTMLPageContentFromRequest(url);
		i:=pos('Композиторы</div>', all);
		if i = 0 then
			i:=pos('Композитор</div>', all);
		if i>0 then begin
			kol:=0;
			//i:=MyPos('<tr><td colspan=3><br /></td></tr>', all, i+1);
			j:=MyPos('<a name="', all, i+1);
			if j = 0 then
				 j := MyPos('<table', all, i+1);
			if j = 0 then
				j := Length(all);
			if (i>0)and(j>0) then begin
				s2 := copy(all, i, j-i);
				ExtractPeopleFull(s2, 4);
			end;
		end
		else begin
			s2 := GetHTMLPageContentFromRequest('http://www.kinopoisk.ru/level/19/film/'+movie_code+'/who_is/composer/');
			ExtractPeopleFull(s2, 4);
		end;

	end
	//if Download full cast/crew is not selected
	else begin
		i := Pos('В главных ролях:', all);
		if i>0 then begin
			k := MyPos('Роли дублировали:', all, i+1);
			if k = 0 then
				k := MyPos('<tr><td align="right" class="desc-title"', all, i+1);
			j := MyPos('</table>', all, i+1);
			if (k>0) and (j>k) then
				j:=k;
			s2 := copy(all, i, j-i);
			ExtractPeople(s2, 3);
		end;
		//режиссеры
		i := Pos('<tr><td class="type">режиссер', all);
		if i>0 then begin
			j:=MyPos('</tr>', all, i+1);
			s := copy(all, i, j-i);
			ExtractPeople(s, 1);
		end;
		//сценаристы
		i := Pos('<tr><td class="type">сценарий', all);
		if i>0 then begin
			j:=MyPos('</tr>', all, i+1);
			s := copy(all, i, j-i);
			ExtractPeople(s, 2);
		end;
		//композиторы
		i := Pos('<tr><td class="type">композитор', all);
		if i>0 then begin
			j:=MyPos('</tr>', all, i+1);
			s := copy(all, i, j-i);
			ExtractPeople(s, 4);
		end;
	end;
	

	//Награды
	if awards_exist and DownloadMovieAwards then begin
		url:='http://www.kinopoisk.ru/level/94/film/'+movie_code+'/';
		//5.03.11
		//all:=DownloadURL(url);
		// all:=DownloadURLWithReferer(url, 'http://www.kinopoisk.ru/level/1/film/'+movie_code+'/');
		all := GetHTMLPageContentFromRequest(url);

		if all<>'-1' then begin
			i:=Pos('<h1 class="level2"><a href="/awards/" class="continue">Награды</a></h1>', all);
			if i>0 then begin
				//На Кинопоиске перед таблицей наград бывает текст, там описываются доп. награды
				k:=Pos('<div style="background-color:#f2f2f2;padding:15px">', all);
				if k>0 then begin
					j:=MyPos('</div>', all, k+1);
					s:=copy(all, k, j-k);
					awards:=DecodeHTML(RemoveTags(s));
				end;
				//Теперь беремся за таблицу наград
				i:=MyPos('<b><a href="/level/94/award/', all, i+1);
				if i=0 then
					i:=MyPos('<b><a href="/awards/', all, i+1);
				if i>0 then begin
					j:=MyPos('<table cellspacing=0 cellpadding=4 width=100% border=0', all, i+1);
					s:=copy(all, i, j-i);
					j := Pos('<b><a href="/awards/', s);
					while j > 0 do begin
						k := MyPos('</table>', s, j + 1);
						s2 := copy(s, j, k-j);
						if awards <> '' then
							awards := awards + '<br> <br>';
						awards := awards + ExtractAwards(s2);
						delete(s, 1, j);
						j := Pos('<b><a href="/awards/', s);
					end;
					//showMessage(awards);
				end;
			end;
		end;
	end;

	//студии
	if DownloadMovieStudios then
  begin
		url:='http://www.kinopoisk.ru/level/91/film/'+movie_code+'/';
		//5.03.11
		//all:=DownloadURL(url);
		// all:=DownloadURLWithReferer(url, 'http://www.kinopoisk.ru/level/1/film/'+movie_code+'/');
    all := GetHTMLPageContentFromRequest(url);

		if all<>'-1' then begin
			i:=Pos('<h1 class="level2">Компании</h1>', all);
			if i>0 then begin
				i := MyPos('<b>Производство:</b>', all, i + 1);
				if i>0 then begin
					j := MyPos('</table>', all, i+1);
					s2 := copy(all, i, j-i);
					i := Pos('/m_act[studio]/', s2);
					if i=0 then
						i := Pos('/m_act%5Bstudio%5D/', s2);
					while i>0 do begin
						j := MyPos('</a>', s2, i+1);
						s := copy(s2, i, j-i);
						name := '';
						if s <> '' then
							name := RemoveTags('<' + s);
						name := DecodeHTML(name);
						if name<>'' then
							SetStudio(name);
						delete(s2, 1, j);
						i := Pos('/m_act[studio]/', s2);
						if i=0 then
							i := Pos('/m_act%5Bstudio%5D/', s2);
					end;
				end;
			end;
		end;
	end;
  // Fade. Movies links
  if (DownloadMovieLinks) then
  begin
	url:='http://www.kinopoisk.ru/level/90/film/' + movie_code + '/';
    all := GetHTMLPageContentFromRequest(url);
    if ((all <> '-1') and
        (all <> '')) then
    begin
      // Status enumeration:
      // 1 - Серия (Начало/Продолжение)
      // 2 - Пародия на
      // 3 - Спародирован в
      // 4 - Отсылки к
      // 5 - Упоминается в
      AddMoviesLinksForStatus(1, 'Начало');
      AddMoviesLinksForStatus(1, 'Продолжение');
      AddMoviesLinksForStatus(2);
      AddMoviesLinksForStatus(3);
      AddMoviesLinksForStatus(4);
      AddMoviesLinksForStatus(5);
    end;
  end;

  // 10.11.2010 Parse trailers from trailer page
  GetAllTrailers();
  //ShowTickCount('End of the GetInfo');
  
	//episodes
	if DownloadMovieSeasonsList and (flEpisodes or flEpisodesTitle) then begin
		while not TVDBDecided do
			Application.ProcessMessages;
		if ((DownloadTVDBEpisodes=0) or TVDBNotFound) and flEpisodes then begin
			url:='http://www.kinopoisk.ru/level/44/film/'+movie_code+'/';

			//5.03.11
			//all:=DownloadURL(url);
			// all:=DownloadURLWithReferer(url, 'http://www.kinopoisk.ru/level/1/film/'+movie_code+'/');
      all := GetHTMLPageContentFromRequest(url);
			if all<>'-1' then begin
				i:=pos('<a name="s1"></a>', all);
				if i>0 then begin
					j:=MyPos('<br /><br /><br /><br /><br />', all, i+1);
					if j>0 then begin
						s:=copy(all, i, j-i);
						season:=0;

						i:=pos('<span style="color:#777">Эпизод ', s);
						while i>0 do begin
							s2:='<h1 class="moviename-big" style="font-size:21px;padding:0px;margin:0px;color:#f60">Сезон ';
							k:=pos(s2, s);
							if (k<i) and (k<>0) then begin
								j:=MyPos('</h1>', s, k+1);
								s3:=copy(s, k+length(s2), j-k-length(s2));
								try
									season:=StrToInt(s3);
								except
									season:=0;
								end;
							end;
							
							j:=MyPos('</tr>', s, i+1);
							if j>0 then begin
							s2:='<span style="color:#777">Эпизод ';
							s3:=copy(s, i+length(s2), j-i-length(s2));
							delete(s, 1, j+4);
							k:=pos('</span>', s3);
							try
								if k>0 then
									episode:=StrToInt(copy(s3, 1, k-1))
								else
									episode:=-1;
							except
								episode:=-1;
							end;
							if episode>=0 then begin
								delete(s3, 1, k+6);
								EpisodeTitle:='';
								k:=pos('<b>', s3);
								if k>0 then begin
									k2:=MyPos('</b>', s3, k+1);
									if k2>0 then begin
										EpisodeTitle:=copy(s3, k+3, k2-k-3);
										EpisodeTitle:=DecodeHTML(EpisodeTitle);
									end;
								end;

									AirDate:='';
								s2:='<td width=20% class="news" align=right valign=bottom style="border-bottom:1px solid #ccc;padding:15px 0px;font-size:12px" align=left>';
								k:=pos(s2, s3);
								if k>0 then begin
									k2:=MyPos('</td>', s3, k+1);
									if k2>0 then
										AirDate:=copy(s3, k+length(s2), k2-k-length(s2));
									end;
							end;

							EpisodeIMDB:='';
							EpisodeDescription:='';
							
							s3:=AirDate;
							AirDate:='';
							k:=pos('&nbsp;', s3);
							if k>0 then begin
								day:=copy(s3, 1, k-1);
								delete(s3, 1, k+5);
								k:=pos('&nbsp;', s3);
								if k>0 then begin
									month:=copy(s3, 1, k-1);
									delete(s3, 1, k+5);
									ayear:=s3;

								k:=1;
								while (k<=12) and (monthes[k]<>month) do begin	
									k:=k+1;
								end;
								if (k<=12) and (month<>'') then begin
									AirDate:=IntToStr(k)+format('/%s/%s', [day, ayear])
								end
								end;
							end;
								
								if (season>0) and (episode>=0) and (episode<=100) then
								SetEpisode(season, episode, EpisodeTitle, EpisodeDescription, EpisodeIMDB, AirDate);

								i:=pos('<span style="color:#777">Эпизод ', s);
							end
							else
								i:=0;
						end;
					end;
				end;
			end;
		end;
	end;
	
	if RegReadInteger('KinopoiskDlType', 1) = 0 then
		media_type := '';
  
end;

function GetMovieLinkKinopoiskDescriptionByStatus(AStatus: Integer): string;
begin
  // Status enumeration:
  // 1 - Серия (Начало/Продолжение)
  // 2 - Пародия на
  // 3 - Спародирован в
  // 4 - Отсылки к
  // 5 - Упоминается в
  Result := '';
  case AStatus of
    2: Result := 'Пародия на';
    3: Result := 'Спародирован в';
    4: Result := 'Отсылки к';
    5: Result := 'Упоминается в';
  end;
end;

procedure AddMoviesLinksForStatus(AStatus: Integer; AStatusStr: string = '');
var
  I: Integer;
  J: Integer;
  K: Integer;
  SearchStr: string;
  MoviesList: string;
  SingleMovie: string;
  // Movie info
  MovieTitle: string;
  MovieYear: string;
  MovieOriginalTitle: string;
  MovieSiteCode: string;
  MovieSiteURL: string;
  s: String;

  function ProcessSingleString(AString: string): string;
  begin
    Result := RemoveTags(AString);
    Result := DecodeHTML(Result);
    Result := ClearExtraSpaces(Result);
  end;

begin
  SearchStr := AStatusStr;
  if (SearchStr = '') then
    SearchStr := GetMovieLinkKinopoiskDescriptionByStatus(AStatus);
  if (SearchStr <> '') then
  begin
	SearchStr := SearchStr + '</td';
    I := Pos(SearchStr, all);
    if (I > 0) then
    begin
      J := MyPos('   </table>', all, I);
      if (J > 0) then
      begin
        MoviesList := Copy(all, I, J - I);
        K := Pos('<span class="name"', MoviesList);
        while (K > 0) do
        begin
          J := MyPos('</table>', MoviesList, K);
          if (J > 0) then
          begin
            SingleMovie := Copy(MoviesList, K, J - K);
            MovieTitle := '';
            MovieYear := '';
            MovieOriginalTitle := '';
            MovieSiteCode := '';
            I := Pos('<a href="/film/', SingleMovie);
            if (I > 0) then
            begin
              I := I + Length('<a href="/film/');
              // movie code
              MovieSiteCode := Copy(SingleMovie, I, MyPos('/', SingleMovie, I + 1) - I);
              // movie title
              J := MyPos('</a>', SingleMovie, I);
              I := MyPos('>', SingleMovie, I);
              if ((I > 0) and
                  (J > 0)) then
              begin
                MovieTitle := Copy(SingleMovie, I + 1, J - I - 1);
                MovieTitle := ProcessSingleString(MovieTitle);
                if (Pos('(сериал)', MovieTitle) > 0) then
                  MovieTitle := Trim(Copy(MovieTitle, 1, Pos('(сериал)', MovieTitle) - 1));
                if (Pos('(ТВ)', MovieTitle) > 0) then
                  MovieTitle := Trim(Copy(MovieTitle, 1, Pos('(ТВ)', MovieTitle) - 1));
                if (Pos('(видео)', MovieTitle) > 0) then
                  MovieTitle := Trim(Copy(MovieTitle, 1, Pos('(видео)', MovieTitle) - 1));
                if (Pos('(мини-сериал)', MovieTitle) > 0) then
                  MovieTitle := Trim(Copy(MovieTitle, 1, Pos('(мини-сериал)', MovieTitle) - 1));
              end;
              // movie Year
              (*I := Pos('/m_act%5Byear%5D/', SingleMovie);
              if (I > 0) then
              begin
                I := I + Length('/m_act%5Byear%5D/');
                MovieYear := Copy(SingleMovie, I, MyPos('/', SingleMovie, I) - I);
                MovieYear := ProcessSingleString(MovieYear);
                if (Length(MovieYear) <> 4) then
                  MovieYear := '';
              end;*)
			  i := Pos(' (', MovieTitle);
			  if i > 0 then begin
				s := GetStr(MovieTitle, '(', ')');
				if NoVideosInSeries and (Pos('видео', s) > 0) and (AStatus = 1) then
					MovieTitle := '';
				delete(MovieTitle, i, length(MovieTitle) - i + 1);
				MovieYear := ParseString(s, '(\d+)', 1);
			  end;
              // movie original title
			  MovieOriginalTitle := GetStr(SingleMovie, '<span class="role"', '</span');
			  if MovieOriginalTitle <> '' then
				MovieOriginalTitle := ClearExtraBlankCharacters(DecodeHTML(RemoveTags('<' + MovieOriginalTitle)));
              (*I := Pos('<font color="#999999">', SingleMovie);
              if (I > 0) then
              begin
                I := I + Length('<font color="#999999">');
                MovieOriginalTitle := Copy(SingleMovie, I, MyPos('</font>', SingleMovie, I) - I);
                MovieOriginalTitle := ProcessSingleString(MovieOriginalTitle);
              end;*)
              // set Movie link if available
              if (Trim(MovieTitle) <> '') then
              begin
                MovieSiteURL := '';
                if (MovieSiteCode <> '') then
                  MovieSiteURL := GetMovieURL(MovieSiteCode, False);
                // update movie link
                SetMovieLink(MovieTitle, MovieSiteCode,
                  ProcessSingleString(MovieYear), MovieOriginalTitle, AStatus,
                  MovieSiteURL);
              end;
            end;
          end;
          K := MyPos('<span class="name"', MoviesList, K + 1);
        end;
      end;
    end;
  end;
end;

function GetTrailerCodeByURL(AURL: string): string;
var
  EndPos: Integer;
  StartPos: Integer;
begin
  Result := '';
  StartPos := Pos('/t/', AURL);
  if (StartPos > 0) then
  begin
    StartPos := StartPos + Length('/t/');
    EndPos := MyPos('/', AURL, StartPos);
    if (EndPos > 0) then
      Result := Copy(AURL, StartPos, EndPos - StartPos);
  end;
end;

procedure GetAllTrailers;
var
  ImageURL: string;
  TrailerCode: string;
  URL: string;
  S: String;
  I: Integer;
  J: Integer;
  K: Integer;
  TrailerDescription: string;
  TrailersCount: Integer;
begin
  TrailersCount := 0;
  // 10.11.2010 trailer
  if (MaxTrailersCount > 0) then
  begin
    url := 'http://www.kinopoisk.ru/film/'+movie_code+'/video/';
    s := GetHTMLPageContentFromRequest(url);
    I := Pos('<table cellspacing=0 cellpadding=0 width=100% border=0>', s);
    if (I > 0) then
      s := Copy(s, I, Length(S) - I);
    if (s <> '')and(s <> '-1') then
    begin
      // Parse trailers from trailer page if necessary
      if (TrailersCount < MaxTrailersCount) then
      begin
        // parse all trailers
        I := Pos('/film/' + movie_code + '/video/', S);
        while ((I > 0) and
               (TrailersCount < MaxTrailersCount)) do
        begin
          // search trailer URL
          K := MyPos('"', S, I + 1);
          if (K > I) then
          begin
            URL := Copy(S, I, K - I);
            if (Pos('#comm', LowerCase(URL)) = 0) then
            begin
              // search Trailer description
              K := MyPos('>', S, I + 1);
              if (K > I) then
              begin
                J := MyPos('</a>', S, K + 1);
                if (J > K) then
                  TrailerDescription := Copy(S, K + 1, J - K - 1);
              end;
              ImageURL := '';
              J := PosBack('''previewFile'': ''', s, I);
              if (J > 0) then
              begin
                J := J + Length('''previewFile'': ''');
                K := MyPos('''', s, J);
                if (K > 0) then
                begin
                  TrailerCode := Trim(Copy(s, J, K - J));
                  if (TrailerCode <> '') then
                    ImageURL := Format('http://tr.kinopoisk.ru/%s' , [TrailerCode]);
                end;
              end
              else
              begin
                J := MyPos('"previewFile": "', s, I);
                if (J > 0) then
                begin
                  J := J + Length('"previewFile": "');
                  K := MyPos('"', s, J);
                  if (K > 0) then
                  begin
                    TrailerCode := Trim(Copy(s, J, K - J));
                    if (TrailerCode <> '') then
                      ImageURL := Format('http://tr.kinopoisk.ru/%s' , [TrailerCode]);
                  end;
                end;
              end;
              SetTrailer('http://www.kinopoisk.ru' + URL, TrailerDescription, ImageURL);
              Inc(TrailersCount);
            end;
          end;
          // Delete(S, 1, I + Length('/film/' + movie_code + '/video/t/'));
          I := MyPos('/film/' + movie_code + '/video/', S, I +
            Length('/film/' + movie_code + '/video/'));
        end;
      end;
    end;
  end;
end;

// get movie frames
procedure ParseKinopoiskShots(s: String);
var
	url, s2, frame_url, frame_page, img_code: string;
	i, j, k, il, l: Integer;
	frames_count: Integer;
begin
	if (s <> '')and(s <> '-1') then begin
		frames_count := 0;
		l := pos('href="/picture/', s);
		if (LatinTitle = '') and (l>0) then begin
			i := MyPos('"', s, l+1);
			j := MyPos('"', s, i+1);
			s2 := copy(s, i+1, j-i-1);
			img_code := ParseString(s2, '\/picture\/(\d+)\/', 1);
			if s2<>'' then begin
				url := 'http://www.kinopoisk.ru' + s2;
				AddRequestForHTMLPageContent(url, True, 'http://www.kinopoisk.ru/level/1/film/'+movie_code+'/');
				s2 := GetHTMLPageContentFromRequest(url);


				if (s2 <> '')and(s2 <> '-1') then begin
					il := pos('logo.gif', s2);
					i := MyPos('/im/kadr/', s2, il);
					if i=0 then
						i := MyPos('src="http://st.kinopoisk.ru/', s2, il);
					if (i > 0) then begin
						//i := MyPos('"', s2, i) + 1;
						j := MyPos('"', s2, i);
						frame_url := copy(s2, i, j-i);
					end;
				end;
			end;
			i := Pos(img_code, frame_url);
			if i>0 then
				delete(frame_url, i - 1, length(frame_url) - i + 2);
			LatinTitle := ParseString(frame_url, 'kinopoisk.ru-(.*?)$', 1);
  		LatinTitle := ReplaceStr(LatinTitle, ' ', '-', -1);
  		LatinTitle := EncodeURL(LatinTitle, 'WINDOWS-1251');
	  	LatinTitle := ReplaceStr(LatinTitle, '%', '_', -1);
		end;
			
		while (l > 0) and (frames_count < MaxShotsCount) do
		begin
			img_code := '';
			frame_url := '';
			i := MyPos('"', s, l) + 1;
			j := MyPos('"', s, i);
			s2 := copy(s, i, j-i);
			img_code := ParseString(s2, '\/picture\/(\d+)\/', 1);
			frame_url := 'http://st3.kinopoisk.ru/im/kadr/'+ copy(img_code, 1, 1) + '/' + copy(img_code, 2, 1) + '/' + copy(img_code, 3, 1) + '/kinopoisk.ru-' + LatinTitle + '-' + img_code + '.jpg';

			//29.12.12
			{frame_url := 'http://st.kinopoisk.ru/images/kadr/' + img_code + '.jpg';}
			if (img_code <> '') and (frame_url <> '') then
			begin
				SetImageName('', frame_url, '', 3);
				frames_count := frames_count + 1;
			end;
			l := MyPos('</td>', s, j+1); 
			delete(s, 1, l);
			l := pos('href="/picture/', s); 
		end; 
	end;
	ShotsDownloading := False;
end;

// get movie posters
procedure ParseKinopoiskPosters(s: string);
var
	url, ReferenceURL, s2, frame_url, frame_page, img_code: string;
	i, j, k, il, l: Integer;
	frames_count: Integer;
begin
	if MaxPostersCount > 0 then begin
		if (s <> '')and(s <> '-1') then
		begin
			frames_count := 0;
			l := pos('href="/picture/', s);
			if (LatinTitle = '') and (l>0) then begin
				i := MyPos('"', s, l+1);
				j := MyPos('"', s, i+1);
				s2 := copy(s, i+1, j-i-1);
				img_code := ParseString(s2, '\/picture\/(\d+)\/', 1);
				if s2<>'' then begin
					url := 'http://www.kinopoisk.ru' + s2;
					ReferenceURL := 'http://www.kinopoisk.ru/level/1/film/'+movie_code+'/';
					AddRequestForHTMLPageContent(url, True, ReferenceURL);
					s2 := GetHTMLPageContentFromRequest(url);

					if (s2 <> '')and(s2 <> '-1') then begin
						il := pos('logo.gif', s2);
						i := MyPos('/im/poster/', s2, il);
						if i=0 then
							i := MyPos('src="http://st.kinopoisk.ru/', s2, il);
						if (i > 0) then begin
							//i := MyPos('"', s2, i) + 1;
							j := MyPos('"', s2, i);
							frame_url := copy(s2, i, j-i);
						end;
					end;
				end;
				i := Pos(img_code, frame_url);
				if i>0 then
					delete(frame_url, i - 1, length(frame_url) - i + 2);
				LatinTitle := ParseString(frame_url, 'kinopoisk.ru-(.*?)$', 1);
    		LatinTitle := ReplaceStr(LatinTitle, ' ', '-', -1);
    		LatinTitle := EncodeURL(LatinTitle, 'WINDOWS-1251');
	    	LatinTitle := ReplaceStr(LatinTitle, '%', '_', -1);
			end;
				
			while (l > 0) and (frames_count < MaxPostersCount) do
			begin
				img_code := '';
				frame_url := '';
				i := MyPos('"', s, l) + 1;
				j := MyPos('"', s, i);
				s2 := copy(s, i, j-i);
				img_code := ParseString(s2, '\/picture\/(\d+)\/', 1);
				frame_url := 'http://st3.kinopoisk.ru/im/poster/'+ copy(img_code, 1, 1) + '/' + copy(img_code, 2, 1) + '/' + copy(img_code, 3, 1) + '/kinopoisk.ru-' + LatinTitle + '-' + img_code + '.jpg';
				if img_code <> '' then
				begin
					SetImageName('', frame_url, '', 4);
					frames_count := frames_count + 1;
				end;
				l := MyPos('</td>', s, j+1); 
				delete(s, 1, l);
				l := pos('href="/picture/', s); 
			end; 
		end;
	end;
	PostersDownloading := False;
end;

// get movie backdrops
procedure ParseKinopoiskBackdrops(s: string);
var
	url, ReferenceURL, s2, frame_url, frame_page, img_code, my_ext: string;
	i, j, k, il, l, m: Integer;
	frames_count: Integer;
begin
	if MaxBackdropsCount > 0 then begin
		if (s <> '')and(s <> '-1') then begin
			frames_count := 0;
			m := pos('href="/picture/', s);
			if (LatinTitle = '') and (m>0) then begin
				i := MyPos('"', s, m+1);
				j := MyPos('"', s, i+1);
				s2 := copy(s, i+1, j-i-1);
				img_code := ParseString(s2, '\/picture\/(\d+)\/', 1);
				if s2<>'' then begin
					url := 'http://www.kinopoisk.ru' + s2;
					ReferenceURL := 'http://www.kinopoisk.ru/level/1/film/'+movie_code+'/';
					AddRequestForHTMLPageContent(url, True, ReferenceURL);
					s2 := GetHTMLPageContentFromRequest(url);

					if (s2 <> '')and(s2 <> '-1') then begin
						il := pos('logo.gif', s2);
						l := MyPos('/im/wallpaper/', s2, il);
						if l=0 then
							l := MyPos('src="http://st.kinopoisk.ru/', s2, il);
						if (l > 0) then begin
							//l := MyPos('"', s2, l) + 1;
							j := MyPos('"', s2, l);
							frame_url := copy(s2, l, j-l);
						end;
					end;
				end;
				l := Pos(img_code, frame_url);
				if l>0 then
					delete(frame_url, l - 1, length(frame_url) - l + 2);
				LatinTitle := ParseString(frame_url, 'kinopoisk.ru-(.*?)$', 1);
    		LatinTitle := ReplaceStr(LatinTitle, ' ', '-', -1);
    		LatinTitle := EncodeURL(LatinTitle, 'WINDOWS-1251');
	    	LatinTitle := ReplaceStr(LatinTitle, '%', '_', -1);
			end;
				
			while (m > 0) and (frames_count < MaxBackdropsCount) do begin
				img_code := '';
				frame_url := '';
				j := MyPos('</td>', s, m);
				s2 := copy(s, m, j-m);
				img_code := ParseString(s2, '\/picture\/(\d+)\/', 1);
				if (Pos('/w_size/1280/', s2)>0) then
					my_ext := '--w--1280.jpg'
				else if (Pos('/w_size/800/', s2)>0) then
					my_ext := '--w--800.jpg'
				else
					my_ext := '.jpg';
				frame_url := 'http://st3.kinopoisk.ru/im/wallpaper/'+ copy(img_code, 1, 1) + '/' + copy(img_code, 2, 1) + '/' + copy(img_code, 3, 1) + '/kinopoisk.ru-' + LatinTitle + '-' + img_code + my_ext;
				if img_code <> '' then
				begin
					SetImageName('', frame_url, '', 7);
					frames_count := frames_count + 1;
				end;
				//i := MyPos('</td>', s, j+1); 
				delete(s, 1, j);
				m := pos('href="/picture/', s); 
			end; 
		end;
	end;
	BackdropsDownloading := False;
end;

//returned images links
procedure GetImages;
var
	kol, i: integer;
	amazon_url: String;
begin
	//fron cover
	amazon_url := '';
	if FoundBigKinopoiskPoster then
		SetImageName('', 'http://www.kinopoisk.ru/images/film_big/' + movie_code + '.jpg', '', 1);
	if (RegReadInteger('KinopoiskAlwaysAmazon', ALWAYS_USE_AMAZON) = 1) or 
	((RegReadInteger('KinopoiskNoAmazonIfBigCoverAvailable', NO_AMAZON_COVER_IF_BIG_AVAILABLE) = 1) and not FoundBigKinopoiskPoster) then
		amazon_url := GetFrontCoverURL2;
	if (not FoundBigKinopoiskPoster) and (front_cover_url<>'') and ((RegReadInteger('KinopoiskNoSmallCover', NO_SMALL_COVER) = 0) or (amazon_url = '')) then begin// front-cover from movie site
		SetImageName('', front_cover_url, '', 1);
	end;
	ShowTickCount('Amazon');

	while EpisodesDownloading do 
		Application.ProcessMessages;
	while PostersDownloading do
		Application.ProcessMessages;
	while ShotsDownloading do
		Application.ProcessMessages;
	while BackdropsDownloading do
		Application.ProcessMessages;
  for i := 0 to EpisodeURLs.Count - 1 do
	GetHTMLPageContentFromRequest(EpisodeURLs[i]);
end;

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

//get person site url
function GetPersonSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:=format('http://www.kinopoisk.ru/level/4/people/%s/', [code])
end;

//иногда требуется логин на сайт
procedure SiteLogin;
var
	url, all: string;
begin
	if UserName='' then begin
		ShowLoginForm;
	end;
	url:=format('http://www.kinopoisk.ru/level/30/?shop_user[login]=%s&shop_user[pass]=%s&shop_user[mem]=on', [UserName, UserPassword]);
	url:=ReplaceStr(url, ' ', '+', -1);
	all:=DownloadURLWithReferer(url, 'post');
	if (GetResponseCode=403) then begin
		ShowLoginForm;
	end;
end;


procedure ButtonClick(Sender: TButton);
begin
	UserName:=edUserName.Text;
	UserPassword:=edPassword.Text;
	SaveLoginInfo(UserName, UserPassword, script_name);

	f.ModalResult := mrOk;
end;

procedure ShowLoginForm;
begin
	f := TForm.Create(nil);
	f.Caption := 'Требуется авторизация';
	f.BorderStyle := bsDialog;
	f.Position := poScreenCenter;
	f.Width:=400;


	labCaption := TLabel.Create(f);
	labCaption.Name := 'labCaption';
	labCaption.Parent := f;
	labCaption.SetBounds(10, 10, 380, 25);
	labCaption.Caption := 'Для получения информации с этого сайта необходима авторизация.';

	labUserName := TLabel.Create(f);
	labUserName.Name := 'labUserName';
	labUserName.Parent := f;
	labUserName.SetBounds(10, 40, 100, 25);
	labUserName.Caption := 'Имя пользователя:';

	edUserName := TEdit.Create(f);
	edUserName.Name := 'Name';
	edUserName.Parent := f;
	edUserName.SetBounds(120, 40, 175, 25);
	edUserName.Text := UserName;

	labPassword := TLabel.Create(f);
	labPassword.Name := 'labPassword';
	labPassword.Parent := f;
	labPassword.SetBounds(10, 70, 380, 25);
	labPassword.Caption := 'Пароль:';

  edPassword := TEdit.Create(f);
	edPassword.Name := 'edPassword';
	edPassword.Parent := f;
	edPassword.SetBounds(120, 70, 175, 25);
	edPassword.Text := UserPassword;

	b := TButton.Create(f);
	b.Name := 'btnOK';
	b.Parent := f;
	b.SetBounds(300, 70, 75, 25);
	b.Caption := '&Вход';
	b.OnClick := @ButtonClick;


	labCaption2 := TLabel.Create(f);
	labCaption2.Name := 'labCaption2';
	labCaption2.Parent := f;
	labCaption2.SetBounds(10, 100, 275, 25);
	labCaption2.Caption := 'Если у вас нет имени и пароля, получите их по этому адресу:';

	edURL := TEdit.Create(f);
	edURL.Name := 'URL';
	edURL.Parent := f;
	edURL.SetBounds(10, 125, 370, 25);
	edURL.Text := 'http://www.kinopoisk.ru/level/30/';

	f.ShowModal;
	f.Free;
end;

//download posters from themoviesdb.org
procedure ParseTMDBPosters(all: String);
var
	url, s, s2: string;
	i, j, k, kol: integer;
begin
	if (MaxPostersCount<=0) or (tmdb_code='') or (all='-1') then begin
		PostersDownloading := False;
		exit;
	end;

	i:=pos('<ul id="posters">', all);
	if i<=0 then begin
		PostersDownloading := False;
		exit;
	end;

	kol:=0;
	i:=pos('<span class="delete">', all);
	while (i>0) and (kol<MaxPostersCount) do begin
		i:=MyPos(' href="', all, i+1);
		if i>0 then begin
			j:=MyPos('"', all, i+9);
			if j>0 then begin
				url:=copy(all, i+9, j-i-9);
				//always use the first server
				//k := Pos('.', url);
				//delete(url, 1, k-1);
				//url := 'http://cf2' + url;
				SetImageName('', url, '', 4);
				kol:=kol+1;
				delete(all, 1, j);
				i:=pos('<span class="delete">', all);
			end;
		end;
	end;
	PostersDownloading := False;
end;


procedure ParseTMDBBackdrops(all: String);
var
	url, s, s2: string;
	i, j, k, kol: integer;
begin
	if MaxBackdropsCount<=0 then begin
		BackdropsDownloading := False;
		exit;
	end;

	if tmdb_code='' then
		exit;
	if all='-1' then
		exit;
	i:=pos('<ul id="backdrops">', all);
	if i<=0 then
		exit;

	kol:=0;
	i:=pos('<div class="image">', all);
	while (i>0) and (kol<MaxBackdropsCount) do begin
		s := GetStr(all, '<div class="image">', '</div>');
		url := GetStr(s, ' href="', '"');
		//always download from the first server
		//k := Pos('.', url);
		//delete(url, 1, k-1);
		//url := 'http://cf2' + url;
		SetImageName('', url, '', 7);
		kol:=kol+1;
		delete(all, 1, i);
		i:=pos('<div class="image">', all);
	end;
	BackdropsDownloading := False;
end;

procedure OnITDBLoaded(AContent: string);
var
	url, all, s, s2, nocaps, movie_link: string;
	i, j, k, kol, year_int: integer;
begin
	all := AContent;
	if (all='-1') or (pos('Nothing found', all)>0) then begin
		if (UseTMDBPosters = 1) then
			PostersDownloading := False;
		if (UseTMDBSnapshots = 1) then
			BackdropsDownloading := False;
		exit;
	end;

	if (tmdb_code = '') then begin
		//загрузилась страница фильма
		if pos('search_results movie', all)=0 then begin
		  s2:='<link rel="canonical" href="http://www.themoviedb.org/movie/';
		  i:=pos(s2, all);
		  if i>0 then begin
			j:=MyPos('"', all, i+length(s2));
			if j>0 then
			  tmdb_code:=copy(all, i+length(s2), j-i-length(s2));
		  end;
		end;

		s:=format('%s</a> <span>(%s)</span>', [original_title, year]);
		nocaps := LowerCase(all);
		i:=pos(LowerCase(s), nocaps);
		//previous and next year
		if i=0 then begin
			try
				year_int := StrToInt(year);
			except
			end;
			s := format('%s</a> <span>(%d)</span>', [original_title, year_int-1]);
			i := pos(LowerCase(s), nocaps);
			if i=0 then begin
				s := format('%s</a> <span>(%d)</span>', [original_title, year_int+1]);
				i := pos(LowerCase(s), nocaps);
			end;
		end;
		if i>0 then begin
		  if (Pos('<a href="http://www.themoviedb.org/movie/', all) > 0) then
			movie_link := '<a href="http://www.themoviedb.org/movie/'
		  else
			movie_link := '<a href="/movie/';
		  while (MyPos(movie_link, all, i-1)<>i) and (i>0) do
				i := i - 1;
		  s2:=movie_link;
		  i:=MyPos(s2, all, i);
		  if i>0 then begin
			j:=MyPos('"', all, i+10);
			if j>0 then begin
				tmdb_code:=copy(all, i+length(s2), j-i-length(s2));
			end;
		  end;
		end;
	end;
	if tmdb_code='' then begin
		if (UseTMDBPosters = 1) then
			PostersDownloading := False;
		if (UseTMDBSnapshots = 1) then
			BackdropsDownloading := False;
		exit;
	end;
	if (UseTMDBPosters = 1) then begin
		url:=format('http://www.themoviedb.org/movie/%s/images?kind=poster&language=en&translate=false&_dc=1345198512', [tmdb_code]);
		AddRequestForHTMLPageContent(url, False, '', 'ParseTMDBPosters');
	end;
	if (UseTMDBSnapshots = 1) then begin
		url:=format('http://www.themoviedb.org/movie/%s/images?kind=backdrop&language=&translate=false&_dc=1345196288', [tmdb_code]);
		AddRequestForHTMLPageContent(url, False, '', 'ParseTMDBBackdrops');
	end;
end;

//search for the title and grab the first search result
//returns the tvdb code of the first search result
function SearchTVDB(tv_name: String; lang: Integer): string;
var
	i, j: Integer;
	s, url, all: String;
begin
	Result := '-1';
	if (tv_name <> '') then begin
		url := format('http://www.thetvdb.com/index.php?seriesname=%s&fieldlocation=1&language=%d&genre=&year=&network=&zap2it_id=&tvcom_id=&imdb_id=&order=translation&searching=Search&tab=advancedsearch', [EncodeURL(tv_name, 'utf-8'), lang]);
		url:=ReplaceStr(url, ' ', '+', -1);
	  // all := DownloadURL(url);
	  AddRequestForHTMLPageContent(url, False);
	  All := GetHTMLPageContentFromRequest(url); 
	  //all := GetHTMLPageContentFromRequest(url);
		if (all<>'-1') and (Pos('No series found', all)=0) then
	  begin
		if (tvdb_code = '') then
		begin
		  tvdb_code := '';
		  i := Pos('<h1>Results', all);
		  if i>0 then begin
			j := MyPos('</table>', all, i+1);
			s := copy(all, i, j-i);
			i := Pos('<a href="/index.php?tab=series&amp;id=', s);
			if i>0 then begin
			  j := MyPos('&amp;lid', s, i+38);
			  tvdb_code := copy(s, i+38, j-i-38);
			  tvdb_code := ClearExtraBlankCharacters(tvdb_code);
			end;
		  end;
		end;
			result := tvdb_code;
		end
		else
			result := '-1';
	end;
end;

procedure OnTVDBMainPageLoaded(AContent: string);
var
	i, j: Integer;
	s, url, all: String;
begin
  all := AContent;
  tvdb_code := '';
	if (all<>'-1') then begin
		i := Pos('<h1>Results', all);
		if i>0 then begin
			j := MyPos('</table>', all, i+1);
			s := copy(all, i, j-i);
			i := Pos('<a href="/index.php?tab=series&amp;id=', s);
			if i>0 then begin
				j := MyPos('&amp;lid', s, i+38);
				tvdb_code := copy(s, i+38, j-i-38);
				tvdb_code := ClearExtraBlankCharacters(tvdb_code);
			end;
		end;
		if (tvdb_code = '-1') or (tvdb_code = '') then begin 
			if original_title <> '' then
				tvdb_code := SearchTVDB(original_title, 7)
			else
				tvdb_code := SearchTVDB(title, 22);
		end;
		if (tvdb_code <> '-1') and (tvdb_code <> '') then begin
			if (DownloadTVDBEpisodes=1) then begin
				url := format('http://www.thetvdb.com/?tab=seasonall&id=%s&lid=22', [tvdb_code]);
				AddRequestForHTMLPageContent(url, False, '', 'OnTVDBSeasonAllPageLoaded');
			end
			else
				EpisodesDownloading := False;
			if (UseTVDBPosters=1) then begin
				url := format('http://www.thetvdb.com/?tab=seriesposters&id=%s', [tvdb_code]);
				AddRequestForHTMLPageContent(url, False, '', 'ParseTVDBPosters');
			end;
			if (UseTVDBFanart=1) then begin
				url := format('http://www.thetvdb.com/?tab=seriesfanart&id=%s', [tvdb_code]);
				AddRequestForHTMLPageContent(url, False, '', 'ParseTVDBFanart');
			end;
		end
		else begin
			if (DownloadTVDBEpisodes = 1) then begin
				EpisodesDownloading := False;
				TVDBNotFound := True;
				TVDBDecided := True;
			end;
			if (UseTVDBPosters = 1) then
				PostersDownloading := False;
			if (UseTVDBFanart = 1) then
				BackdropsDownloading := False;
		end;
	end;
end;

procedure OnTVDBSeasonAllPageLoaded(AContent: string);
var
	i, j, k, l, season, episode, episodes_count: Integer;
	s, s2, s3, s4, url, all, EpisodeTitle, AirDate, EpisodeDescription, EpisodeIMDB, year, month, day, NotConvertedTitle, SeasonImage, EpisodeImage, season_id, series_id, episode_id, last_season_id, temp: String;
	checkd, previous_title: Boolean;
begin
	checkd := False;
	previous_title := False;
	episodes_count := 0;
	EpisodeIMDB := '';
	EpisodeDescription := '';
	if (tvdb_code <> '-1') and (tvdb_code <> '') then begin
		// url := format('http://www.thetvdb.com/?tab=seasonall&id=%s&lid=22', [tvdb_code]);
		// all := DownloadURL(url);
		all := AContent;//GetHTMLPageContentFromRequest(url);
		if all <> '-1' then begin
			i := Pos('<h2>All Seasons</h2>', all);
			if i>0 then begin
				j := MyPos('</table>', all, i+1);
				s := copy(all, i, j-i);
				last_season_id := '';
				i := Pos('<a href="/?tab=episode&seriesid=', s);
				while i>0 do begin
					j := MyPos('</tr>', s, i+1);
					s2 := copy(s, i, j-i);
					season_id := GetStr(s2, 'seasonid=', '&');
					series_id := GetStr(s2, 'seriesid=', '&');
					episode_id := GetStr(s2, '&id=', '&');
					k := Pos('</td><td class="', s2);
					l := MyPos('</a>', s2, k+1);
					s4 := copy(s2, k, l-k);
					NotConvertedTitle := RemoveTags(s4);
					EpisodeTitle := NotConvertedTitle;
					//Air Date
					k := MyPos('</td>', s2, l+9);
					AirDate := '';
					if k>l then begin
						s3 := copy(s2, l, k-l);
						s3 := RemoveTags(s3);
						year := copy(s3, 1, 4);
						month := copy(s3, 6, 2);
						day := copy(s3, 9, 2);
						if (year<>'') and (month<>'') and (day<>'') then
							AirDate := format('%s/%s/%s', [month, day, year]);
					end;
					//Episode number, season number
					k := Pos('</a>', s2);
					s3 := copy(s2, 1, k-1);
					s3 := RemoveTags(s3);
					s4 := ParseString(s3, '^(\d+) ', 1);
					if s4<>'' then
						try
							season := StrToInt(s4);
						except
							season := 0;
						end;
					s4 := ParseString(s3, ' (\d+)$', 1);
					if s4 <> '' then
						try
							episode := StrToInt(s4);
						except
							episode := 0;
						end;
					// Fade - add conditions for downloading
					if ((DownloadSeasonsCovers) and (season_id <> last_season_id) and (season_id <> '')) then begin
						if (not ExistSeasonImage(season)) then begin
						  url := 'http://www.thetvdb.com/?tab=season&seriesid=' + series_id + '&seasonid=' + season_id + '&lid=7';
						  AddRequestForHTMLPageContent(url, False);
						  temp := GetHTMLPageContentFromRequest(url);
						  SeasonImage := GetStr(temp, 'href="banners/seasons/', '"');
						  if SeasonImage <> '' then begin
							SeasonImage := 'http://www.thetvdb.com/banners/seasons/' + SeasonImage;
							SetImageName('', SeasonImage, '', 9, False, '', season, 0);
						  end;
						end;
						last_season_id := season_id;
					end;
					// Fade - add conditions for downloading          
					if ((DownloadEpisodesCovers) and (Pos('src="/images/checkmark.png"', s2) > 0) and
					(not ExistEpisodeImage(season, episode))) then begin
						EpisodeImage := 'http://www.thetvdb.com/banners/episodes/' + series_id + '/' + episode_id + '.jpg';
						SetImageName('', EpisodeImage, '', 10, False, '', season, episode);
					end;
					EpisodeDescription:='';
					//Episode description
					if (DownloadTVDBEpisodeDescriptions = 1) then begin
						k := 0;
						//check for russian characters in the episode title
						while (not checkd) and (k < Length(EpisodeTitle)) do begin
							if EpisodeTitle[k] in ['А'..'я'] then
								checkd := True;
							k := k + 1;
						end;
						if (DownloadTVDBEnglishDesc = 1) or checkd then begin
							k := Pos('/?tab=episode&seriesid=', s2);
							if k>0 then begin
								l := MyPos('"', s2, k+1);
								s4 := copy(s2, k, l-k);
								if s4 <> '' then begin
									//EpisodeDescription := GetTVDBEpisodeDescription('http://www.thetvdb.com' + s4);
									s4 := ReplaceStr(s4, '&amp;', '&', -1);
									AddRequestForHTMLPageContent('http://www.thetvdb.com' + s4, False, '', 'GetTVDBEpisodeDescription');
									EpisodeURLs.Add('http://www.thetvdb.com' + s4);
									episodes_count := episodes_count + 1;
								end;
							end;
						end
						else begin
							episodes_count := episodes_count + 1;
							if (EpisodeTitle = '') and (EpisodeDescription = '') then begin
								if not previous_title then begin
									TVDBNotFound := True;
									TVDBDecided := True;
								end
								else
									EpisodeTitle := Format(GetLangStr(518), [episode]);
							end
							else
								previous_title := True;
							if not TVDBNotFound then
								SetEpisode(season, episode, EpisodeTitle, EpisodeDescription, EpisodeIMDB, AirDate);
						end;
					end
					else begin
						episodes_count := episodes_count + 1;
						if (EpisodeTitle = '') then begin
							if not previous_title then begin
								TVDBNotFound := True;
								TVDBDecided := True;
							end
							else
								EpisodeTitle := Format(GetLangStr(518), [episode]);
						end
						else
							previous_title := True;
						if not TVDBNotFound then
							SetEpisode(season, episode, EpisodeTitle, EpisodeDescription, EpisodeIMDB, AirDate);
					end;
					delete(s, 1, j);
					i := Pos('<a href="/?tab=episode&seriesid=', s);
				end;
			end;
		end;
	end;
	EpisodesDownloading := False;
	if (DownloadTVDBEnglishDesc = 0) and (not checkd) then
		TVDBDecided := True;
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;


//download page with episode description and extract the description
procedure GetTVDBEpisodeDescription(all: string);
var
	i, j : Integer;
	s, s2, desc: String;
	not_done, previous_title: boolean;
	EpisodeTitle, EpisodeDescription, AirDate, day, month, year: String;
	season, episode: Integer;
begin
	desc := '';
	not_done := true;
	// all := DownloadURL(url);
  //all := GetHTMLPageContentFromRequest(url);
	if all<>'-1' then begin
		s := GetStr(all, '<h2>', '</h2>');
		s := ClearExtraBlankCharacters(RemoveTags(s));
		s := ParseString(s, 'Season (\d+)$', 1);
		s2 := GetStr(all, 'name="EpisodeNumber" value="', '"');
		EpisodeDescription := '';
		season := 0;
		episode := 0;
		try
			season := StrToInt(s);
			episode := StrToInt(s2);
		except
		end;
		EpisodeTitle := GetStr(all, 'name="EpisodeName_22" value="', '"');
		if EpisodeTitle = '' then
			EpisodeTitle := GetStr(all, 'name="EpisodeName_7" value="', '"');
		s2 := GetStr(all, 'name="FirstAired" value="', '"');
		year := copy(s2, 1, 4);
		month := copy(s2, 6, 2);
		day := copy(s2, 9, 2);
		if (year<>'') and (month<>'') and (day<>'') then
			AirDate := format('%s/%s/%s', [month, day, year])
		else
			AirDate := '';
		i := Pos('name="Overview_22"', all);
		if i>0 then begin
			i := MyPos('>', all, i+1);
			j := MyPos('<', all, i+1);
			s := copy(all, i+1, j-i-1);
			if s<>'' then begin
				EpisodeDescription := DecodeHTML(s);
				not_done := false;
			end;
		end;
		if not_done then begin
			i := Pos('name="Overview_7"', all);
			if i>0 then begin
				i := MyPos('>', all, i+1);
				j := MyPos('<', all, i+1);
				EpisodeDescription := DecodeHTML(copy(all, i+1, j-i-1));
			end;
		end;
		s2 := GetStr(all, '<h1>Episode Image</h1>', '</table>');
		if (season > 0) and (episode > 0) then begin
			if (EpisodeTitle = '') and (EpisodeDescription = '') then begin
				if not previous_title then begin
					TVDBNotFound := True;
					TVDBDecided := True;
					exit;
				end
				else
					EpisodeTitle := Format(GetLangStr(518), [episode]);
			end
			else
				previous_title := True;
			SetEpisode(season, episode, EpisodeTitle, EpisodeDescription, '', AirDate);			
		end;
	end;
	TVDBDecided := True;
end;


procedure ParseTVDBPosters(all: String);
var
	i, j, posters_count: Integer;
	s, poster_code, poster_url, url: String;
begin
	posters_count := 0;
	if all <> '-1' then begin
		i := Pos('<h1>Posters</h1>', all);
		if i>0 then begin
			j := MyPos('<div class="footer">', all, i+1);
			s := copy(all, i, j-i);
			i := Pos('<a href="banners/posters/', s);
			while (i>0) and (posters_count < MaxPostersCount) do begin
				posters_count := posters_count + 1;
				j := MyPos('.jpg"', s, i+1);
				poster_code := copy(s, i+25, j-i-25);
				poster_url := 'http://www.thetvdb.com/banners/posters/'+poster_code+'.jpg';
				SetImageName('', poster_url, '', 4);
				delete(s, 1, j);
				i := Pos('<a href="banners/posters/', s);
			end;
		end;
	end;
	PostersDownloading := False;
end;

procedure ParseTVDBFanart(all: String);
var
	i, j, posters_count: Integer;
	s, poster_code, poster_url, url: String;
begin
	posters_count := 0;
	if all <> '-1' then begin
		i := Pos('<h1>Fan Art</h1>', all);
		if i>0 then begin
			j := MyPos('<div class="footer">', all, i+1);
			s := copy(all, i, j-i);
			i := Pos('<a href="banners/fanart/', s);
			while (i>0) and (posters_count < MaxPostersCount) do begin
				posters_count := posters_count + 1;
				j := MyPos('.jpg"', s, i+1);
				poster_code := copy(s, i+24, j-i-24);
				poster_url := 'http://www.thetvdb.com/banners/fanart/'+poster_code+'.jpg';
				SetImageName('', poster_url, '', 7);
				delete(s, 1, j);
				i := Pos('<a href="banners/fanart/', s);
			end;
		end;
	end;
	BackdropsDownloading := False;
end;

//show available settings for the script
function ShowScriptOptions: integer;
var
	s: string;
	f: TForm;
	b: TButton;
	cbUseTmdbPosters, cbUseTmdbSnapshots, cbDownloadTvdbEpisodes, cbDownloadTvdbEpisodeDesc, cbTvdbEnglishDesc, cbNoSmallCover, cbNoAmazon, cbUseTvdbPosters, cbUseTvdbFanart, cbKinopoiskBigCover, cbDlType, cbNoVideosInSeries, cbDlBiggerPhoto: TCheckBox;
	TMDBGroup, TVDBGroup: TGroupBox;
	AmazonGroup: TGroupBox;
	rbNoAmazonIfKinopoiskBigCover, rbAlwaysAmazon, rbNeverAmazon: TRadioButton;
	my_value: integer;
	
procedure EpisodeTitlesClick(Sender: TCheckBox);
begin
	if cbDownloadTvdbEpisodes.Checked then begin
		cbDownloadTvdbEpisodeDesc.Enabled := True;
		cbTvdbEnglishDesc.Enabled := True;
	end
	else begin
		cbDownloadTvdbEpisodeDesc.Enabled := False;
		cbTvdbEnglishDesc.Enabled := False;
	end;	
end;

procedure AmazonClick(Sender: TRadioButton);
begin
	if rbNeverAmazon.Checked then begin
		cbNoSmallCover.Enabled := False;
		cbNoSmallCover.Checked := False;
	end
	else begin
		cbNoSmallCover.Enabled := True;
	end;
end;


procedure ButtonClick(Sender: TButton);
var
	zn: integer;
begin
	try
		if cbUseTmdbPosters.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskUseTmdbPosters', zn);	
		if cbUseTmdbSnapshots.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskUseTmdbBackdrops', zn);
		if cbDownloadTvdbEpisodes.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskTVDBEpisodes', zn);
		if cbDownloadTvdbEpisodeDesc.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskTVDBDescriptions', zn);	
		if cbTvdbEnglishDesc.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskTVDBEngDesc', zn);
		if cbNoSmallCover.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskNoSmallCover', zn);
		if cbKinopoiskBigCover.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskBigCover', zn);
		if cbUseTvdbPosters.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskTVDBPosters', zn);
		if cbUseTvdbFanart.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskTVDBFanart', zn);
		if rbAlwaysAmazon.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskAlwaysAmazon', zn);
		if rbNeverAmazon.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskNeverAmazon', zn);
		if rbNoAmazonIfKinopoiskBigCover.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskNoAmazonIfBigCoverAvailable', zn);
		if cbDlType.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskDlType', zn);
		if cbNoVideosInSeries.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskNoVideosInSeries', zn);
		if cbDlBiggerPhoto.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('KinopoiskDlBiggerPhoto', zn);
	except
	end;

	f.ModalResult := mrOk;
end;

begin
	result:=0;
	f := TForm.Create(nil);
	f.Caption := GetLangStr(1924);
	f.BorderStyle := bsDialog;
	f.Position := poScreenCenter;
	f.Width:=420;
	f.Height:=400;
	f.AutoSize:=false;

	TMDBGroup := TGroupBox.Create(f);
	TMDBGroup.Name := 'TMDBGroup';
	TMDBGroup.Parent := f;
	TMDBGroup.SetBounds(10, 10, 390, 40);
	TMDBGroup.Caption := 'Для фильмов скачивать с themoviedb, а не с Кинопоиска:';
	
	cbUseTmdbPosters := TCheckBox.Create(f);
	cbUseTmdbPosters.Name := 'cbUseTmdbPosters';
	cbUseTmdbPosters.Parent := f;
	cbUseTmdbPosters.SetBounds(20, 25, 100, 20);
	cbUseTmdbPosters.Caption := GetLangStr(1425);
	my_value := RegReadInteger('KinopoiskUseTmdbPosters', DL_TMDB_POSTERS);
	if my_value=1 then
		cbUseTmdbPosters.Checked := True;

	cbUseTmdbSnapshots := TCheckBox.Create(f);
	cbUseTmdbSnapshots.Name := 'cbUseTmdbSnapshots';
	cbUseTmdbSnapshots.Parent := f;
	cbUseTmdbSnapshots.SetBounds(120, 25, 100, 20);
	cbUseTmdbSnapshots.Caption := 'Обои';
	my_value := RegReadInteger('KinopoiskUseTmdbBackdrops', DL_TMDB_BACKDROPS);
	if my_value=1 then
		cbUseTmdbSnapshots.Checked := True;
		
	TVDBGroup := TGroupBox.Create(f);
	TVDBGroup.Name := 'TVDBGroup';
	TVDBGroup.Parent := f;
	TVDBGroup.SetBounds(10, 60, 390, 90);
	TVDBGroup.Caption := 'Для сериалов скачивать с thetvdb, а не с Кинопоиска:';
		
	cbDownloadTvdbEpisodes := TCheckBox.Create(f);
	cbDownloadTvdbEpisodes.Name := 'cbDownloadTvdbEpisodes';
	cbDownloadTvdbEpisodes.Parent := f;
	cbDownloadTvdbEpisodes.SetBounds(20, 75, 150, 20);
	cbDownloadTvdbEpisodes.Caption := 'Названия эпизодов';
	my_value := RegReadInteger('KinopoiskTVDBEpisodes', DL_TVDB_EPISODES);
	if my_value=1 then
		cbDownloadTvdbEpisodes.Checked := True;
		
	cbDownloadTvdbEpisodeDesc := TCheckBox.Create(f);
	cbDownloadTvdbEpisodeDesc.Name := 'cbDownloadTvdbEpisodeDesc';
	cbDownloadTvdbEpisodeDesc.Parent := f;
	cbDownloadTvdbEpisodeDesc.SetBounds(30, 95, 150, 20);
	cbDownloadTvdbEpisodeDesc.Caption := 'Описания эпизодов';
	my_value := RegReadInteger('KinopoiskTVDBDescriptions', DL_TVDB_DESCRIPTIONS);
	if my_value=1 then
		cbDownloadTvdbEpisodeDesc.Checked := True;
		
	cbTvdbEnglishDesc := TCheckBox.Create(f);
	cbTvdbEnglishDesc.Name := 'cbTvdbEnglishDesc';
	cbTvdbEnglishDesc.Parent := f;
	cbTvdbEnglishDesc.SetBounds(30, 115, 250, 20);
	cbTvdbEnglishDesc.Caption := 'Описания на английском, если нет русских';
	my_value := RegReadInteger('KinopoiskTVDBEngDesc', DL_TVDB_ENG_DESC);
	if my_value=1 then
		cbTvdbEnglishDesc.Checked := True;
		
	cbUseTvdbPosters := TCheckBox.Create(f);
	cbUseTvdbPosters.Name := 'cbUseTvdbPosters';
	cbUseTvdbPosters.Parent := f;
	cbUseTvdbPosters.SetBounds(290, 75, 100, 20);
	cbUseTvdbPosters.Caption := GetLangStr(1425);
	my_value := RegReadInteger('KinopoiskTVDBPosters', DL_TVDB_POSTERS);
	if my_value=1 then
		cbUseTvdbPosters.Checked := True;
		
	cbUseTvdbFanart := TCheckBox.Create(f);
	cbUseTvdbFanart.Name := 'cbUseTvdbFanart';
	cbUseTvdbFanart.Parent := f;
	cbUseTvdbFanart.SetBounds(290, 95, 100, 20);
	cbUseTvdbFanart.Caption := 'Обои';
	my_value := RegReadInteger('KinopoiskTVDBFanart', DL_TVDB_FANART);
	if my_value=1 then
		cbUseTvdbFanart.Checked := True;
		
	cbKinopoiskBigCover := TCheckBox.Create(f);
	cbKinopoiskBigCover.Name := 'cbKinopoiskBigCover';
	cbKinopoiskBigCover.Parent := f;
	cbKinopoiskBigCover.SetBounds(10, 155, 380, 20);
	cbKinopoiskBigCover.Caption := 'Загружать большую обложку с Кинопоиска, если она есть';
	my_value := RegReadInteger('KinopoiskBigCover', DL_BIG_KINOPOISK_COVER);
	if my_value=1 then
		cbKinopoiskBigCover.Checked := True;
		
	AmazonGroup := TGroupBox.Create(f);
	AmazonGroup.Name := 'AmazonGroup';
	AmazonGroup.Parent := f;
	AmazonGroup.SetBounds(10, 175, 390, 80);
	AmazonGroup.Caption := 'Загружать обложку с Амазона';
	
	rbAlwaysAmazon := TRadioButton.Create(f);
	rbAlwaysAmazon.Name := 'rbAlwaysAmazon';
	rbAlwaysAmazon.Parent := f;
	rbAlwaysAmazon.SetBounds(20, 190, 350, 20);
	rbAlwaysAmazon.Caption := 'Всегда';
	my_value := RegReadInteger('KinopoiskAlwaysAmazon', ALWAYS_USE_AMAZON);
	if my_value=1 then
		rbAlwaysAmazon.Checked := True;
	
	rbNoAmazonIfKinopoiskBigCover := TRadioButton.Create(f);
	rbNoAmazonIfKinopoiskBigCover.Name := 'rbNoAmazonIfKinopoiskBigCover';
	rbNoAmazonIfKinopoiskBigCover.Parent := f;
	rbNoAmazonIfKinopoiskBigCover.SetBounds(20, 210, 350, 20);
	rbNoAmazonIfKinopoiskBigCover.Caption := 'Только если большая не загружена с Кинопоиска';
	my_value := RegReadInteger('KinopoiskNoAmazonIfBigCoverAvailable', NO_AMAZON_COVER_IF_BIG_AVAILABLE);
	if my_value=1 then
		rbNoAmazonIfKinopoiskBigCover.Checked := True;
	
	rbNeverAmazon := TRadioButton.Create(f);
	rbNeverAmazon.Name := 'rbNeverAmazon';
	rbNeverAmazon.Parent := f;
	rbNeverAmazon.SetBounds(20, 230, 350, 20);
	rbNeverAmazon.Caption := 'Никогда';
	my_value := RegReadInteger('KinopoiskNeverAmazon', NEVER_USE_AMAZON);
	if my_value=1 then
		rbNeverAmazon.Checked := True;
	
		
	cbNoSmallCover := TCheckBox.Create(f);
	cbNoSmallCover.Name := 'cbNoSmallCover';
	cbNoSmallCover.Parent := f;
	cbNoSmallCover.SetBounds(20, 260, 380, 20);
	s := GetLangStr(1953);
	if s<>'' then
		cbNoSmallCover.Caption := s
	else
		cbNoSmallCover.Caption := 'Не загружать маленькую обложку, если найдена большая на Амазоне';
	my_value := RegReadInteger('KinopoiskNoSmallCover', NO_SMALL_COVER);
	if my_value=1 then
		cbNoSmallCover.Checked := True;
		
		
	cbDlType := TCheckBox.Create(f);
	cbDlType.Name := 'cbDlType';
	cbDlType.Parent := f;
	cbDlType.SetBounds(20, 280, 380, 20);
	cbDlType.Caption := 'Загружать тип фильма (сериал, ТВ и т.п.)';
	my_value := RegReadInteger('KinopoiskDlType', 1);
	if my_value = 1 then
		cbDlType.Checked := True;
		
	cbNoVideosInSeries := TCheckBox.Create(f);
	cbNoVideosInSeries.Name := 'cbNoVideosInSeries';
	cbNoVideosInSeries.Parent := f;
	cbNoVideosInSeries.SetBounds(20, 300, 380, 20);
	cbNoVideosInSeries.Caption := 'Не загружать фильмы типа "видео" для начала/продолжения серии';
	my_value := RegReadInteger('KinopoiskNoVideosInSeries', 1);
	if my_value = 1 then
		cbNoVideosInSeries.Checked := True;
		
	cbDlBiggerPhoto := TCheckBox.Create(f);
	cbDlBiggerPhoto.Name := 'cbDlBiggerPhoto';
	cbDlBiggerPhoto.Parent := f;
	cbDlBiggerPhoto.SetBounds(20, 320, 380, 20);
	cbDlBiggerPhoto.Caption := 'Загружать большие фотографии';
	my_value := RegReadInteger('KinopoiskDlBiggerPhoto', 1);
	if my_value = 1 then
		cbDlBiggerPhoto.Checked := True;		

	rbNeverAmazon.OnClick := @AmazonClick;
	rbAlwaysAmazon.OnClick := @AmazonClick;
	rbNoAmazonIfKinopoiskBigCover.OnClick := @AmazonClick;
	AmazonClick(rbNeverAmazon);
		

	b := TButton.Create(f);
	b.Name := 'btnOK';
	b.Parent := f;
	b.SetBounds(170, 340, 80, 25);
	b.Caption := '&OK';
	b.OnClick := @ButtonClick;
	
	cbDownloadTvdbEpisodes.OnClick := @EpisodeTitlesClick;
	EpisodeTitlesClick(cbDownloadTvdbEpisodes);

	f.ShowModal;
	f.Free;
end;

procedure SaveLog(s: string);
var
	fs: TFileStream;
begin
		try
			fs:=TFileStream.Create('c:\data.htm', fmCreate);
			fs.Write(s, Length(s));
			fs.Free;
		except
		end;
end;

function RemoveSpacesInText(text: String): String;
var
	i: Integer;
begin
	i := Pos('  ', text);
	while i>0 do begin
		delete(text, i, 1);
		i := Pos('  ', text);
	end;
	result := text;
end;

begin
	DownloadMovieBigCover:=true;
	DownloadMovieShortCast:=true;
	DownloadMovieBigDescription:=true;
	DownloadMovieComments:=true;
	DownloadMovieStudios:=true;
	DownloadMovieAwards:=true;
	DownloadMovieEarnings:=true;
	DownloadMovieAdditionalInfo:=true;
	DownloadMovieSeasonsList:=true;
	MaxShotsCount:=3;
	MaxPostersCount:=0;

	monthes[1]:='января';
	monthes[2]:='февраля';
	monthes[3]:='марта';
	monthes[4]:='апреля';
	monthes[5]:='мая';
	monthes[6]:='июня';
	monthes[7]:='июля';
	monthes[8]:='августа';
	monthes[9]:='сентября';
	monthes[10]:='октября';
	monthes[11]:='ноября';
	monthes[12]:='декабря';


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

	//download posters and backdrops from themoviesdb.org
	tmdb_code:='';
	UseTMDBPosters:=RegReadInteger('KinopoiskUseTmdbPosters', DL_TMDB_POSTERS);
	UseTMDBSnapshots:=RegReadInteger('KinopoiskUseTmdbBackdrops', DL_TMDB_BACKDROPS);
	DownloadTVDBEpisodeDescriptions:=RegReadInteger('KinopoiskTVDBDescriptions', DL_TVDB_DESCRIPTIONS);
	DownloadTVDBEpisodes:=RegReadInteger('KinopoiskTVDBEpisodes', DL_TVDB_EPISODES);
	DownloadTVDBEnglishDesc:=RegReadInteger('KinopoiskTVDBEngDesc', DL_TVDB_ENG_DESC);
	UseTVDBPosters:=RegReadInteger('KinopoiskUseTvdbPosters', DL_TVDB_POSTERS);
	UseTVDBFanart:=RegReadInteger('KinopoiskUseTvdbFanart', DL_TVDB_FANART);
	flUseTMDB:=false;
	NoVideosInSeries := RegReadInteger('KinopoiskNoVideosInSeries', 1) = 1;


	//SiteLogin;
  RequestParameters := TStringList.Create();
  RequestParameters.Add('Host=www.kinopoisk.ru');
  RequestParameters.Add('AcceptLanguage=ru-RU');
  RequestParameters.Add('Connection=Keep-Alive');  
end.
