//Fixed bug on Original title when using local service
//Added options - reorganized options interface

const
	script_name='imdb';
	language='Multiple';
	version=145;
	author='JeF';
	MinProgramBuild=6200;
	PCount = 12;
	main_server=['imdb.com', 'imdb.de', 'imdb.es', 'imdb.fr', 'imdb.it', 'imdb.pt'];
	defaultPicSizeX=800;
	defaultPicSizeY=600;
	
var
	DownloadMovieBigCover, DownloadMovieShortCast, DownloadMovieFullCast, 
	DownloadMovieBigDescription, DownloadMovieComments,
	DownloadMovieStudios,	DownloadMovieAwards, DownloadMovieEarnings, 
	DownloadMovieAdditionalInfo, DownloadMovieSeasonsList, DownloadMovieLinks: boolean;
	MaxShotsCount, MaxPostersCount, MaxBackdropsCount: integer;
	// 10.11.2010
	MaxTrailersCount: Integer;
	DownloadSeasonsCovers: Boolean;
	DownloadEpisodesCovers: Boolean;
	DownloadedPersonPhotosForMovie: Integer;

	OvrMainDlOptions, DlOriginalTitle, DlYear, DlGenres, DlCountries, DlDuration, DlStudios, DlEpisodes : boolean;
	DlDirectors, DlActors, DlWriters, DlComposers, DlAwards : boolean;

	title, MovieName, MovieTitle, MovieYear, MovieBarcode, year, director, name, character, BasicURL, description, country, salary, awards, tagline, media_type: string;
	movie_code, movie_site_url, title_code, imdb_code: string;
	duration: integer;
	titles_count: integer;
	i, j: integer;
	code: string;
	imdb_rating, rating: double;
	front_cover_url: string;
	posters_exist: boolean;
	original_title, mpaa, mpaa_rating: string;
	prefixes: array [1..PCount] of string;
	monthes: array [1..12] of string;
	goCode: string;  // 20090519-JeF
	jShowTraceSettings, jTraceMode, jTraceLevel, jTraceAsk: integer;   // 20101017-JeF
	DownloadTrivia, DownloadGoofs, DownloadQuotes, DownloadConnections, DownloadSoundtracks, ImportDesc, AkaSearch, ShowPlotAuthors, EpisodeFullDesc, AkasInDesc, ImportMPAAReasons, IMDBLocalService: Integer;
	TitleLang, MPAADefault, MPAAReplace: String;
	resolution, barcode, aspect_ratio, features, media_format, video_codec: String;
	SubtitlesCount: Integer;
	AudioTracksCount: Integer;
	tmdb_code, tvdb_code: String;
	RequestParameters, EpisodeURLs: TStringList;
	RequestParametersWithCookies: TStringList;
	EpisodesDownloading, PostersDownloading, BackdropsDownloading, ShotsDownloading: Boolean;
	UseTMDBPosters, UseTMDBSnapshots, DownloadTVDBEpisodeDescriptions, DownloadTVDBEpisodes,
    DownloadTVDBEnglishDesc, DownloadSeasonPosters, DownloadEpisodeImages,
    UseTVDBPosters, UseTVDBFanart, TVDBLID, DownloadActorsEpisodesForTVSeries: integer;
	
	f: TForm;
	b: TButton;
	edUserName, edPassword, edURL: TEdit;
	labCaption, labCaption2, labUserName, labPassword: TLabel;

	// 18.03.2013. Fade - global cookies from HTTPS
	GlobalHTTPSCookies: string;


	
//determine if MovieName is a code number and remember this code  // 20090519-JeF
function checkCode(MovieName: string): Boolean;
var
	i,j: integer;
begin
	goCode:='';
	while (copy(MovieName,1,1)=' ') do delete(MovieName,1,1);
	while (copy(MovieName,length(MovieName),1)=' ') do delete(MovieName,length(MovieName),1);
	//Check if only a code
	i:=1;
	if (length(MovieName)>0) then goCode:=MovieName;
	while (i<length(goCode)) do begin 
		if (copy(goCode,i,1) < '0') or (copy(goCode,i,1) > '9') then goCode:='';
		i:=i+1;
	end;
	if (length(goCode)<7) then goCode:='';
	//Check if tt999999 somewhere in title
	i:=pos('TT',UpperCase(MovieName));
	while (i>0) and (goCode='') do begin
		j:=i+2;
		while (j<=length(MovieName)) and (goCode='') do begin
			if (copy(MovieName,j,1) < '0') or (copy(MovieName,j,1) > '9') then goCode:=copy(MovieName,i+2,j-i-2);
			if (j=length(MovieName)) and (goCode='') then goCode:=copy(MovieName,i+2,j-i-1);  //20120414-JeF
			j:=j+1;
		end;
		if (length(goCode)<7) then goCode:='';
		i:=MyPos('TT',UpperCase(MovieName),i+1);
	end;
	result:=(goCode>'');
end;
	
function MovieSearch: integer;
const
	pop_match=['<p><b>Popular Titles</b>', '<p><b>Meistgesuchte Titel</b>', 'tulos Populares</b> (Mostrando', '<p><b>Titres Populaires</b>', '<p><b>Titoli popolari</b>', 'tulos Populares</b> (Exibir'];
	exact_match=['<p><b>Titles (Exact Matches)', '<p><b>Titel (genaue ', 'tulos (Resultados Exactos)</b> (Mostrando', 'sultats Exacts)</b> (Affichant', '<p><b>Titoli (risultati esatti)', 'tulos (Exato)</b> (Exibir'];
	partial_match=['<p><b>Titles (Partial Matches)</b>', '<p><b>Titel (teilweise ', 'tulos (Resultados Parciales)</b> (Mostrando', 'sultats Partiels)</b>', '<p><b>Titoli (risultati parziali)', 'o Parcial)</b> (Exibir'];
	no_match=['<b>No Matches.</b>', '<b>Keine Treffer.</b>', '<b>No hay resultados.</b>', '<b>Pas de ', '<b>Nessun risultato.</b>', '<b>Busca imcompat'];
var
	i, j, k, l, next_section: integer;
	title, s, s2, s3, year, original_title, description, small_cover: string;
begin
	//is MovieName a code number ? Yes => force url and only ONE result to continue directly to movie download // 20090519-JeF
	if length(goCode)>0 then begin
		titles_count:=1;
		SetSearchResult(goCode, goCode);
		result:=titles_count;
		exit;
	end;

	s:='';
	next_section:=0;
	titles_count:=0;
	
	//this is for the method used with barcodes
	i := Pos('<table class="results">', all);
	if i>0 then begin
		j := MyPos('</table>', all, i+1);
		s := copy(all, i, j-i);
		if s<>'' then begin
			i := Pos('<tr class="even detailed">', s);
			delete(s, 1, i-1);
			i := Pos('</tr>', s);
			while i>0 do begin
				s2 := copy(s, 1, i-1);
				k := Pos('<a href="/title/tt', s2);
				if k>0 then begin
					j := MyPos('</a>', s2, k + 1);
					s3 := copy(s2, k, j-k);
					title_code := ParseString(s3, '<a href="/title/tt(\d+)/', 1);
					title := ParseString(s3, '\/" title="(.*?)"><img', 1);
					title := DecodeHTML(title);
					small_cover := ParseString(s3, '<img src="(.*?).jpg" ', 1);
					if small_cover <>'' then
						small_cover := small_cover + '.jpg';
					if title_code <> '' then begin
						titles_count := titles_count + 1;
						SetSearchResult2(title, title_code, '', '', '', small_cover);
					end;
				end;
				delete(s, 1, i+3);
				i := Pos('</tr>', s);
				if MovieBarcode <> '' then
					i := 0; //let's grab only the first result
			end;
		end;
	end
	else begin	
		//new search design - 2012-11-28
		i := Pos('<a name="tt"></a>Titles</h3>', all);
		if i>0 then begin
			j := MyPos('</table>', all, i+1);
			s := copy(all, i, j-i);
			if s <> '' then begin
				i := Pos('<tr class="findResult', s);
				while i>0 do begin
					s2 := GetStr(s, '<tr class="findResult', '</tr>');
					title := GetStr(s2, '<td class="result_text">', '</a>');
					title := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(title)));
					title_code := ParseString(s2, '<a href="/title/tt(\d+)', 1);
					s3 := GetStr(s2, '<td class="result_text">', '</td>');
					k := Pos('</a>', s3);
					delete(s3, 1, k + 3);
					year := ParseString(s3, '.*? \((\d+)\)', 1);
					description := ParseString(s2, '\(\d+\) \((.*?)\)', 1);
					description := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(description)));
					small_cover := GetStr(s2, ' src="', '"');
					if (Pos('nopicture', small_cover)>0) then
						small_cover := '';
					original_title := '';
					original_title := GetStr(s3, '<i>', '</i>');
					original_title := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(original_title)));
					if (Pos('Video Game', description)>0) then
						title := '';
					if (title <> '') and (title_code <> '') then begin
						inc(titles_count);
						SetSearchResult2(title, title_code, year, original_title, description, small_cover);
					end;
					delete(s, 1, i);
					i := Pos('<tr class="findResult', s);
				end;
			end;
		end
		//end new search design -2012-11-28
		else begin
			i := Pos(exact_match[ifthen((AkaSearch=1),0,IMDBLocalService)], all);    //20110123-JeF
			j := Pos('<p><b>Titles (Approx Matches)</b> (Displaying', all);
			k := Pos(pop_match[ifthen((AkaSearch=1),0,IMDBLocalService)], all);      //20110123-JeF
			l := Pos(partial_match[ifthen((AkaSearch=1),0,IMDBLocalService)], all);  //20110123-JeF
			if (k<i) and (k>0) then begin
				next_section := i;
				i := k;
			end
			else if (i=0) then
				i := k
			else
				next_section := k;
			if (l<j) and (l>0) then
				j := l;
			if (i=0) and (k=0) then
				i := j;
			//for the movie info page (no search results shown)
			s3 := ReplaceStr('href="http://www.imdb.com/title/tt', 'imdb.com', main_server[ifthen((AkaSearch=1),0,IMDBLocalService)], -1);    //20110123-JeF
			if i=0 then begin
				if (Pos('<h1', all)>0) then begin
					i := Pos('<link rel="canonical" ' + s3, all);
					if i>0 then begin
						j := MyPos('>', all, i+1);
						s := copy(all, i, j-i);
						title_code := ParseString(s, s3+'(\d+)"', 1);
						if title_code = '' then
							title_code := ParseString(s, s3+'(\d+)/', 1);
						titles_count := 1;
						SetSearchResult('title', title_code);
						i := 0;
						s := '';
					end;
				end;
			end;
			//end for short titles
			if i>0 then begin
				j:=MyPos('</td></tr></table>', all, i+1);
				if j>0 then
					s:=copy(all, i+3, j-i-3);
			end;

			if (s='') or (pos(no_match[ifthen((AkaSearch=1),0,IMDBLocalService)], all)>0) then
				//Movie not found
			else begin
				repeat
				  i := pos('<table>',s);
				  s := copy(s,i+7,length(s));
				  i:=pos('</tr>', s);
				  if i=0 then
					i:=next_section;
				  if i=0 then
					i:=Length(s);
				  while i>0 do begin
						titles_count:=titles_count+1;
						s2:=copy(s, 1, i-1);

						j:=Pos('<a href="/title/tt', s2);
						k:=MyPos('</a>', s2, j+1);
						s3:=copy(s2, j, k-j);
						title_code:=ParseString(s3, '<a href="/title/tt(\d+)/"', 1);
						
						title := '';
						k := Pos('<br><a href="/title/', s2);
						if k=0 then
							k := Pos('<td valign="top"><a href="/title/', s2);
						if k>0 then begin
							l := MyPos('</a>', s2, k+1);
							title := copy(s2, k, l-k);
						end;
						title:=RemoveTags(title);
						title:=DecodeHTML(title);
						title:=ClearExtraSpaces(title);
						
						original_title := '';
						
						year := '';
						k := Pos('</a> (', s2);
						if k>0 then begin
							l := MyPos(')', s2, k);
							year := copy(s2, k+6, l-k-6);
						end;
						
						small_cover := '';
						k := Pos('<img src="http://ia.media-imdb.com/images/', s2);
						if k >0 then begin
							l := MyPos('"', s2, k+11);
							small_cover := copy(s2, k+10, l-k-10);
							k := Pos('_V1._', small_cover);
							if k = 0 then
								k := Pos('_V1_', small_cover);
							if k>0 then begin
								l := MyPos('_.', small_cover, k+5);
								s3 := copy(small_cover, l, length(small_cover)-l+1);
								delete(small_cover, k+5, length(small_cover)-k-4);
								//set maximum image resolution
								small_cover := small_cover + 'SY100_SX100' +  s3;
							end;
						end;
						
						description := '';
						k := Pos('<p ', s2);
						if k>0 then begin
							description := copy(s2, k, length(s2)-k+1);
							description := ReplaceStr(description, '</p>', ' ', -1);
							description := RemoveTags(description);
							description := DecodeHTML(description);
							description := ClearExtraSpaces(description);
						end;
						// showMessage(description);
						
						while (length(title)>0) and (title[1]=' ') do
							delete(title, 1, 1);
						SetSearchResult2(title, title_code, year, original_title, description, small_cover);
						delete(s, 1, i+4);
						i:=pos('</tr>', s);
						if i=0 then
							i:=Length(s);
					end;
					//this will work for short titles
					i:=next_section;
					next_section:=MyPos(partial_match[ifthen((AkaSearch=1),0,IMDBLocalService)], all, i+1);
					s:='';
					if i>0 then begin
						j:=MyPos('</td></tr></table>', all, i+1);
						if j>0 then
							s:=copy(all, i+3, j-i-3);
					end;
				until s='';
				//end sort titles
			end;
		end;
	end;
	//if nothing is found by title and year, then try again by title only
	if (titles_count = 0) and (MovieYear <> '') then begin
		s := GetSearchURLByName(MovieTitle, '', '');
		all := DownloadURL(s, False, RequestParametersWithCookies);
		result := MovieSearch;
		exit;
	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, False, RequestParametersWithCookies);
	//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;

// 18.03.2013. Fade - function connects to imdb using given ALogin-APassword
function ConnectToIMDB(ALogin: string; APassword: string): Boolean;
const
  LOGIN_FORM_URL = 'https://secure.imdb.com/oauth/login?origurl=http://www.imdb.com/&show_imdb_panel=1';
  ENABLE_ADULT_CONTENT_URL = 'http://www.imdb.com/find';
  HIDDEN_VALUE_NAME = '49e6c';
  HIDDEN_VALUE_SEARCH = 'input type="hidden" name="' + HIDDEN_VALUE_NAME + '" value="';
var
  I: Integer;
  HiddenValue: string;
  HiddenValuePos: Integer;
  LoginFormContent, ResponsePage: string;
begin
  // open login form for parsing hidden value
  Result := True;
  LoginFormContent := DownloadURLWithRefererThroughHTTPS(LOGIN_FORM_URL, '',
    GlobalHTTPSCookies);
  HiddenValue := '';
  HiddenValuePos := MyPos(HIDDEN_VALUE_SEARCH, LoginFormContent, -1);
  // if hidden value wasn't found - we already connected to IMDB
  if (HiddenValuePos > 0) then
  begin
    HiddenValuePos := HiddenValuePos + Length(HIDDEN_VALUE_SEARCH);
    if (MyPos('"', LoginFormContent, HiddenValuePos) > 0) then
    begin
      // connect to IMDB taking into account hidden value/login/password
      HiddenValue := Copy(LoginFormContent, HiddenValuePos,
        MyPos('"', LoginFormContent, HiddenValuePos) - HiddenValuePos);
      if (HiddenValue <> '') then
      begin
        // now connect to imdb
        ResponsePage := DownloadURLWithRefererThroughHTTPS(LOGIN_FORM_URL, LOGIN_FORM_URL, GlobalHTTPSCookies,
          [HIDDEN_VALUE_NAME + '=' + HiddenValue, 'login=' + ALogin, 'password=' + APassword]);
        // enable adult content
        DownloadURLWithRefererThroughHTTPS(ENABLE_ADULT_CONTENT_URL, '', GlobalHTTPSCookies,
          ['q=', 's=all', 'ttype=', 'toggleAdult=1']);
		//check if the login was successful
		if (Pos('<h1>Sign in ', ResponsePage) > 0) then Result := False;
      end;
    end;
  end;
end;
//Get search URL by movie name
function GetSearchURLbyName(MovieName: string; AYear: string; ABarcode: String): string;
var
	url, s: string;
	i: integer;
	site: string;		// 20090701-JeF
begin
	s := copy(MovieName, 1, Length(MovieName));
	s := ClearExtraBlankCharacters(s);
	s := EncodeURL(s, 'utf-8');
	MovieTitle := MovieName;
	MovieYear := AYear;
	MovieBarcode := ABarcode;
	if AYear <> '' then begin
		i := Pos(' (', s);
		if i>0 then
			delete(s, i, length(s)- i + 1);
		url := Format('http://www.imdb.com/search/title?release_date=%s,%s&title=%s', [AYear, AYear, s]);
		url:=ReplaceStr(url, ' ', '+', -1);
	end
	else begin
		if AkaSearch=1 then site:='http://akas.imdb.com/'
		else site:='http://www.imdb.com/';
		if RegReadInteger('IMDBAdvSearch', 0) = 1 then
			url := site + 'search/title?title=' + s
		else
			url:=site+format('find?q=%s&s=tt&ref_=fn_al_tt_ex', [s]);
		url:=ReplaceStr(url, ' ', '+', -1);
		if AkaSearch=0 then // 20110123-JeF
			url:=ReplaceStr(url, 'imdb.com', main_server[IMDBLocalService], -1);
		goCode := '';
		if (length(s)>5) and (checkCode(s)) then url:=GetMovieSiteURL(goCode);  // 20090519-JeF
	end;
	result:=url;
end;
procedure LoginButtonClick(Sender: TButton);
begin
	if (edUserName.Text <> '') and (edPassword.Text <> '') then begin
		UserName:=edUserName.Text;
		UserPassword:=edPassword.Text;
		SaveLoginInfo(UserName, UserPassword, script_name);
		if ConnectToIMDB(UserName, UserPassword) then
			f.ModalResult := mrOk
		else begin
			showMessage(GetLangStr(3707));
			f.ModalResult := mrNone;
		end;
	end
	else begin
		if (edUserName.Text = '') then
			ShowMessage(GetLangStr(3708))
		else if (edPassword.Text = '') then
			ShowMessage(GetLangStr(3709));
		f.ModalResult := mrNone;
	end;
end;

procedure ShowLoginForm;
begin
	f := TForm.Create(nil);
	f.Caption := GetLangStr(3701) + ': IMDb';
	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 := GetLangStr(3701) + ': IMDb';

	labUserName := TLabel.Create(f);
	labUserName.Name := 'labUserName';
	labUserName.Parent := f;
	labUserName.SetBounds(10, 40, 100, 25);
	labUserName.Caption := GetLangStr(1835) + ':';

	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 := GetLangStr(1836) + ':';

	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 := GetLangStr(3693);
	b.OnClick := @LoginButtonClick;


	labCaption2 := TLabel.Create(f);
	labCaption2.Name := 'labCaption2';
	labCaption2.Parent := f;
	labCaption2.SetBounds(10, 100, 275, 25);
	labCaption2.Caption := GetLangStr(3717) + ':';

	edURL := TEdit.Create(f);
	edURL.Name := 'URL';
	edURL.Parent := f;
	edURL.SetBounds(10, 125, 370, 25);
	edURL.Text := 'https://secure.imdb.com/register-imdb/form-v2';

	f.ShowModal;
	f.Free;
end;


//Download search results from URL
function DownloadSearchURL(url: string): integer;
begin
	if (jTraceLevel > 0) then TraceAlert;   				 // 20101017-JeF
	all:=DownloadURL(url, False, RequestParametersWithCookies);
	if (jTraceLevel >= 1) then TraceExecute('Search',all);   // 20101017-JeF
	if all='-1' then
		result:=-1
	else
		result:=MovieSearch;
end;

function GetMovieURL(code: string; images_only: boolean): string;
begin
	if images_only then
		result:=format('http://www.imdb.com/title/tt%s', [code])
	else
		result:=format('http://www.imdb.com/title/tt%s/combined', [code])
end;

                          
//save front cover to file
function SaveFrontCover(url, FileName: string): boolean;
var
  fs: TFileStream;
	s: string;
begin
	all:=DownloadURL(url, False, RequestParametersWithCookies);
	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 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;

function ExtractAwards(text: string): string;
var
	i, j, k, l, m: integer;
	s, s2, extracted_awards: string;
begin
	extracted_awards:='';
	i:=Pos('<td valign="top">', text);
	while i>0 do begin
		//What the award is for
		j:=MyPos('<br>', text, i+1);
		s:=copy(text, i+17, j-i-17);
		s:=ClearExtraBlankCharacters(s);
		if extracted_awards<>'' then
			extracted_awards:=extracted_awards+#13#10;
		extracted_awards := extracted_awards + s;
		//Now who got the award
		i:=j+4;
		j:=MyPos('</small>', text, i+1);
		m:=MyPos('<small>', text, i+1);
		s:=copy(text, i, j-i);
		k:=Pos('<a href="/name/', s);
		if extracted_awards <> '' then
			extracted_awards := extracted_awards + ' ';
		if (k>0) and (extracted_awards<>'') then
			extracted_awards:=extracted_awards+': ';
		while k>0 do begin
			l:=MyPos('</a>', s, k+1);
			s2:=copy(s, k, l-k);
			s2:=ClearExtraBlankCharacters(RemoveTags(s2));
			if s2<>'' then
				extracted_awards := extracted_awards + s2;
			delete(s, 1, l);
			k:=Pos('<a href="/name/', s);
			if k>m then
				k:=0
			else if k>0 then
				extracted_awards := extracted_awards + ', ';
		end;
		s2:=copy(text, m+7, j-m-7);
		s2 := ClearExtraBlankCharacters(RemoveTags(s2));
		s2 := ReplaceStr(s2, #10, '', -1);
		s2 := RemoveSpacesInText(s2);
		if s2<>'' then
			extracted_awards := extracted_awards + '(' + s2 + ')';
		delete(text, 1, j);
		i:=Pos('<td valign="top">', text);
	end;
	Result := DecodeHTML(extracted_awards);  // 20090910-JeF
end;

procedure ParseImageSizeFromURL(AURL: string; var AHeight: Integer; var AWidth: Integer);
var
  TempStr: string;
  SearchCount: Integer;
  Index: Integer;
  DeltaX: Integer;
  DeltaY: Integer;
begin
  if (AURL <> '') then
  begin
    AHeight := 0;
    AWidth := 0;
    Index := Length(AURL);
    SearchCount := 0;
    TempStr := '';
    DeltaX := 0;
    DeltaY := 0;

    if (AURL[Index] = '_') then
    begin
      Dec(Index);
      while ((Index > 0) and
             (SearchCount < 4)) do
      begin
        if ((AURL[Index] = ',') or
            (AURL[Index] = 'R')) then
        begin
          case SearchCount of
            0: AHeight := StrToInt(TempStr);
            1: AWidth := StrToInt(TempStr);
            2: DeltaY := StrToInt(TempStr);
            3: DeltaX := StrToInt(TempStr);
          end;
          TempStr := '';
          Inc(SearchCount);
        end
        else
          TempStr := AURL[Index] + TempStr;
        Dec(Index);
      end;
    end;
    if (AWidth > 0) then
      AWidth := AWidth + Round(2 * DeltaX);
    if (AHeight > 0) then
      AHeight := AHeight + Round(2 * DeltaY);
  end;
end;

//gets movie frames
function GetFramesPreview(AMovieCode: string; frame_type: string; frame_limit, frame_code: integer): integer;
var
  url, all, s, frame_url: string;
  preview_url: string;
  i, j, k, picSizeX, picSizeY: Integer;
  frames_count: Integer;
  Height: Integer;
  Width: Integer;
  SizeURL: string;
begin
  frames_count:=0;
  if frames_count=0 then
  begin
    picSizeX := 150;
    picSizeY := 150;
    url := 'http://www.imdb.com/title/tt' + AMovieCode + '/mediaindex?refine='+frame_type;
    all:=DownloadURL(url, False, RequestParametersWithCookies);
    if (all <> '')and(all <> '-1') then
    begin
      j := pos('<div class="thumb_list"', all);
      k := MyPos('</div>', all, j);
      if (j>0) and (k>0) then begin
        s := copy(all, j, k-j);
        i := pos(' src=', s);
        delete(s,1,i);
        while (i>0) and (frames_count<frame_limit) do begin
          i:= pos('"', s) + 1;
          j:= MyPos('"', s, i+1);
          frame_url:=copy(s, i, j-i);
          //cut off the filename of the url
          i:= pos('V1._', frame_url);
		  if i = 0 then
			i:= pos('V1_', frame_url);
          if i>0 then
          begin
            SizeURL := frame_url;
            if Pos('_SS', SizeURL) > 0 then
              SIzeURL := copy(SizeURL, 1, Pos('_SS', SizeURL));

            frame_url:=copy(frame_url, 1, i+1);
            //insert the pattern to load the larger image
            preview_url := frame_url;
            preview_url := preview_url + '_SX' + IntToStr(picSizeX);
            preview_url := preview_url + '_SY' + IntToStr(picSizeY);
            preview_url := preview_url + '_';

            ParseImageSizeFromURL(SizeURL, Height, Width);
            frame_url:=frame_url+'.jpg';
            preview_url := preview_url + '.jpg';
          end;
          SetImagePreviewLink(preview_url, frame_url, frame_code, Height, Width);
          frames_count:=frames_count+1;
          i:=pos(' src=', s);
          delete(s, 1, i);
        end;
      end;
    end;
  end;
  result := frames_count;
end;


procedure GetImagesPreview(url: string);
const
  MAX_LOAD_IMAGE_COUNT = 100;
var
  I: Integer;
  J: Integer;
  S: string;
  S2: string;
  DownloadStr: string;
  BasicURL: string;
  FrontCoverUrl: string;
  PostersExists: Boolean;
  ImdbCode: string;
  MovieCode: string;

  PreviewURL: string;
	shots_downloaded, shots_left, posters_downloaded, bts_downloaded: Integer;   //20101017-JeF
  // fade
  Height: Integer;
  Width: Integer;
  SizeURL: string;
begin
	i:=pos('/combined', url);
	if I>0 then
		BasicURL:=copy(url, 1, i-1)
	else
		BasicURL:=url;
	DownloadStr := DownloadURL(ReplaceStr(BasicURL, 'imdb.com', main_server[IMDBLocalService], -1), False, RequestParametersWithCookies);
	imdbCode := ParseString(url, 'http://www.imdb.com/title/tt(\d+)', 1);
	MovieCode := ImdbCode;
  FrontCoverUrl := '';
	if ((DownloadStr <> '-1') and
      (DownloadStr <> '')) then
  begin
    // search front cover
    s2 := '<a name="poster" href="photogDownloadStrery" ';
    i := pos(s2, DownloadStr);
    if i=0 then begin
      s2 := '<a name="poster" href="';
      i := pos(s2, DownloadStr);
    end;
    if i=0 then
      i := Pos('id="img_primary">', DownloadStr);
    if i=0 then
      i := Pos('<div class="media_strip_thumbs">',DownloadStr);   //20101017-JeF
    if i > 0 then
    begin
      j := MyPos('</a>', DownloadStr, i+1);
      s := copy(DownloadStr, i, j-i);
      //do not download any video frames
      if (Pos('<img class="video"', s) = 0) then
      begin
        i := MyPos('src="',DownloadStr,i+1) + 5;
        j := MyPos('"',DownloadStr,i+1);
        if j > 0 then
        begin
          FrontCoverUrl := copy(DownloadStr,i,j-i);
          i:=pos('V1._', FrontCoverUrl);
		  if i = 0 then
			i:=pos('V1_', FrontCoverUrl);
          if (i>0) then
          begin
            SizeURL := FrontCoverUrl;
            if Pos('_SS', SizeURL) > 0 then
              SIzeURL := copy(SizeURL, 1, Pos('_SS', SizeURL))
            else if Pos('_.jpg', SizeURL) > 0 then
              SizeURL := copy(SizeURL, 1, Pos('_.jpg', SizeURL));
            FrontCoverUrl:=copy(FrontCoverUrl, 1, i+1);
            PreviewURL := FrontCoverUrl;
            ParseImageSizeFromURL(SizeURL, Height, Width);
            FrontCoverUrl := FrontCoverUrl+'.jpg';

            PreviewURL := PreviewURL + '_SX' + IntToStr(150);
            PreviewURL := PreviewURL + '_SY' + IntToStr(150);
            PreviewURL := PreviewURL + '_';
            PreviewURL := PreviewURL+'.jpg';
            SetImagePreviewLink(PreviewURL, FrontCoverUrl, 1, Height, Width);
          end;
        end;
      end;
    end;

    PostersExists := False;
    s := '/title/tt' + MovieCode + '/posters';
    if pos(s, DownloadStr)>0 then
      PostersExists:=true;


    shots_downloaded := GetFramesPreview(MovieCode, 'still_frame', MAX_LOAD_IMAGE_COUNT, 3);
    // posters and shots
    if PostersExists then
      posters_downloaded := GetFramesPreview(MovieCode, 'poster', MAX_LOAD_IMAGE_COUNT, 4);
    bts_downloaded := GetFramesPreview(MovieCode, 'behind_the_scenes', MAX_LOAD_IMAGE_COUNT, 3);
    //20101017-JeF : No image found, try with no frame type
    // GetFramesPreview(MovieCode, '', MaxPostersCount + MaxShotsCount, 6);
  end;
end;

function GetInfo(url: string; images_only: boolean): string;
const
	user_rating_name=['<h5>User Rating:</h5>', '<h5>Nutzer-Bewertung:</h5>', '<h5>Calificaci', '<h5>Note G', '<h5>Voti degli utenti:</h5>', '<h5>Classifica'];
	cert_name=['<h5>Certification:</h5>', '<h5>Altersfreigabe:</h5>', '<h5>Clasificaci', '<h5>Classification:</h5>', '<h5>Divieti:</h5>', '<h5>Certifica'];
	fun_stuff_name=['<h3>Fun Stuff</h3>', '<h3>Unterhaltsames</h3>', '<h3>Cosas divertidas</h3>', '<h3>Curiosit', '<h3>Info divertenti</h3>', '<h3>Fatos engra'];
	fun_facts_name=['<h2>Fun Facts</h2>', '<h3>Unterhaltsames</h3>', '<h3>Cosas divertidas</h3>', '<h3>Curiosit', '<h3>Info divertenti</h3>', '<h3>Fatos engra'];	
	director_short_cast=['Director:', 'Regisseur:', 'Director:', 'alisateur</h5>', '<h5>Regista', '<h5>Diretor:'];
	directors_short_cast=['Directors:', 'Regisseur:', 'Director:', 'alisateur</h5>', '<h5>Regista', '<h5>Diretor:'];
	writer_short_cast=['Writer:', '<h5>Drehbuchautor', '<h5>Guionista', '<h5>Sc', '<h5>Sceneggiatore', '<h5>Roteirista'];
	writers_short_cast=['Writers:', '<h5>Drehbuchautor', '<h5>Guionista', '<h5>Sc', '<h5>Sceneggiatore', '<h5>Roteirista'];
	runtime_name=['Runtime:', 'nge:</h5>', '<h5>Duraci', '<h5>Dur', '<h5>Durata:</h5>', '<h5>Dura'];
	genre_name=['Genre:', '<h5>Genre:</h5>', 'nero:</h5>', '<h5>Genre:</h5>', '<h5>Genere:</h5>', 'nero:</h5>'];
	genres_name=['Genres:', '<h5>Genre:</h5>', 'nero:</h5>', '<h5>Genre:</h5>', '<h5>Genere:</h5>', 'nero:</h5>'];
	country_name=['Country:', '<h5>Land:</h5>', '<h5>Pa', '<h5>Pays:</h5>', '<h5>Nazionalit', '<h5>Pa'];
	studio_name=['Production Co:', '<h5>Firma:</h5>', '<h5>Compa', '<h5>Soci', '<h5>Compagnia:</h5>', '<h5>Companhia :'];
	studio2_name=['Production Comp', '<h5>Firma:</h5>', '<h5>Compa', '<h5>Soci', '<h5>Compagnia:</h5>', '<h5>Companhia :'];
	plot_name=['<h5>Plot:</h5>', '<h5>Handlung:</h5>', '<h5>Trama:</h5>', '<h5>Intrigue:</h5>', '<h5>Trama:</h5>', '<h5>Argumento:</h5>'];
	story_name=['<h2>Storyline</h2>', '<h5>Handlung:</h5>', '<h5>Trama:</h5>', '<h5>Intrigue:</h5>', '<h5>Trama:</h5>', '<h5>Argumento:</h5>'];
	aka_name=['<h5>Also known as:</h5>', '<h5>Auch bekannt als:</h5>', '<h5>Conocido como:</h5>', '<h5>Alias:</h5>', '<h5>Alias:</h5>', 'Conhecido Como:</h5>'];
	original_title_name=['(original title)','(Originaltitel)','tulo original)','(titre original)','(titolo originale)','tulo original)'];  //20111009-JeF
	episodes_name=['Seasons', 'Staffeln', 'Temporadas', 'Saisons', 'Stagioni', 'Temporadas'];
	
var 
	keyword, s, s2, s3, plot_outline, photo_url, temp, temp1: string;
	i, j, kol, k, l, m, p, season, episode: integer;
	AirDate, EpisodeTitle, EpisodeIMDB, EpisodeDescription, day, month, ayear: string;
	LoadSummary, LoadSynopsis: boolean;					//20090317-JeF
	EpisodeUrl, EpisodePage, EpFullDesc: string;		//20090709-JeF
	TVShow, GetOriginalTitle, FirstMethod, isTVSeries: boolean;
	FunStuffInfo, LocalURL, EpisodeRequestURL: string;								// 20090808-JeF
	sl: TStringList;    //20110114-JeF
	RequestURL, TVDBURL, TMDBURL: string;
	picSizeX, picSizeY, EpCnt: Integer;
	SeasonList: TStringList;
begin
	// 05.04.2012. Fade: add initialization of the local variables
	plot_outline := '';
	FunStuffInfo := '';
    media_type := '';

	EpisodeURLs := TStringList.Create;
	result:='';
	i:=pos('/combined', url);
	LocalURL := ReplaceStr(url, 'imdb.com', main_server[IMDBLocalService], -1);
	if i>0 then
		BasicURL:=copy(url, 1, i-1)
	else
		BasicURL:=url;

	imdb_code:=ParseString(url, 'http://www.imdb.com/title/tt(\d+)', 1);
	movie_code:=imdb_code;
	movie_site_url:=GetMovieSiteURL(movie_code);
	
	picSizeX := RegReadInteger('IMDBPicSizeX', defaultPicSizeX);
	picSizeY := RegReadInteger('IMDBPicSizeY', defaultPicSizeY);

  // Fade: add threaded Requests for page
  // add request for full credits URL
  AddRequestForHTMLPageContent('http://www.imdb.com/title/tt'+movie_code+'/fullcredits', False);
  // add request for awards
  AddRequestForHTMLPageContent(BasicURL+'/awards', False);
  // add request for akas
  AddRequestForHTMLPageContent(BasicURL+'/releaseinfo', False);
  // add request for trivia
	if DownloadMovieAdditionalInfo then begin
		AddRequestForHTMLPageContent(BasicURL + '/trivia', False);
		if (BasicURL <> url) then
			AddRequestForHTMLPageContent(BasicURL);
	end;
  // add request for goofs
  if (DownloadGoofs = 1) then 
    AddRequestForHTMLPageContent(BasicURL + '/goofs', False);
  // add request for quotes
  if (DownloadQuotes = 1) then
    AddRequestForHTMLPageContent(BasicURL + '/quotes', False);
  // add request for movie connection
  if DownloadMovieLinks then
    AddRequestForHTMLPageContent(BasicURL + '/movieconnections', False, '', '', RequestParameters);
  // add request for soundtracks
  if (DownloadSoundtracks = 1) then
    AddRequestForHTMLPageContent(BasicURL + '/soundtrack', False);
  // add requests for trailers
  if (MaxTrailersCount > 0) then
    AddRequestForHTMLPageContent('http://www.imdb.com/title/tt' + movie_code + '/videogallery', False);
  // plot
  AddRequestForHTMLPageContent(BasicURL + '/plotsummary', False);
  AddRequestForHTMLPageContent(ReplaceStr(BasicURL, 'imdb.com',
    main_server[IMDBLocalService], -1) + '/plotsummary', False);
	
	

	// add requests for images
	RequestURL := 'http://www.imdb.com/title/tt'+movie_code+'/mediaindex?refine=';

	if (MaxShotsCount > 0) then begin
		AddRequestForHTMLPageContent(RequestURL + 'still_frame', False);
		AddRequestForHTMLPageContent(RequestURL + 'behind_the_scenes', False);
		AddRequestForHTMLPageContent(RequestURL, False);
	end;
  // FAde - end adding request for additional pages

	if (jTraceLevel > 0) then TraceAlert;   			   // 20101017-JeF
	if DownloadMovieFullCast then
		all:=DownloadURLWithReferer(LocalURL, '', False, RequestParametersWithCookies)
	else
		all:=DownloadURLWithReferer(ReplaceStr(BasicURL, 'imdb.com', main_server[IMDBLocalService], -1), '', False, RequestParametersWithCookies);

	if all='-1' then
		result:='-1'
	else
		result:=all;
		
		
	GetOriginalTitle := False;
	s2:=ParseString(all, '<title>(.*)</title>', 1);
	//type of the video
	if Pos('(V)', s2) > 0 then
		media_type := 'Video';
	if Pos('(TV)', s2) > 0 then
		media_type := 'TV movie';
	if Pos('TV Series:</h5>', all) > 0 then
		media_type := 'TV episode';
	//movie year
	year := ParseString(s2, '\((\d+)', 1);
	//movie title
	title:=ParseString(s2, '^(.*?) \(', 1);
	title:=RemoveTags(title);
	if (Pos('&#', title)>0) then
		GetOriginalTitle := True;
	title:=DecodeHTML(title);
	title:=ClearExtraSpaces(title);
	title := ClearExtraQuotes(title);
	title := MovePrefixLeft(title);
	
	if Pos('IMDb - ', title)>0 then
		delete(title, 1, 7);
		
	s := '/title/tt'+movie_code+'/posters';
	if pos(s, all)>0 then
		posters_exist:=true
	else
		posters_exist:=false;
		
	if posters_exist and (MaxPostersCount > 0) then begin
		AddRequestForHTMLPageContent(RequestURL + 'poster', False);
	end;
		
	EpisodesDownloading := False;
	PostersDownloading := False;
	BackdropsDownloading := False;
	//detect if this is a tv series
	isTVSeries := False;
	temp := format('<h5>%s:</h5>', [episodes_name[IMDBLocalService]]);
	temp1 := '<h5>Seasons:</h5>';
	if (Pos(temp, all)>0) or (Pos('<h4 class="inline">Season: </h4>', all)>0) or (Pos(temp1, all)>0) then
		isTVSeries := True;
		
	//download information from thetvdb, if applicable
	if isTVSeries and ((DownloadTVDBEpisodes = 1) or (((UseTVDBPosters=1) or (not posters_exist)) and (MaxPostersCount>0)) 
	or ((UseTVDBFanart=1) and (MaxBackdropsCount>0))) then begin
		if (DownloadTVDBEpisodes = 1) then
			EpisodesDownloading := True;
		if (UseTVDBPosters=1) and (MaxPostersCount>0) then
			PostersDownloading := True;
		if (UseTVDBFanart=1) and (MaxBackdropsCount>0) then
			BackdropsDownloading := True;
		TVDBURL := 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', [title, year]);
		TVDBURL := ReplaceStr(TVDBURL, ' ', '+', -1);
		AddRequestForHTMLPageContent(TVDBURL, False, '', 'OnTVDBMainPageLoaded');
	end;
	//download information from themoviedb, if applicable
	if (not isTVSeries) and (((UseTMDBPosters=1) or (not posters_exist)) and (MaxPostersCount > 0)) or ((UseTMDBSnapshots=1) and (MaxBackdropsCount > 0)) then begin
		if (UseTMDBPosters=1) and (MaxPostersCount > 0) then
			PostersDownloading := True;
		if (UseTMDBSnapshots=1) and (MaxBackdropsCount > 0) then
			BackdropsDownloading := True;
		TMDBURL := format('http://www.themoviedb.org/search/movie?query=%s&movie_page=&movie_collection_page=&person_page=&company_page=&keyword_page=&active=0', [title]);
		TMDBURL := ReplaceStr(TMDBURL, ' ', '+', -1);
		AddRequestForHTMLPageContent(TMDBURL, False, '', 'OnITDBLoaded');
	end;
	//seasons
	SeasonList := TStringList.Create;
	if DownloadMovieSeasonsList and (DownloadTVDBEpisodes = 0) then begin
		EpisodeRequestURL := 'http://www.imdb.com/title/tt'+movie_code+'/episodes/_ajax?season=';
		if isTVSeries then begin
			i := Pos(temp, all);
			if i = 0 then
				i := Pos(temp1, all);
			FirstMethod := False;
			if i=0 then begin
				i := Pos('<h4 class="inline">Season: </h4>', all);
				FirstMethod := True;
			end;
			j := MyPos('</div>', all, i+1);
			s := copy(all, i, j-i);
			i := Pos('<a href', s);
			if FirstMethod then
				i := Pos('href="episodes?', s);
			while i>0 do begin
				j := MyPos('</a>', s, i+1);
				s2 := copy(s, i, j-i);
				if FirstMethod then
					s2 := '<' + s2;
				s2 := RemoveTags(s2);
				if LowerCase(s2) = 'unknown' then
					s2 := '-1';
				if Length(s2) < 3 then begin
					SeasonList.Add(s2);
					AddRequestForHTMLPageContent(EpisodeRequestURL + s2, False);
				end;
				delete(s, 1, j);
				i := Pos('<a href', s);
				if FirstMethod then
					i := Pos('href="episodes?', s);
			end;
		end;
	end;
		
		
	if (jTraceLevel >= 2) then TraceExecute('Info',all);   // 20101017-JeF

	
	original_title := '';
	if DlOriginalTitle then begin
		i := Pos('<span class="title-extra">', all);
		if i>0 then begin
			j := MyPos(' <i>(original title)', all, i+1);
			if j>i then begin
				s2 := copy(all, i+26, j-i-26);
				s2 := DecodeHTML(s2);
				if s2 <>'' then begin
					original_title := s2;
					GetOriginalTitle := True;    //20110113-JeF
				end;
			end;
		end;
	end;
	
	//replace title with original title, if a localized version was received
//	if GetOriginalTitle and (original_title <> '') then
//		title := original_title;
	//copy title to original title, if there is no original title
	if (original_title = '') and DlOriginalTitle then
		original_title := title;
	if title='' then
		exit;
		

	sl:=TStringList.Create;
	
	//imdb rating
	imdb_rating:=0;
	rating:=0;
	i:=pos(user_rating_name[IMDBLocalService], all);
	if i=0 then
		i:=Pos('user-rate"><b>', all);

	if i>0 then begin
		i:=MyPos('<b>', all, i+1);

		if i>0 then begin
			j:=MyPos('</b>', all, i+1);
			if j>0 then begin	
				s2:=copy(all, i, j-i);

				if length(s2)>0 then begin
					delete(s2, 1, 3);
					i:=pos('/', s2);
					if i>0 then
						s2:=copy(s2, 1, i-1);
					i:=pos('.', s2);
					if i>0 then
						s2[i]:=DecimalSeparator;
						try
							imdb_rating:=StrToFloat(s2);
							rating:=imdb_rating;
						except
						end;
				end;
			end;
		end;
	end;
	//alternative imdb rating
	if imdb_rating=0 then begin
		i := Pos('Ratings: <strong>', all);
		if i>0 then begin
			j := MyPos('</strong>', all, i+1);
			s2 := copy(all, i+9, j-i-9);
			s2 := RemoveTags(s2);
			s2 := ClearExtraBlankCharacters(s2);
			i:=pos('.', s2);
			if i>0 then
				s2[i]:=DecimalSeparator;
				try
					imdb_rating:=StrToFloat(s2);
					rating:=imdb_rating;
				except
				end;
		end;
	end;

	//mpaa
	s2 := '';
	mpaa:=MPAADefault;
	mpaa_rating:='';
	i:=pos('<h5><a href="/mpaa">MPAA</a>:</h5>', all);    // 20091120-JeF
	if i=0 then
		i:=Pos('ng (<a href="/mpaa">MPAA</a>)</h4>', all);
	if i>0 then begin
		j:=MyPos('</div>', all, i+1);
		if j>0 then begin
			s2:=copy(all, i+34, j-i-34);    // 20091120-JeF
			i := Pos('<span', s2);
			if i>0 then
				delete(s2, i, length(s2) - i + 1);
		end;
	end
	else begin
		s2 := GetStr(all, '<h5>Certification:</h5>', '</div>');
		s := RegReadString('IMDBMPAAReplace', 'USA');
		if s='' then
			s := 'USA';
		mpaa := GetStr(s2, '>' + s + ':', '<');
		if (s = 'USA') and (not (mpaa in ['G', 'PG', 'PG-13', 'NC-17', 'R'])) then begin
			delete(s2, 1, Pos('>' + s + ':', s2));
			s3 := GetStr(s2, '>' + s + ':', '<');
			if s3<>'' then
				mpaa := s3;
		end;
	end;
	//alternative mpaa
	i := Pos('<span itemprop="contentRating">', all);
	if i>0 then begin
		j:= MyPos('</span>', all, i+1);
		s2 := copy(all, i+length('<span itemprop="contentRating">'), j-i-length('<span itemprop="contentRating">'));
	end;
	
	//extract mpaa
	i:=pos('Rated ', s2);
	if i>0 then begin
		delete(s2, 1, i+5);
		i:=pos(' ', s2);
		if i>0 then begin
			mpaa:=copy(s2, 1, i-1);
			delete(s2, 1, i);
			if ImportMPAAReasons = 1 then begin
				mpaa_rating:=s2;
			end;
		end;
	end;
	
	//certification
	i := Pos(cert_name[IMDBLocalService], all);
	if i>0 then begin
		j := MyPos('</div>', all, i+1);
		s := copy(all, i, j-i);
		MPAAReplace := UpperCase(MPAAReplace);
		s := UpperCase(RemoveTags(s));
		i := Pos(MPAAReplace, s);
		s2 := '';
		if i>0 then begin
			i := MyPos(':', s, i+1);
			j := MyPos(' ', s, i+1);
			s2 := copy(s, i+1, j-i-1);
		end;
		if s2<>'' then
			mpaa := s2;
	end;
	
	//Tagline
	tagline := '';
	i:=Pos('<h5>Tagline:</h5>', all);
	if i>0 then begin
		j := MyPos('</div>', all, i+1);
		s := copy(all, i+17, j-i-17);
		i := Pos('<a ', s);
		if i>0 then
			delete(s, i, length(s)-i+1);
		s := RemoveTags(s);
		s := DecodeHTML(s);
		i := Pos('(season', LowerCase(s));
		if i>0 then
			delete(s, i, length(s)-i+1);
		i := Pos('(re-release', s);
		if i>0 then
			delete(s, i, length(s)-i+1);			
		tagline := ClearExtraBlankCharacters(s);
	end;
		
	// 20090808-JeF_Begin : Add Fun Stuff at bottom of description
	i:=pos(fun_stuff_name[IMDBLocalService],all);
	if i=0 then
		i:=Pos('<h3>Did You Know?</h3>', all);
	if i=0 then
		i:=Pos('<h2>Did You Know?</h2>', all);
	if (i>0) then begin
		j:=MyPos('<hr/>',all,i+1);
		if j=0 then
			j := MyPos('<noscript>', all, i+1);
		FunStuffInfo:=copy(all,i,j-i);
	end;
	// 20090808-JeF_End
	
	if i=0 then begin
		i:=pos(fun_facts_name[IMDBLocalService],all);
		if (i>0) then begin
			j:=MyPos('<h2>',all,i+1);
			FunStuffInfo:=copy(all,i,j-i);
		end;		
	end;
	
	// 20090710-JeF_Begin : Person search for TV shows differs from a movie search : cast is on another page...
	TVShow:=false;
	// 20100221-JeF //if (pos('<a href="episodes" class="link">', all)>0) then begin
	// 20100921-JeF //if (pos('href="episodes" class="link">', all)>0) then begin   // 20100221-JeF
	if (pos('href="episodes"', all)>0) then begin   // 20100921-JeF
		TVShow:=true;
		EpisodeUrl:='http://www.imdb.com/title/tt'+movie_code+'/fullcredits';
		// EpisodePage:=DownloadURL(EpisodeUrl);
    EpisodePage := GetHTMLPageContentFromRequest(EpisodeUrl);
		if (jTraceLevel >= 3) then TraceExecute('FullCredits',all);   // 20101017-JeF
		if (EpisodePage='-1') then EpisodePage:='';
	end;
	// 20090710-JeF_End
	
	//movie directors
	if DlDirectors then begin
		i:=0;
		if DownloadMovieFullCast or OvrMainDlOptions then begin   // 20100330-JeF
			i:=pos('<h5><a class="glossary" name="directors"', all);   // 20100328-JeF
			if TVShow then i:=pos('name="directors"', EpisodePage);
		end;
		if (DownloadMovieFullCast or OvrMainDlOptions) and (i>0) then begin	// 20100328-JeF
			// 20100328-JeF //i:=pos('<h5><a class="glossary" name="directors" href="/Glossary/D#director">Directed by</a></h5>', all);
			// 20100330-JeF //if TVShow then i:=pos('name="directors"', EpisodePage);   // 20090710-JeF
			if i>0 then	begin
				kol:=0;
				j:=MyPos('</td></tr></table>', all, i+1);
				if TVShow then j:=MyPos('</td></tr></table>', EpisodePage, i+1);   // 20090710-JeF
				if j>0 then 
				begin
					s2 := copy(all, i, j-i);
					if TVShow then s2 := copy(EpisodePage, i, j-i);   // 20090710-JeF
					if length(s2)>0 then begin
						i:=pos('</a>', s2);
						while (i>0) and (kol<=MaxPersonsCount) do begin
							s3:=copy(s2, 1, i+3);
							code:=ParseString(s3, '<a href="/name/nm(\d+)/"', 1);
							name:=ParseString(s3, '<a href="/name/nm\d+/">(.*?)</a>', 1);
							name:=RemoveTags(name);
							name:=DecodeHTML(name);
							name:=ClearExtraSpaces(name);
							if name<>'' then begin
								SetPersonName(name, '', 1, code);
								kol:=kol+1;
							end;
							delete(s2, 1, i+3);
							i:=pos('</a>', s2);
						end;
					end
				end
			end;
		end
		else begin
			i := Pos(director_short_cast[IMDBLocalService],  all);
			if i=0 then
				i := Pos(directors_short_cast[IMDBLocalService],  all);
			if TVShow then i:=pos('name="directors"', EpisodePage);
			if i>0 then begin
				j:=MyPos('</div>', all, i+1);
				if TVShow then j:=MyPos('</td></tr></table>', EpisodePage, i+1);
				s2 := copy(all, i, j-i);
				if TVShow then s2 := copy(EpisodePage, i, j-i);
				i := Pos(' href="/name/nm', s2);
				while i>0 do begin
					j := MyPos('</a>', s2, i+1);
					s3 := copy(s2, i, j-i);
					name := RemoveTags(s3);
					i := Pos('>', name);
					if i>0 then
						delete(name, 1, i);
					name := DecodeHTML(name);
					name:=ClearExtraSpaces(name);
					code := ParseString(s3, ' href="/name/nm(\d+)/"', 1);
					if name<>'' then
						SetPersonName(name, '', 1, code);
					delete(s2, 1, j);
					i := Pos(' href="/name/nm', s2);
				end;
			end;
		end;
	end;			
	
	
	//movie writers
	if DlWriters then begin
		i:=0;
		if DownloadMovieFullCast or OvrMainDlOptions then begin   // 20100330-JeF
			i:=pos('<h5><a class="glossary" name="writers"', all);
			if TVShow then i:=pos('name="writers"', EpisodePage);
		end;
		if (DownloadMovieFullCast or OvrMainDlOptions) and (i>0) then begin
			// 20100328-JeF //i:=pos('<h5><a class="glossary" name="writers" href="/Glossary/W#writer">Writing credits</a></h5>', all);
			// 20100330-JeF //if TVShow then i:=pos('name="writers"', EpisodePage);   // 20090710-JeF
			if i>0 then begin
				j:=MyPos('</td></tr></table>', all, i+1);
				if TVShow then j:=MyPos('</td></tr></table>', EpisodePage, i+1);   // 20090710-JeF
				if j>0 then begin
					kol:=0;
					s2 := copy(all, i, j-i);
					if TVShow then s2 := copy(EpisodePage, i, j-i);   // 20090710-JeF
					if length(s2)>0 then begin
						i:=pos('</a>', s2);
						while (i>0) and (kol<=MaxPersonsCount) do begin
							s3:=copy(s2, 1, i+3);
							code:=ParseString(s3, '<a href="/name/nm(\d+)/"', 1);
							name:=ParseString(s3, '<a href="/name/nm\d+/">(.*?)</a>', 1);
							name:=RemoveTags(name);
							name:=DecodeHTML(name);
							name:=ClearExtraSpaces(name);
							if name<>'' then begin
								SetPersonName(name, '', 2, code);
								kol:=kol+1;
							end;
							delete(s2, 1, i+3);
							i:=pos('</a>', s2);
						end;
					end
				end;
			end;
		end
		else begin
			i := Pos(writer_short_cast[IMDBLocalService],  all);
			if i=0 then
				i := Pos(writers_short_cast[IMDBLocalService],  all);
			if TVShow then i:=pos('name="writers"', EpisodePage);
			if i>0 then begin
				j:=MyPos('</div>', all, i+1);
				if TVShow then j:=MyPos('</td></tr></table>', EpisodePage, i+1);
				s2 := copy(all, i, j-i);
				if TVShow then s2 := copy(EpisodePage, i, j-i);
				i := Pos(' href="/name/nm', s2);
				while i>0 do begin
					j := MyPos('</a>', s2, i+1);
					s3 := copy(s2, i, j-i);
					name := RemoveTags(s3);
					i := Pos('>', name);
					if i>0 then
						delete(name, 1, i);
					name := DecodeHTML(name);
					name:=ClearExtraSpaces(name);
					code := ParseString(s3, ' href="/name/nm(\d+)/"', 1);
					if name<>'' then
						SetPersonName(name, '', 2, code);
					delete(s2, 1, j);
					i := Pos(' href="/name/nm', s2);
				end;
			end;
		end;
	end;

	//movie composers
	if DlComposers then begin
		i:=pos('<h5><a class="glossary" name="music_original"', all);
		if TVShow then i:=pos('name="music_original"', EpisodePage);   // 20090710-JeF
		if i>0 then begin
			j:=MyPos('</td></tr></table>', all, i+1);
			if TVShow then j:=MyPos('</td></tr></table>', EpisodePage, i+1);   // 20090710-JeF
			if j>0 then begin
				kol:=0;
				s2 := copy(all, i, j-i);
				if TVShow then s2 := copy(EpisodePage, i, j-i);   // 20090710-JeF
				if length(s2)>0 then begin
					i:=pos('</a>', s2);
					while (i>0) and (kol<=MaxPersonsCount) do begin
						s3:=copy(s2, 1, i+3);
						code:=ParseString(s3, '<a href="/name/nm(\d+)/"', 1);
						name:=ParseString(s3, '<a href="/name/nm\d+/">(.*?)</a>', 1);
						name:=RemoveTags(name);
						name:=DecodeHTML(name);
						name:=ClearExtraSpaces(name);
						if name<>'' then begin
							SetPersonName(name, '', 4, code);
							kol:=kol+1;
						end;
						delete(s2, 1, i+3);
						i:=pos('</a>', s2);
					end;
				end
			end;
		end;
	end;

	
	//movie cast
	if DlActors then begin
		i:=pos('<table class="cast">', all);
		if i=0 then
			i := Pos('<table class="cast_list">', all);
		if TVShow then i:=pos('<table class="cast">', EpisodePage);   // 20090710-JeF
		if i>0 then begin
			j:=MyPos('</table>', all, i+1);
			if TVShow then j:=MyPos('</table>', EpisodePage, i+1);   // 20090710-JeF
			if j>0 then begin
				kol:=0;
				s2:=copy(all, i, j-i);
				if TVShow then s2 := copy(EpisodePage, i, j-i);   // 20090710-JeF
				if length(s2)>0 then begin
					i:=pos('</tr>', s2);
					while (i>0) and (kol<=MaxPersonsCount) do begin
						s3:=copy(s2, 1, i+4);
						code:=ParseString(s3, ' href="/name/nm(\d+)/"', 1);
						// 20090626-JeF // name:=ParseString(s3, '<a href="/name/nm\d+/">(.*?)</a>', 1);  
						name:=ParseString(s3, 'link=/name/nm\d+/.;">(.*?)</a>', 1);  // 20090626-JeF
						photo_url := ParseString(s3, '<img src="(.*?)\._SY30_SX23_.jpg"', 1);
						if photo_url = '' then begin
							photo_url := ParseString(s3, ' src="http://ia.media-imdb.com/images/(.*?)\._SY44_', 1);
							if photo_url = '' then
								photo_url := ParseString(s3, ' src="http://ia.media-imdb.com/images/(.*?)\._SX32_', 1);
							if photo_url = '' then
								photo_url := ParseString(s3, ' src="http://ia.media-imdb.com/images/(.*?)\._SX23_', 1);
							if photo_url <> '' then
								photo_url := 'http://ia.media-imdb.com/images/' + photo_url;
						end;
						if photo_url <> '' then begin
							if picSizeX>0 then
								photo_url := photo_url + '_SX' + IntToStr(picSizeX);
							if picSizeY>0 then
								photo_url := photo_url + '_SY' + IntToStr(picSizeY);
							if (picSizeX>0) or (picSizeY>0) then
								photo_url := photo_url + '_';
							photo_url := photo_url + '.jpg';
						end;
						if (RemoveTags(name)='') then 
							name:=ParseString(s3, ' href="/name/nm\d+/">(.*?)</a>', 1);   // 20090710-JeF
						//2011-11-07 Vlad
						if (name='') then
							name :=ClearExtraBlankCharacters(RemoveTags(ParseString(s3, '<td class="name">(.*?)</td>', 1)));
						j:=pos(' ...', s3);
						if j>0 then begin
							character:=s3;
							delete(character, 1, j+length(' ...')-1);
							character:=RemoveTags(character);
							character:=DecodeHTML(character);
							j:=pos(' ...',character);   // 20090710-JeF
							if (j>0) then delete(character,j-1,6);   // 20090710-JeF
							//remove (as <actor's name>) in the character string
							j:=Pos('(', character);
							if IntToBool(RegReadInteger('IMDBFullCharacterName', 0)) then j:=0;   //20120414-JeF
							// 20100921-JeF //if (j>0) then
              // 20.12.2012 - Fade (add option for actors episodes downloading)
							if (j>0) and ((not TVShow) or (not IntToBool(DownloadActorsEpisodesForTVSeries))) then  // 20100921-JeF
								delete(character, j, length(character)-j+1);
							character:=ClearExtraSpaces(character);
						end
						// 20090714-JeF_Begin
						else if TVShow then begin
							character:='';
							j:=pos('<td class="char">',s3);
							k:=MyPos('</td>',s3,j+1);
							s3:=copy(s3,j,k-j+5);
							s3:=RemoveTags(s3);
							s3:=DecodeHTML(s3);
							s3:=ClearExtraSpaces(s3);
							if (pos('(',s3)>0) and (pos(')',s3)>0) then character:=s3;
						end
						// 20090714-JeF_End
						else
							character:='';
						name:=RemoveTags(name);
						name:=DecodeHTML(name);
						name:=ClearExtraSpaces(name);
						if name<>'' then begin
							SetPersonName(name, character, 3, code, photo_url);
							kol:=kol+1;
						end;
						delete(s2, 1, i+4);
						i:=pos('</tr>', s2);
					end;
				end
			end;
		end;
	end;
	

	//movie image
	s2 := '<a name="poster" href="photogallery" ';
	i := pos(s2, all);
	if i=0 then begin
		s2 := '<a name="poster" href="';
		i := pos(s2, all);
	end;
	if i=0 then
		i := Pos('id="img_primary">', all);
	if i=0 then
		i := Pos('<div class="media_strip_thumbs">',all);   //20101017-JeF
	if i > 0 then begin
		j := MyPos('</a>', all, i+1);
		s := copy(all, i, j-i);
		//do not download any video frames
		if (Pos('<img class="video"', s) = 0) then
    begin
			i := MyPos('src="',all,i+1) + 5;
			j := MyPos('"',all,i+1);
			if j > 0 then begin
				front_cover_url := copy(all,i,j-i);
				i:=pos('V1._', front_cover_url);
				if i = 0 then
					i:=pos('V1_', front_cover_url);
				if (i>0) then begin
					front_cover_url:=copy(front_cover_url, 1, i+1);
					k := RegReadInteger('IMDBPicSizeX', defaultPicSizeX);
					l := RegReadInteger('IMDBPicSizeY', defaultPicSizeY);
					if k>0 then
						front_cover_url := front_cover_url + '_SX' + IntToStr(k);
					if l>0 then
						front_cover_url := front_cover_url + '_SY' + IntToStr(l);
					if (k>0) or (l>0) then
						front_cover_url := front_cover_url + '_';
					front_cover_url:=front_cover_url+'.jpg';
				end;
			end;
		end;
	end;
	
	
	//movie duration (minutes)
	duration:=0;
	if DlDuration then begin
		i := Pos(runtime_name[IMDBLocalService], all);
		if i>0 then begin
			j := MyPos('</div>', all, i+1);
			s := copy(all, i, j-i);
			i := Pos('(', s);
			if i>0 then
				delete(s, i, length(s) - i + 1);
			s2:=ParseString(s, '.*?(\d+?) ', 1);
			duration:=0;
			if s2<>'' then
				try
					duration:=StrToInt(s2);
				except
				end;
		end;
	end;

	//movie genres
	if DlGenres then begin
		i := Pos(genre_name[IMDBLocalService], all);
		if i=0 then
			i := Pos(genres_name[IMDBLocalService], all);
		if i>0 then begin
			j := MyPos('</div>', all, i+1);
			s := copy(all, i, j-i);
			s2:=ParseString(s, '</h5>(.*?)$', 1);
			if s2='' then
				s2:=ParseString(s, '</h4>(.*?)$', 1);
			if length(s2)>0 then begin
				repeat
					i:=pos(' | ', s2);
					k := 2;
					if i=0 then begin
						i := Pos('|', s2);
						k := 0;
					end;
					if i>0 then
						name := copy(s2, 1, i-1)
					else
						name := s2;
					name := RemoveTags(name);
					name := ClearExtraBlankCharacters(DecodeHTML(name));
					j := Pos('See more', name);
					if j>0 then
						delete(name, j, length(name)-j+1);
					if name<>'' then begin
						SetGenre(name);
						(*//types of movies by genre
						if name = 'Animation' then
							media_type := 'Animation';
						if name = 'Documentary' then
							media_type := 'Documentary';*)
					end;
					delete(s2, 1, i+k);
				until i=0;
			end;
		end;
	end;

	//movie countries
	if DlCountries then begin
		i := Pos(country_name[IMDBLocalService], all);
		if i>0 then begin
			j :=MyPos('</div>', all, i+1);
			s := copy(all, i, j-i);
			s2:=ParseString(s, '</h5>(.*?)$', 1);
			if s2='' then
				s2 := ParseString(s, '</h4>(.*?)$', 1);
			if length(s2)>0 then begin
				repeat
					i:=pos(' | ', s2);
					k := 2;
					if i=0 then begin
						i:=Pos('|', s2);
						k:=0;
					end;
					if i>0 then
						name := copy(s2, 1, i-1)
					else
						name := s2;
					name := RemoveTags(name);
					name := DecodeHTML(name);
					if name<>'' then
						SetCountry(name);
					delete(s2, 1, i+k);
				until i=0;
			end;
		end;
	end;
	
	//original_title
	if (IMDBLocalService>0) and DlOriginalTitle then begin
		i := Pos(aka_name[IMDBLocalService], all);
		if i>0 then begin
			{ 20111009-JeF
			i := MyPos('>"', all, i+1);
			if i>0 then begin
				j := MyPos('"', all, i+2);
				original_title := copy(all, i+2, j-i-2);
				original_title := DecodeHTML(original_title);
			end;  
			20111009-JeF }
			// 20111009-JeF
			i := i + length(aka_name[IMDBLocalService]);
			j := MyPos('<h', all, i+1);
			if j>0 then begin
				s := copy(all, i, j-i);
				i := 1;
				while (j>0) do begin
					j := Pos('<br>', s);
					if (j>0) then begin
						s2 := copy(s,i,j);
						k := Pos(original_title_name[IMDBLocalService], s);
						if k>0 then begin
							s2 := copy(s2,1,k-1);
							s2 := RemoveTags(s2);
							s2 := ClearExtraBlankCharacters(s2);
							if pos('"',s2) >0 then begin
								while s2[length(s2)] <> '"' do delete(s2,length(s2),1);
							end;
							s2 := ClearExtraQuotes(s2);
							s2 := DecodeHTML(s2);
							original_title := s2;
							j := 0;
						end;
					end;
					delete(s, 1, j+3); //Vlad
				end;
			end;
		end;
	end;
	
	//movie studios
	if (DownloadMovieStudios and Not OvrMainDlOptions) or DlStudios then begin
		i := Pos(studio_name[IMDBLocalService], all);
		if i=0 then
			i := Pos(studio2_name[IMDBLocalService], all);
		if i>0 then begin
			j := MyPos('</div>', all, i+1);
			k := MyPos('</ul>', all, i+1);
			if (k>0) and (k<j) then
				j := k;
			s := copy(all, i, j-i);
			s2:=ParseString(s, '</h5>(.*?)$', 1);
			if s2 = '' then
				s2:=ParseString(s, '</h4>(.*?)$', 1);
			if s2 = '' then
				s2:=ParseString(s, '</b><ul>(.*?)$', 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, ' href="/company/co.*?>(.*?)</a>', 1);
					name := DecodeHTML(name);
					if name<>'' then begin
						SetStudio(name);
					end;
					delete(s2, 1, i+3);
					i:=pos('</a>', s2);
				end;
			end;
		end;
	end;		

	i:=pos(plot_name[IMDBLocalService], all);
	k:=length(plot_name[IMDBLocalService]);
	if i=0 then begin
		i:=pos('<h5>Plot Outline:</h5> ', all);
		if i<=0 then
			i:=pos('<h5>Plot Summary:</h5>', all);
		k:=length('<h5>Plot Outline:</h5> ');
	end;
	if i>0 then begin
		j:=MyPos('</div>', all, i+1);
		l:=MyPos('<a ', all, i+1);
		if (l>0) and (l<j) then j:=l;
		s2:=copy(all, i, j-i-1);
		delete(s2, 1, k+1);
		plot_outline := s2;
		plot_outline:=DecodeHTML(plot_outline);
		plot_outline:=RemoveTags(plot_outline);
		plot_outline:=ClearExtraSpaces(plot_outline);
		if pos('more',plot_outline) = length(plot_outline)-3 then
			plot_outline := copy(plot_outline,1,length(plot_outline)-5);
		plot_outline:=ClearExtraBlankCharacters(plot_outline);
		description := plot_outline;
	end;
	
	i := Pos(story_name[IMDBLocalService], all);
	if i>0 then begin
		j := MyPos('</p>', all, i+1);
		k := MyPos('</div>', all, i+1);
		if j<k then begin
			s := copy(all, i, j-i);
			plot_outline := ParseString(s, '<p>(.*?)$', 1);
		end
		else begin
			s := copy(all, i, k-i);
			plot_outline := ParseString(s, '</h5>(.*?)$', 1);
		end;
		k := Pos('<a ', plot_outline);
		delete(plot_outline, k, length(plot_outline) - k + 1);
		plot_outline:=DecodeHTML(plot_outline);
		plot_outline:=RemoveTags(plot_outline);
		plot_outline:=ClearExtraSpaces(plot_outline);
		plot_outline:=ClearExtraBlankCharacters(plot_outline);
		description := plot_outline;
	end;
	
	//gross
	if DownloadMovieAdditionalInfo then begin
		if (BasicURL <> url) then
			temp := GetHTMLPageContentFromRequest(BasicURL)
		else
			temp := all;
		s := GetStr(temp, '<h3>Box Office</h3>', '<hr />');
		temp := '';
		i := Pos('<div class="txt-block">', s);
		while i>0 do begin
			s2 := GetStr(s, '<div class="txt-block">', '</div>');
			s2 := RemoveTags(s2);
			s2 := ReplaceStr(s2, #10, ' ', -1);
			s2 := ClearExtraBlankCharacters(DecodeHTML(s2));
			s2 := RemoveSpacesInText(s2);
			if temp <> '' then
				temp := temp + #13#10;
			temp := temp + s2;
			delete(s, 1, i);
			i := Pos('<div class="txt-block">', s);
		end;
		salary := temp;		
	end;

	//20090317-JeF_Begin
	// Remeber if extended plot is present before loading another page
	LoadSummary:=(  (pos('href="plotsummary"',all)>0) or
					(pos('href="/title/tt'+movie_code+'/plotsummary',all)>0)	);
	LoadSynopsis:=(pos('href="synopsis"',all)>0);
	//20090317-JeF_End

	//episodes
	if (not EpisodesDownloading) and ((DownloadMovieSeasonsList and Not OvrMainDlOptions) or DlEpisodes) then begin
		for EpCnt := 0 to SeasonList.Count - 1 do begin
			season := 0;
			episode := 0;
			try
				season := StrToInt(SeasonList[EpCnt]);
			except
			end;
			if season = -1 then
				season := 999;
			temp := GetHTMLPageContentFromRequest(EpisodeRequestURL + SeasonList[EpCnt]);
			if (jTraceLevel >= 3) then TraceExecute('Episodes',temp);   // 20101017-JeF
			if temp<>'-1' then begin
				i:=pos('<div class="list_item ', temp);
				while i>0 do begin
					j := MyPos('<div class="clear">', temp, i+1);
					s := copy(temp, i, j-i);
					s2 := ParseString(s, '<meta itemprop="episodeNumber" content="(\d+)"', 1);
					if s2<> '' then
						try
							episode := StrToInt(s2);
						except
						end;
					AirDate := '';
					s2 := ParseString(s, '<div class="airdate">(.*?)</div>', 1);
					s2 := ClearExtraBlankCharacters(s2);
					k:=pos(' ', s2);
					if k>0 then begin
						month:=copy(s2, 1, k-1);
						delete(s2, 1, k);
						k := Pos('.', month);
						if k>0 then
							delete(month, k, 1);
						k:=pos(', ', s2);
						if k>0 then begin
							day:=copy(s2, 1, k-1);
							delete(s2, 1, k+1);
							ayear:=s2;

							k:=1;
							while (k<=12) and (Pos(month, monthes[k]) = 0) do begin	
								k:=k+1;
							end;
							if (k<=12) and (month<>'') then begin
								AirDate:=IntToStr(k)+format('/%s/%s', [day, ayear])
							end;
						end;
					end;
					EpisodeTitle := ParseString(s, '<strong>(.*?)</strong>', 1);
					EpisodeTitle := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(EpisodeTitle)));
					EpisodeDescription := ParseString(s, 'itemprop="description">(.*?)</div>', 1);
					EpisodeDescription := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(EpisodeDescription)));
					EpisodeIMDB:=ParseString(s, 'href="/title/tt(\d+)/"', 1);
					if (EpisodeIMDB > '') and IntToBool(RegReadInteger('IMDB_Mov_ImdbIdInEpisodeTitle', 0))
						then EpisodeTitle := EpisodeTitle + ' (tt' + EpisodeIMDB + ')';    //20120414-JeF
//					showMessage(Format('SE%d EP%d: %s (%s) %s: %s', [season, episode, EpisodeIMDB, AirDate, EpisodeTitle, EpisodeDescription]));
					
							// 20090709-JeF_Begin : Load episode full description if exists and episode full desc option is on
							if EpisodeFullDesc = 1 then begin
								EpisodeUrl:='http://www.imdb.com/title/tt'+EpisodeIMDB+'/plotsummary';
								EpisodePage:=DownloadURL(EpisodeUrl);
								if (jTraceLevel >= 3) then TraceExecute('EpPlotSummary',all);   // 20101017-JeF
								if (EpisodePage<>'-1') then begin
									EpFullDesc:= '';
									k:=pos('<p class="plotpar">',EpisodePage);
									while k>0 do 
									begin
										k:=k+19;
										l:=MyPos('<i>',EpisodePage,k+1);
										if l>0 then
										begin
											s3:= copy(EpisodePage,k+1,l-k-2);
											k := l + 3;
											l := MyPos('</i>',EpisodePage,k+1);
											s2 := copy(EpisodePage,k,l-k);
											s2 := RemoveTags(s2);
											s2 := ReplaceStr(s2, #10, '', -1);
											s2:=ClearExtraSpaces(s2);
											s2:=ClearExtraCharacters(s2);
											if ShowPlotAuthors=1 then   // 20090706-JeF
												EpFullDesc := EpFullDesc + s3 + #10 + '//' + s2 + #10 + #10
											else EpFullDesc := EpFullDesc + s3 + #10 + #10;   // 20090706-JeF
										end;
										delete(EpisodePage,1,k-1);
										k := pos('<p class="plotpar">',EpisodePage);
									end;						
									delete(EpFullDesc,length(EpFullDesc)-1,2);
									if (length(EpFullDesc)>0) then EpisodeDescription:=EpFullDesc;
								end;
							end;
							// 20090709-JeF_End
							
					if (episode<=100) and (season < 999) then
						SetEpisode(season, episode, EpisodeTitle, EpisodeDescription, EpisodeIMDB, AirDate);
					delete(temp, 1, j);
					i:=pos('<div class="list_item ', temp);
				end;
			end;
		end;
	end;

	SeasonList.Free;

	// keywods
	if pos('<div class="link"><i>-</i><a href="keywords">plot keywords</a></div>',all) > 0 then
	begin
		// New page for getting keywords
		url := 'http://www.imdb.com/title/tt'+movie_code+'/keywords';
//		all:=DownloadURL(url);
		i := pos('<ul>'+#10+'<li><b class="keyword">',all);
		j := Mypos('</ul>'+#10,all, i+1);
		//s2 := ''; /////////// for testing
		if (i>0)and(j>0) then
		begin
			i := i + 55;
			s := copy(all,i,j-i);
			i := pos('<a href="/keyword/',s);
			while i>0 do
			begin
				j := MyPos('</a>',s,i+1);
				if j>0 then
				begin
					keyword := copy(s,i,j-i);
					keyword := DecodeHTML(keyword);
					keyword := RemoveTags(keyword);
					keyword := ClearExtraSpaces(keyword);
					////
					//  СОХРАНЕНИЕ КЛЮЧЕВОГО СЛОВА
					//  SetMovieKeyword(movie_code, keyword);
					////
					//s2 := s2 + ', ' + keyword; ///////////// for testing keywords
				end;
				delete(s,1,j+3);
				i := pos('<a href="/keyword/',s);
			end;
		end;
		//ShowMessage('KEYWORDS: ' + s2); ///////////// for testing keywords
	end;
	
	// if not images_only then begin   // 20090627-JeF
	if (not images_only) and ((DownloadMovieBigDescription and Not OvrMainDlOptions) or (ImportDesc = 1)) then begin   // 20090627-JeF
		if (plot_outline='') or LoadSummary or LoadSynopsis then begin  // 20090317-JeF
		//movie plot
			// 20090317-JeF //if (pos('<a href="plotsummary">', all)>0) or (pos('<a href="synopsis">', all)>0) then begin
			if LoadSummary or LoadSynopsis then begin  // 20090317-JeF
				if (description='') then
					url:=BasicURL+'/plotsummary'
				else
					url:=ReplaceStr(BasicURL, 'imdb.com', main_server[IMDBLocalService], -1) + '/plotsummary';
				// all:=DownloadURL(url);
        All := GetHTMLPageContentFromRequest(url);
				if (jTraceLevel >= 3) then TraceExecute('PlotSummary',all);   // 20101017-JeF
			
				description := '';
				i := pos('<p class="plotpar">',all);
				if i=0 then begin
					i:=Pos('<div id="swiki.2', all);
					if i>0 then begin
						j := MyPos('</div>', all, i+1);
						description := copy(all, i, j-i);
						description := RemoveTags(description);
						description := DecodeHTML(description);
						while (length(description) > 0) and (ord(description[1]) in [1..20]) do
						delete(description, 1, 1);
					end;
				end
				else while i>0 do 
				begin
					i := i + 19;
					j := MyPos('<i>',all,i+1);
					if j>0 then
					begin
						s := copy(all,i+1,j-i-2);
						i := j + 3;
						j := MyPos('</i>',all,i+1);
						s2 := copy(all,i,j-i);
						s2 := ReplaceStr(s2, #10, '', -1);
						s2:=ClearExtraSpaces(s2);
						s2:=ClearExtraCharacters(s2);
						if ShowPlotAuthors = 1 then   // 20090706-JeF
							description := description + s + #10 + '//' + s2 + #10 + #10
						else description := description + s + #10 + #10;   // 20090706-JeF
					end;
					delete(all,1,i-1);
					i := pos('<p class="plotpar">',all);
				end;

				delete(description,length(description)-1,2);
				if description='' then
					description:=plot_outline;
			end
			else
				description:=plot_outline;
		end
		else description:=plot_outline;

		description:=ReplaceStr(description, '</p>', #10, -1);
		description:=ReplaceStr(description, '<br>', #10, -1);
		description:=DecodeHTML(description);
		description:=RemoveTags(description);
		description:=ReplaceStr(description, #10, '<br>', -1);
		description:=ClearExtraSpaces(description); ///////
	end;
	if (ImportDesc = 0) then description:='';   // 20090627-JeF
	
	//Awards
	awards:='';
	if (DownloadMovieAwards and Not OvrMainDlOptions) or DlAwards then begin
		url:=BasicURL+'/awards';
		// all:=DownloadURL(url);
    all := GetHTMLPageContentFromRequest(url);    
		if (jTraceLevel >= 5) then TraceExecute('Awards',all);   // 20101017-JeF
		i:=Pos('<big><a href="/Sections/Awards/', all);
		if i>0 then begin
			//we copy the table of awards
			j:=MyPos('</table>', all, i+1);
			s:=copy(all, i, j-i);
			repeat begin
				if awards<>'' then
					awards:=awards+'<br><br>';
				j:=Pos('<td colspan="4">&nbsp;</td>', s);
				s2:=copy(s, 1, j);
				//Who gives the award
				s3:=ParseString(s2, '<big>.*?">(.*?)</a></big>', 1);
				if s3<>'' then
					awards:=awards+s3+'<br>';
				//The name of the award
				s3:=ParseString(s2, 'valign="middle">(.*?)</td>', 1);
				if s3<>'' then
					awards:=awards+s3+' - ';
				//Year
				s3:=ParseString(s2, '">(\d+) </a>', 1);
				if s3<>'' then
					awards:=awards+s3;

				k:=Pos('<b>Won</b></td>', s2);
				if k>0 then begin
					awards:=awards+'<br>Won<br>';
					l:=MyPos('<b>Nominated</b></td>', s2, k+1);
					if l=0 then
						l:=length(s2);
					s3:=copy(s2, k, l-k);
					awards:=awards+ExtractAwards(s3);
				end;
				k:=Pos('<b>Nominated</b></td>', s2);
				if k>0 then begin
					awards:=awards+'<br>Nominated<br>';
					s3:=copy(s2, k, length(s2) - k);
					awards:=awards+ExtractAwards(s3);
				end;
				delete(s, 1, j+10);
				i:=Pos('<big><a href="/Sections/Awards/', s);
				end
			until i=0;
		end;
		awards := ReplaceStr(awards, '<br>', #13#10, -1);
		awards:=DecodeHTML(RemoveTags(awards));  // 20090910-JeF
	end;

	// 20090627-JeF_Begin : Set Title to aka in local language
	if (TitleLang>'') or (AkasInDesc = 1) then begin
		// Load akas page
		url:=BasicURL+'/releaseinfo';
		//all:=DownloadURL(url);
    all := GetHTMLPageContentFromRequest(url);    
		if (jTraceLevel >= 3) then TraceExecute('ReleaseInfo',all);   // 20101017-JeF
		// extract akas
		i:=pos(' name="akas"',all);
		j:=MyPos('</table>',all,i+15);
		s2:=copy(all,i+15,j-i-15);
		if (TitleLang>'') then begin
			//20110114-JeF : TitleLang can now be an ordered list, search each value and stops at first match
			j:=0;
			sl.CommaText:=TitleLang;
			while (j<sl.count) do begin
				i:=pos(UpperCase(sl[j]),UpperCase(s2));
				if (i>0) then begin
					delete(s2, 1, i-1);
					s3 := GetStr(s2, '<td>', '</td');
					s3 := ClearExtraBlankCharacters(DecodeHTML(s3));
					if (s3<>'') and (Pos('<', s3) = 0) then
						title := s3;
					j:=sl.count;
				end;
				j:=j+1;
			end;
		end;
		// 20090729-JeF_Begin : Add akas in description
		if AkasInDesc = 1 then begin
			description:=description+'<br><br>Also Known As:';
			i:=pos('<tr',s2);
			while (i>0) do begin
				s3 := GetStr(s2, '<tr', '</tr>');
				s3:=DecodeHTML(s3);
				temp := '';
				k := Pos('<td>', s3);
				while k > 0 do begin
					temp1 := ClearExtraBlankCharacters(RemoveTags(GetStr(s3, '<td>', '</td>')));
					if (temp <> '') and (temp1 <> '') then
						temp := temp + ' - ';
					temp := temp + temp1;
					delete(s3, 1, k);
					k := Pos('<td>', s3);
				end;
				description:=description+'<br>'+temp;
				delete(s2, 1, i);
				i:=pos('<tr',s2);
			end;
		end;
		// 20090729-JeF_End
	end;
	// 20090627-JeF_End
	
	// 20090808-JeF_Begin : Add Fun Stuff at bottom of description
	// 20100419-Rewritten by Vlad because of changes on IMDB
	//FUN STUFF begin
	if DownloadMovieAdditionalInfo or OvrMainDlOptions then begin
		s:=FunStuffInfo;
		//TRIVIA
		if (DownloadTrivia = 1) then begin
				 //all := DownloadURL(BasicURL + '/trivia');
        all := GetHTMLPageContentFromRequest(BasicURL + '/trivia');        
			i := Pos('<div class="sodatext">', all);    //20120419-JeF
			if (i>0) then begin
				if (jTraceLevel >= 8) then TraceExecute('Trivia',all);   // 20101017-JeF

        // Fade: 05.04.2012 - Add TRIVIA only if text exists
				if description <> '' then
					description := description + '<br><br>';
				description := description + 'TRIVIA:<br><br>';
				k := Pos('<div class="sodatext">', all);
				while k>0 do begin
					// Get Sub Section Title before proceeding
					m := Pos('<h4', all);
					if (m>0) then p := MyPos('</h4>', all, m+1)
					else p:=0;
					if (m>0) and (m<k) and (p>0) then begin  
						s2 := copy(all, m, p-m);
						s2 := RemoveTags(s2);
						s2 := DecodeHTML(s2);
						s2 := ClearExtraBlankCharacters(s2);
						if (s2>'') then begin
							s2 := ' --- '+s2+' ---<br><br>';
							description := description + s2;
						end;
					end;
					// Proceed with item
					l := MyPos('<span class="linksoda">', all, k+1);
					s2 := copy(all, k, l-k);
					s2 := RemoveTags(s2);
					s2 := DecodeHTML(s2);
					s2 := ReplaceStr(s2, #10#10, #10, -1);
					s2 := ReplaceStr(s2, #10, #13#10, -1);
					s2 := ClearExtraBlankCharacters(s2);
					if s2<>'' then
						description := description + s2 + '<br><br>';
					delete(all, 1, l-1);
					k := Pos('<div class="sodatext">', all);
				end;
				delete(description, length(description)-7, 8);
			end;
		end;
		//GOOFS
		if (DownloadGoofs = 1) then begin
				 //all := DownloadURL(BasicURL + '/goofs');
        all := GetHTMLPageContentFromRequest(BasicURL + '/goofs');        
			i := Pos('<li><a name=', all);    //20120419-JeF
			if (i=0) then i := Pos('<div id="gf', all);
			if (i>0) then begin
				if (jTraceLevel >= 8) then TraceExecute('Goofs',all);   // 20101017-JeF
				if description <> '' then
					description := description + '<br><br>';
				description := description + 'GOOFS:<br><br>';
				k := Pos('<li><a name=', all);
				FirstMethod := True;
				if k=0 then begin
					k := Pos('<div id="gf', all);
					FirstMethod := False;
				end;
				while k>0 do begin
					// Get Sub Section Title before proceeding
					m := Pos('<h4', all);
					if (m>0) then p := MyPos('</h4>', all, m+1)
					else p:=0;
					if (m>0) and (m<k) and (p>0) then begin  
						s2 := copy(all, m, p-m);
						s2 := RemoveTags(s2);
						s2 := DecodeHTML(s2);
						s2 := ClearExtraBlankCharacters(s2);
						if (s2>'') then begin
							s2 := ' --- '+s2+' ---<br><br>';
							description := description + s2;
						end;
					end;
					// Proceed with item
					if FirstMethod then
						l := MyPos('<br>', all, k+1)
					else
						l := MyPos('<span class="linksoda">', all, k+1);
					s2 := copy(all, k, l-k);
					s2 := ReplaceStr(s2, '</h4>', ':&nbsp;</h4>', -1);
					s2 := RemoveTags(s2);
					s2 := DecodeHTML(s2);
					s2 := ReplaceStr(s2, #10, '', -1);
					s2 := ClearExtraBlankCharacters(s2);
					if s2<>'' then
						description := description + s2 + '<br><br>';
					delete(all, 1, l-1);
					k := Pos('<li><a name=', all);
					if k=0 then
						k := Pos('<div id="gf', all);
				end;
				delete(description, length(description)-7, 8);
			end;
		end;
		//QUOTES
		if (DownloadQuotes = 1) then begin
				 //all := DownloadURL(BasicURL + '/quotes');
        all := GetHTMLPageContentFromRequest(BasicURL + '/quotes');        
			i := Pos(' class="quote soda', all);    //20120419-JeF
			if (i>0) then begin
				if (jTraceLevel >= 8) then TraceExecute('Quotes',all);   // 20101017-JeF
				if description <> '' then
					description := description + '<br><br>';
				description := description + 'QUOTES:<br><br>';
				k := Pos(' class="quote soda', all);
				while k>0 do begin
					l := MyPos('<span class="linksoda"', all, k+1);
					s2 := copy(all, k, l-k);
					s2 := ReplaceStr(s2, '>Share this quote<', '><', -1);
					if s2 <> '' then
						s2 := RemoveTags('<' + s2);
					s2 := DecodeHTML(s2);
					s2 := ReplaceStr(s2, #10#10#10, #10#10, -1);
					s2 := ReplaceStr(s2, #10, #13#10, -1);
					s2 := ClearExtraBlankCharacters(s2);
					if s2<>'' then
						description := description + s2 + '<br><br>';
					delete(all, 1, l-1);
					k := Pos(' class="quote soda', all);
				end;
				delete(description, length(description)-7, 8);
			end;
		end;
		//SOUNDTRACK
		if (DownloadSoundtracks = 1) then begin
				 //all := DownloadURL(BasicURL + '/soundtrack');
        all := GetHTMLPageContentFromRequest(BasicURL + '/soundtrack');
			i := Pos('class="soundTrack soda', all);      //20120419-JeF
			if (i>0) then begin
				if (jTraceLevel >= 8) then TraceExecute('Soundtrack',all);   // 20101017-JeF
				if description <> '' then
					description := description + '<br><br>';
				description := description + 'SOUNDTRACK:<br><br>';
				k := Pos('class="soundTrack soda', all);
				while k > 0 do begin
					l := MyPos('</div>', all, k+1);
					s2 := copy(all, k, l-k);
					s2 := ReplaceStr(s2, '<br />', #13#10, -1);
					if s2 <> '' then
						s2 := RemoveTags('<' + s2);
					s2 := DecodeHTML(s2);
					s2 := ClearExtraBlankCharacters(s2);
					if s2<>'' then
						description := description + s2 + '<br><br>';
					delete(all, 1, l-1);
					k := Pos('class="soundTrack soda', all);
				end;
				delete(description, length(description)-7, 8);
			end;
		end;
	end;
	
	//MOVIE CONNECTIONS
	if DownloadMovieLinks then begin
        all := GetHTMLPageContentFromRequest(BasicURL + '/movieconnections');
		//prequel
		i := Pos('Follows&nbsp;</h4>', all);
		if i>0 then begin
			delete(all, 1, i);
			ExtractMovieLinks(all, 1);
		end;
		//sequel
		i := Pos('Followed by&nbsp;</h4>', all);
		if i>0 then begin
			delete(all, 1, i);
			ExtractMovieLinks(all, 1);
		end;
		//references
		i := Pos('References&nbsp;</h4>', all);
		if i>0 then begin
			delete(all, 1, i);
			ExtractMovieLinks(all, 4);
		end;
		//referenced in
		i := Pos('Referenced in&nbsp;</h4>', all);
		if i>0 then begin
			delete(all, 1, i);
			ExtractMovieLinks(all, 5);
		end;
		//spoofs
		i := Pos('Spoofs&nbsp;</h4>', all);
		if i>0 then begin
			delete(all, 1, i);
			ExtractMovieLinks(all, 2);
		end;
		//spoofed in
		i := Pos('Spoofed in&nbsp;</h4>', all);
		if i>0 then begin
			delete(all, 1, i);
			ExtractMovieLinks(all, 3);
		end;
	end;
	if Not DlYear then year := '';   //Only Done here to keep year info available for other functions
	GetAllTrailers();
	sl.Free;   //20110114-JeF
  
	//types of movies
	if isTVSeries then
		media_type := 'TV Series';
	if media_type = '' then
		media_type := 'Movie';
	
	if RegReadInteger('IMDB_Mov_DlType', 1) = 0 then
		media_type := '';
  
end;

procedure ExtractMovieLinks(text: String; link_type: Integer);
var
	s, temp, title, year, code, page_url: String;
	i, j: Integer;
const
	do_not_include=['Video Game', 'TV Episode'];
begin
	i := Pos('<h4 ', text);
	if i = 0 then
		i := Length(text);
	s := copy(text, 1, i-1);
	i := Pos('<div class="soda', s);
	while i>0 do begin
		temp := GetStr(s, '<div class="soda', '</div>');
		title := GetStr(temp, ' href="/title/', '</a>');
		code := ParseString(title, '^tt(\d+)', 1);
		title := ClearExtraBlankCharacters(DecodeHTML(RemoveTags('<' + title)));
		year := ParseString(temp, 'nbsp;\((\d+)\)', 1);
		page_url := GetMovieSiteURL(code);
		for j := 0 to length(do_not_include) - 1 do begin
			if Pos(do_not_include[j], temp) > 0 then
				title := '';
		end;
		if (title <> '') and (code <> '') then
			SetMovieLink(title, code, year, '', link_type, page_url);
		delete(s, 1, i);
		i := Pos('<div class="soda', s);
	end;
end;

procedure GetAllTrailers;
var
  MainTrailerURL: string;
  URL: string;
  S: String;
  S2: string;
  I: Integer;
  J: Integer;
  K: Integer;
  TrailerDescription: string;
  TrailerImage: string;
  TrailersCount: Integer;
begin
  TrailersCount := 0;
  MainTrailerURL := '';  
  // Load all trailers from trailer page
  if (TrailersCount < MaxTrailersCount) then
  begin
    // receive Trailer page
    S2 := 'http://www.imdb.com/title/tt' + movie_code + '/videogallery';
    // Load all trailers from trailer page
    // S := DownloadURL(S2);
    S := GetHTMLPageContentFromRequest(S2);
    if ((S <> '') and (S <> '-1')) then
    begin
      J := Pos(' href="/video/imdb', S);
      while ((J > 0) and
             (TrailersCount < MaxTrailersCount)) do
      begin
        // Parse URL
        K := MyPos('</a>', S, J + Length(' href="/video/imdb'));
        if (K > J) then
        begin
          S2 := Copy(S, J, K - J);
          K := MyPos('"', S2, Length(' href="/'));
          if (K > 0) then
          begin
            // Parse URL and if it's not empty parse trailer description
            URL := Copy(S2, Length(' href="') + 1, K - Length(' href="/'));
            if ((URL <> '') and
                (URL <> MainTrailerURL)) then
            begin
              TrailerDescription := '';
              // Parse trailer description
              I := Pos('alt="', S2);
              if (I > 0) then
              begin
                K := MyPos('"', S2, I + Length('alt="'));
                if (K > I) then
                  TrailerDescription := Copy(S2, I + Length('alt="'), K - I - Length('alt="'));
              end;
              // parse trailer image link
              TrailerImage := '';
              I := Pos('loadlate="', S2);
              if (I > 0) then
              begin
                K := MyPos('"', S2, I + Length('loadlate="'));
                if (K > I) then
                  TrailerImage := Copy(S2, I + Length('loadlate="'), K - I - Length('loadlate="'));
              end;
              // set Trailer info
              SetTrailer('http://www.imdb.com' + URL, TrailerDescription, TrailerImage);
              Inc(TrailersCount);
            end;
          end;
        end;
        Delete(S, 1, J + Length(' href="/video/imdb'));
        // links for trailers are duplicate (for text and video). Delete if it's exist
        I := Pos(URL, S);
        if (I > 0) then
          Delete(S, 1, I + Length(URL));
        J := Pos(' href="/video/imdb', S);
      end;
    end;
  end;
end;

//gets movie frames
function GetFrames(frame_type: string; frame_limit, frame_code: integer): integer;
var
	url, all, s, frame_url: string;
	i, j, k, picSizeX, picSizeY: Integer;
	frames_count: Integer;
begin
	frames_count:=0;
	if frames_count=0 then begin
		picSizeX := RegReadInteger('IMDBPicSizeX', defaultPicSizeX);
		picSizeY := RegReadInteger('IMDBPicSizeY', defaultPicSizeY);
		url := 'http://www.imdb.com/title/tt'+movie_code+'/mediaindex?refine='+frame_type;
		// all := DownloadURL(url);
		All := GetHTMLPageContentFromRequest(url);
		if (jTraceLevel >= 5) then TraceExecute('Mediaindex_'+frame_type,all);   // 20101017-JeF
		if (all <> '')and(all <> '-1') then
		begin
			j := pos('<div class="media_index_thumb_list"', all);
			k := MyPos('</div>', all, j);
			if (j>0) and (k>0) then begin
				s := copy(all, j, k-j);
				i := pos('src=', s);
				delete(s,1,i);
				while (i>0) and (frames_count<frame_limit) do begin
					i:= pos('"', s) + 1;
					j:= MyPos('"', s, i+1);
					frame_url:=copy(s, i, j-i);
					//cut off the filename of the url
					i:= pos('V1._', frame_url);
					if i = 0 then
						i:= pos('V1_', frame_url);
					if i>0 then begin
						frame_url:=copy(frame_url, 1, i+1);
						//insert the pattern to load the larger image
						if picSizeX>0 then
							frame_url := frame_url + '_SX' + IntToStr(picSizeX);
						if picSizeY>0 then
							frame_url := frame_url + '_SY' + IntToStr(picSizeY);
						if (picSizeX>0) or (picSizeY>0) then
							frame_url := frame_url + '_';
						frame_url:=frame_url+'.jpg';
					end;
					SetImageName('', frame_url, '', frame_code);
					frames_count:=frames_count+1;
					i:=pos('src=', s);
					delete(s, 1, i);
				end;
			end;
		end;
	end;
	result := frames_count;
end;


//returned images links
procedure GetImages;
var
	shots_downloaded, shots_left, posters_downloaded, bts_downloaded: Integer;   //20101017-JeF
begin
	posters_downloaded := 0;
	shots_downloaded := 0;
	if front_cover_url<>'' then // front-cover from movie site
		SetImageName('', front_cover_url, '', 1);
	if posters_exist and (MaxPostersCount>0) then begin
		posters_downloaded := GetFrames('poster', MaxPostersCount, 4);
	end;
	if MaxShotsCount>0 then begin
		shots_downloaded := GetFrames('still_frame', MaxShotsCount, 3);
		if shots_downloaded<MaxShotsCount then begin
			shots_left := MaxShotsCount - shots_downloaded;
			bts_downloaded := GetFrames('behind_the_scenes', shots_left, 3);
		end;
	end;
	//20101017-JeF : No image found, try with no frame type
	if ((posters_downloaded + shots_downloaded + bts_downloaded = 0) and
      (MaxPostersCount + MaxShotsCount > 0)) then begin
		GetFrames('', MaxPostersCount + MaxShotsCount, 5);
	end;
	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]);
	EpisodeURLs.Free;
	if RegReadInteger('IMDB_Mov_DlTitle', 1) = 0 then
		title := '';
	
end;

//get movie site url
function GetMovieSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:='http://www.imdb.com/title/tt'+code;
end;

//get person site url
function GetPersonSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else	
		result:=format('http://www.imdb.com/name/nm%s', [code]);
end;


// File Exists Tool // 20101017-JeF
function MyFileExists(FileName: string): boolean;
var
	fs: TFileStream;
	s: string;
begin
	try
		fs:=TFileStream.Create(FileName, fmOpenRead);
		fs.Free;
		result:=true;
	except
		result:=false;
	end;
end;

function IfThen(AValue: Boolean; const ATrue: Integer; const AFalse: Integer = 0): Integer;
begin
	if AValue then result := ATrue
	else result := AFalse;
end;

// Trace Message when Trace is Active (Debug) // 20101017-JeF
procedure TraceAlert;
var
	s: string;
begin
	if (jTraceMode=1) then s:=GetLangStr(1687)
	else s:=GetLangStr(1688);
	showmessage(format(GetLangStr(1689),[s,IntToStr(jTraceLevel)]));
end;

// Save Trace To Disc (Debug) // 20101017-JeF
procedure SaveTraceToDisc(DumpName, DumpData: string);
var
	DumpFile: string;
	sl: TStringList;
begin
	sl:=TStringList.Create;
	DumpFile:=ScriptsPath+script_name+'_'+DumpName+'.trc';
	try
		sl.Text:=DumpData;
		sl.SaveToFile(DumpFile);
	except
		sl.Clear;
	end;
	sl.Free;
end;

// Load Trace From Disc (Debug) // 20101017-JeF
function LoadTraceFromDisc(DumpName: string): string;
var
	DumpFile: string;
	LoadIt: Boolean;
	i: integer;
	s: string;
	sl: TStringList;
begin
	result:='';
	sl:=TStringList.Create;
	DumpFile:=ScriptsPath+script_name+'_'+DumpName+'.trc';
	LoadIt:=False;
	if MyFileExists(DumpFile) then begin
		if jTraceAsk then begin
			s:=Format(GetLangStr(1690),[DumpName]);
			i:=MessageDlg(s,mtCustom,mbYes+mbCancel, 0);
			LoadIt:=(i=mrYes);
		end;
		if LoadIt then begin
			try
				sl.LoadFromFile(DumpFile);
				result:=sl.Text;
			except
				result:='';
			end;
		end;
	end;
	sl.Free;
end;

// Load or Save Trace according to Trace Mode (Debug) // 20101017-JeF
procedure TraceExecute(DumpName: string; VAR DumpData: string);
var
	DumpFile, s: string;
begin
	s:=DumpData;
	if jTraceMode = 1 then begin
		s:=LoadTraceFromDisc(DumpName);
		if (s <> '') then DumpData:=s;
	end
	else SaveTraceToDisc(DumpName, DumpData);
end;

function BoolToInt(b: boolean): integer;
begin
  if b then result:=1
  else result:=0;
end;

function IntToBool(intval: integer): boolean;
begin
  if intval < 1 then result := false
  else result := true;
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>', [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>', [title, year_int-1]);
			i := pos(LowerCase(s), nocaps);
			if i=0 then begin
				s := format('%s</a> <span>(%d)</span>', [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;

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

//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') and (Pos('No series found', all)=0) 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 
			tvdb_code := SearchTVDB(title, 7);
		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=7', [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 DownloadMovieSeasonsList and (DownloadTVDBEpisodeDescriptions = 1) then begin
						if (DownloadTVDBEnglishDesc = 1) or (NotConvertedTitle <> EpisodeTitle) 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 := 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, Format('name="EpisodeName_%d" value="', [TVDBLID]), '"');
		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(Format('name="Overview_%d"', [TVDBLID]), 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;

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;

//show available settings for the script
function ShowScriptOptions: integer;
var
	s: string;
	f: TForm;
	b: TButton;
	cbDownloadTrivia, cbDownloadGoofs, cbDownloadQuotes, cbDownloadConnections, cbDownloadSoundtracks, cbImportDesc, cbAkaSearch: TCheckBox;
	cbShowPlotAuthors, cbEpisodeFullDesc, cbAkasInDesc, cbImportMPAAReasons, cbAdvSearch: TCheckBox;
	cbOvrMainDlOptions, cbDlOriginalTitle, cbDlYear, cbDlGenres, cbDlCountries, cbDlDuration, cbDlType: TCheckBox;
	cbDlDirectors, cbDlActors, cbDlWriters, cbDlComposers, cbDlStudios, cbDlEpisodes, cbDlAwards: TCheckBox;
	cbImdbIdInEpisodeTitle, cbFullCharacterName: TCheckBox;
	gbDlOptions, gbDescOptions, gbPictures, gbLanguage, gbSearch, gbMpaa, gbTVSeries: TGroupBox;
	labTitleLang, labMPAADefault, labMPAAReplace, labLocalService, labPicSize, labPicMulti: TLabel;
	edTitleLang, edMPAADefault, edMPAAReplace, edPicSizeX, edPicSizeY: TEdit;
	comboLocalService: TComboBox;
	gbTrace: TGroupBox;								  // 20101017-JeF
	rbTraceModeSave, rbTraceModeLoad: TRadioButton;   // 20101017-JeF
	labTraceLevel: TLabel;							  // 20101017-JeF
	edTraceLevel: TEdit;							  // 20101017-JeF
	cbTraceAsk, cbTVDBPosters, cbTVDBFanart: TCheckBox;							  // 20101017-JeF
	posx, posy, my_value: integer;
	cbTMDBPosters, cbTMDBImages, cbTVDBEpisodes, cbTVDBEpisodeDesc,
    cbTVDBEpisodeDescEng, cbTVSeriesSaveActorsEpisodesNumbers, cbAdultContent, cbDlTitle: TCheckBox;

procedure ButtonClick(Sender: TButton);
var
	zn: integer;
begin
	try
		RegWriteInteger('IMDB_Mov_OvrMainDlOptions', BoolToInt(cbOvrMainDlOptions.Checked));
		RegWriteInteger('IMDB_Mov_DlOriginalTitle' , BoolToInt(cbDlOriginalTitle.Checked));
		RegWriteInteger('IMDB_Mov_DlYear'          , BoolToInt(cbDlYear.Checked));
		RegWriteInteger('IMDB_Mov_DlGenres'        , BoolToInt(cbDlGenres.Checked));
		RegWriteInteger('IMDB_Mov_DlCountries'     , BoolToInt(cbDlCountries.Checked));
		RegWriteInteger('IMDB_Mov_DlDuration'      , BoolToInt(cbDlDuration.Checked));
		RegWriteInteger('IMDB_Mov_DlStudios'       , BoolToInt(cbDlStudios.Checked));
		RegWriteInteger('IMDB_Mov_DlType'          , BoolToInt(cbDlType.Checked));
		RegWriteInteger('IMDB_Mov_DlEpisodes'      , BoolToInt(cbDlEpisodes.Checked));
		RegWriteInteger('IMDB_Mov_DlDirectors'     , BoolToInt(cbDlDirectors.Checked));
		RegWriteInteger('IMDB_Mov_DlActors'        , BoolToInt(cbDlActors.Checked));
		RegWriteInteger('IMDB_Mov_DlWriters'       , BoolToInt(cbDlWriters.Checked));
		RegWriteInteger('IMDB_Mov_DlComposers'     , BoolToInt(cbDlComposers.Checked));
		RegWriteInteger('IMDB_Mov_DlAwards'        , BoolToInt(cbDlAwards.Checked));
		RegWriteInteger('IMDB_Mov_DlTitle'        , BoolToInt(cbDlTitle.Checked));

		RegWriteInteger('IMDBDownloadTrivia', BoolToInt(cbDownloadTrivia.Checked));
		RegWriteInteger('IMDBDownloadGoofs', BoolToInt(cbDownloadGoofs.Checked));
		RegWriteInteger('IMDBDownloadQuotes', BoolToInt(cbDownloadQuotes.Checked));
		RegWriteInteger('IMDBDownloadConnections', BoolToInt(cbDownloadConnections.Checked));
		RegWriteInteger('IMDBDownloadSoundtracks', BoolToInt(cbDownloadSoundtracks.Checked));
		RegWriteInteger('IMDBImportDesc', BoolToInt(cbImportDesc.Checked));

		RegWriteInteger('IMDB_Mov_ImdbIdInEpisodeTitle' , BoolToInt(cbImdbIdInEpisodeTitle.Checked));  //20120414-JeF
		RegWriteInteger('IMDBFullCharacterName'         , BoolToInt(cbFullCharacterName.Checked));     //20120414-JeF
		RegWriteInteger('IMDBUseTmdbPosters', BoolToInt(cbTMDBPosters.Checked));
		RegWriteInteger('IMDBUseTmdbBackdrops', BoolToInt(cbTMDBImages.Checked));
		RegWriteInteger('IMDBUseTvdbPosters', BoolToInt(cbTVDBPosters.Checked));
		RegWriteInteger('IMDBUseTvdbFanart', BoolToInt(cbTVDBFanart.Checked));
		RegWriteInteger('IMDBTVDBEpisodes', BoolToInt(cbTVDBEpisodes.Checked));
		RegWriteInteger('IMDBTVDBDescriptions', BoolToInt(cbTVDBEpisodeDesc.Checked));
		RegWriteInteger('IMDBDownloadActorsEpisodesForTVSeries', BoolToInt(cbTVSeriesSaveActorsEpisodesNumbers.Checked));

		if cbAkaSearch.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('IMDBAkaSearch', zn);
		if cbShowPlotAuthors.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('IMDBShowPlotAuthors', zn);	
		if cbEpisodeFullDesc.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('IMDBEpisodeFullDesc', zn);
		if cbAkasInDesc.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('IMDBAkasInDesc', zn);
		try 
			zn := StrToInt(edPicSizeX.Text);
			RegWriteInteger('IMDBPicSizeX', zn);
		except
		end;
		try
			zn := StrToInt(edPicSizeY.Text);
			RegWriteInteger('IMDBPicSizeY', zn);
		except
		end;
		if cbImportMPAAReasons.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('IMDBImportMPAAReasons', zn);			

		// 20101017-JeF
		if rbTraceModeLoad.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('IMDBTraceMode', zn);
		try 
			zn := StrToInt(edTraceLevel.Text);
			RegWriteInteger('IMDBTraceLevel', zn);
		except
		end;
		if cbTraceAsk.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('IMDBTraceAsk', zn);
		if cbAdvSearch.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('IMDBAdvSearch', zn);
		
		if cbTMDBPosters.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('IMDBTMDBPosters', zn);
		if cbTMDBImages.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('IMDBTMDBImages', zn);
		if cbAdultContent.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('IMDBAdultContent', zn);
		
		RegWriteString('IMDBTitleLang', edTitleLang.Text);
		RegWriteString('IMDBMPAADefault', edMPAADefault.Text);
		RegWriteString('IMDBMPAAReplace', edMPAAReplace.Text);
		RegWriteInteger('IMDBLocalService', comboLocalService.ItemIndex);
	except
	end;

	jTraceMode := RegReadInteger('IMDBTraceMode', 0);     // 20101017-JeF
	jTraceLevel := RegReadInteger('IMDBTraceLevel', 0);   // 20101017-JeF
	jTraceAsk := RegReadInteger('IMDBTraceAsk', 1);  	  // 20101017-JeF

	f.ModalResult := mrOk;
end;

begin
	result:=0;
	f := TForm.Create(nil);
	f.Caption := GetLangStr(1924);
	f.BorderStyle := bsDialog;
	f.Position := poScreenCenter;
	f.Width:=900;
	if jShowTraceSettings then f.Width:=1000;  // 20101017-JeF
	f.Height:=500;
	f.AutoSize:=false;

	posx :=  10;
	posy := -10;
	
	posy := posy + 20;
	cbOvrMainDlOptions := TCheckBox.Create(f);
	cbOvrMainDlOptions.Name := 'cbOvrMainDlOptions';
	cbOvrMainDlOptions.Parent := f;
	cbOvrMainDlOptions.SetBounds(posx, posy, 350, 20);
	if GetLangStr(2744) = '' 
		then cbOvrMainDlOptions.Caption := 'Override Global Download Options (F10)'
	else cbOvrMainDlOptions.Caption := GetLangStr(2744);
	if GetLangStr(2745) = '' 
		then cbOvrMainDlOptions.Hint := 'Override values/flags set in main download options window (F10)'
	else cbOvrMainDlOptions.Hint := GetLangStr(2745);
	cbOvrMainDlOptions.Checked := IntToBool(RegReadInteger('IMDB_Mov_OvrMainDlOptions', 0));

	{--------------}
	{--- Search ---}
	{--------------}
	posx :=  10;
	posy := posy + 50;

	gbSearch:=TGroupBox.Create(f);
	gbSearch.Name:='gbSearch';
	gbSearch.Parent:=f;
	gbSearch.SetBounds(posx, posy, 485, 30);
	gbSearch.Caption:=' ' + GetLangStr(44) + ' ';
	gbSearch.Hint:=GetLangStr(44);
	posy := 0;
	
	posy := posy + 20;
	gbSearch.Height := gbSearch.Height + 20;
	cbAkaSearch := TCheckBox.Create(f);
	cbAkaSearch.Name := 'cbAkaSearch';
	cbAkaSearch.Parent := gbSearch;
	cbAkaSearch.SetBounds(posx, posy, 370, 20);
	cbAkaSearch.Caption := GetLangStr(1939);
	my_value := RegReadInteger('IMDBAkaSearch', 0);
	if my_value=1 then
		cbAkaSearch.Checked := True;
		
	posy := posy + 20;
	gbSearch.Height := gbSearch.Height + 20;
	cbAdvSearch := TCheckBox.Create(f);
	cbAdvSearch.Name := 'cbAdvSearch';
	cbAdvSearch.Parent := gbSearch;
	cbAdvSearch.SetBounds(posx, posy, 370, 20);
	cbAdvSearch.Caption := 'Alternative search';
	s := GetLangStr(1490);
	if s<>'' then
		cbAdvSearch.Caption := s;
	my_value := RegReadInteger('IMDBAdvSearch', 0);
	if my_value=1 then
		cbAdvSearch.Checked := True;
		
	posy := posy + 20;
	gbSearch.Height := gbSearch.Height + 20;
	cbAdultContent := TCheckBox.Create(f);
	cbAdultContent.Name := 'cbAdultContent';
	cbAdultContent.Parent := gbSearch;
	cbAdultContent.SetBounds(posx, posy, 370, 20);
	cbAdultContent.Caption := 'Show adult titles (login to IMDb is required)';
	s := GetLangStr(4152);
	if s<>'' then
		cbAdultContent.Caption := s;
	my_value := RegReadInteger('IMDBAdultContent', 0);
	if my_value=1 then
		cbAdultContent.Checked := True;

	{-----------------}
	{--- Main Data ---}
	{-----------------}
	posx :=  10;
	posy := gbSearch.Top + gbSearch.Height + 15;

	gbDlOptions:=TGroupBox.Create(f);
	gbDlOptions.Name:='gbDlOptions';
	gbDlOptions.Parent:=f;
	gbDlOptions.SetBounds(posx, posy, 485, 30);
	if GetLangStr(2746) = '' 
		then gbDlOptions.Caption := ' Main Data '
	else gbDlOptions.Caption := ' ' + GetLangStr(2746) + ' ';
	gbDlOptions.Hint := gbDlOptions.Caption;
	posy := 0;
	
	posy := posy + 20;
	gbDlOptions.Height := gbDlOptions.Height + 20;
	cbDlOriginalTitle := TCheckBox.Create(f);
	cbDlOriginalTitle.Name := 'cbDlOriginalTitle';
	cbDlOriginalTitle.Parent := gbDlOptions;
	cbDlOriginalTitle.SetBounds(posx, posy, 200, 20);
	cbDlOriginalTitle.Caption := GetLangStr(167);
	cbDlOriginalTitle.Checked := IntToBool(RegReadInteger('IMDB_Mov_DlOriginalTitle', 1));
		
	posy := posy + 20;
	gbDlOptions.Height := gbDlOptions.Height + 20;
	cbDlDuration := TCheckBox.Create(f);
	cbDlDuration.Name := 'cbDlDuration';
	cbDlDuration.Parent := gbDlOptions;
	cbDlDuration.SetBounds(posx, posy, 200, 20);
	cbDlDuration.Caption := GetLangStr(147);
	cbDlDuration.Checked := IntToBool(RegReadInteger('IMDB_Mov_DlDuration', 1));
		
	posy := posy + 20;
	gbDlOptions.Height := gbDlOptions.Height + 20;
	cbDlYear := TCheckBox.Create(f);
	cbDlYear.Name := 'cbDlYear';
	cbDlYear.Parent := gbDlOptions;
	cbDlYear.SetBounds(posx, posy, 200, 20);
	cbDlYear.Caption := GetLangStr(169);
	cbDlYear.Checked := IntToBool(RegReadInteger('IMDB_Mov_DlYear', 1));
		
	posy := posy + 20;
	gbDlOptions.Height := gbDlOptions.Height + 20;
	cbDlGenres := TCheckBox.Create(f);
	cbDlGenres.Name := 'cbDlGenres';
	cbDlGenres.Parent := gbDlOptions;
	cbDlGenres.SetBounds(posx, posy, 200, 20);
	cbDlGenres.Caption := GetLangStr(179);
	cbDlGenres.Checked := IntToBool(RegReadInteger('IMDB_Mov_DlGenres', 1));
		
	posy := posy + 20;
	gbDlOptions.Height := gbDlOptions.Height + 20;
	cbDlCountries := TCheckBox.Create(f);
	cbDlCountries.Name := 'cbDlCountries';
	cbDlCountries.Parent := gbDlOptions;
	cbDlCountries.SetBounds(posx, posy, 200, 20);
	cbDlCountries.Caption := GetLangStr(180);
	cbDlCountries.Checked := IntToBool(RegReadInteger('IMDB_Mov_DlCountries', 1));
		
	posy := posy + 20;
	gbDlOptions.Height := gbDlOptions.Height + 20;
	cbDlStudios := TCheckBox.Create(f);
	cbDlStudios.Name := 'cbDlStudios';
	cbDlStudios.Parent := gbDlOptions;
	cbDlStudios.SetBounds(posx, posy, 200, 20);
	cbDlStudios.Caption := GetLangStr(493);
	cbDlStudios.Checked := IntToBool(RegReadInteger('IMDB_Mov_DlStudios', 1));
	
	posy := posy + 20;
	gbDlOptions.Height := gbDlOptions.Height + 20;
	cbDlType := TCheckBox.Create(f);
	cbDlType.Name := 'cbDlType';
	cbDlType.Parent := gbDlOptions;
	cbDlType.SetBounds(posx, posy, 200, 20);
	cbDlType.Caption := GetLangStr(173);
	cbDlType.Checked := IntToBool(RegReadInteger('IMDB_Mov_DlType', 1));	

	posx := 220;
	posy := 0;
	
	posy := posy + 20;
	cbDlEpisodes := TCheckBox.Create(f);
	cbDlEpisodes.Name := 'cbDlEpisodes';
	cbDlEpisodes.Parent := gbDlOptions;
	cbDlEpisodes.SetBounds(posx, posy, 200, 20);
	cbDlEpisodes.Caption := GetLangStr(525);
	cbDlEpisodes.Hint := GetLangStr(1285);
	cbDlEpisodes.Checked := IntToBool(RegReadInteger('IMDB_Mov_DlEpisodes', 1));

	posy := posy + 20;
	cbDlDirectors := TCheckBox.Create(f);
	cbDlDirectors.Name := 'cbDlDirectors';
	cbDlDirectors.Parent := gbDlOptions;
	cbDlDirectors.SetBounds(posx, posy, 200, 20);
	cbDlDirectors.Caption := GetLangStr(181);
	cbDlDirectors.Checked := IntToBool(RegReadInteger('IMDB_Mov_DlDirectors', 1));
		
	posy := posy + 20;
	cbDlActors := TCheckBox.Create(f);
	cbDlActors.Name := 'cbDlActors';
	cbDlActors.Parent := gbDlOptions;
	cbDlActors.SetBounds(posx, posy, 200, 20);
	cbDlActors.Caption := GetLangStr(164);
	cbDlActors.Checked := IntToBool(RegReadInteger('IMDB_Mov_DlActors', 1));
		
	posy := posy + 20;
	cbDlWriters := TCheckBox.Create(f);
	cbDlWriters.Name := 'cbDlWriters';
	cbDlWriters.Parent := gbDlOptions;
	cbDlWriters.SetBounds(posx, posy, 200, 20);
	cbDlWriters.Caption := GetLangStr(182);
	cbDlWriters.Checked := IntToBool(RegReadInteger('IMDB_Mov_DlWriters', 1));
		
	posy := posy + 20;
	cbDlComposers := TCheckBox.Create(f);
	cbDlComposers.Name := 'cbDlComposers';
	cbDlComposers.Parent := gbDlOptions;
	cbDlComposers.SetBounds(posx, posy, 200, 20);
	cbDlComposers.Caption := GetLangStr(491);
	cbDlComposers.Checked := IntToBool(RegReadInteger('IMDB_Mov_DlComposers', 1));
		
	posy := posy + 20;
	cbDlAwards := TCheckBox.Create(f);
	cbDlAwards.Name := 'cbDlAwards';
	cbDlAwards.Parent := gbDlOptions;
	cbDlAwards.SetBounds(posx, posy, 200, 20);
	cbDlAwards.Caption := GetLangStr(574);
	cbDlAwards.Checked := IntToBool(RegReadInteger('IMDB_Mov_DlAwards', 1));
	
	posy := posy + 20;
	cbDlTitle := TCheckBox.Create(f);
	cbDlTitle.Name := 'cbDlTitle';
	cbDlTitle.Parent := gbDlOptions;
	cbDlTitle.SetBounds(posx, posy, 200, 20);
	cbDlTitle.Caption := GetLangStr(48);
	cbDlTitle.Checked := IntToBool(RegReadInteger('IMDB_Mov_DlTitle', 1));
	
	{--------------------}
	{--- Descriptions ---}
	{--------------------}
	posx := gbDlOptions.Left + gbDlOptions.Width + 20;
	posy := gbSearch.Top;

	gbDescOptions:=TGroupBox.Create(f);
	gbDescOptions.Name:='gbDescOptions';
	gbDescOptions.Parent:=f;
	gbDescOptions.SetBounds(posx, posy, 485, 30);
	gbDescOptions.Caption:=' ' + GetLangStr(162) + ' ';
	gbDescOptions.Hint:=GetLangStr(162);
	posx := 10;
	posy := 0;
	
	posy := posy + 20;
	gbDescOptions.Height := gbDescOptions.Height + 20;
	cbImportDesc := TCheckBox.Create(f);
	cbImportDesc.Name := 'cbImportDesc';
	cbImportDesc.Parent := gbDescOptions;
	cbImportDesc.SetBounds(posx, posy, 370, 20);
	cbImportDesc.Caption := GetLangStr(1938);
	my_value := RegReadInteger('IMDBImportDesc', 1);
	if my_value=1 then
		cbImportDesc.Checked := True;
		
	posy := posy + 20;
	gbDescOptions.Height := gbDescOptions.Height + 20;
	cbShowPlotAuthors := TCheckBox.Create(f);
	cbShowPlotAuthors.Name := 'cbShowPlotAuthors';
	cbShowPlotAuthors.Parent := gbDescOptions;
	cbShowPlotAuthors.SetBounds(posx, posy, 370, 20);
	cbShowPlotAuthors.Caption := GetLangStr(1940);
	my_value := RegReadInteger('IMDBShowPlotAuthors', 1);
	if my_value=1 then
		cbShowPlotAuthors.Checked := True;
		
	posy := posy + 20;
	gbDescOptions.Height := gbDescOptions.Height + 20;
	cbAkasInDesc := TCheckBox.Create(f);
	cbAkasInDesc.Name := 'cbAkasInDesc';
	cbAkasInDesc.Parent := gbDescOptions;
	cbAkasInDesc.SetBounds(posx, posy, 370, 20);
	cbAkasInDesc.Caption := GetLangStr(1942);
	my_value := RegReadInteger('IMDBAkasInDesc', 0);
	if my_value=1 then
		cbAkasInDesc.Checked := True;
		
	posy := posy + 20;
	gbDescOptions.Height := gbDescOptions.Height + 20;
	cbDownloadTrivia := TCheckBox.Create(f);
	cbDownloadTrivia.Name := 'cbDownloadTrivia';
	cbDownloadTrivia.Parent := gbDescOptions;
	cbDownloadTrivia.SetBounds(posx, posy, 350, 20);
	cbDownloadTrivia.Caption := GetLangStr(1933);
	my_value := RegReadInteger('IMDBDownloadTrivia', 1);
	if my_value=1 then
		cbDownloadTrivia.Checked := True;
		
	posy := posy + 20;
	gbDescOptions.Height := gbDescOptions.Height + 20;
	cbDownloadGoofs := TCheckBox.Create(f);
	cbDownloadGoofs.Name := 'cbDownloadGoofs';
	cbDownloadGoofs.Parent := gbDescOptions;
	cbDownloadGoofs.SetBounds(posx, posy, 350, 20);
	cbDownloadGoofs.Caption := GetLangStr(1934);
	my_value := RegReadInteger('IMDBDownloadGoofs', 1);
	if my_value=1 then
		cbDownloadGoofs.Checked := True;
		
	posy := posy + 20;
	gbDescOptions.Height := gbDescOptions.Height + 20;
	cbDownloadQuotes := TCheckBox.Create(f);
	cbDownloadQuotes.Name := 'cbDownloadQuotes';
	cbDownloadQuotes.Parent := gbDescOptions;
	cbDownloadQuotes.SetBounds(posx, posy, 350, 20);
	cbDownloadQuotes.Caption := GetLangStr(1935);
	my_value := RegReadInteger('IMDBDownloadQuotes', 0);
	if my_value=1 then
		cbDownloadQuotes.Checked := True;
		
	posy := posy + 20;
	gbDescOptions.Height := gbDescOptions.Height + 20;
	cbDownloadConnections := TCheckBox.Create(f);
	cbDownloadConnections.Name := 'cbDownloadConnections';
	cbDownloadConnections.Parent := gbDescOptions;
	cbDownloadConnections.SetBounds(posx, posy, 350, 20);
	cbDownloadConnections.Caption := GetLangStr(1936);
	my_value := RegReadInteger('IMDBDownloadConnections', 0);
	if my_value=1 then
		cbDownloadConnections.Checked := True;

	posy := posy + 20;
	gbDescOptions.Height := gbDescOptions.Height + 20;
	cbDownloadSoundtracks := TCheckBox.Create(f);
	cbDownloadSoundtracks.Name := 'cbDownloadSoundtracks';
	cbDownloadSoundtracks.Parent := gbDescOptions;
	cbDownloadSoundtracks.SetBounds(posx, posy, 370, 20);
	cbDownloadSoundtracks.Caption := GetLangStr(1937);
	my_value := RegReadInteger('IMDBDownloadSoundtracks', 0);
	if my_value=1 then
		cbDownloadSoundtracks.Checked := True;	
		
	posy := posy + 20;
	gbDescOptions.Height := gbDescOptions.Height + 20;
	cbEpisodeFullDesc := TCheckBox.Create(f);
	cbEpisodeFullDesc.Name := 'cbEpisodeFullDesc';
	cbEpisodeFullDesc.Parent := gbDescOptions;
	cbEpisodeFullDesc.SetBounds(posx, posy, 370, 20);
	cbEpisodeFullDesc.Caption := GetLangStr(1941);
	my_value := RegReadInteger('IMDBEpisodeFullDesc', 0);
	if my_value=1 then
		cbEpisodeFullDesc.Checked := True;
		
	{-----------------------------}
	{-------- TV series ----------}
	{-----------------------------}
		
	posy := gbDescOptions.Top + gbDescOptions.Height + 20;
	posx := gbDescOptions.Left;

	gbTVSeries:=TGroupBox.Create(f);
	gbTVSeries.Name:='gbTVSeries';
	gbTVSeries.Parent:=f;
	gbTVSeries.SetBounds(posx, posy, 485, 30);
	if GetLangStr(3875) = '' 
		then gbTVSeries.Caption := ' TV Series '
	else gbTVSeries.Caption := ' ' + GetLangStr(3875) + ' ';
	gbTVSeries.Hint := gbTVSeries.Caption;
	posx := 10;
	posy := 0;
		
	posy := posy + 20;
	gbTVSeries.Height := gbTVSeries.Height + 20;
	cbTVDBEpisodes := TCheckBox.Create(f);
	cbTVDBEpisodes.Name := 'cbTVDBEpisodes';
	cbTVDBEpisodes.Parent := gbTVSeries;
	cbTVDBEpisodes.SetBounds(posx, posy, 420, 20);
	cbTVDBEpisodes.Caption := 'Download episode names, season posters, episode covers from thetvdb.com';
	s := GetLangStr(3880);
	if s<>'' then
		cbTVDBEpisodes.Caption := Format(s, ['thetvdb.com']);
	my_value := RegReadInteger('IMDBTVDBEpisodes', 1);
	if my_value=1 then
		cbTVDBEpisodes.Checked := True;

	posy := posy + 20;
	gbTVSeries.Height := gbTVSeries.Height + 20;
	cbTVDBEpisodeDesc := TCheckBox.Create(f);
	cbTVDBEpisodeDesc.Name := 'cbTVDBEpisodeDesc';
	cbTVDBEpisodeDesc.Parent := gbTVSeries;
	cbTVDBEpisodeDesc.SetBounds(posx, posy, 420, 20);
	cbTVDBEpisodeDesc.Caption := 'Download episode descriptions from thetvdb.com (time consuming)';
	s := GetLangStr(3881);
	if s<>'' then
		cbTVDBEpisodeDesc.Caption := Format(s, ['thetvdb.com']);
	my_value := RegReadInteger('IMDBTVDBDescriptions', 1);
	if my_value=1 then
		cbTVDBEpisodeDesc.Checked := True;
  // SaAve actors' episodes for TVSeries
	posy := posy + 20;
	gbTVSeries.Height := gbTVSeries.Height + 20;
	cbTVSeriesSaveActorsEpisodesNumbers := TCheckBox.Create(f);
	cbTVSeriesSaveActorsEpisodesNumbers.Name := 'cbTVSeriesSaveActorsEpisodesNumbers';
	cbTVSeriesSaveActorsEpisodesNumbers.Parent := gbTVSeries;
	cbTVSeriesSaveActorsEpisodesNumbers.SetBounds(posx, posy, 420, 20);
	cbTVSeriesSaveActorsEpisodesNumbers.Caption := 'Download actors episodes for TV Series';
	s := GetLangStr(3927);
	if s<>'' then
		cbTVSeriesSaveActorsEpisodesNumbers.Caption := s;
	my_value := RegReadInteger('IMDBDownloadActorsEpisodesForTVSeries', 0);
	if my_value=1 then
		cbTVSeriesSaveActorsEpisodesNumbers.Checked := True;


	{-----------------------------}
	{--- Miscellaneous options ---}
	{-----------------------------}
	posx := gbDescOptions.Left + 10;
	posy := 10;
	
	//20120414-JeF
	cbImdbIdInEpisodeTitle := TCheckBox.Create(f);
	cbImdbIdInEpisodeTitle.Name := 'cbImdbIdInEpisodeTitle';
	cbImdbIdInEpisodeTitle.Parent := f;
	cbImdbIdInEpisodeTitle.SetBounds(posx, posy, 370, 20);
	cbImdbIdInEpisodeTitle.Caption := GetLangStr(2747);
	if cbImdbIdInEpisodeTitle.Caption = '' 
		then cbImdbIdInEpisodeTitle.Caption := 'Add episode imdb id to episode title : (tt...)';
	cbImdbIdInEpisodeTitle.Checked := IntToBool(RegReadInteger('IMDB_Mov_ImdbIdInEpisodeTitle', 0));

	//20120414-JeF
	posy := posy + 20;
	cbFullCharacterName := TCheckBox.Create(f);
	cbFullCharacterName.Name := 'cbFullCharacterName';
	cbFullCharacterName.Parent := f;
	cbFullCharacterName.SetBounds(posx, posy, 370, 20);
	cbFullCharacterName.Caption := GetLangStr(2748);
	if cbFullCharacterName.Caption = '' 
		then cbFullCharacterName.Caption := 'Full Character Name (including brackets)';
	cbFullCharacterName.Checked := IntToBool(RegReadInteger('IMDBFullCharacterName', 0));

	{----------------}
	{--- Pictures ---}
	{----------------}
	posx :=  10;
	posy := gbDlOptions.Top + gbDlOptions.Height + 15;

	gbPictures:=TGroupBox.Create(f);
	gbPictures.Name:='gbPictures';
	gbPictures.Parent:=f;
	gbPictures.SetBounds(posx, posy, 485, 35);
	gbPictures.Caption:=' ' + GetLangStr(199) + ' ';
	gbPictures.Hint:=GetLangStr(199);
	posy := 0;
	
	posy := posy + 20;
	gbPictures.Height := gbPictures.Height + 25;
	edPicSizeX := TEdit.Create(f);
	edPicSizeX.Name := 'edPicSizeX';
	edPicSizeX.Parent := gbPictures;
	edPicSizeX.SetBounds(posx, posy, 40, 25);
	edPicSizeX.Text := IntToStr(RegReadInteger('IMDBPicSizeX', defaultPicSizeX));
	
	labPicMulti := TLabel.Create(f);
	labPicMulti.Name := 'labPicMulti';
	labPicMulti.Parent := gbPictures;
	labPicMulti.SetBounds(posx + 46, edPicSizeX.Top + 3, 10, 25);
	labPicMulti.Caption := 'X';
	
	edPicSizeY := TEdit.Create(f);
	edPicSizeY.Name := 'edPicSizeY';
	edPicSizeY.Parent := gbPictures;
	edPicSizeY.SetBounds(posx + 60, posy, 40, 25);
	edPicSizeY.Text := IntToStr(RegReadInteger('IMDBPicSizeY', defaultPicSizeY));
	
	labPicSize := TLabel.Create(f);
	labPicSize.Name := 'labPicSize';
	labPicSize.Parent := gbPictures;
	labPicSize.SetBounds(posx + 110, edPicSizeX.Top + 3, 160, 25);
	labPicSize.Caption := GetLangStr(1948);
	posy := posy + 10;

	posy := posy + 20;
	gbPictures.Height := gbPictures.Height + 20;
	cbTMDBPosters := TCheckBox.Create(f);
	cbTMDBPosters.Name := 'cbTMDBPosters';
	cbTMDBPosters.Parent := gbPictures;
	cbTMDBPosters.SetBounds(posx, posy, 370, 20);
	cbTMDBPosters.Caption := 'Download movie posters from themoviedb.org';
	s := GetLangStr(3876);
	if s<>'' then
		cbTMDBPosters.Caption := Format(s, ['themoviedb.org']);;
	my_value := RegReadInteger('IMDBUseTmdbPosters', 0);
	if my_value=1 then
		cbTMDBPosters.Checked := True;
		
	posy := posy + 20;
	gbPictures.Height := gbPictures.Height + 20;
	cbTMDBImages := TCheckBox.Create(f);
	cbTMDBImages.Name := 'cbTMDBImages';
	cbTMDBImages.Parent := gbPictures;
	cbTMDBImages.SetBounds(posx, posy, 370, 20);
	cbTMDBImages.Caption := 'Download movie backdrops from themoviedb.org';
	s := GetLangStr(3877);
	if s<>'' then
		cbTMDBImages.Caption := Format(s, ['themoviedb.org']);
	my_value := RegReadInteger('IMDBUseTmdbBackdrops', 1);
	if my_value=1 then
		cbTMDBImages.Checked := True;
		
	posy := posy + 20;
	gbPictures.Height := gbPictures.Height + 20;
	cbTVDBPosters := TCheckBox.Create(f);
	cbTVDBPosters.Name := 'cbTVDBPosters';
	cbTVDBPosters.Parent := gbPictures;
	cbTVDBPosters.SetBounds(posx, posy, 370, 20);
	cbTVDBPosters.Caption := 'Download posters for TV series from thetvdb.com';
	s := GetLangStr(3878);
	if s<>'' then
		cbTVDBPosters.Caption := Format(s, ['thetvdb.com']);
	my_value := RegReadInteger('IMDBUseTvdbPosters', 0);
	if my_value=1 then
		cbTVDBPosters.Checked := True;
		
	posy := posy + 20;
	gbPictures.Height := gbPictures.Height + 20;
	cbTVDBFanart := TCheckBox.Create(f);
	cbTVDBFanart.Name := 'cbTVDBFanart';
	cbTVDBFanart.Parent := gbPictures;
	cbTVDBFanart.SetBounds(posx, posy, 370, 20);
	cbTVDBFanart.Caption := 'Download backdrops for TV series from thetvdb.com';
	s := GetLangStr(3879);
	if s<>'' then
		cbTVDBFanart.Caption := Format(s, ['thetvdb.com']);
	my_value := RegReadInteger('IMDBUseTvdbFanart', 1);
	if my_value=1 then
		cbTVDBFanart.Checked := True;

	{----------------}
	{--- Language ---}
	{----------------}
	posx :=  10;
	posy := gbPictures.Top + gbPictures.Height + 15;

	gbLanguage:=TGroupBox.Create(f);
	gbLanguage.Name:='gbLanguage';
	gbLanguage.Parent:=f;
	gbLanguage.SetBounds(posx, posy, 485, 35);
	gbLanguage.Caption:=' ' + GetLangStr(87) + ' ';
	gbLanguage.Hint:=GetLangStr(87);
	posy := 0;
	
	posy := posy + 20;
	gbLanguage.Height := gbLanguage.Height + 20;
	comboLocalService := TComboBox.Create(f);
	comboLocalService.Name := 'comboLocalService';
	comboLocalService.Parent := gbLanguage;
	comboLocalService.SetBounds(posx, posy, 100, 20);
	comboLocalService.Style := csDropDownList;
	comboLocalService.Items.Add('imdb.com');
	comboLocalService.Items.Add('imdb.de');
	comboLocalService.Items.Add('imdb.es');
	comboLocalService.Items.Add('imdb.fr');
	comboLocalService.Items.Add('imdb.it');
	comboLocalService.Items.Add('imdb.pt');
	comboLocalService.ItemIndex := RegReadInteger('IMDBLocalService', 0);
	
	labLocalService:=TLabel.Create(f);
	labLocalService.Name := 'labLocalService';
	labLocalService.Parent := gbLanguage;
	labLocalService.SetBounds(posx + 110, comboLocalService.Top + 3, 160, 20);
	labLocalService.Caption := GetLangStr(1947);
	posy := posy + 10;
	gbLanguage.Height := gbLanguage.Height + 10;
		
	posy := posy + 20;
	gbLanguage.Height := gbLanguage.Height + 20;
	edTitleLang := TEdit.Create(f);
	edTitleLang.Name := 'edTitleLang';
	edTitleLang.Parent := gbLanguage;
	edTitleLang.SetBounds(posx, posy, 100, 25);
	edTitleLang.Text := RegReadString('IMDBTitleLang', '');
		
	labTitleLang:=TLabel.Create(f);
	labTitleLang.Name := 'labTitleLang';
	labTitleLang.Parent := gbLanguage;
	labTitleLang.SetBounds(posx + 110, edTitleLang.Top + 3, 160, 25);
	labTitleLang.Caption := GetLangStr(1943);
	posy := posy + 10;
		
	{------------}
	{--- MPAA ---}
	{------------}
	posx := gbTVSeries.Left;
	posy := gbTVSeries.Top + gbTVSeries.Height + 15;

	gbMpaa:=TGroupBox.Create(f);
	gbMpaa.Name:='gbMpaa';
	gbMpaa.Parent:=f;
	gbMpaa.SetBounds(posx, posy, 485, 35);
	gbMpaa.Caption:=' ' + GetLangStr(383) + ' ';
	gbMpaa.Hint:=GetLangStr(383);
	posx := 10;
	posy := 0;
	
	posy := posy + 20;
	gbMpaa.Height := gbMpaa.Height + 20;
	cbImportMPAAReasons := TCheckBox.Create(f);
	cbImportMPAAReasons.Name := 'cbImportMPAAReasons';
	cbImportMPAAReasons.Parent := gbMpaa;
	cbImportMPAAReasons.SetBounds(posx, posy, 370, 20);
	cbImportMPAAReasons.Caption := GetLangStr(1946);
	my_value := RegReadInteger('IMDBImportMPAAReasons', 1);
	if my_value=1 then
		cbImportMPAAReasons.Checked := True;
		
	posy := posy + 25;
	gbMpaa.Height := gbMpaa.Height + 25;
	edMPAADefault := TEdit.Create(f);
	edMPAADefault.Name := 'edMPAADefault';
	edMPAADefault.Parent := gbMpaa;
	edMPAADefault.SetBounds(posx, posy, 100, 25);
	edMPAADefault.Text := RegReadString('IMDBMPAADefault', '');
		
	labMPAADefault:=TLabel.Create(f);
	labMPAADefault.Name := 'labMPAADefault';
	labMPAADefault.Parent := gbMpaa;
	labMPAADefault.SetBounds(posx + 110, edMPAADefault.Top + 3, 160, 25);
	labMPAADefault.Caption := GetLangStr(1944);
	posy := posy + 10;
	gbMpaa.Height := gbMpaa.Height + 10;
		
	posy := posy + 20;
	gbMpaa.Height := gbMpaa.Height + 20;
	edMPAAReplace := TEdit.Create(f);
	edMPAAReplace.Name := 'edMPAAReplace';
	edMPAAReplace.Parent := gbMpaa;
	edMPAAReplace.SetBounds(posx, posy, 100, 25);
	edMPAAReplace.Text := RegReadString('IMDBMPAAReplace', '');
		
	labMPAAReplace:=TLabel.Create(f);
	labMPAAReplace.Name := 'labMPAAReplace';
	labMPAAReplace.Parent := gbMpaa;
	labMPAAReplace.SetBounds(posx + 110, edMPAAReplace.Top + 3, 160, 25);
	labMPAAReplace.Caption := GetLangStr(1945);

	posx :=  10;
	posy := gbLanguage.Top + gbLanguage.Height - 5;

	// 20101017-JeF
	if jShowTraceSettings then begin
		gbTrace:=TGroupBox.Create(f);
		gbTrace.Name:='gbTrace';
		gbTrace.Parent:=f;
		gbTrace.SetBounds(gbDescOptions.Left  + gbDescOptions.Width - 200, 10, 200, 105);
		gbTrace.Caption:=GetLangStr(1691);
		gbTrace.Hint:=GetLangStr(1692);
		rbTraceModeSave:=TRadioButton.Create(f);
		rbTraceModeSave.Name:='rbTraceModeSave';
		rbTraceModeSave.Parent:=gbTrace;
		rbTraceModeSave.SetBounds(10, 20, 80, 20);
		rbTraceModeSave.Caption:=GetLangStr(1688);
		rbTraceModeSave.Hint:=GetLangStr(1693);
		rbTraceModeLoad:=TRadioButton.Create(f);
		rbTraceModeLoad.Name:='rbTraceModeLoad';
		rbTraceModeLoad.Parent:=gbTrace;
		rbTraceModeLoad.SetBounds(100, 20, 100, 20);
		rbTraceModeLoad.Caption:=GetLangStr(1687);
		rbTraceModeLoad.Hint:=GetLangStr(1694);
		my_value := RegReadInteger('IMDBTraceMode', 0);
		if my_value=0 then
			rbTraceModeSave.Checked := True
		else if my_value=1 then
			rbTraceModeLoad.Checked := True;
		labTraceLevel:=TLabel.Create(f);
		labTraceLevel.Name := 'labTraceLevel';
		labTraceLevel.Parent := gbTrace;
		labTraceLevel.SetBounds(10, 50, 100, 25);
		labTraceLevel.Caption := GetLangStr(1695);
		labTraceLevel.Hint:=GetLangStr(1696);
		edTraceLevel := TEdit.Create(f);
		edTraceLevel.Name := 'edTraceLevel';
		edTraceLevel.Parent := gbTrace;
		edTraceLevel.SetBounds(170, 45, 20, 25);
		edTraceLevel.Text := IntToStr(RegReadInteger('IMDBTraceLevel', 0));
		edTraceLevel.Hint := labTraceLevel.Hint;
		cbTraceAsk := TCheckBox.Create(f);
		cbTraceAsk.Name := 'cbTraceAsk';
		cbTraceAsk.Parent := gbTrace;
		cbTraceAsk.SetBounds(10, 80, 185, 20);
		cbTraceAsk.Caption := GetLangStr(1697);
		my_value := RegReadInteger('IMDBTraceAsk', 1);
		if my_value=1 then
			cbTraceAsk.Checked := True;
	end;

	f.Height := posy + 110;
	f.Width  := gbDescOptions.Left + gbDescOptions.Width + 20;
	
	b := TButton.Create(f);
	b.Name := 'btnOK';
	b.Parent := f;
	b.SetBounds(trunc(f.width/2)-40, f.Height-70, 80, 25);
	b.Caption := '&OK';
	b.OnClick := @ButtonClick;

	f.ShowModal;
	f.Free;
end;


begin

	monthes[1]:='January';
	monthes[2]:='February';
	monthes[3]:='March';
	monthes[4]:='April';
	monthes[5]:='May';
	monthes[6]:='June';
	monthes[7]:='July';
	monthes[8]:='August';
	monthes[9]:='September';
	monthes[10]:='October';
	monthes[11]:='November';
	monthes[12]:='December';

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

	//RegWriteInteger('IMDBShowTraceSettings', 1);
	jShowTraceSettings := RegReadInteger('IMDBShowTraceSettings', 0);
	jTraceMode := RegReadInteger('IMDBTraceMode', 0);     // 20101017-JeF
	jTraceLevel := RegReadInteger('IMDBTraceLevel', 0);   // 20101017-JeF
	jTraceAsk := RegReadInteger('IMDBTraceAsk', 1);  	  // 20101017-JeF

	OvrMainDlOptions := IntToBool(RegReadInteger('IMDB_Mov_OvrMainDlOptions', 0));
	DlOriginalTitle  := IntToBool(RegReadInteger('IMDB_Mov_DlOriginalTitle', 1));
	DlYear           := IntToBool(RegReadInteger('IMDB_Mov_DlYear', 1));
	DlGenres         := IntToBool(RegReadInteger('IMDB_Mov_DlGenres', 1));
	DlCountries      := IntToBool(RegReadInteger('IMDB_Mov_DlCountries', 1));
	DlDuration       := IntToBool(RegReadInteger('IMDB_Mov_DlDuration', 1));
	DlStudios        := IntToBool(RegReadInteger('IMDB_Mov_DlStudios', 1));
	DlEpisodes       := IntToBool(RegReadInteger('IMDB_Mov_DlEpisodes', 1));
	DlDirectors      := IntToBool(RegReadInteger('IMDB_Mov_DlDirectors', 1));
	DlActors         := IntToBool(RegReadInteger('IMDB_Mov_DlActors', 1));
	DlWriters        := IntToBool(RegReadInteger('IMDB_Mov_DlWriters', 1));
	DlComposers      := IntToBool(RegReadInteger('IMDB_Mov_DlComposers', 1));
	DlAwards         := IntToBool(RegReadInteger('IMDB_Mov_DlAwards', 1));
	
	DownloadTrivia := RegReadInteger('IMDBDownloadTrivia', 1);
	DownloadGoofs := RegReadInteger('IMDBDownloadGoofs', 1);
	DownloadQuotes := RegReadInteger('IMDBDownloadQuotes', 0);
	DownloadConnections := RegReadInteger('IMDBDownloadConnections', 0);
	DownloadSoundtracks := RegReadInteger('IMDBDownloadSoundtracks', 0);
	ImportDesc := RegReadInteger('IMDBImportDesc', 1);
	AkaSearch := RegReadInteger('IMDBAkaSearch', 0);
	ShowPlotAuthors := RegReadInteger('IMDBShowPlotAuthors', 1);
	EpisodeFullDesc := RegReadInteger('IMDBEpisodeFullDesc', 0);
	AkasInDesc := RegReadInteger('IMDBAkasInDesc', 0);
	ImportMPAAReasons := RegReadInteger('IMDBImportMPAAReasons', 1);
	TitleLang := RegReadString('IMDBTitleLang', '');
	MPAADefault := RegReadString('IMDBMPAADefault', '');
	MPAAReplace := RegReadString('IMDBMPAAReplace', '');
	IMDBLocalService := RegReadInteger('IMDBLocalService', 0);
	RequestParameters := TStringList.Create;
	RequestParametersWithCookies := TStringList.Create();
	case IMDBLocalService of
		1: RequestParameters.Add('AcceptLanguage=de-DE');
		2: RequestParameters.Add('AcceptLanguage=es-ES');
		3: RequestParameters.Add('AcceptLanguage=fr-FR');
		4: RequestParameters.Add('AcceptLanguage=it-IT');
		5: RequestParameters.Add('AcceptLanguage=pt-PT');
	else
		RequestParameters.Add('AcceptLanguage=en-US');
	end;
	RequestParametersWithCookies.Assign(RequestParameters);

	if RegReadInteger('IMDBAdultContent', 0) = 1 then begin
		if (GlobalHTTPSCookies = '') then begin
			if (UserName = '') and (RegReadString('UserName_imdb', '') <> '') then
				//opening settings
			else begin
				if (UserName = '') or (not ConnectToIMDB(UserName, UserPassword)) then begin
					ShowLoginForm;
				end;
			end;
		end;
		if (GlobalHTTPSCookies <> '') then
			RequestParametersWithCookies.Add('Cookie=' + GlobalHTTPSCookies);
	end;
	case IMDBLocalService of
		1: TVDBLID := 14;
		2: TVDBLID := 16;
		3: TVDBLID := 17;
		4: TVDBLID := 15;
		5: TVDBLID := 26;
	else
		TVDBLID := 7;
	end;
	UseTMDBPosters:=RegReadInteger('IMDBUseTmdbPosters', 0);
	UseTMDBSnapshots:=RegReadInteger('IMDBUseTmdbBackdrops', 1);
	DownloadTVDBEpisodeDescriptions:=RegReadInteger('IMDBTVDBDescriptions', 1);
	DownloadActorsEpisodesForTVSeries := RegReadInteger('IMDBDownloadActorsEpisodesForTVSeries', 0);
	DownloadTVDBEpisodes:=RegReadInteger('IMDBTVDBEpisodes', 1);
	DownloadTVDBEnglishDesc:=RegReadInteger('IMDBTVDBEngDesc', 1);
	UseTVDBPosters:=RegReadInteger('IMDBUseTvdbPosters', 0);
	UseTVDBFanart:=RegReadInteger('IMDBUseTvdbFanart', 1);

end.