const
	script_name='filmweb';
	language='Polish';
	version=6;
	author='Vlad';
	MinProgramBuild=6000;
	PCount = 12;
	//MaxPicturesCount = 3;
var
	DownloadMovieBigCover, DownloadMovieShortCast, DownloadMovieFullCast, 
	DownloadMovieBigDescription, DownloadMovieComments, 
	DownloadMovieStudios,	DownloadMovieAwards, DownloadMovieEarnings, 
	DownloadMovieAdditionalInfo, DownloadMovieSeasonsList: boolean;
	MaxShotsCount, MaxPostersCount, MaxTrailersCount, MaxBackdropsCount: integer;

	title, MovieName, s, s2, s3, s4, year, director, name, character, BasicURL, country, description, salary, awards: string;
	episodes, movie_code, movie_site_url, title_code, imdb_code: string;
	titles: array of string;
	titles_count: integer;
	i, j: integer;
	director_code, code: string;
	directors, writers, actors, characters, genres, imdb_codes: array of string;
	duration: integer;
	rating, imdb_rating: double;
	front_cover_url: string;
	posters_exists, ask_amazon: boolean;
	EpisodesDownloading, PostersDownloading, BackdropsDownloading, ShotsDownloading: boolean;
	original_title, mpaa, mpaa_rating: string;
	prefixes: array [1..PCount] of string;
	resolution, barcode, aspect_ratio, features, media_format, video_codec: string;
	TrailersURL, ShotsURL, PostersURL, tvdb_code: string;
	DownloadTVDBEpisodeDescriptions, DownloadTVDBEpisodes, DownloadTVDBEnglishDesc, DownloadSeasonPosters, DownloadEpisodeImages, UseTVDBPosters, UseTVDBFanart: integer;
	RequestParameters, EpisodeURLs: TStringList;
	DownloadSeasonsCovers: Boolean;
	DownloadEpisodesCovers: Boolean;

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

function ClearExtraBlankCharacters(text: string): string;
begin
	// Clear all extra blank charackters
	while (length(text) > 0) and (ord(text[1]) in [1..32]) do
		delete(text, 1, 1);
	while (length(text) > 0) and (ord(text[length(text)]) in [1..32]) do
		delete(text, length(text), 1);
	Result := text;
end;
	
function DeleteBadChars(text: String): String;
var
	i: Integer;
	s : String;
begin
	s := '';
	for i := 1 to Length(text) do begin
		if not (ord(text[i]) in [1..20]) then
			s := s + text[i];
	end;
	Result := s;
end;

function MovieSearch: integer;
var
	i, j, k, l: integer;
	title, tempCode, small_cover, year, director, description, item_type, original_title: string;
begin
	s:='';
	titles_count:=0;
	i := Pos('resultsList">', all);
	if i>0 then begin
		delete(all, 1, i);
		i := Pos('<div class=hitDesc>', all);
		while i>0 do begin
			j := MyPos('<div class=hitDesc>', all, i + 1);
			if j = 0 then
				j := Length(all);
			tempCode := copy(all, i, j-i);
			item_type := LowerCase(GetStr(tempCode, 'searchResultTypeAlias', '</'));
				title := GetStr(tempCode, '<h3>', '</h3>');
				//movie code
				code := ParseString(title, 'href="/film/.*?-(\d+)"', 1);
				if code = '' then
					code := ParseString(title, 'href="/serial/.*?-(\d+)"', 1);
				if code = '' then
					code := ParseString(tempCode, '"dropdownTarget (\d+)_FILM', 1);
				//movie title
				title := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(title)));
				//movie year
				year := '';
				k := Pos('(', title);
				if k>0 then begin
					year := ParseString(title, '\((\d+)', 1);
					delete(title, k, length(title));
					title := ClearExtraBlankCharacters(title);
				end;
				//original title
				original_title := '';
				k := Pos(' / ', title);
				if k>0 then begin
					original_title := copy(title, k + 3, length(title) - 3);
					delete(title, k, length(title) - k + 1);
				end;
				//cover
				small_cover := GetStr(tempCode, '<img src="', '"');
				if Pos('NoImg', small_cover) > 0 then
					small_cover := '';
				//if code = '' then
					//code := GetCodeFromImageURL(small_cover);
				description := GetStr(tempCode, 'searchHitCast>', '</div>');
				description := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(description)));
				if (title <> '') and (code <> '') then begin
					titles_count := titles_count + 1;
					SetSearchResult2(title, code, year, original_title, description, small_cover);
				end;
			delete(all, 1, i);
			i := Pos('<div class=hitDesc>', all);
		end;
	end;

	result:=titles_count;
end;

//get  movie name by barcode(UPC-12)
function GetMovieNameByUPC(barcode: string): string;
var
	url, all, s2, s3, res: string;
	i, j: integer;
begin
	res:='';
	url:=format('http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&SubscriptionId=0J0N83PT9M72BYH98YR2&Operation=ItemSearch&Keywords=%s&SearchIndex=Video&ResponseGroup=Request,Images,Tracks,ItemAttributes', [barcode]);	
	url:=ReplaceStr(url, ' ', '+', -1);
	all:=DownloadURL(url);
	//search image by title
	i:=pos('<Item>', all);
	while (i>0) and (res='') do begin
		j:=MyPos('</Item>', all, i+1);
		if j>0 then begin
			s2:=copy(all, i, j-i);
			s3:=ParseString(s2, '<Title>(.*?) \(.*\)</Title>', 1);
			if s3='' then
				s3:=ParseString(s2, '<Title>(.*?)</Title>', 1);
			if s3<>'' then
				res:=s3;
		end;
		i:=MyPos('<Item>', all, i+1);
	end;
	i:=pos('[', res);
	if i>0 then begin
		j:=MyPos(']', res, i+1);
		if j>0 then
			delete(res, i, j-i+1);
	end;
	result:=res;
end;

//Get search URL by movie name
function GetSearchURLbyName(MovieName, AYear, ABarcode: string): string;
var
	url: string;
begin
	MovieName := EncodeURL(MovieName, 'utf-8');
	url:=format('http://www.filmweb.pl/search?q=%s', [MovieName]);
	url:=ReplaceStr(url, ' ', '+', -1);
	result:=url;
end;

//Download search results from URL
function DownloadSearchURL(url: string): integer;
begin
	all:=DownloadURL(url);
	if all='-1' then
		result:=-1
	else
		result:=MovieSearch;
end;

function GetMovieURL(code: string; images_only: boolean): string;
begin
	result:='http://www.filmweb.pl/film/s-1999-'+code;
end;

//returned link to front cover
function GetAmazonImages: string;
var
	res, all, url, s, s2, s3, amazon_url, my_title: string;
	i, j: integer;
begin
	//discard info in brackets
	s:=title;
	my_title := title;
	i := Pos('[', my_title);
	if i>0 then
		delete(my_title, i, length(my_title) - i + 1);
	url:=format('http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&SubscriptionId=0J0N83PT9M72BYH98YR2&Operation=ItemSearch&Keywords=%s&SearchIndex=Video&ResponseGroup=Request,Images,Tracks,ItemAttributes', [my_title]);
	url:=ReplaceStr(url, ' ', '+', -1);
	all:=DownloadURL(url);
	//search image by title
	amazon_url:='';
	i:=pos('<Item>', all);
	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:=ParseString(s2, '<Title>(.*?) \(.*\)</Title>', 1);
			if s3='' then
				s3:=ParseString(s2, '<Title>(.*?)</Title>', 1);
			s3:=DecodeHTML(s3);
			if s3<>'' then 
			begin
				//if title=s3 then begin //!!!
				if pos(UpperCase(title), UpperCase(s3))=1 then 
				begin
					amazon_url:=ParseString(s2, '<LargeImage><URL>(.*?)</URL>', 1);
				end;
			end;
		end;
		i:=MyPos('<Item>', all, i+1);
	end;
	if amazon_url<>'' then begin
		SetImageName('', amazon_url, '', 1);
		res:=amazon_url;
	end;
	result:=res;
end;

//save front cover to file
function SaveFrontCover(url, FileName: string): boolean;
var
  fs: TFileStream;
	s: string;
begin
	s:=DownloadURL(url);
	if (length(s)>0) and (s<>'-1') then begin
		try
			fs:=TFileStream.Create(FileName, fmCreate);
			fs.Write(s, Length(s));
			fs.Free;
			result:=true;
		except
			result:=false;
		end;
	end
	else
		result:=false;
end;

function MovePrefixLeft(name: string): string;
var
	i, j: integer;
begin
	// replace "The", "A", "An"... to the left
	for j:=1 to PCount do
	begin
		i:=pos(', '+Prefixes[j], name);
		if i>0 then
			if (i = length(name)-length(Prefixes[j])-1) or
			(length(name) >= i+2+length(Prefixes[j])) and (name[i+2+length(Prefixes[j])]=':') then
			begin
				if Prefixes[j][length(Prefixes[j])] = '''' then
					name := Prefixes[j] + copy(name, 1, i-1) + copy(name, i+length(Prefixes[j])+2, length(name)-i-length(Prefixes[j])-2+1)
				else
					name := Prefixes[j]+' ' + copy(name, 1, i-1) + copy(name, i+length(Prefixes[j])+2, length(name)-i-length(Prefixes[j])-2+1);
				break;
			end;
	end;
	Result := name;
end;

function ClearExtraQuotes(name: string): string;
begin
	// Clears extra quotes «"»
	if length(name)>0 then
		if (name[1]='"') and (name[length(name)]='"') then
			name := copy(name,2,length(name)-2);
	Result := name;
end;

function GetCodeFromImageURL(image: String): String;
var
	i, j : Integer;
	code : String;
begin
	i := Pos('.pl/', image);
	code := copy(image, i + 4, length(image) - i - 3);
	for i := 1 to 3 do begin
		j := Pos('/', code);
		if j > 0 then
			delete(code, 1, j);
	end;
	code := ParseString(code, '^(\d+)', 1);
	Result := code;
end;

procedure ExtractPeople(text: String; start, mode: integer);
var
	i, j: Integer;
	temp, s, name, code, character, small_photo: String;
begin
	i := MyPos('</dd>', text, start);
	if i>0 then begin
		temp := copy(text, start, i - start);
		i := Pos('<li>', temp);
		while i>0 do begin
			s := GetStr(temp, '<li>', '</li>');
			character := '';
			//name
			name := GetStr(s, '<span class=personName>', '</span>');
			name := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(name)));
			//photo
			small_photo := GetStr(s, ' src="', '"');
			if (Pos('NoImg', small_photo) > 0) then
				small_photo := '';
			small_photo := ReplaceStr(small_photo, '.2.jpg', '.1.jpg', -1);
			//code
			code := GetStr(s, ' href="/person/', '"');
			code := ParseString(code, '-(\d+)$', 1);
			//extract code from the photo for popular people
			if code = '' then
				code := GetCodeFromImageURL(small_photo);
			if mode = 3 then begin
				character := GetStr(s, '<span class=roleName>', '</span>');
				character := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(character)));
			end;
			//remove dubbing people
			if (Pos('dubbing', s) > 0) then
				name := '';
			if (name <> '') then
				SetPersonName(name, character, mode, code, small_photo);
			delete(temp, 1, i);
			i := Pos('<li>', temp);
		end;
	end;
end;


function GetInfo(url: string; images_only: boolean): string;
var 
	keyword, s, s2, s3, plot_outline, shot, shot_prefix, shot_ext, my_url, temp, small_photo: string;
	i, j, k, l, frames_count, hours, mins: integer;
	actors, awards_exist: boolean;
	cast_url, awards_url, desc_url: String;
	name, code, character, film_info: String;
begin
	result:='';
	all := DownloadURL(url);
	if all='-1' then
		result:='-1'
	else
		result:=all;
		
	EpisodesDownloading := False;
	PostersDownloading := False;
	BackdropsDownloading := False;
	EpisodeURLs := TStringList.Create;
		
	movie_code := ParseString(url, '(\d+)$', 1);
	movie_site_url:=GetMovieSiteURL(movie_code);
	
	title := GetStr(all, '<h1', '</h1>');
	title := ClearExtraBlankCharacters(DecodeHTML(RemoveTags('<' + title)));
	if title='' then
		exit;
	
(*	awards_url := '';
	if (DownloadMovieAwards) and (pos('/awards', all)>0) then begin
		awards_url := movie_site_url + '/awards';
		AddRequestForHTMLPageContent(awards_url, False);
	end;
*)
		
	cast_url := '';
	if (DownloadMovieFullCast) and (Pos('/cast', all)>0) then begin
		cast_url := movie_site_url + '/cast';
		AddRequestForHTMLPageContent(cast_url, False);
	end;
		
	ShotsURL := '';
	if (MaxShotsCount > 6) and (Pos('/photos', all)>0) then begin
		ShotsURL := movie_site_url + '/photos';
		AddRequestForHTMLPageContent(ShotsURL, False);
	end;
	
	PostersURL := '';
	if (MaxPostersCount > 0) and (Pos('/posters', all)>0) then begin
		PostersURL := movie_site_url + '/posters';
		AddRequestForHTMLPageContent(PostersURL, False);
	end;
		
	TrailersURL := '';
	if (MaxTrailersCount > 4) and (Pos('/video', all)>0) then begin
		TrailersURL := movie_site_url + '/video';
		AddRequestForHTMLPageContent(TrailersURL, False);
	end;
		
	desc_url := '';
	if (DownloadMovieBigDescription) and (Pos('/descs', all)>0) then begin
		desc_url := movie_site_url + '/descs';
		AddRequestForHTMLPageContent(desc_url, False);
	end;
	
	//original title
	s := GetStr(all, '<h2 class="text-large caption">', '</h2>');
	original_title := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
	original_title := MovePrefixLeft(original_title);
	
	//year
	year := GetStr(all, '<span id=filmYear', '</span>');
	year := ParseString(year, '>\((\d+)\)', 1);
	
	//download info about tv series from thetvdb
	s := GetStr(all, '</h1>', '</span>');
	if Pos('serial TV', s) > 0 then begin
		if DownloadTVDBEpisodes = 1 then
			EpisodesDownloading := True;
		if UseTVDBPosters = 1 then
			PostersDownloading := True;
		if UseTVDBFanart = 1 then
			BackdropsDownloading := True;
		s := EncodeURL(title, 'utf-8');
		temp := 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]);
		AddRequestForHTMLPageContent(temp, False, '', 'OnTVDBMainPageLoaded');
	end;
	
	//duration
	s := GetStr(all, '<div class=filmTime>', '</div>');
	s2 := ParseString(s, '(\d+) godz.', 1);
	s3 := ParseString(s, '(\d+) min.', 1);
	hours := 0;
	mins := 0;
	try
		hours := StrToInt(s2);
		mins := StrToInt(s3);
	except;
	end;
	duration := hours * 60 + mins;
	
	//site rating
	rating := 0;
	s := GetStr(all, '<span class=filmRate>', '</strong');
	s := ClearExtraBlankCharacters(RemoveTags(s));
	i := Pos(',', s);
	if i > 0 then
		s[i] := DecimalSeparator;
	try
		rating := StrToFloat(s);
	except
	end;
	
	//movie plot
	description := GetStr(all, '<div class=filmPlot>', '</div>');
	if description = '' then
		description := GetStr(all, '<p class=text property="v:summary">', '</p>');
	description := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(description)));
	
	//front cover
	s := GetStr(all, '<div class=filmPosterBox>', '</a></div>');
	front_cover_url := GetStr(s, ' src="', '?');
	
	//film info
	film_info := GetStr(all, '<div class=filmInfo>', '</div>');
	
	//genres
	s := GetStr(film_info, 'gatunek:', '</tr>');
	while (Pos('<li>', s)>0) do begin
		SetGenre(ClearExtraBlankCharacters(RemoveTags(GetStr(s, '<li>', '</li>'))));
		delete(s, 1, Pos('<li>', s));
	end;
	
	//countries
	s := GetStr(film_info, 'produkcja:', '</tr>');
	while (Pos('<li>', s)>0) do begin
		SetCountry(ClearExtraBlankCharacters(RemoveTags(GetStr(s, '<li>', '</li>'))));
		delete(s, 1, Pos('<li>', s));
	end;

	//cast and crew - full page
	if (cast_url <> '') then begin
		temp := GetHTMLPageContentFromRequest(cast_url);
		i := Pos('pełna obsada</h2>', temp);
		if i>0 then begin
			delete(temp, 1, i);
			//directors
			i := Pos('<dt id="role-director">', temp);
			if i = 0 then
				i := Pos('<dt id=role-director>', temp);
			if i>0 then
				ExtractPeople(temp, i, 1);
			//screenplay writers
			i := Pos('<dt id="role-screenwriter">', temp);
			if i = 0 then
				i := Pos('<dt id=role-screenwriter>', temp);
			if i>0 then
				ExtractPeople(temp, i, 2);
			//actors
			i := Pos('<dt id="role-actors">', temp);
			if i = 0 then
				i := Pos('<dt id=role-actors>', temp);
			if i>0 then
				ExtractPeople(temp, i, 3);
			//composers
			i := Pos('<dt id="role-music">', temp);
			if i = 0 then
				i := Pos('<dt id=role-music>', temp);
			if i>0 then
				ExtractPeople(temp, i, 4);
		end;
	end
	//short cast and crew
	else begin
		//cast
		temp := GetStr(all, 'obsada</a></h2>', '<div class=clear>');
		i := Pos('<li>', temp);
		while i>0 do begin
			s := GetStr(temp, '<li>', '</li>');
			code := GetStr(s, ' href="/person/', '"');
			code := ParseString(code, '(\d+)$', 1);
			small_photo := GetStr(s, ' src="', '"');
			if (Pos('NoImg', small_photo) > 0) then
				small_photo := '';
			small_photo := ReplaceStr(small_photo, '.2.jpg', '.1.jpg', -1);
			if code = '' then
				code := GetCodeFromImageURL(small_photo);
			name := GetStr(s, '<span class=personName>', '</span>');
			name := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(name)));
			character := GetStr(s, '<span class=roleName>', '</span>');
			character := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(character)));
			if (name <> '') then
				SetPersonName(name, character, 3, code, small_photo);
			delete(temp, 1, i);
			i := Pos('<li>', temp);
		end;
	end;
	
	//descriptions
	if (desc_url <> '') then begin
		temp := GetHTMLPageContentFromRequest(desc_url);
		i := Pos('opisy filmu</h2>', temp);
		if i>0 then begin
			delete(temp, 1, i);
			i := Pos('<script', temp);
			delete(temp, i, length(temp)-i+1);
			s := GetStr(temp, '<p class=text>', '</p>');
			if s <> '' then begin
				if description <> '' then
					description := description + #13#10#13#10;
				description := description + ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
			end;
		end;
	end;	
end;

procedure GetShots;
var
	s, temp, img_url: String;
	img_cnt, i: Integer;
begin
	img_cnt := 0;
	temp := GetHTMLPageContentFromRequest(ShotsURL);
	i := Pos('zdjęcia</h2>', temp);
	if i>0 then begin
		delete(temp, 1, i);
		i := Pos(' src="', temp);
		while (i>0) and (img_cnt < MaxShotsCount) do begin
			img_url := GetStr(temp, ' src="', '"');
			img_url := ReplaceStr(img_url, '.2.jpg', '.1.jpg', -1);
			img_url := ReplaceStr(img_url, '.0.jpg', '.1.jpg', -1);
			if (img_url <> '') and (Pos('.js', img_url) = 0) then begin
				SetImageName('', img_url, '', 3);
				Inc(img_cnt);
			end;
			delete(temp, 1, i);
			i := Pos(' src="', temp);
		end;
	end;
end;

procedure GetTrailers;
var
	s, temp, trailer_url, img_url: String;
	i, img_cnt: Integer;
begin
	img_cnt := 0;
	temp := GetHTMLPageContentFromRequest(TrailersURL);
	i := Pos('zwiastuny <span class=caption>', temp);
	if i>0 then begin
		delete(temp, 1, i);
		i := Pos(' href="/video/trailer/', temp);
		while (i>0) and (img_cnt < MaxTrailersCount) do begin
			trailer_url := GetStr(temp, ' href="/video/trailer/', '"');
			if trailer_url <> '' then begin
				trailer_url := 'http://www.filmweb.pl/video/trailer/' + trailer_url;
				img_url := GetStr(temp, 'url(''', '''');
				SetTrailer(trailer_url, '', img_url);
			end;
			delete(temp, 1, i);
			i := Pos(' href="/video/trailer/', temp);
		end;
	end;
end;

procedure GetPosters;
var
	s, temp, img_url: String;
	i, img_cnt: Integer;
begin
	img_cnt := 0;
	temp := GetHTMLPageContentFromRequest(PostersURL);
	i := Pos('plakaty</h2>', temp);
	if i>0 then begin
		delete(temp, 1, i);
		i := Pos('<script', temp);
		if i>0 then
			delete(temp, i, length(temp)-i+1);
		i := Pos('<li', temp);
		while (i > 0) and (img_cnt < MaxPostersCount) do begin
			s := GetStr(temp, '<li', '</li>');
			img_url := GetStr(s, ' src="', '"');
			img_url := ReplaceStr(img_url, '.2.jpg', '.3.jpg', -1);
			if (img_url <> '') and (Pos('.js', img_url) = 0) then begin
				SetImageName('', img_url, '', 4);
				Inc(img_cnt);
			end;
			delete(temp, 1, i);
			i := Pos('<li', temp);
		end;
	end;		
end;

//returned images links
procedure GetImages;
var
	i, img_cnt: Integer;
	temp, img_url, trailer_url: String;
begin
	if front_cover_url<>'' then begin
		front_cover_url := ReplaceStr(front_cover_url, '.6.jpg', '.3.jpg', -1);
		SetImageName('', front_cover_url, '', 1);
	end;
		
	//shots from the movie
	if ShotsURL <> '' then
		GetShots
	else begin
		img_cnt := 0;
		temp := GetStr(all, 'zdjęcia</a></h2>', '</div></div>');
		i := Pos(' src="', temp);
		while (i>0) and (img_cnt < MaxShotsCount) do begin
			img_url := GetStr(temp, ' src="', '"');
			img_url := ReplaceStr(img_url, '.2.jpg', '.1.jpg', -1);
			if (img_url <> '') and (Pos('.js', img_url) = 0) then begin
				SetImageName('', img_url, '', 3);
				Inc(img_cnt);
			end;
			delete(temp, 1, i);
			i := Pos(' src="', temp);
		end;
	end;
	//trailers
	if TrailersURL <> '' then
		GetTrailers
	else begin
		img_cnt := 0;
		temp := GetStr(all, 'zwiastuny</a></h2>', '</div></div>');
		i := Pos(' href="/video/trailer/', temp);
		while (i>0) and (img_cnt < MaxTrailersCount) do begin
			trailer_url := GetStr(temp, ' href="/video/trailer/', '"');
			if trailer_url <> '' then begin
				trailer_url := 'http://www.filmweb.pl/video/trailer/' + trailer_url;
				img_url := GetStr(temp, 'url(''', '''');
				SetTrailer(trailer_url, '', img_url);
			end;
			delete(temp, 1, i);
			i := Pos(' href="/video/trailer/', temp);
		end;
	end;
	if (PostersURL <> '') then
		GetPosters;
	while EpisodesDownloading do 
		Application.ProcessMessages;
	while PostersDownloading do
		Application.ProcessMessages;
	while BackdropsDownloading do
		Application.ProcessMessages;
	for i := 0 to EpisodeURLs.Count - 1 do
		GetHTMLPageContentFromRequest(EpisodeURLs[i]);
	EpisodeURLs.Free;
end;

//get movie site url
function GetMovieSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:='http://www.filmweb.pl/film/s-1999-'+code;
end;

//get person site url
function GetPersonSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:='http://www.filmweb.pl/person/s-'+code;
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, 18);
		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=18', [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
				EpisodesDownloading := False;
			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;
begin
	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
						if (DownloadTVDBEnglishDesc = 1) 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;
					end
					else begin
						episodes_count := episodes_count + 1;
						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;
end;

//download page with episode description and extract the description
procedure GetTVDBEpisodeDescription(all: string);
var
	i, j : Integer;
	s, s2, desc: String;
	not_done: 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_18" 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_18"', 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
			SetEpisode(season, episode, EpisodeTitle, EpisodeDescription, '', AirDate);			
		end;
	end;
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;


begin

prefixes[1]:='The';
prefixes[2]:='A';
prefixes[3]:='An';
prefixes[4]:='La';
prefixes[5]:='Les';
prefixes[6]:='Des';
prefixes[7]:='L''';
prefixes[8]:='Un';
prefixes[9]:='El';
prefixes[10]:='Il';
prefixes[11]:='Le';
prefixes[12]:='Uno';

DownloadTVDBEpisodeDescriptions := 1;
DownloadTVDBEpisodes := 1;
DownloadTVDBEnglishDesc := 1;
DownloadSeasonPosters := 1;
DownloadEpisodeImages := 1;
UseTVDBPosters := 1;
UseTVDBFanart := 1;


end.