//////////////////////////////////////////////////////////////////////////////
// This is movie script for site  www.TheTVDB.com                           //
// I'm using site apis to get data.                                         //
// You can put your own ApiKey in Script Options (you can get one for free  //
// by registering (also free) on www.TheTVDB.com)                           //
// If you haven't got your own ApiKey , you can use mine (set by default    //
// if none present)                                                         //
// The use of my own ApiKey for public use has only been made possible with //
// courtesy of Scott Zsori from www.TheTVDB.com (Thanks again!).            //
// Please visit and contribute to this site whenever you can.               //
// JeF                                                                      //
//////////////////////////////////////////////////////////////////////////////

const
	script_name='TheTVDB';
	language='Multiple';
	version=7;
	author='JeF';  
	MinProgramBuild=6100;
	PCount = 12;
	main_server=['imdb.com', 'imdb.de', 'imdb.es', 'imdb.fr', 'imdb.it', 'imdb.pt'];
	defaultPicSizeX=800;
	defaultPicSizeY=600;
	
	//languages url = http://thetvdb.com/api/<ApiKey>/languages.xml
	//user rating = http://thetvdb.com/api/GetRatingsForUser.php?apikey=YOUR_API_KEY&accountid=CUSTOMER_ACCOUNT_ID&seriesid=SERIES_ID

var
	DownloadMovieBigCover, DownloadMovieShortCast, DownloadMovieFullCast, 
	DownloadMovieBigDescription, DownloadMovieComments, 
	DownloadMovieStudios,	DownloadMovieAwards, DownloadMovieEarnings, 
	DownloadMovieAdditionalInfo, DownloadMovieSeasonsList: boolean;
	IMDBLocalService, MaxShotsCount, MaxPostersCount: integer;
	MaxTrailersCount, MaxBackdropsCount: Integer;

	title, MovieName, year, director, name, character, BasicURL, IMDBurl, description, country, salary, awards: string;
	SeriesId, MainXmlData, 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, banner_url, fanart_url: string;
	original_title, mpaa, mpaa_rating: string;
	goCode, TvdbApiKey: string;
	DownloadTrivia, DownloadGoofs, DownloadQuotes, DownloadConnections, DownloadSoundtracks, ImportDesc, AkasInDesc: Integer;
	jTraceMode, jTraceLevel, jTraceAsk: integer;   // 20101017-JeF
	
//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)) then goCode:=copy(MovieName,i+2,j-i-1);
			j:=j+1;
		end;
		if (length(goCode)<7) then goCode:='';
		i:=MyPos('TT',UpperCase(MovieName),i+1);
	end;
	//Get tvdb id from imdb id
	if (goCode>'') then goCode:=GetTvdbIdFromImdbId(goCode);
	result:=(goCode>'');
end;
	
function GetTvdbIdFromImdbId(ImdbCode: string): string;
var
	url, all, s, s2: string;
begin
	s:=ImdbCode;
	s2:='';
	result:='';
	while (s>'') do begin
		if (copy(s,1,1)>='0') and (copy(s,1,1)<='9') then s2:=s2+copy(s,1,1);
		delete(s,1,1);
	end;
	while (length(s2)<7) do s2:='0'+s2;
	url:=format('http://thetvdb.com/api/GetSeriesByRemoteID.php?imdbid=tt%s',[s2]);
	all:=DownloadURL(url);
	result:=GetXmlTagValue('<seriesid>',all,1);
end;

//Get IMDB Infos (sets imdb_code, imdb_rating, mpaa, mpaa_rating)  // 20090701-JeF
procedure GetIMDBInfos(MovieTitle, Year: string);
var
	url,all,title,NakedMovieTitle,s,s2,s3: string;
	matches_count, section, i, j, k: integer;
	sl: TStringList;
begin
	NakedMovieTitle:=ReplaceStr(MovieTitle,'?','',-1);
	NakedMovieTitle:=ReplaceStr(NakedMovieTitle,'!','',-1);
	NakedMovieTitle:=ReplaceStr(NakedMovieTitle,'.','',-1);
	NakedMovieTitle:=ReplaceStr(NakedMovieTitle,',','',-1);
	NakedMovieTitle:=ReplaceStr(NakedMovieTitle,'-','',-1);
	NakedMovieTitle:=ReplaceStr(NakedMovieTitle,'  ',' ',-1);
	NakedMovieTitle:=ReplaceStr(NakedMovieTitle,'&','e',-1);    // 20100721-JeF
	// search for imdb_code
	if (imdb_code='') and (year>'') then begin
		// launch imdb movie search
		url:='http://akas.imdb.com/'
			+format('find?q=%%5E%s%%24&type=regexp&tv=both&from_year=1890&to_year=2009&sort=smart;tt=1', [MovieTitle]);
		url:=ReplaceStr(url, ' ', '+', -1);
		all:=DownloadURL(url);
		if (all<>'-1') then for section:=1 to 2 do begin   // 20100721-JeF
			// imdb movie search result page analysis
			s:='';
			matches_count:=0;
			if (section=1)   // 20100721-JeF
				then i:=pos('<p><b>Popular Titles</b> (Displaying', all)
			else i:=pos('<p><b>Titles (Approx Matches)</b> (Displaying', all);
			if (i>0) then i:=MyPos('<table>', all, i+1);
			if (i>0) then begin
				j:=MyPos('</table>', all, i+1);
				if j>0 then
					s:=copy(all, i, j-i);
			end;
			if (s='') or (pos('<b>No Matches.</b>', all)>0) then
				//Movie not found
			else begin
				i:=pos('</tr>', s);
				while i>0 do begin
					s2:=copy(s, 1, i-1);
					j:=Pos('</td>', s2);
					j:=MyPos('</td>', s2, j+1);
					s2:=copy(s, j+5, length(s2)-j-4);
					j:=Pos('<a href="/title/tt', s2);
					k:=MyPos('"', s2, j+15);   // 20091126-JeF
					s3:=copy(s2, j, k-j+1);   // 20091126-JeF
					title:=RemoveTags(s2);
					title:=DecodeHTML(title);
					title:=ClearExtraSpaces(title);
					title:=ReplaceStr(title,'?','',-1);
					title:=ReplaceStr(title,'!','',-1);
					title:=ReplaceStr(title,'.','',-1);
					title:=ReplaceStr(title,',','',-1);
					title:=ReplaceStr(title,'-','',-1);
					title:=ReplaceStr(title,'  ',' ',-1);
					if (pos('AKA "'+UpperCase(NakedMovieTitle)+'"',UpperCase(title))>0) 
					or (pos(' AKA ',UpperCase(title))=0) and (pos(UpperCase(NakedMovieTitle),UpperCase(title))=1)
					or (pos(UpperCase(NakedMovieTitle),UpperCase(title))=1)
					or (pos('"'+UpperCase(NakedMovieTitle)+'"',UpperCase(title))=1) then begin
						if (pos(Year,title)>0)
						or (pos(IntToStr(StrToInt(Year)+1),title)>0)
						or (pos(IntToStr(StrToInt(Year)-1),title)>0) then begin
							matches_count:=matches_count+1;
							if (imdb_code='') then imdb_code:=ParseString(s3, '<a href="/title/tt(\d+)/"', 1);
						end;
					end;
					delete(s, 1, i+4);
					i:=pos('</tr>', s);
				end;
			end;
			if (matches_count>1) then imdb_code:='';
		end;
	end;
	// imdb_code already known or found by imdb search : retrieve IMDB infos
	if (imdb_code>'') then begin
		imdb_rating:=0;
		mpaa:='';
		mpaa_rating:='';
		url:=format('http://www.imdb.com/title/tt%s', [imdb_code]);
		all:=DownloadURL(url);
		if (all<>'-1') then begin
			//imdb rating
			imdb_rating:=0;
			i:=pos('<h5>User Rating:</h5>', 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 begin
								s2:=copy(s2, 1, i-1);
								i:=pos('.', s2);
								if i>0 then
									s2[i]:=DecimalSeparator;
								try
									imdb_rating:=StrToFloat(s2);
								except
								end;
							end;
						end;
					end;
				end;
			end;
			//mpaa
			mpaa:='';
			mpaa_rating:='';
			i:=pos('<h5><a href="/mpaa">MPAA</a>:</h5>', all);
			if i>0 then begin
				j:=MyPos('</div>', all, i+1);
				if j>0 then begin
					s2:=copy(all, i, j-i);
					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);
							i:=pos('.', s2);
							if i>0 then begin
								mpaa_rating:=copy(s2, 1, i-1);
							end;
						end;
					end;
				end;
			end;
		end;  // all <> -1
	end;  // imdb_code > ''
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, year, s, s2, s3, description: 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;
    i:=GetNextXmlTagPos('<Series>',all,1);
    while (i>0) do begin
        s:=GetXmlTagValue('<Series>',all,i);
		if (RegReadString('TheTVDB_SearchLangCode','all') = 'all')
        or (GetXmlTagValue('<language>',s,1) = RegReadString('TheTVDB_SearchLangCode','all')) then begin
            titles_count:=titles_count+1;
            title_code:=GetXmlTagValue('<seriesid>',s,1);
            title:=GetXmlTagValue('<SeriesName>',s,1);
            title:=DecodeHTML(title);
			year:=GetXmlTagValue('<FirstAired>',s,1);
			if (length(year)>4) then year:=copy(year,1,4);
			//if (year>'') and (pos(year,title)=0) then title:=title + ' ('+year+')';
			if (RegReadString('TheTVDB_SearchLangCode','all')='all')
				then title:=title+' ('+GetXmlTagValue('<language>',s,1)+')';
			description:=GetXmlTagValue('<Overview>',s,1);
            SetSearchResult2(title, title_code, year, '', description, '');
        end;
        i:=GetNextXmlTagPos('<Series>',all,i+2);
    end;
    result:=titles_count;
end;

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

//Get search URL by movie name
//function GetSearchURLbyName(MovieName: string): string;
function GetSearchURLbyName(MovieName, AYear, ABarcode: string): string;
var
	url, s: string;
	i: integer;
begin
	if (TvdbApiKey = '') then SetDefaultTvdbApiKey;
	s := copy(MovieName, 1, Length(MovieName));
	s := ClearExtraBlankCharacters(s);
	s := EncodeURL(s, 'utf-8');

	url:=format('http://www.thetvdb.com/api/GetSeries.php?seriesname=%s&language=%s',
				[s,RegReadString('TheTVDB_SearchLangCode','all')]);

	//url:=ReplaceStr(url, ' ', '+', -1);
	goCode := '';
	if (length(s)>5) and (checkCode(s)) then url:=GetMovieSiteURL(goCode);
	
	result:=url;
end;

//Download search results from URL
function DownloadSearchURL(url: string): integer;
begin
	if (jTraceLevel > 0) then TraceAlert;   				 // 20101017-JeF
	all:=DownloadURL(url);
	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
	result:=format('http://thetvdb.com/api/%s/series/%s/all/%s.xml',
					[TvdbApiKey,Code,RegReadString('TheTVDB_DataLangCode','en')]);
end;


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

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

// Clear extra simple or double Quotes Tool
function ClearExtraSDQuotes(name: string): string;
begin
	if length(name)>0 then
		if (name[1]='"') and (name[length(name)]='"')
		or (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 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+'<br>';
		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 (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:=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(s, m+7, j-m-7);
		if s2<>'' then
			extracted_awards := extracted_awards + '(' + RemoveTags(s2) + ')';
		delete(text, 1, j);
		i:=Pos('<td valign="top">', text);
	end;
	Result := DecodeHTML(extracted_awards);  // 20090910-JeF
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 :'];
	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>'];
	
var 
	keyword, s, s2, s3, plot_outline: string;
	i, j, kol, k, l, season, episode: integer;
	AirDate, EpisodeTitle, EpisodeIMDB, EpisodeDescription, day, month, ayear: string;
	LoadSummary, LoadSynopsis: boolean;					//20090317-JeF
	EpisodeUrl, EpisodePage, EpFullDesc: string;		//20090709-JeF
	TVShow: boolean;									//20090710-JeF
	FunStuffInfo, LocalURL: string;								// 20090808-JeF
	SeriesData, CastData, EpisodeData: string;
	ImdbMainPage, ImdbAwardsPage, ImdbReleaseInfoPage: string;
	ImdbTriviaPage, ImdbGoofsPage, ImdbQuotesPage, ImdbConnectionsPage, ImdbSoundtrackPage: string;

	sl:TStringList;
	
begin
	sl:=TStringList.Create;
	if (TvdbApiKey = '') then SetDefaultTvdbApiKey;
	result:='';

	if (jTraceLevel > 0) then TraceAlert;   			   // 20101017-JeF

	LocalURL:=url;
	BasicURL:=url;
	IMDBurl:='';
	all:=DownloadURL(url);
	//all:=DownloadURL(url);
	MainXmlData:=all;
	result:=all;
	if (jTraceLevel >= 2) then TraceExecute('Info',all);   // 20101017-JeF
	
	if NOT images_only then images_only:=(RegReadInteger('TheTVDB_ImagesOnly', 0)>0);

	SeriesData:=GetXmlTagValue('<Series>',all,1);
	SeriesId:=GetXmlTagValue('<id>',SeriesData,1);
	
	imdb_code:=GetXmlTagValue('IMDB_ID',SeriesData,1);
	while (imdb_code>'') and ((copy(imdb_code,1,1)<'0') or (copy(imdb_code,1,1)>'9'))
		do delete(imdb_code,1,1);
	if (imdb_code>'') then IMDBurl:=ReplaceStr('http://www.imdb.com/title/tt'+imdb_code, 'imdb.com', main_server[IMDBLocalService], -1);
	movie_code:=GetXmlTagValue('<id>',SeriesData,1);
	movie_site_url:=GetMovieSiteURL(movie_code);

	//FirstAired Year
	year:='';
	if NOT images_only then begin
		s2:=GetXmlTagValue('<FirstAired>',SeriesData,1);
		if (length(s2)>4) then year:=copy(s2,1,4)
		else year:=s2;
	end;
	
	//Series Name (Title)
	title:=GetXmlTagValue('<SeriesName>',SeriesData,1);
	title:=DecodeHTML(title);
	title:=ClearExtraSpaces(title);
	title:=ClearExtraQuotes(title);
	//original_title := title;
	
	if title='' then
		exit;

	if (imdb_code>'') then GetIMDBInfos(title,year);
	//imdb rating
	imdb_rating:=0;
	rating:=0;
	if NOT images_only then begin
		s2:=GetXmlTagValue('<Rating>',SeriesData,1);
		imdb_rating:=StrToFloatDef(s2,0.0);
		rating:=imdb_rating;
	end;
	
	//Directors
	if NOT images_only and (RegReadInteger('TheTVDB_ImportDirectors', 1)>0) then begin
		i:=GetNextXmlTagPos('<Director>',all,1);
		while (i>0) do begin
			s2:=GetXmlTagValue('<Director>',all,i);
			if (pos('|',s2)>0) 
				then sl.CommaText:=SepTextToCommaText(s2,'|')
			else sl.CommaText:=SepTextToCommaText(s2,',');
			for j:=0 to sl.Count-1 do begin
				code:='';
				name:=sl[j];
				name:=DecodeHTML(name);
				name:=ClearExtraSpaces(name);
				code:=name;
				if name<>'' then SetPersonName(name, '', 1, code);
			end;
			i:=GetNextXmlTagPos('<Director>',all,i+2);
		end;
	end;
	
	//Writers
	if NOT images_only and (RegReadInteger('TheTVDB_ImportWriters', 1)>0) then begin
		i:=GetNextXmlTagPos('<Writer>',all,1);
		while (i>0) do begin
			s2:=GetXmlTagValue('<Writer>',all,i);
			if (pos('|',s2)>0) 
				then sl.CommaText:=SepTextToCommaText(s2,'|')
			else sl.CommaText:=SepTextToCommaText(s2,',');
			for j:=0 to sl.Count-1 do begin
				code:='';
				name:=sl[j];
				name:=DecodeHTML(name);
				name:=ClearExtraSpaces(name);
				code:=name;
				if name<>'' then SetPersonName(name, '', 2, code);
			end;
			i:=GetNextXmlTagPos('<Writer>',all,i+2);
		end;
	end;

	//movie composers
	//if name<>'' then SetPersonName(name, '', 4, code);
	
	//Cast
	url:=format('http://www.thetvdb.com/api/%s/series/%s/actors.xml',[TvdbApiKey,SeriesId]);
	CastData:=DownloadURL(url);
	if (CastData='-1') then CastData:='';
	if NOT images_only and (RegReadInteger('TheTVDB_ImportActors', 1)>0) then begin
		i:=GetNextXmlTagPos('<Actor>',CastData,1);
		while (i>0) do begin
			s2:=GetXmlTagValue('<Actor>',CastData,i);
			code:=GetXmlTagValue('<id>',s2,1);
			name:=GetXmlTagValue('<Name>',s2,1);
			name:=DecodeHTML(name);
			name:=ClearExtraSpaces(name);
			code:=name;   //untill there's a people db
			character:=GetXmlTagValue('<Role>',s2,1);
			character:=DecodeHTML(character);
			character:=ClearExtraSpaces(character);
			//TODO note: <Image> tag contains relative url to actor's picture
			if name<>'' then SetPersonName(name, character, 3, code);
			i:=GetNextXmlTagPos('<Actor>',CastData,i+2);
		end;
		if (CastData='') then begin
			s2:=GetXmlTagValue('<Actors>',SeriesData,1);
			sl.CommaText:=SepTextToCommaText(s2,'|');
			for i:=0 to sl.Count-1 do begin
				code:='';
				name:=sl[i];
				name:=DecodeHTML(name);
				name:=ClearExtraSpaces(name);
				code:=name;
				if name<>'' then SetPersonName(name, '', 3, code);
			end;
		end;
	end;
	
	//movie duration (minutes)
	duration:=0;
	if NOT images_only then begin
		s2:=GetXmlTagValue('<Runtime>',SeriesData,1);
		duration:=StrToIntDef(s2,0);
	end;

	//movie genres
	if NOT images_only then begin
		s2:=GetXmlTagValue('<Genre>',SeriesData,1);
		sl.CommaText:=SepTextToCommaText(s2,'|');
		for i:=0 to sl.Count-1 do begin
			name:=sl[i];
			name:=DecodeHTML(name);
			name:=ClearExtraSpaces(name);
			if name<>'' then SetGenre(name);
		end;
	end;

	//movie countries
	//if name<>'' then SetCountry(name);
	
	//movie studios
	if NOT images_only and DownloadMovieStudios then begin
		s2:=GetXmlTagValue('<Network>',SeriesData,1);
		sl.CommaText:=SepTextToCommaText(s2,'|');
		for i:=0 to sl.Count-1 do begin
			name:=sl[i];
			name:=DecodeHTML(name);
			name:=ClearExtraSpaces(name);
			if name<>'' then SetStudio(name);
		end;
	end;

	//Main Poster
	front_cover_url:='*None';
	if (RegReadInteger('TheTVDB_MainPoster', 1)>0) then begin
		front_cover_url:='';
		s2:=GetXmlTagValue('<poster>',SeriesData,1);
		if (s2>'') then front_cover_url:='http://www.thetvdb.com/banners/'+s2;
	end;
	
	//Main Banner
	banner_url:='';
	if (RegReadInteger('TheTVDB_MainBanner', 1)>0) then begin
		s2:=GetXmlTagValue('<banner>',SeriesData,1);
		if (s2>'') then banner_url:='http://www.thetvdb.com/banners/'+s2;
	end;
	
	//Main Fanart
	fanart_url:='';
	if (RegReadInteger('TheTVDB_MainFanart', 1)>0) then begin
		s2:=GetXmlTagValue('<fanart>',SeriesData,1);
		if (s2>'') then banner_url:='http://www.thetvdb.com/banners/'+s2;
	end;

	//episodes
	if NOT images_only and DownloadMovieSeasonsList then begin
		i:=GetNextXmlTagPos('<Episode>',MainXmlData,1);
		while (i>0) do begin
			EpisodeData:=GetXmlTagValue('<Episode>',MainXmlData,i);
			season:=StrToIntDef(GetXmlTagValue('<SeasonNumber>',EpisodeData,1),99);
			if (season=0) then season:=99;
			episode:=StrToIntDef(GetXmlTagValue('<EpisodeNumber>',EpisodeData,1),0);
			
			EpisodeIMDB:=GetXmlTagValue('<IMDB_ID>',EpisodeData,1);
			while (EpisodeIMDB>'') and ((copy(EpisodeIMDB,1,1)<'0') or (copy(EpisodeIMDB,1,1)>'9'))
				do delete(EpisodeIMDB,1,1);
			EpisodeTitle:=GetXmlTagValue('<EpisodeName>',EpisodeData,1);
			EpisodeTitle:=DecodeHTML(EpisodeTitle);
			s3:=GetXmlTagValue('<FirstAired>',EpisodeData,1);
			ayear:=copy(s3,1,4);
			month:=copy(s3, 6, 2);
			day:=copy(s3, 9, 2);
			AirDate:=format('%s/%s/%s', [month, day, ayear]);
			s3 := GetXmlTagValue('<filename>', EpisodeData, 1);
			if s3<>'' then
				SetImageName('', 'http://www.thetvdb.com/banners/' + s3, '', 10, False, '', season, episode);
			EpisodeDescription:='';
			if (RegReadInteger('TheTVDB_ImportEpisodeDesc', 1)>0) then begin
				EpisodeDescription:=GetXmlTagValue('<Overview>',EpisodeData,1);
				EpisodeDescription:=DecodeHTML(EpisodeDescription);
			end;
			
{showmessage('create ep'+#13#10+
'S'+inttostr(season)+'E'+inttostr(episode)+':'+EpisodeTitle+#13#10+
EpisodeDescription+#13#10+#13#10+
EpisodeIMDB+#13#10+AirDate
);}
			if episode<=100 then
				SetEpisode(season, episode, EpisodeTitle, EpisodeDescription, EpisodeIMDB, AirDate);
				
			i:=GetNextXmlTagPos('<Episode>',MainXmlData,i+2);

		end;
	end;

	//Keywords
	//  SetMovieKeyword(movie_code, keyword);
	
	//Description
	if NOT images_only then begin
		description:=GetXmlTagValue('<Overview>',SeriesData,1);
		description:=DecodeHTML(description);
		description:=ReplaceStr(description, #10, '<br>', -1);
		description:=ClearExtraSpaces(description);
		if (ImportDesc = 0) then description:='';
	end;
	
	//---------------------------- Extra Infos to download from IMDB --------------------------------

	if NOT images_only and (IMDBurl>'') then begin

		//Download related pages
		if (RegReadInteger('TheTVDB_ImdbOriginalTitle', 0)>0)
		or (RegReadInteger('TheTVDB_ImdbCountry', 0)>0)
			then ImdbMainPage:=DownloadURL(IMDBurl);
		if (DownloadMovieAwards) and (RegReadInteger('TheTVDB_ImdbAwards', 0)>0)
			then ImdbAwardsPage:=DownloadURL(IMDBurl+'/awards');
		if DownloadMovieAdditionalInfo then begin
			if (RegReadInteger('TheTVDB_ImdbAkasInDesc', 0)>0)
				then ImdbReleaseInfoPage:=DownloadURL(IMDBURL + '/releaseinfo');
			if (RegReadInteger('TheTVDB_ImdbTrivia', 0)>0)
				then ImdbTriviaPage:=DownloadURL(IMDBURL + '/trivia');
			if (RegReadInteger('TheTVDB_ImdbGoofs', 0)>0)
				then ImdbGoofsPage:=DownloadURL(IMDBURL + '/goofs');
			if (RegReadInteger('TheTVDB_ImdbQuotes', 0)>0)
				then ImdbQuotesPage:=DownloadURL(IMDBURL + '/quotes');
			if (RegReadInteger('TheTVDB_ImdbConnections', 0)>0)
				then ImdbConnectionsPage:=DownloadURL(IMDBURL + '/movieconnections');
			if (RegReadInteger('TheTVDB_ImdbSoundtrack', 0)>0)
				then ImdbSoundtrackPage:=DownloadURL(IMDBURL + '/soundtrack');
		end;
		if (jTraceLevel >= 5) then TraceExecute('ImdbMain',ImdbMainPage);
		if (jTraceLevel >= 6) then begin
			TraceExecute('ImdbTrivia',ImdbTriviaPage);
			TraceExecute('ImdbGoofs',ImdbGoofsPage);
			TraceExecute('ImdbQuotes',ImdbQuotesPage);
			TraceExecute('ImdbConnections',ImdbConnectionsPage);
			TraceExecute('ImdbSoundtrack',ImdbSoundtrackPage);
		end;
		
		//Original Title
		if (RegReadInteger('TheTVDB_ImdbOriginalTitle', 0)>0) then begin
			original_title := '';
			i := Pos('<span class="title-extra">', ImdbMainPage);
			if i>0 then begin
				j := MyPos('<i>(original title)', ImdbMainPage, i+1);
				if j>i then begin
					s2 := copy(ImdbMainPage, i+26, j-i-26);
					s2 := DecodeHTML(s2);
					s2 := ClearExtraBlankCharacters(s2);
					s2 := ClearExtraSDQuotes(s2);
					if s2 <>'' then
						original_title := s2;
				end;
			end;
			if IMDBLocalService>0 then begin
				i := Pos(aka_name[IMDBLocalService], ImdbMainPage);
				j := MyPos('<a ', ImdbMainPage, i);
				if (i>0) and (j>0) then begin
					s2:=copy(ImdbMainPage,i,j-i);
					s2:=DecodeHTML(s2);
					i := MyPos('>"', s2, i+1);
					if i>0 then begin
						j := MyPos('"', s2, i+2);
						original_title := copy(s2, i+2, j-i-2);
						original_title := DecodeHTML(original_title);
					end
					else begin
						i := Pos(aka_name[IMDBLocalService], ImdbMainPage);
						i := i + length(aka_name[IMDBLocalService]);
						j := MyPos('<a ', ImdbMainPage, i);
						if j>0 then begin
							s2 := copy(ImdbMainPage, i, j-i);
							i := pos('<em>',s2);
							if (i>0) then s2 := copy(s2,1,i-1);
							s2 := RemoveTags(s2);
							s2 := DecodeHTML(s2);
							s2 := ClearExtraBlankCharacters(s2);
							if (copy(s2,1,1)='"') and (MyPos('"',s2,2)>0) 
								then s2:=copy(s2,2,MyPos('"',s2,2)-2);
							original_title := ClearExtraBlankCharacters(s2);
						end;
					end;
				end;
			end;
		end;

		//Countries
		if (RegReadInteger('TheTVDB_ImdbCountry', 0)>0) then begin
			i := Pos(country_name[IMDBLocalService], ImdbMainPage);
			if i>0 then begin
				j :=MyPos('</div>', ImdbMainPage, i+1);
				s := copy(ImdbMainPage, 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;
		
		//Awards
		if (DownloadMovieAwards) and (RegReadInteger('TheTVDB_ImdbAwards', 0)>0) and (IMDBurl>'') then begin
			awards:='';
			i:=Pos('<big><a href="/Sections/Awards/', ImdbAwardsPage);
			if i>0 then begin
				//we copy the table of awards
				j:=MyPos('</table>', ImdbAwardsPage, i+1);
				s:=copy(ImdbAwardsPage, 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:=DecodeHTML(awards);  // 20090910-JeF
		end;

		if (AkasInDesc = 1) then begin
			// extract akas
			i:=pos('<a name="akas">',ImdbReleaseInfoPage);
			j:=MyPos('</table>',ImdbReleaseInfoPage,i+15);
			s2:=copy(ImdbReleaseInfoPage,i+15,j-i-15);
			i:=pos('<tr>',s2);
			if (i>0) then description:=description+'<br><br>Also Known As:';
			while (i>0) do begin
				delete(s2,1,i-1);
				j:=pos('</tr>',s2);
				s3:=copy(s2,1,j-1);
				s3:=DecodeHTML(s3);
				s3:=ReplaceStr(s3, #10, '', -1);
				s3:=ReplaceStr(s3, '</td><td>', ' - ', -1);
				s3:=RemoveTags(s3);
				s3:=ClearExtraCharacters(s3);
				s3:=ClearExtraSpaces(s3);
				description:=description+'<br>'+s3;
				i:=MyPos('<tr>',s2,3);
			end;
		end;
		
		//FUN STUFF begin
		if DownloadMovieAdditionalInfo then begin
			i:=pos(fun_stuff_name[IMDBLocalService],ImdbMainPage);
			if (i>0) then begin
				j:=MyPos('<hr/>',ImdbMainPage,i+1);
				FunStuffInfo:=copy(ImdbMainPage,i,j-i);
			end;
			if i=0 then begin
				i:=pos(fun_facts_name[IMDBLocalService],ImdbMainPage);
				if (i>0) then begin
					j:=MyPos('<h2>',ImdbMainPage,i+1);
					FunStuffInfo:=copy(ImdbMainPage,i,j-i);
				end;		
			end;
			s:=FunStuffInfo;
			//TRIVIA
			if (DownloadTrivia = 1) then begin
				k := Pos('<div class="sodatext">', ImdbTriviaPage);
				if (k>0) then begin
					if description <> '' then
						description := description + '<br><br>';
					description := description + 'TRIVIA:<br><br>';
				end;
				while k>0 do begin
					l := MyPos('<br>', ImdbTriviaPage, k+1);
					s2 := copy(ImdbTriviaPage, k, l-k);
					s2 := RemoveTags(s2);
					s2 := DecodeHTML(s2);
					s2 := ClearExtraBlankCharacters(s2);
					if s2<>'' then
						description := description + s2 + '<br><br>';
					delete(ImdbTriviaPage, 1, l-1);
					k := Pos('<div class="sodatext">', ImdbTriviaPage);
				end;
				if (copy(description, length(description)-7, 8)='<br><br>')
					then delete(description, length(description)-7, 8);
			end;
			//GOOFS
			if (DownloadGoofs = 1) then begin
				k := Pos('<li><a name=', ImdbGoofsPage);
				if (k>0) then begin
					if description <> '' then
						description := description + '<br><br>';
					description := description + 'GOOFS:<br><br>';
				end;
				while k>0 do begin
					l := MyPos('<br>', ImdbGoofsPage, k+1);
					s2 := copy(ImdbGoofsPage, k, l-k);
					s2 := RemoveTags(s2);
					s2 := DecodeHTML(s2);
					s2 := ClearExtraBlankCharacters(s2);
					if s2<>'' then
						description := description + s2 + '<br><br>';
					delete(ImdbGoofsPage, 1, l-1);
					k := Pos('<li><a name=', ImdbGoofsPage);
				end;
				if (copy(description, length(description)-7, 8)='<br><br>')
					then delete(description, length(description)-7, 8);
			end;
			//QUOTES
			if (DownloadQuotes = 1) then begin
				k := Pos('<div class="sodatext">', ImdbQuotesPage);
				if (k>0) then begin
					if description <> '' then
						description := description + '<br><br>';
					description := description + 'QUOTES:<br><br>';
				end;
				while k>0 do begin
					l := MyPos('</div>', ImdbQuotesPage, k+1);
					s2 := copy(ImdbQuotesPage, k, l-k);
					s2 := ReplaceStr(s2, '>Share this quote<', '><', -1);
					s2 := RemoveTags(s2);
					s2 := DecodeHTML(s2);
					s2 := ClearExtraBlankCharacters(s2);
					s2:=ReplaceStr(s2,#13, '', -1);
					s2:=ReplaceStr(s2,#10, '', -1);
					if s2<>'' then
						description := description + s2 + '<br><br>';
					delete(ImdbQuotesPage, 1, l-1);
					k := Pos('<div class="sodatext">', ImdbQuotesPage);
				end;
				if (copy(description, length(description)-7, 8)='<br><br>')
					then delete(description, length(description)-7, 8);
			end;
			//MOVIE CONNECTIONS
			if (DownloadConnections = 1) then begin
				k := MyPos('<h5>', ImdbConnectionsPage, k+1);
				if k>0 then begin
					if description <> '' then
						description := description + '<br><br>';
					description := description + 'MOVIE CONNECTIONS:<br><br>';
					l := MyPos('<hr/>', ImdbConnectionsPage, k + 1);
					s2 := copy(ImdbConnectionsPage, k, l-k);
					s2 := RemoveTags(s2);
					s2 := DecodeHTML(s2);
					s2 := ReplaceStr(s2, #10, '<br>', -1);
					s2 := ClearExtraBlankCharacters(s2);
					if s2<>'' then
						description := description + s2 + '<br><br>';
				end;
				if (copy(description, length(description)-7, 8)='<br><br>')
					then delete(description, length(description)-7, 8);
			end;
			//SOUNDTRACK
			if (DownloadSoundtracks = 1) then begin
				k := Pos('<ul class="trivia">', ImdbSoundtrackPage);
				if k>0 then begin
					k := MyPos('<li>', ImdbSoundtrackPage, k+1);
					if (k>0) then begin
						if description <> '' then
							description := description + '<br><br>';
						description := description + 'SOUNDTRACK:<br><br>';
					end;
					while k>0 do begin
						l := MyPos('</li>', ImdbSoundtrackPage, k+1);
						s2 := copy(ImdbSoundtrackPage, k, l-k);
						s2 := ReplaceStr(s2, '<br>', ' ', -1);
						s2 := RemoveTags(s2);
						s2 := DecodeHTML(s2);
						s2 := ClearExtraBlankCharacters(s2);
						if s2<>'' then
							description := description + s2 + '<br><br>';
						delete(ImdbSoundtrackPage, 1, l-1);
						k := Pos('<li>', ImdbSoundtrackPage);
					end;
					if (copy(description, length(description)-7, 8)='<br><br>')
						then delete(description, length(description)-7, 8);
				end;
			end;
		end;
	end;
	
	sl.Free;
end;


//gets movie frames from imdb
function GetFramesFromImdb(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'+imdb_code+'/mediaindex?refine='+frame_type;
		all := DownloadURL(url);
		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 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, banners_downloaded, fanarts_downloaded, seasonCovers_downloaded: Integer;
	url, BannersData, EpisodeData, s, s2, btype, btype2, sn, en: string;
	season, episode: integer;
	prev_seasons : TStringList;
begin
	prev_seasons := TStringList.Create;
	if (RegReadInteger('TheTVDB_MainPoster', 1)>0) and (front_cover_url<>'') 
		then SetImageName('', front_cover_url, '', 1);
	if (RegReadInteger('TheTVDB_MainFanart', 1)>0) and (fanart_url<>'') then begin
		if (front_cover_url='') then begin
			front_cover_url:=fanart_url;
			SetImageName('', front_cover_url, '', 1);
		end
		else SetImageName('', fanart_url, '', 7);
	end;
	if (RegReadInteger('TheTVDB_MainBanner', 1)>0) and (banner_url<>'') then begin
		if (front_cover_url='') then begin
			front_cover_url:=banner_url;
			SetImageName('', front_cover_url, '', 1);
		end
		else SetImageName('', banner_url, '', 7);
	end;

	if (RegReadInteger('TheTVDB_OvrMaxPosters', 0)>0) 
		then MaxPostersCount := RegReadInteger('TheTVDB_MaxPosters', MaxPostersCount);
		
	//Additional Images
	if (RegReadInteger('TheTVDB_ExtraImages', 1)>0) then begin
		//Episodes Images
		if (RegReadInteger('TheTVDB_EpisodeImages', 0)>0) then begin
			i:=GetNextXmlTagPos('<Episode>',MainXmlData,1);
			while (i>0) do begin
				EpisodeData:=GetXmlTagValue('<Episode>',MainXmlData,i);
				if (GetXmlTagValue('<EpImgFlag>',EpisodeData,1)>'') 
				and (GetXmlTagValue('<filename>',EpisodeData,1)>'')
				then begin
					url:='http://www.thetvdb.com/banners/' + GetXmlTagValue('<filename>',EpisodeData,1);
					SetImageName('', url, '', 7);  // shot
					//SetImageName('', url, '', 5);  // TODO : 5=user image -> Episode image type
				end;
				i:=GetNextXmlTagPos('<Episode>',MainXmlData,i+2);
			end;
		end;
		//Extra Banners/Posters/Fanarts
		url:=format('http://www.thetvdb.com/api/%s/series/%s/banners.xml',[TvdbApiKey,SeriesId]);
		BannersData:=DownloadURL(url);
		if (BannersData='-1') then BannersData:='';
		i:=GetNextXmlTagPos('<Banner>',BannersData,1);
		while (i>0) do begin
			s:=GetXmlTagValue('<Banner>',BannersData,i);
			// Banner Types : fanart, poster, series, season (see http://www.thetvdb.com/wiki/index.php/API:banners.xml)
			btype:=GetXmlTagValue('<BannerType>',s,1);
			btype2:=GetXmlTagValue('<BannerType2>',s,1);
			// Posters
			if (btype='poster') and (posters_downloaded<MaxPostersCount) then begin
				url:='http://www.thetvdb.com/banners/' + GetXmlTagValue('<BannerPath>',s,1);
				if (url<>banner_url) or (front_cover_url='') then begin
					if (front_cover_url='') then begin
						front_cover_url:=url;
						SetImageName('', front_cover_url, '', 1);
					end
					else begin
						if (posters_downloaded < MaxPostersCount) then begin
							SetImageName('', url, '', 4);  // Poster
							posters_downloaded:=posters_downloaded+1;
						end;
					end;
				end;
			end;
			// Fanarts
			if (btype='fanart') and (posters_downloaded<RegReadInteger('TheTVDB_MaxFanarts', 3)) then begin
				url:='http://www.thetvdb.com/banners/' + GetXmlTagValue('<BannerPath>',s,1);
				if (url<>fanart_url) or (front_cover_url='') then begin
					if (front_cover_url='') then begin
						front_cover_url:=url;
						SetImageName('', front_cover_url, '', 1);
					end
					else begin
						if (fanarts_downloaded < MaxBackdropsCount) then begin
							SetImageName('', url, '', 7);  // TODO : 5=user image -> fanart type
							fanarts_downloaded:=fanarts_downloaded+1;
						end;
					end;
				end;
			end;
			// Series Graphical Banner
			if (btype='series') and (btype2='graphical')
			and (banners_downloaded<RegReadInteger('TheTVDB_MaxBanners', 3)) then begin
				url:='http://www.thetvdb.com/banners/' + GetXmlTagValue('<BannerPath>',s,1);
				if (fanarts_downloaded < MaxBackdropsCount) then begin
					SetImageName('', url, '', 7);  // TODO : 5=user image -> Series Banner type
					banners_downloaded:=banners_downloaded+1;
					fanarts_downloaded:=fanarts_downloaded+1;
				end;
			end;
			// Season Cover (std dvd cover size)
			if (btype='season') and (btype2='season')
			//and (seasonCovers_downloaded<RegReadInteger('TheTVDB_MaxSeasonCovers', 0)) then begin
			then begin
				url:='http://www.thetvdb.com/banners/' + GetXmlTagValue('<BannerPath>',s,1);
				sn := GetXmlTagValue('<Season>',s,1);
				season := 0;
				try
					season := StrToInt(sn);
				except
				end;
				if (season>0) and (prev_seasons.IndexOf(sn) < 0) then begin
					SetImageName('', url, '', 9, False, '', season, 0);
					prev_seasons.Add(sn);
				end
				else if (fanarts_downloaded < MaxBackdropsCount) then begin
						SetImageName('', url, '', 7);  // TODO : 5=user image -> Season Cover #n type
						fanarts_downloaded:=fanarts_downloaded+1;
				end;
				seasonCovers_downloaded:=seasonCovers_downloaded+1;
			end;
			// Season Banner
			if (btype='season') and (btype2='seasonwide')
			and (banners_downloaded<RegReadInteger('TheTVDB_MaxBanners', 3)) then begin
				url:='http://www.thetvdb.com/banners/' + GetXmlTagValue('<BannerPath>',s,1);
				if (fanarts_downloaded < MaxBackdropsCount) then begin
					SetImageName('', url, '', 7);  // TODO : 5=user image -> Season Banner #n type
					banners_downloaded:=banners_downloaded+1;
					fanarts_downloaded:=fanarts_downloaded+1;
				end;
			end;
			// Next Banner...
			i:=GetNextXmlTagPos('<Banner>',BannersData,i+2);
		end;
	end;
	
	//Get Images from Imdb site
	if (RegReadInteger('TheTVDB_ImdbImages', 0)>0) and (imdb_code>'') then begin
		if (MaxPostersCount>0) then
			GetFramesFromImdb('poster', MaxPostersCount, 4);
		if (MaxShotsCount>0) then begin
			shots_downloaded := GetFramesFromImdb('still_frame', MaxShotsCount, 3);
			if shots_downloaded<MaxShotsCount then begin
				shots_left := MaxShotsCount - shots_downloaded;
				GetFramesFromImdb('behind_the_scenes', shots_left, 3);
			end;
		end;
		//No image found, try with no frame type
		if (posters_downloaded + shots_downloaded + bts_downloaded = 0)
		and (MaxPostersCount + MaxShotsCount > 0) 
			then GetFramesFromImdb('', MaxPostersCount + MaxShotsCount, 6);
	end;
	prev_seasons.Free;

end;

//get movie site url
function GetMovieSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:=format('http://www.thetvdb.com/?tab=series&id=%s&lid=%s',
						[Code,RegReadString('TheTVDB_DataLangId','1')]);
end;

//get person site url
function GetPersonSiteURL(code: string): string;
begin
	if name='' then
		result:=''
	else	
		result:=format('http://www.imdb.com/find?s=nm&q=%s', [ReplaceStr(code,' ','+',-1)]);   // TODO
end;

function StrToIntDef (strval : string; dftval : Integer) : Integer;
begin
	try
		result:=StrToInt(strval);
	except 
		result:=dftval;
	end;
end;

function StrToFloatDef (strval : string; dftval : Extended) : Extended;
begin
	try
		result:=StrToFloat(strval);
	except 
		result:=dftval;
	end;
end;

function BoolToInt(b: Boolean): integer;
begin
	if b then result:=1
	else result:=0;
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 GetNextXmlTagPos(Tag,XmlData: string; StartPos: integer): integer;
var
	t: string;
begin
	t:=UpperCase(Tag);
	if (copy(t,1,1) <> '<') then t:='<'+t;
	result:=MyPos(t,UpperCase(XmlData),StartPos);
end;

function GetXmlTagValue(Tag,XmlData: string; StartPos: integer): string;
var
	t, tEnd, xdCaps: string;
	i, j, k: integer;
begin
	result:='';
	xdCaps:=UpperCase(XmlData);
	t:=UpperCase(Tag);
	if (copy(t,1,1) <> '<') then t:='<'+t;
	tEnd:='</'+copy(t,2,length(t)-1);
	i:=MyPos(t,xdCaps,StartPos);
	if (i>0) then begin
		i:=i+length(t);
		if (copy(XmlData,i,1)='>') then i:=i+1;
		j:=MyPos(tEnd,xdCaps,i);
		if (j=0) then j:=MyPos('/>',xdCaps,i);
		if (j>i) then result:=copy(XmlData,i,j-i);
	end;
end;

function SepTextToCommaText(stxt,sep: string): string;
var
	s: string;
	lsep: integer;
begin
	s:=stxt;
	lsep:=length(sep);
	if (copy(s,1,lsep) = sep) then delete(s,1,lsep);
	s:='"'+s;
	if (copy(s,length(s)-lsep+1,lsep) = sep) then delete(s,length(s)-lsep+1,lsep);
	s:=s+'"';
	s:=ReplaceStr(s,sep,'","',-1);
	result:=s;
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;

procedure GetLanguages(VAR sl: TStringList);
var
	xmldata, s, name, abrev, id: string;
	i: integer;
begin
	sl.Clear;
	xmldata:=xmldata+'<Language><name>Dansk</name><abbreviation>da</abbreviation><id>10</id></Language>';
	xmldata:=xmldata+'<Language><name>Suomeksi</name><abbreviation>fi</abbreviation><id>11</id></Language>';
	xmldata:=xmldata+'<Language><name>Nederlands</name><abbreviation>nl</abbreviation><id>13</id></Language>';
	xmldata:=xmldata+'<Language><name>Deutsch</name><abbreviation>de</abbreviation><id>14</id></Language>';
	xmldata:=xmldata+'<Language><name>Italiano</name><abbreviation>it</abbreviation><id>15</id></Language>';
	xmldata:=xmldata+'<Language><name>Espaсol</name><abbreviation>es</abbreviation><id>16</id></Language>';
	xmldata:=xmldata+'<Language><name>Franзais</name><abbreviation>fr</abbreviation><id>17</id></Language>';
	xmldata:=xmldata+'<Language><name>Polski</name><abbreviation>pl</abbreviation><id>18</id></Language>';
	xmldata:=xmldata+'<Language><name>Magyar</name><abbreviation>hu</abbreviation><id>19</id></Language>';
	xmldata:=xmldata+'<Language><name>????????</name><abbreviation>el</abbreviation><id>20</id></Language>';
	xmldata:=xmldata+'<Language><name>Tьrkзe</name><abbreviation>tr</abbreviation><id>21</id></Language>';
	xmldata:=xmldata+'<Language><name>??????? ????</name><abbreviation>ru</abbreviation><id>22</id></Language>';
	xmldata:=xmldata+'<Language><name> ?????</name><abbreviation>he</abbreviation><id>24</id></Language>';
	xmldata:=xmldata+'<Language><name>???</name><abbreviation>ja</abbreviation><id>25</id></Language>';
	xmldata:=xmldata+'<Language><name>Portuguкs</name><abbreviation>pt</abbreviation><id>26</id></Language>';
	xmldata:=xmldata+'<Language><name>??</name><abbreviation>zh</abbreviation><id>27</id></Language>';
	xmldata:=xmldata+'<Language><name>ceљtina</name><abbreviation>cs</abbreviation><id>28</id></Language>';
	xmldata:=xmldata+'<Language><name>Slovenski</name><abbreviation>sl</abbreviation><id>30</id></Language>';
	xmldata:=xmldata+'<Language><name>Hrvatski</name><abbreviation>hr</abbreviation><id>31</id></Language>';
	xmldata:=xmldata+'<Language><name>???</name><abbreviation>ko</abbreviation><id>32</id></Language>';
	xmldata:=xmldata+'<Language><name>English</name><abbreviation>en</abbreviation><id>7</id></Language>';
	xmldata:=xmldata+'<Language><name>Svenska</name><abbreviation>sv</abbreviation><id>8</id></Language>';
	xmldata:=xmldata+'<Language><name>Norsk</name><abbreviation>no</abbreviation><id>9</id></Language>';
	//xmldata:=DownloadURL('http://thetvdb.com/api/22AB688C9DDE05F6/languages.xml');
	//xmldata:=ConvertUTF8ToAnsi(xmldata);
    i:=GetNextXmlTagPos('<Language>',xmldata,1);
    while (i>0) do begin
        s:=GetXmlTagValue('<Language>',xmldata,i);
		name:=GetXmlTagValue('<name>',s,1);
		abrev:=GetXmlTagValue('<abbreviation>',s,1);
		id:=GetXmlTagValue('<id>',s,1);
		if (id='20') then name:='Greek'
		else if (id='22') then name:='Russian'
		else if (id='24') then name:='Hebrew'
		else if (id='25') then name:='Japanese'
		else if (id='27') then name:='Chinese'
		else if (id='28') then name:='Czech'
		else if (id='32') then name:='Korean';
		sl.Add(name+'=<abbreviation>'+abrev+'</abbreviation><id>'+id+'</id>');
        i:=GetNextXmlTagPos('<Language>',xmldata,i+2);
    end;
	sl.Sort;
end;

procedure SetDefaultTvdbApiKey;
var s: string;
begin
	s:='This message will only be displayed once.'+#13#10+#13#10+
		'This script uses www.TheTVDB.com site apis.'+#13#10+
		'You can put your own ApiKey in Script Options (you can get one for free'+#13#10+
		'by registering (also free) on www.TheTVDB.com)'+#13#10+
		'If you haven''t got your own ApiKey , you can use mine (set by default'+#13#10+
		'if none present, what is happening right now)'+#13#10+#13#10+
		'The use of my own ApiKey for public use has only been made possible with'+#13#10+
		'courtesy of Scott Zsori from www.TheTVDB.com (Thanks again!).'+#13#10+#13#10+
		'Please visit and contribute to www.TheTVDB.com whenever you can.'+#13#10+#13#10+
		'JeF.';
	Showmessage(s);
	RegWriteString('TheTVDB_ApiKey', '22AB688C9DDE05F6');
	TvdbApiKey:=RegReadString('TheTVDB_ApiKey', '');
end;

//show available settings for the script
function ShowScriptOptions: integer;
var
	s: string;
	f: TForm;
	b: TButton;
	gbData, gbImages, gbImdb: TGroupBox;
	cbDownloadTrivia, cbDownloadGoofs, cbDownloadQuotes, cbDownloadConnections, cbDownloadSoundtracks: TCheckBox;
	cbImportDesc, cbImportEpDesc, cbActors, cbDirectors, cbWriters, cbAkasInDesc: TCheckBox;
	cbImagesOnly, cbMainPoster, cbMainBanner, cbMainFanart, cbExtraImages, cbPosters, cbEpImages: TCheckBox;
	cbImdbImages, cbImdbOriginalTitle, cbImdbCountry, cbImdbAwards, cbImdbAkasInDesc: TCheckBox;
	labBanners, labFanarts, labSeasonCovers, labDataLang, labSearchLang, labApiKey: TLabel;
	edPosters, edBanners, edFanarts, edSeasonCovers, edApiKey: TEdit;
	comboDataLang, comboSearchLang: TComboBox;
	gbTrace: TGroupBox;								  // 20101017-JeF
	rbTraceModeSave, rbTraceModeLoad: TRadioButton;   // 20101017-JeF
	labTraceLevel: TLabel;							  // 20101017-JeF
	edTraceLevel: TEdit;							  // 20101017-JeF
	cbTraceAsk: TCheckBox;							  // 20101017-JeF
	my_value, i: integer;
	sl, slLang: TStringList;

procedure OnClick(Sender: TControl);
var
	s, s2: string;
	zn: integer;
begin
	if Sender.Name='btnOK' then begin
		try
			RegWriteInteger('TheTVDB_ImagesOnly', BoolToInt(cbImagesOnly.Checked));
			RegWriteString('TheTVDB_ApiKey', edApiKey.Text);
			TvdbApiKey:=RegReadString('TheTVDB_ApiKey', '');

			RegWriteInteger('TheTVDB_ImportDesc', BoolToInt(cbImportDesc.Checked));
			ImportDesc := RegReadInteger('TheTVDB_ImportDesc', 1);
			RegWriteInteger('TheTVDB_ImportEpisodeDesc', BoolToInt(cbImportEpDesc.Checked));
			RegWriteInteger('TheTVDB_ImportActors', BoolToInt(cbActors.Checked));
			RegWriteInteger('TheTVDB_ImportDirectors', BoolToInt(cbDirectors.Checked));
			RegWriteInteger('TheTVDB_ImportWriters', BoolToInt(cbWriters.Checked));

			RegWriteInteger('TheTVDB_ExtraImages', BoolToInt(cbExtraImages.Checked));
			RegWriteInteger('TheTVDB_OvrMaxPosters', BoolToInt(cbPosters.Checked));
			RegWriteInteger('TheTVDB_MaxPosters', StrToIntDef(edPosters.Text,3));
			RegWriteInteger('TheTVDB_MaxBanners', StrToIntDef(edBanners.Text,3));
			RegWriteInteger('TheTVDB_MaxFanarts', StrToIntDef(edFanarts.Text,3));
			RegWriteInteger('TheTVDB_EpisodeImages', BoolToInt(cbEpImages.Checked));
			RegWriteInteger('TheTVDB_MainPoster', BoolToInt(cbMainPoster.Checked));
			RegWriteInteger('TheTVDB_MainBanner', BoolToInt(cbMainBanner.Checked));
			RegWriteInteger('TheTVDB_MainFanart', BoolToInt(cbMainFanart.Checked));
			
			s := comboDataLang.Items[comboDataLang.ItemIndex];
			s2:= slLang.Values[s];
			RegWriteString('TheTVDB_DataLangName', s);
			RegWriteString('TheTVDB_DataLangCode', GetXmlTagValue('<abbreviation>',s2,1));
			RegWriteString('TheTVDB_DataLangId', GetXmlTagValue('<id>',s2,1));
			s := comboSearchLang.Items[comboSearchLang.ItemIndex];
			if (comboSearchLang.ItemIndex = 0) 
				then s2 := '<abbreviation>all</abbreviation><id>0</id>'
			else s2:= slLang.Values[s];
			RegWriteString('TheTVDB_SearchLangName', s);
			RegWriteString('TheTVDB_SearchLangCode', GetXmlTagValue('<abbreviation>',s2,1));
			RegWriteString('TheTVDB_SearchLangId', GetXmlTagValue('<id>',s2,1));
			
			RegWriteInteger('TheTVDB_ImdbImages', BoolToInt(cbImdbImages.Checked));
			RegWriteInteger('TheTVDB_ImdbOriginalTitle', BoolToInt(cbImdbOriginalTitle.Checked));
			RegWriteInteger('TheTVDB_ImdbCountry', BoolToInt(cbImdbCountry.Checked));
			RegWriteInteger('TheTVDB_ImdbAwards', BoolToInt(cbImdbAwards.Checked));
			RegWriteInteger('TheTVDB_ImdbAkasInDesc', BoolToInt(cbImdbAkasInDesc.Checked));
			RegWriteInteger('TheTVDB_ImdbTrivia', BoolToInt(cbDownloadTrivia.Checked));
			RegWriteInteger('TheTVDB_ImdbGoofs', BoolToInt(cbDownloadGoofs.Checked));
			RegWriteInteger('TheTVDB_ImdbQuotes', BoolToInt(cbDownloadQuotes.Checked));
			RegWriteInteger('TheTVDB_ImdbConnections', BoolToInt(cbDownloadConnections.Checked));
			RegWriteInteger('TheTVDB_ImdbSoundtracks', BoolToInt(cbDownloadSoundtracks.Checked));
			AkasInDesc := RegReadInteger('TheTVDB_ImdbAkasInDesc', 1);
			DownloadTrivia := RegReadInteger('TheTVDB_ImdbTrivia', 1);
			DownloadGoofs := RegReadInteger('TheTVDB_ImdbGoofs', 1);
			DownloadQuotes := RegReadInteger('TheTVDB_ImdbQuotes', 0);
			DownloadConnections := RegReadInteger('TheTVDB_ImdbConnections', 0);
			DownloadSoundtracks := RegReadInteger('TheTVDB_ImdbSoundtracks', 0);

			RegWriteInteger('TheTVDB_TraceMode', BoolToInt(rbTraceModeLoad.Checked));   // 20101017-JeF
			RegWriteInteger('TheTVDB_TraceLevel', StrToIntDef(edTraceLevel.Text,0));        // 20101017-JeF
			RegWriteInteger('TheTVDB_TraceAsk', BoolToInt(cbTraceAsk.Checked));             // 20101017-JeF
			jTraceMode := RegReadInteger('TheTVDB_TraceMode', 0);     // 20101017-JeF
			jTraceLevel := RegReadInteger('TheTVDB_TraceLevel', 0);   // 20101017-JeF
			jTraceAsk := RegReadInteger('TheTVDB_TraceAsk', 1);  	  // 20101017-JeF
			
		except
		end;
		f.ModalResult := mrOk;
	end
	else if Sender.Name='cbExtraImages' then begin
		gbImages.Visible:=cbExtraImages.Checked;
	end
	else if Sender.Name='cbImagesOnly' then begin
		gbData.Visible:=(cbImagesOnly.Checked = false);
		gbImdb.Visible:=(cbImagesOnly.Checked = false);
	end
	else if Sender.Name='cbPosters' then begin
		edPosters.Visible:=cbPosters.Checked;
	end;

end;

begin
	sl:=TStringList.Create;
	slLang:=TStringList.Create;
	GetLanguages(slLang);

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

	cbImagesOnly := TCheckBox.Create(f);
	cbImagesOnly.Name := 'cbImagesOnly';
	cbImagesOnly.Parent := f;
	cbImagesOnly.SetBounds(10, 10, 380, 20);
	cbImagesOnly.Caption := GetLangStr(2714);
	cbImagesOnly.Hint:=GetLangStr(2715);
	my_value := RegReadInteger('TheTVDB_ImagesOnly', 0);
	if my_value=1 then
		cbImagesOnly.Checked := True;
	cbImagesOnly.OnClick := @OnClick;
	
	gbData:=TGroupBox.Create(f);
	gbData.Name:='gbData';
	gbData.Parent:=f;
	gbData.SetBounds(10, 35, 396, 90);
	gbData.Caption:=GetLangStr(2734);
	gbData.Hint:=GetLangStr(2734);
	gbData.Visible:=(cbImagesOnly.Checked = false);

	cbImportDesc := TCheckBox.Create(f);
	cbImportDesc.Name := 'cbImportDesc';
	cbImportDesc.Parent := gbData;
	cbImportDesc.SetBounds(10, 20, 185, 20);
	cbImportDesc.Caption := GetLangStr(162);
	my_value := RegReadInteger('TheTVDB_ImportDesc', 1);
	if my_value=1 then
		cbImportDesc.Checked := True;

	cbImportEpDesc := TCheckBox.Create(f);
	cbImportEpDesc.Name := 'cbImportEpDesc';
	cbImportEpDesc.Parent := gbData;
	cbImportEpDesc.SetBounds(10, 40, 185, 20);
	cbImportEpDesc.Caption := GetLangStr(2739);
	my_value := RegReadInteger('TheTVDB_ImportEpisodeDesc', 1);
	if my_value=1 then
		cbImportEpDesc.Checked := True;

	cbActors := TCheckBox.Create(f);
	cbActors.Name := 'cbActors';
	cbActors.Parent := gbData;
	cbActors.SetBounds(200, 20, 190, 20);
	cbActors.Caption := GetLangStr(68);
	my_value := RegReadInteger('TheTVDB_ImportActors', 1);
	if my_value=1 then
		cbActors.Checked := True;
		
	cbDirectors := TCheckBox.Create(f);
	cbDirectors.Name := 'cbDirectors';
	cbDirectors.Parent := gbData;
	cbDirectors.SetBounds(200, 40, 190, 20);
	cbDirectors.Caption := GetLangStr(66);
	my_value := RegReadInteger('TheTVDB_ImportDirectors', 1);
	if my_value=1 then
		cbDirectors.Checked := True;
		
	cbWriters := TCheckBox.Create(f);
	cbWriters.Name := 'cbWriters';
	cbWriters.Parent := gbData;
	cbWriters.SetBounds(200, 60, 190, 20);
	cbWriters.Caption := GetLangStr(67);
	my_value := RegReadInteger('TheTVDB_ImportWriters', 1);
	if my_value=1 then
		cbWriters.Checked := True;
		
	gbImdb:=TGroupBox.Create(f);
	gbImdb.Name:='gbImdb';
	gbImdb.Parent:=f;
	gbImdb.SetBounds(10, 135, 396, 130);
	gbImdb.Caption:=GetLangStr(2730);
	gbImdb.Hint:=GetLangStr(2730);
	gbImdb.Visible:=NOT cbImagesOnly.Checked;

	cbImdbOriginalTitle := TCheckBox.Create(f);
	cbImdbOriginalTitle.Name := 'cbImdbOriginalTitle';
	cbImdbOriginalTitle.Parent := gbImdb;
	cbImdbOriginalTitle.SetBounds(10, 20, 185, 20);
	cbImdbOriginalTitle.Caption := GetLangStr(167);
	cbImdbOriginalTitle.Hint:=GetLangStr(2731);
	my_value := RegReadInteger('TheTVDB_ImdbOriginalTitle', 0);
	if my_value=1 then
		cbImdbOriginalTitle.Checked := True;
	
	cbImdbCountry := TCheckBox.Create(f);
	cbImdbCountry.Name := 'cbImdbCountry';
	cbImdbCountry.Parent := gbImdb;
	cbImdbCountry.SetBounds(10, 40, 185, 20);
	cbImdbCountry.Caption := GetLangStr(180);
	cbImdbCountry.Hint:=GetLangStr(2732);
	my_value := RegReadInteger('TheTVDB_ImdbCountry', 0);
	if my_value=1 then
		cbImdbCountry.Checked := True;
	
	cbImdbAwards := TCheckBox.Create(f);
	cbImdbAwards.Name := 'cbImdbAwards';
	cbImdbAwards.Parent := gbImdb;
	cbImdbAwards.SetBounds(10, 60, 185, 20);
	cbImdbAwards.Caption := GetLangStr(574);
	cbImdbAwards.Hint:=GetLangStr(2733);
	my_value := RegReadInteger('TheTVDB_ImdbAwards', 0);
	if my_value=1 then
		cbImdbAwards.Checked := True;
	
	cbImdbAkasInDesc := TCheckBox.Create(f);
	cbImdbAkasInDesc.Name := 'cbImdbAkasInDesc';
	cbImdbAkasInDesc.Parent := gbImdb;
	cbImdbAkasInDesc.SetBounds(10, 80, 185, 20);
	cbImdbAkasInDesc.Caption := GetLangStr(1665);
	cbImdbAkasInDesc.Hint:=GetLangStr(1666);
	my_value := RegReadInteger('TheTVDB_ImdbAkasInDesc', 0);
	if my_value=1 then
		cbImdbAwards.Checked := True;
	
	sl.CommaText:=GetLangStr(1673);
	cbDownloadTrivia := TCheckBox.Create(f);
	cbDownloadTrivia.Name := 'cbDownloadTrivia';
	cbDownloadTrivia.Parent := gbImdb;
	cbDownloadTrivia.SetBounds(200, 20, 190, 20);
	cbDownloadTrivia.Caption := ClearExtraSDQuotes(sl[0]);
	my_value := RegReadInteger('TheTVDB_ImdbTrivia', 0);
	if my_value=1 then
		cbDownloadTrivia.Checked := True;
		
	cbDownloadGoofs := TCheckBox.Create(f);
	cbDownloadGoofs.Name := 'cbDownloadGoofs';
	cbDownloadGoofs.Parent := gbImdb;
	cbDownloadGoofs.SetBounds(200, 40, 190, 20);
	cbDownloadGoofs.Caption := ClearExtraSDQuotes(sl[1]);
	my_value := RegReadInteger('TheTVDB_ImdbGoofs', 1);
	if my_value=1 then
		cbDownloadGoofs.Checked := True;
		
	cbDownloadQuotes := TCheckBox.Create(f);
	cbDownloadQuotes.Name := 'cbDownloadQuotes';
	cbDownloadQuotes.Parent := gbImdb;
	cbDownloadQuotes.SetBounds(200, 60, 190, 20);
	cbDownloadQuotes.Caption := ClearExtraSDQuotes(sl[2]);
	my_value := RegReadInteger('TheTVDB_ImdbQuotes', 0);
	if my_value=1 then
		cbDownloadQuotes.Checked := True;
		
	cbDownloadConnections := TCheckBox.Create(f);
	cbDownloadConnections.Name := 'cbDownloadConnections';
	cbDownloadConnections.Parent := gbImdb;
	cbDownloadConnections.SetBounds(200, 80, 190, 20);
	cbDownloadConnections.Caption := ClearExtraSDQuotes(sl[3]);
	my_value := RegReadInteger('TheTVDB_ImdbConnections', 0);
	if my_value=1 then
		cbDownloadConnections.Checked := True;
		
	cbDownloadSoundtracks := TCheckBox.Create(f);
	cbDownloadSoundtracks.Name := 'cbDownloadSoundtracks';
	cbDownloadSoundtracks.Parent := gbImdb;
	cbDownloadSoundtracks.SetBounds(200, 100, 190, 20);
	cbDownloadSoundtracks.Caption := ClearExtraSDQuotes(sl[4]);
	my_value := RegReadInteger('TheTVDB_ImdbSoundtracks', 0);
	if my_value=1 then
		cbDownloadSoundtracks.Checked := True;	
		
	cbMainPoster := TCheckBox.Create(f);
	cbMainPoster.Name := 'cbMainPoster';
	cbMainPoster.Parent := f;
	cbMainPoster.SetBounds(10, 275, 380, 20);
	cbMainPoster.Caption := GetLangStr(2742);
	cbMainPoster.Hint:= GetLangStr(2743);
	my_value := RegReadInteger('TheTVDB_MainPoster', 1);
	if my_value=1 then
		cbMainPoster.Checked := True;
	
	cbMainBanner := TCheckBox.Create(f);
	cbMainBanner.Name := 'cbMainBanner';
	cbMainBanner.Parent := f;
	cbMainBanner.SetBounds(10, 295, 380, 20);
	cbMainBanner.Caption := GetLangStr(2735);
	cbMainBanner.Hint:=GetLangStr(2736);
	my_value := RegReadInteger('TheTVDB_MainBanner', 1);
	if my_value=1 then
		cbMainBanner.Checked := True;
	
	cbMainFanart := TCheckBox.Create(f);
	cbMainFanart.Name := 'cbMainFanart';
	cbMainFanart.Parent := f;
	cbMainFanart.SetBounds(10, 315, 380, 20);
	cbMainFanart.Caption := GetLangStr(2737);
	cbMainFanart.Hint:=GetLangStr(2738);
	my_value := RegReadInteger('TheTVDB_MainFanart', 1);
	if my_value=1 then
		cbMainFanart.Checked := True;
	
	cbExtraImages := TCheckBox.Create(f);
	cbExtraImages.Name := 'cbExtraImages';
	cbExtraImages.Parent := f;
	cbExtraImages.SetBounds(10, 335, 380, 20);
	cbExtraImages.Caption := GetLangStr(2716);
	cbExtraImages.Hint:=GetLangStr(2717);
	my_value := RegReadInteger('TheTVDB_ExtraImages', 1);
	if my_value=1 then
		cbExtraImages.Checked := True;
	cbExtraImages.OnClick := @OnClick;
	
	gbImages:=TGroupBox.Create(f);
	gbImages.Name:='gbImages';
	gbImages.Parent:=f;
	gbImages.SetBounds(26, 337, 380, 175);
	gbImages.Caption:=GetLangStr(2716);
	gbImages.Hint:=GetLangStr(2717);
	gbImages.Visible := cbExtraImages.Checked;
	
	cbPosters := TCheckBox.Create(f);
	cbPosters.Name := 'cbPosters';
	cbPosters.Parent := gbImages;
	cbPosters.SetBounds(10, 20, 320, 20);
	cbPosters.Caption := GetLangStr(2740);
	cbPosters.Hint := GetLangStr(2741);
	my_value := RegReadInteger('TheTVDB_OvrMaxPosters', 0);
	if my_value=1 then
		cbPosters.Checked := True;
	cbPosters.OnClick := @OnClick;
	edPosters := TEdit.Create(f);
	edPosters.Name := 'edPosters';
	edPosters.Parent := gbImages;
	edPosters.SetBounds(330, 20, 40, 25);
	edPosters.Text := IntToStr(RegReadInteger('TheTVDB_MaxPosters', 3));
	edPosters.Hint := cbPosters.Hint;
	edPosters.Visible := cbPosters.Checked;
	
	labBanners:=TLabel.Create(f);
	labBanners.Name := 'labBanners';
	labBanners.Parent := gbImages;
	labBanners.SetBounds(10, 50, 320, 20);
	labBanners.Caption := GetLangStr(2718);
	labBanners.Hint := GetLangStr(2718);
	edBanners := TEdit.Create(f);
	edBanners.Name := 'edBanners';
	edBanners.Parent := gbImages;
	edBanners.SetBounds(330, 45, 40, 25);
	edBanners.Text := IntToStr(RegReadInteger('TheTVDB_MaxBanners', 3));
	edBanners.Hint := labBanners.Hint;
	
	labFanarts:=TLabel.Create(f);
	labFanarts.Name := 'labFanarts';
	labFanarts.Parent := gbImages;
	labFanarts.SetBounds(10, 75, 320, 20);
	labFanarts.Caption := GetLangStr(2719);
	labFanarts.Hint := GetLangStr(2719);
	edFanarts := TEdit.Create(f);
	edFanarts.Name := 'edFanarts';
	edFanarts.Parent := gbImages;
	edFanarts.SetBounds(330, 70, 40, 25);
	edFanarts.Text := IntToStr(RegReadInteger('TheTVDB_MaxFanarts', 3));
	edFanarts.Hint := labFanarts.Hint;
	
	labSeasonCovers:=TLabel.Create(f);
	labSeasonCovers.Name := 'labSeasonCovers';
	labSeasonCovers.Parent := gbImages;
	labSeasonCovers.SetBounds(10, 100, 320, 20);
	labSeasonCovers.Caption := GetLangStr(2720);
	labSeasonCovers.Hint := GetLangStr(2720);
	edSeasonCovers := TEdit.Create(f);
	edSeasonCovers.Name := 'edSeasonCovers';
	edSeasonCovers.Parent := gbImages;
	edSeasonCovers.SetBounds(330, 95, 40, 25);
	edSeasonCovers.Text := IntToStr(RegReadInteger('TheTVDB_MaxSeasonCovers', 0));
	edSeasonCovers.Hint := labSeasonCovers.Hint;
	
	cbEpImages := TCheckBox.Create(f);
	cbEpImages.Name := 'cbEpImages';
	cbEpImages.Parent := gbImages;
	cbEpImages.SetBounds(10, 125, 370, 20);
	cbEpImages.Caption := GetLangStr(2721);
	cbEpImages.Hint:=GetLangStr(2722);
	my_value := RegReadInteger('TheTVDB_EpisodeImages', 0);
	if my_value=1 then
		cbEpImages.Checked := True;
	
	cbImdbImages := TCheckBox.Create(f);
	cbImdbImages.Name := 'cbImdbImages';
	cbImdbImages.Parent := gbImages;
	cbImdbImages.SetBounds(10, 145, 370, 20);
	cbImdbImages.Caption := GetLangStr(2723);
	cbImdbImages.Hint:=GetLangStr(2724);
	my_value := RegReadInteger('TheTVDB_ImdbImages', 1);
	if my_value=1 then
		cbImdbImages.Checked := True;
	
	labDataLang:=TLabel.Create(f);
	labDataLang.Name := 'labDataLang';
	labDataLang.Parent := f;
	labDataLang.SetBounds(550, 15, 150, 20);
	labDataLang.Caption := GetLangStr(2725);
	labDataLang.Hint:=GetLangStr(2726);

	comboDataLang := TComboBox.Create(f);
	comboDataLang.Name := 'comboDataLang';
	comboDataLang.Parent := f;
	comboDataLang.SetBounds(420, 10, 120, 20);
	comboDataLang.Hint:=labDataLang.Hint;
	comboDataLang.Style := csDropDownList;
	for i:=0 to slLang.Count - 1 do begin
		comboDataLang.Items.Add(slLang.Names[i]);
		if (RegReadString('TheTVDB_DataLangCode', 'en') = GetXmlTagValue('<abbreviation>',slLang[i],1))
			then comboDataLang.ItemIndex := i;
	end;
	
	labSearchLang:=TLabel.Create(f);
	labSearchLang.Name := 'labSearchLang';
	labSearchLang.Parent := f;
	labSearchLang.SetBounds(550, 45, 150, 20);
	labSearchLang.Caption := GetLangStr(2727);
	labSearchLang.Hint:=GetLangStr(2728);

	comboSearchLang := TComboBox.Create(f);
	comboSearchLang.Name := 'comboSearchLang';
	comboSearchLang.Parent := f;
	comboSearchLang.SetBounds(420, 40, 120, 20);
	comboSearchLang.Hint:=labSearchLang.Hint;
	comboSearchLang.Style := csDropDownList;
	comboSearchLang.Items.Add(GetLangStr(2729));
	comboSearchLang.ItemIndex := 0;
	for i:=0 to slLang.Count - 1 do begin
		comboSearchLang.Items.Add(slLang.Names[i]);
		if (RegReadString('TheTVDB_SearchLangCode', 'all') = GetXmlTagValue('<abbreviation>',slLang[i],1))
			then comboSearchLang.ItemIndex := i+1;
	end;
	
	labApiKey:=TLabel.Create(f);
	labApiKey.Name := 'labApiKey';
	labApiKey.Parent := f;
	labApiKey.SetBounds(550, 75, 150, 20);
	labApiKey.Caption := 'ApiKey';
	edApiKey := TEdit.Create(f);
	edApiKey.Name := 'edApiKey';
	edApiKey.Parent := f;
	edApiKey.SetBounds(420, 70, 120, 25);
	if (RegReadString('TheTVDB_ApiKey', '')='') then SetDefaultTvdbApiKey;
	edApiKey.Text := RegReadString('TheTVDB_ApiKey', '');

	// 20101017-JeF
	gbTrace:=TGroupBox.Create(f);
	gbTrace.Name:='gbTrace';
	gbTrace.Parent:=f;
	gbTrace.SetBounds(500, 407, 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('TheTVDB_TraceMode', 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('TheTVDB_TraceLevel', 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('TheTVDB_TraceAsk', 1);
	if my_value=1 then
		cbTraceAsk.Checked := True;

	b := TButton.Create(f);
	b.Name := 'btnOK';
	b.Parent := f;
	b.SetBounds(trunc(f.width/2)-40, f.height-65, 80, 25);
	b.Caption := '&OK';
	b.OnClick := @OnClick;
	
	f.ShowModal;
	f.Free;
	slLang.Free;
	sl.Free;
end;


begin

	jTraceMode := RegReadInteger('TheTVDB_TraceMode', 0);     // 20101017-JeF
	jTraceLevel := RegReadInteger('TheTVDB_TraceLevel', 0);   // 20101017-JeF
	jTraceAsk := RegReadInteger('TheTVDB_TraceAsk', 1);  	  // 20101017-JeF

	TvdbApiKey:=RegReadString('TheTVDB_ApiKey', '');
	ImportDesc := RegReadInteger('TheTVDB_ImportDesc', 1);
	IMDBLocalService := RegReadInteger('IMDBLocalService', 0);
	AkasInDesc := RegReadInteger('TheTVDB_ImdbAkasInDesc', 1);
	DownloadTrivia := RegReadInteger('TheTVDB_ImdbTrivia', 1);
	DownloadGoofs := RegReadInteger('TheTVDB_ImdbGoofs', 1);
	DownloadQuotes := RegReadInteger('TheTVDB_ImdbQuotes', 0);
	DownloadConnections := RegReadInteger('TheTVDB_ImdbConnections', 0);
	DownloadSoundtracks := RegReadInteger('TheTVDB_ImdbSoundtracks', 0);

end.