program modern_program;

uses 'modern_program_variables.pas', 'modern_program_part1.pas', 'modern_program_part2.pas', 'modern_program_part3.pas';

//userref: 109-129 - Movie page tabs
//userref: 140-149 - Person page tabs
//userref: 131-134 - filmography sort order (for person pages)
//userref: 9 - return loan

const                 
	script_name='Modern';
	language='';
	version=93;
	author='movienizer.com';

//version 6.0
//19.12.2012

function GetMovieTabs(MovieCode, SeasonNr, SeasonCnt: Integer; Awards, Shots, Params, Posters, Trailers, Desc, Connections: Boolean): String;
var
	s, media_format, prev_media_format : String;
	i, k, my_tabs, PageWidth, SeasonTabs, PageTabs, RecordCount: Integer;
	sl: TStringList;
begin
	PageWidth := GetHTMLWidth - TabBorders;
	SeasonTabs := PageWidth div SeasonTabWidth;
	PageTabs := PageWidth div TabWidth;
	s := '<tr><td colspan="2"><table';
	if (ActiveTab <> 2) and (ActiveTab <> 7) then
		s := s + ' width="100%"';
	s := s + '><tr>';
	if (ActiveTab = 2) or (ActiveTab = 7) then
		s := s + '<td width="205"></td>';
	//general info tab
	if ActiveTab = 1 then
		s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(161)])
	else
		s := s + Format('<td class="movie-inactive-tab"><a href="userref:109,%d">%s</a></td>', [MovieCode, GetLangStr(161)]);
	PageTabs := PageTabs - 1;
	//screenshots	
	if (Shots) and (PageTabs > 0) and (RegReadInteger('ShowShotTab', 1) = 1) then begin
		PageTabs := PageTabs - 1;
		if ActiveTab = 2 then
			s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(1429)])
		else
			s := s + Format('<td class="movie-inactive-tab"><a href="userref:110,%d">%s</a></td>', [MovieCode, GetLangStr(1429)]);
	end;
	//posters
	if (Posters) and (PageTabs > 0) and (RegReadInteger('ShowPosterTab', 1) = 1) then begin
		PageTabs := PageTabs - 1;
		if ActiveTab = 7 then
			s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(1425)])
		else
			s := s + Format('<td class="movie-inactive-tab"><a href="userref:115,%d">%s</a></td>', [MovieCode, GetLangStr(1425)]);
	end;
	//trailers
	if (Trailers) and (PageTabs > 0) and (RegReadInteger('ShowTrailerTab', 1) = 1) then begin
		PageTabs := PageTabs - 1;
		if ActiveTab = 9 then 
			s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(1458)])
		else
			s := s + Format('<td class="movie-inactive-tab"><a href="userref:117,%d">%s</a></td>', [MovieCode, GetLangStr(1458)]);
			
	end;
	
	//awards
	if (Awards) and (PageTabs > 0) and (RegReadInteger('ShowAwardsTab', 1) = 1) then begin
		PageTabs := PageTabs - 1;
		if ActiveTab = 3 then
			s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(574)])
		else
			s := s + Format('<td class="movie-inactive-tab"><a href="userref:111,%d">%s</a></td>', [MovieCode, GetLangStr(574)]);
	end;
	
	//actors
	if (PageTabs > 0) and (RegReadInteger('ShowActorTab', 1) = 1) then begin
		PageTabs := PageTabs - 1;
		if ActiveTab = 4 then
			s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(68)])
		else
			s := s + Format('<td class="movie-inactive-tab"><a href="userref:112,%d">%s</a></td>', [MovieCode, GetLangStr(68)]);
	end;
	//parameters
	if (Params) and (PageTabs > 0) and (RegReadInteger('ShowParameterTab', 1) = 1) then begin
		PageTabs := PageTabs - 1;
		if ActiveTab = 5 then
			s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(1254)])
		else
			s := s + Format('<td class="movie-inactive-tab"><a href="userref:113,%d">%s</a></td>', [MovieCode, GetLangStr(1254)]);
	end;
	
	//description
	if (Desc) and (PageTabs > 0) and (RegReadInteger('ShowDescriptionTab', 1) = 1) then begin
		PageTabs := PageTabs - 1;
		if ActiveTab = 10 then
			s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(162)])
		else
			s := s + Format('<td class="movie-inactive-tab"><a href="userref:118,%d">%s</a></td>', [MovieCode, GetLangStr(162)]);
	end;

	//loans
	if (PageTabs > 0) and (RegReadInteger('ShowLoanTab', 0) = 1) then begin
		PageTabs := PageTabs - 1;
		if ActiveTab = 8 then
			s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(1440)])
		else
			s := s + Format('<td class="movie-inactive-tab"><a href="userref:116,%d">%s</a></td>', [MovieCode, GetLangStr(1440)]);
	end;	
	
	//Connections
	if (Connections) and (PageTabs > 0) and (RegReadInteger('ShowConnectionsTab', 1) = 1) then begin
		PageTabs := PageTabs - 1;
		if ActiveTab = 11 then
			s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(4155)])
		else
			s := s + Format('<td class="movie-inactive-tab"><a href="userref:119,%d">%s</a></td>', [MovieCode, GetLangStr(4155)]);
	end;

	//seasons
	if (SeasonCnt > 0) and (PageTabs > 0) and (RegReadInteger('ShowSeasonTab', 1) = 1) then begin
		if ActiveTab = 6 then
			s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(521)])
		else
			s := s + Format('<td class="movie-inactive-tab"><a href="userref:114,%d;%d">%s</a></td>', [MovieCode, SeasonNr, GetLangStr(521)]);
	end;
	
	//media format logo
	if (ActiveTab <> 2) and (ActiveTab <> 7) then begin
		s := s + '<td width="100%"></td>';
		sl := TStringList.Create;
		with sl do begin
			Clear;
			Add('select m.name from editions e');
			Add('left outer join manuals m on m.code=e.media_format');
			Add(format('where e.movie=%d', [MovieCode]));
			Add('order by e.media_format');
		end;
		RecordCount:=ExecuteSQL(sl.text);
		prev_media_format := '';
		k := 0;
		for i:=1 to RecordCount do begin
			media_format := LowerCase(GetStringField('m.name'));
			if (prev_media_format <> media_format) and (PageTabs > 0) then begin
				if (media_format = 'blu-ray') then begin
					s := s + format('<td align="right"><img alt="Blu-Ray" src="%sbd-logo-medium.gif"></td>', [ImgPath]);
					k := k + 1;
				end;
				if (media_format = 'dvd') then begin
					s := s + format('<td align="right"><img alt="DVD" src="%sdvd-logo-medium.gif"></td>', [ImgPath]);
					k := k + 1;
				end;
				if (media_format = 'hd dvd') then begin
					s := s + format('<td align="right"><img alt="HD DVD" src="%shddvd-logo-medium.gif"></td>', [ImgPath]);
					k := k + 1;
				end;
				if (Pos('mkv', media_format)>0) then begin
					if (PageTabs >= 1) and (k=0) then begin
						s := s + format('<td align="right"><img alt="MKV Matroska" src="%smkv-logo-medium.gif"></td>', [ImgPath]);
						k := k + 2;
					end
					else begin
						s := s + format('<td align="right"><img alt="MKV Matroska" src="%smkv-logo-cut-medium.gif"></td>', [ImgPath]);
						k := k + 1;
					end;
				end;
				prev_media_format := media_format;
				if k >= 2 then begin
					k := 0;
					PageTabs := PageTabs - 1;
				end;
			end;
			GetNextRecord;
		end;
		//video codec logo (divx, xvid)
		with sl do begin
			Clear;
			Add('select m.name from editions e');
			Add('left outer join manuals m on m.code=e.video_codec');
			Add(format('where e.movie=%d', [MovieCode]));
			Add('order by e.sort_order');
		end;
		RecordCount:=ExecuteSQL(sl.text);
		prev_media_format := '';
		for i:=1 to RecordCount do begin
			media_format := LowerCase(GetStringField('m.name'));
			if (media_format <> prev_media_format) and (PageTabs > 0) then begin
				if (Pos('divx', media_format)>0) then begin
					s := s + format('<td align="right"><img alt="DivX" src="%sdivx-logo-medium.gif"></td>', [ImgPath]);
					k := k + 2;
				end;
				if (Pos('xvid', media_format)>0) then begin
					s := s + format('<td align="right"><img alt="XviD" src="%sxvid-logo-medium.gif"></td>', [ImgPath]);
					k := k + 2;
				end;
				prev_media_format := media_format;
				if k >= 2 then begin
					k := 0;
					PageTabs := PageTabs - 1;
				end;
			end;
			GetNextRecord;
		end;
		sl.Free;
	end;
	
	//filter by seasons
	if (ActiveTab = 6) then begin
		//tabs for seasons
		if SeasonCnt > 1 then begin
			s := s + '</tr></table></td></tr><tr><td colspan="2"><table><tr>';
			my_tabs := 1;
			if SeasonNr = 0 then
				s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(40)])
			else
				s := s + Format('<td class="movie-inactive-tab"><a href="userref:114,%d;%d">%s</a></td>', [MovieCode, 0, GetLangStr(40)]);
			for i := 1 to SeasonCnt do begin
				//depending on the page's width show season numbers in several rows
				if my_tabs > SeasonTabs then begin
					s := s + '</tr><tr>';
					my_tabs := 0;
				end;
				if SeasonNr = i then
					s := s + Format('<td class="movie-active-tab">%d</td>', [i])
				else
					s := s + Format('<td class="movie-inactive-tab"><a href="userref:114,%d;%d">%d</a></td>', [MovieCode, i, i]);
				my_tabs := my_tabs + 1;
			end;
		end;
	end;
	s := s + '</tr></table></td></tr>';
	Result := s;
end;

function GetMovie(MovieCode, season: integer; FullDesc: boolean): string;
begin
	result:=GetMovie3(MovieCode, season, FullDesc, false, false);
end;

//show movie's info
function GetMovie3(MovieCode, season: integer; FullDesc, FullComments, FullPersons: boolean): string;
begin
	result:=GetMovie4(MovieCode, season, FullDesc, FullComments, FullPersons, false);
end;

function GetMovie4(MovieCode, season: integer; FullDesc, FullComments, FullPersons, FullAwards: boolean): string;
begin
	result := GetMovie5(MovieCode, season, FullDesc, FullComments, FullPersons, FullAwards);
end;

function GetPersonTabs(PersonCode: Integer; Bio, Facts, Photos, Awards: Boolean): String;
var
	s: String;
	i, my_tabs, PageWidth, PageTabs: Integer;
begin
	PageWidth := GetHTMLWidth - TabBorders;
	PageTabs := PageWidth div TabWidth;
	s := '<tr><td colspan="2"><table><tr>';
	if (PersonActiveTab = 2) then
		s := s + '<td width="187"></td>';
	//general info tab
	if PersonActiveTab = 1 then
		s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(161)])
	else
		s := s + Format('<td class="movie-inactive-tab"><a href="userref:140,%d">%s</a></td>', [PersonCode, GetLangStr(161)]);
	//photos
	if Photos then begin
		if PersonActiveTab = 2 then
			s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(1400)])
		else
			s := s + Format('<td class="movie-inactive-tab"><a href="userref:141,%d">%s</a></td>', [PersonCode, GetLangStr(1400)]);
	end;
	//biography
	if Bio then begin
		if PersonActiveTab = 3 then
			s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(282)])
		else
			s := s + Format('<td class="movie-inactive-tab"><a href="userref:142,%d">%s</a></td>', [PersonCode, GetLangStr(282)]);
	end;
	//facts
	if Facts then begin
		if PersonActiveTab = 4 then
			s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(1435)])
		else
			s := s + Format('<td class="movie-inactive-tab"><a href="userref:143,%d">%s</a></td>', [PersonCode, GetLangStr(1435)]);
	end;
	//awards
	if Awards then begin
		if PersonActiveTab = 6 then
			s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(574)])
		else
			s := s + Format('<td class="movie-inactive-tab"><a href="userref:145,%d">%s</a></td>', [PersonCode, GetLangStr(574)]);
	end;
	//filmography
	if PersonActiveTab = 5 then
		s := s + Format('<td class="movie-active-tab">%s</td>', [GetLangStr(42)])
	else
		s := s + Format('<td class="movie-inactive-tab"><a href="userref:144,%d">%s</a></td>', [PersonCode, GetLangStr(42)]);
	s := s + '</tr></table></td></tr><tr><td class="free-space"></td></tr>';
	result := s;
end;

//counts how many movies/persons would fit the previous pages (before the current page),
// or how many pages would be needed for the given number of movies/persons
// (after the current page)
//returns the number of movies that would fit the given number of pages
//saves the number of processed records to the ProcessedRecords global variable
//saves the number of counted pages to the CountedPages global variable
function CountItemsForPages(page_width, prev_page, RecordCount, i, lines, ItemHeight, StandardWidth: Integer): Integer;
var
	page_width_copy, LastCode, my_code, j, PicWidth, TotalItems, total_pages, PicHeight, lines_copy: Integer;
	PreviousCodes: TStringList;
begin
	page_width_copy := page_width;
	LastCode := 0;
	lines_copy := lines;
	j := 0;
	TotalItems := 0;
	total_pages := 0;
	PreviousCodes := TStringList.Create;
	while (i<=RecordCount) and (prev_page > 1) do begin
		my_code := GetIntegerField('code');
		//disregard duplicate items
		if (PreviousCodes.IndexOf(IntToStr(my_code)) < 0) then begin
			PreviousCodes.Add(IntToStr(my_code));
			//check the width of every item
			PicHeight := GetIntegerField('i.height');
			if PicHeight > 0 then
				PicWidth := Round(GetIntegerField('i.width') * (ItemHeight / PicHeight)) + NormalImageBorders
			else
				PicWidth := StandardWidth;
			page_width_copy := page_width_copy - PicWidth;
			LastCode := my_code;
			//if it still fits the page, count it
			if (page_width_copy >= 0) then begin
				j := j + 1;
			end
			//if the item doesn't fit the page anymore, remember how many items fit the page
			else if lines_copy > 1 then begin
				//proceed to the next line
				page_width_copy := page_width - PicWidth;
				TotalItems := TotalItems + j;
				//the current record goes to the next line
				j := 1;
				lines_copy := lines_copy - 1;
			end
			//next page
			else begin
				lines_copy := lines;
				TotalItems := TotalItems + j;
				total_pages := total_pages + 1;
				prev_page := prev_page - 1;
				page_width_copy := page_width - PicWidth;
				//if prev_page <= 1, the loop will be broken, and the record
				//will go to the current page (j := 0), otherwise the record will
				//go to another previous page (j := 1)
				if (prev_page > 1) then
					j := 1
				else
					j := 0;
			end;
		end
		else begin
			GetNextRecord;
			i := i + 1;
		end;
	end;
	if j > 0 then begin
		total_pages := total_pages + 1;
		TotalItems := TotalItems + j;
	end;
	PreviousCodes.Free;
	//a global variable is used to return the second result
	ProcessedRecords := i;
	//a global variable is used to return the third result
	CountedPages := total_pages;
	Result := TotalItems;
end;

//shows the loan page
function GetLoans: string;
var
	all, s, loan_date, return_date: String;
	i, j, RecordCount, EditionCode, MovieCode: Integer;
	sl: TStringList;
begin
	sl := TStringList.Create;
	with sl do begin
	  Clear;
	  Add('select l.code, l.loan_date, l.due_date, l.edition, l.movie, l.comment, m.name, mv.title from loans l');
	  Add('inner join manuals m on m.code=l.location');
	  Add('inner join editions ed on ed.code=l.edition');
	  Add('inner join movies mv on mv.code=l.movie');
	  Add('where (return_date='''' or return_date is null)');
	  Add('order by mv.title_sort');
	end;
	RecordCount:=ExecuteSQL(sl.text);
	all := GetPatternTop + '<p class="title">' + GetLangStr(1440) + format(' (%d)', [RecordCount])+'</p></td>'+ClosePatternTop;
	all := all + Format('<tr><td><table class="content"><tr><td style="background:url(%s) repeat-x;">&nbsp;</td></tr>', [WhiteBarFile]);
	//no loans
	if RecordCount = 0 then
		all := all + '<tr><td>' + GetLangStr(1455) + '</td></tr>'
	else begin
		all := all + '<tr><td><table class="loans">';
		all := all + format('<tr><td class="loan-title"><b>%s</b></td><td class="loan-title"><b>%s</b></td><td class="loan-title"><b>%s</b></td><td class="loan-title"><b>%s</b></td><td class="loan-title"><b>%s</b></td><td class="loan-title"><b>%s</b></td><td class="loan-title"><b>%s</b></td></tr>', [GetLangStr(46), GetLangStr(239), GetLangStr(240), GetLangStr(241), GetLangStr(245), GetLangStr(163), GetLangStr(1446)]);
		for i:=1 to RecordCount do begin
			all := all + '<tr>';
			EditionCode := GetIntegerField('l.edition');
			MovieCode := GetIntegerField('l.movie');
			loan_date := GetSmartDate(GetStringField('l.loan_date'));
			return_date := Format('<a href="userref:11,%d;%d;%d;loan-page">%s</a>', [EditionCode, MovieCode, GetIntegerField('l.code'), GetLangStr(1445)]);
			all := all + format('<td><a href="movie:%d">%s</a></td>', [MovieCode, GetStringField('mv.title')]);
			all := all + format('<td class="loan-date">%s</td>', [loan_date]);
			all := all + format('<td class="loan-date">%s</td>', [GetSmartDate(GetStringField('l.due_date'))]);
			all := all + format('<td class="loan-date">%s</td>', [return_date]);
			all := all + format('<td>%s</td>', [GetStringField('m.name')]);
			all := all + format('<td>%s</td>', [GetStringField('l.comment')]);
			all := all + format('<td><a class="picture" href="userref:14,%d;%d;%d;loan-page"><img src="%sdelete.png"></a></td>', [EditionCode, MovieCode, GetIntegerField('l.code'), ImgPath]);
			all := all + '</tr>';
			GetNextRecord;
		end;
		all := all + '</table></td></tr>';
	end;
	
	all := all + '</table>' + GetPatternBottom;
	sl.Free;
	result := all;
end;

function GetUserReference(code: integer; text: string): string;
begin
	result:=GetUserReference2(code, text, 1);
end;
	
//show movies by selected user reference
//links like <a href='userref:Code,Text'>link</a>
//links like <a href='userref:Code,Text,Page'>link</a>
function GetUserReference2(code: integer; text: string; page: integer): string;
var
  sl, TempList, PreviousCodes: TStringList;
  i, j, kol, RecordCount, rating, page_width, LastCode, my_i, my_code, movie_code: integer;
  s, s2, description, year, director, writer, actor, bio, character, movie, movie_top: string;
  all, FileName, img, rate: string;
  IMDBRating: double;
  StartItem, EndItem, MoviesPage, ii, TotalItems, lines, SeasonNr, PageItems: integer;
  fl, ShowLastUpdated, loan_page: boolean;
  dd, mm, yy, loan_code, page_width_copy, PicWidth, PicHeight: integer;
  header_img, temp: String;
begin
	result:='';
	ProgramReference:='';
	TempReferenceCode:=code;
	TempReference:=666;
	TempText:=text;
	if code=100 then
		result := GetPatternTop+format('<p class="title">%s</p></td>', [GetLangStr(1333)])+ClosePatternTop+'<tr><td><table class="content"><tr><td><p class="header">'+ShowScriptOptions+'</p></td></tr></table></td></tr>'+GetPatternBottom
	//Movie tabs
	else if code in [109..129]	then begin
		my_code := 0;
		SeasonNr := 0;
		i := Pos(';', text);
		if i>0 then begin
			s := copy(text, i+1, length(text) - i);
			delete(text, i, length(text) - i + 1);
			try
				SeasonNr := StrToInt(s);
			except
			end;
		end;
		try
			my_code := StrToInt(text);
		except
		end;

		//18.11.10
		SetMode(1, my_code);

		ActiveTab := code - 108;
		if my_code > 0 then
			result := GetMovie5(my_code, SeasonNr, false, false, false, false);
	end
	//person tabs
	else if code in [140..149] then begin
		my_code := 0;
		try
			my_code := StrToInt(text);
		except
		end;
		PersonActiveTab := code - 139;
		SetMode(2, my_code);
		if my_code > 0 then
			result := GetPerson(my_code, false, false);
	end
	else begin

		sl:=TStringList.Create;
		all:='';		
		
		// movies by studio
		if code = 12 then begin
			with sl do begin
				Clear;
				Add('select m.title, m.code as code, m.in_collection, m.rating, m.imdb_rating, i.path, i.width, i.height');
				Add('from movies m');
				Add('inner join movies_manuals mm on mm.movie=m.code and mm.reference=12');
				Add('inner join manuals mg on mg.code=mm.ref_code');
				Add('left outer join images i on i.movie=m.code and i.mode=1');
				Add(format('where mg.name=%s and m.in_collection=1', [TempText]));
				Add('order by m.title_sort');
			end;
			RecordCount:=ExecuteSQL(sl.text);
			all := ProcessMovieReference(sl, text, page);
		end;
		
		// movies by award
		if code = 135 then begin
			//detect award winners
			with sl do begin
				Clear;
				Add('select code, awards from movies');
				Add('where awards like ''%' + TempText + '%'' and in_collection=1');
			end;
			RecordCount := ExecuteSQL(sl.text);
			TempList := TStringList.Create;
			header_img := '';
			i := 0;
			while i < RecordCount do begin
				s := LowerCase(GetStringField('awards'));
				s2 := '';
				j := Pos(LowerCase(TempText), s);
				if j > 0 then begin
					my_i := MyPos('<br><br>', s, j + 1);
					if my_i = 0 then
						my_i := MyPos('<br> <br>', s, j + 1);
					if my_i = 0 then
						my_i := Length(s);
					s2 := copy(s, j, my_i - j);
				end;
				if (Pos('won<br>', s2) > 0) or (Pos('победитель', s2) > 0) or (Pos('премия "' + LowerCase(TempText), s) > 0) then begin
					TempList.Add(IntToStr(GetIntegerField('code')));
				end;
				GetNextRecord;
				i := i + 1;
			end;
			//select award winners
			with sl do begin
				Clear;
				Add('select m.title, m.code as code, m.in_collection, m.rating, m.imdb_rating, i.path, i.width, i.height');
				Add('from movies m');
				Add('left outer join images i on i.movie=m.code and i.mode=1');
				Add(Format('where m.code in (%s)', [TempList.CommaText]));
				Add('order by m.title_sort, i.sort_order');
			end;
			(*TempList.LoadFromFile(PicturesPath + 'awards\awards.txt');
			for i := 0 to TempList.Count - 1 do
				if Pos(LowerCase(TempText), LowerCase(TempList[i])) = 1 then
					header_img := TempList.Values[TempList.Names[i]];
			if header_img <> '' then
				header_img := PicturesPath + 'awards/' + header_img;*)
			TempList.Free;
			RecordCount:=ExecuteSQL(sl.text);
			all := ProcessMovieReference(sl, TempText, page);
		end;
			
		//filmography sorting
		if code in [131..134] then begin
			my_code := 0;
			s := '';
			i := Pos(';', text);
			s := copy(text, 1, i-1);
			s := s+'FilmSort';
			delete(text, 1, i);
			try
				my_code := StrToInt(text);
			except
			end;
			if code = 131 then
				RegWriteString(s, 'title asc');
			if code = 132 then
				RegWriteString(s, 'title desc');
			if code = 133 then
				RegWriteString(s, 'year asc');
			if code = 134 then
				RegWriteString(s, 'year desc');
			SetMode(2, my_code);
			all := GetPerson(my_code, false, false);
		end;
		
		//movies from the home page
		if (RegReadInteger('ShowLastUpdated', 0) = 1) then
			ShowLastUpdated := True
		else
			ShowLastUpdated := False;
		if ((code > 0) and (code < 6)) then begin
			with sl do begin
				Clear;
				Add('select m.code as code, m.title, m.year, m.rating, m.imdb_rating, m.in_collection, i.path, i.height, i.width');
				Add('from movies m');
				Add('left outer join images i on i.movie=m.code and i.mode=1');
				case code of
					2: Add('where 1=1');
					3: Add('where seen<>1');
					4: Add('where m.date_update is not null');
					//8: Add('where 1=1');
					else
						if ShowLastUpdated then
							Add('where m.date_update is not null')
						else
							Add('where m.date_add is not null');
				end;
				Add('and m.in_collection=1');
				//Add('and i.mode=1');
				case code of
					2: Add('order by m.rating desc, m.date_add desc, m.code, i.sort_order, i.code');
					4: Add('order by m.date_update desc, m.code, i.sort_order, i.code');
					5: Add('order by m.title_sort, m.year, i.sort_order, i.code');
					else
						if ShowLastUpdated then
							Add('order by m.date_update desc, m.code, i.sort_order, i.code')
						else
							Add('order by m.date_add desc, m.code, i.sort_order, i.code');
				end;
			end;
			all := ProcessMovieReference(sl, text, page);
		end;
		
		// people by award
		if code = 136 then begin
			header_img := '';
			//detect award winners
			with sl do begin
				Clear;
				Add('select code, awards from persons');
				Add('where awards like ''%' + TempText + '%'' and in_collection=1');
			end;
			RecordCount := ExecuteSQL(sl.text);
			TempList := TStringList.Create;
			i := 0;
			while i < RecordCount do begin
				s := LowerCase(GetStringField('awards'));
				s2 := '';
				temp := s;
				j := Pos(LowerCase(TempText), temp);
				while j > 0 do begin
					my_i := MyPos('<br><br>', temp, j + 1);
					if my_i = 0 then
						my_i := MyPos('<br> <br>', temp, j + 1);
					if my_i = 0 then
						my_i := Length(temp);
					s2 := copy(temp, j, my_i - j);
					if (Pos('won<br>', s2) > 0) or (Pos('победитель', s2) > 0) then
						TempList.Add(IntToStr(GetIntegerField('code')));
					delete(temp, 1, j);
					j := Pos(LowerCase(TempText), temp);
				end;
				GetNextRecord;
				i := i + 1;
			end;
			//select award winners
			with sl do begin
				Clear;
				Add('select p.code as code, p.name, p.rating, p.birth_date, i.path, i.width, i.height, p.in_collection');
				Add('from persons p');
				Add('left outer join images i on i.person=p.code');
				Add(Format('where p.code in (%s)', [TempList.CommaText]));
				Add('order by p.name, i.sort_order');
			end;
			(*TempList.LoadFromFile(PicturesPath + 'awards\awards.txt');
			for i := 0 to TempList.Count - 1 do
				if Pos(LowerCase(TempText), LowerCase(TempList[i])) = 1 then
					header_img := TempList.Values[TempList.Names[i]];
			if header_img <> '' then
				header_img := PicturesPath + 'awards/' + header_img;*)
			TempList.Free;
			RecordCount:=ExecuteSQL(sl.text);
		end;
		
		//people from the homepage
		if (code > 5) and (code < 10) or (code = 136) then begin
			if code <> 136 then begin
				header_img := '';
				with sl do begin
					Clear;

					Add('select p.code as code, p.name, p.rating, i.path, i.width, i.height, p.in_collection');
					Add('from persons p');
					Add('left outer join images i on i.person=p.code');
					case code of
						7: Add('where 1=1');
						8: Add('where p.date_update is not null');
						9: Add('where p.birth_date like ''%' + Format('%s', [GetTodaysDate]) + '%''');
						else
							if ShowLastUpdated then
								Add('where p.date_update is not null')
							else
								Add('where p.date_add is not null');
					end;
					Add('and p.in_collection=1');
					case code of
						7: Add('order by p.rating desc, p.date_add desc, p.code, i.mode desc, i.sort_order');
						8: Add('order by p.date_update desc, p.code, i.mode desc, i.sort_order');
						9: Add('order by p.date_add desc, p.code, i.sort_order');
						else
							if ShowLastUpdated then
								Add('order by p.date_update desc, p.code, i.mode desc, i.sort_order')
							else
								Add('order by p.date_add desc, p.code, i.mode desc, i.sort_order');
					end;
				end;
				RecordCount:=ExecuteSQL(sl.text);
			end;
			PreviousCodes := TStringList.Create;
			lines := RegReadInteger('LinesPeople', DefaultLinesPeople);
			page_width := GetHTMLWidth - WholePageBorder;
			CountedPages := 0;
			TotalItems := CountItemsForPages(page_width, page, RecordCount, 1, lines, PhotoHeight, StandardPhotoWidth);
			i := ProcessedRecords;
			movie := '';
			all := '';
			fl:=true;
			PageItems := 0;
			LastCode := 0;
			page_width_copy := page_width;
			while (i<=RecordCount) and fl do begin
				my_code:=GetIntegerField('code');
				if PreviousCodes.IndexOf(IntToStr(my_code)) < 0 then begin
					PreviousCodes.Add(IntToStr(my_code));
					LastCode:=my_code;
					PicHeight := GetIntegerField('i.height');
					if PicHeight > 0 then
						PicWidth := Round(GetIntegerField('i.width') * (PhotoHeight / PicHeight)) + NormalImageBorders
					else
						PicWidth := CoverCellWidth;
					if PicWidth < CoverCellWidth then
						PicWidth := CoverCellWidth;
					page_width_copy := page_width_copy - PicWidth;
					if (page_width_copy < 0) then begin
						all := all + movie + '</tr></table></tr></td><tr><td align="center"><table class="ref-boxes"><tr>';
						movie := '';
						lines := lines - 1;
						page_width_copy := page_width - PicWidth;
					end;
					if (page<>0) and (lines <= 0) then
						fl:=false
					else begin	
					
						rating := GetIntegerField('p.rating');
						rate:='';
						if rating > 0 then begin
							for my_i:=1 to 10 do begin
								if my_i mod 2=1 then begin
									if my_i<=rating then
								rate:=rate+format('<img src="%sstar-left.gif" align="absmiddle" border="0">',  [ImgPath])
									else
								rate:=rate+format('<img src="%snot-star-left.gif" align="absmiddle" border="0">',  [ImgPath])
								end
								else begin
									if my_i<=rating then
								rate:=rate+format('<img src="%sstar-right.gif" align="absmiddle" border="0">',  [ImgPath])
									else
								rate:=rate+format('<img src="%snot-star-right.gif" align="absmiddle" border="0">',  [ImgPath])
								end;
							end;
						end;
						FileName := GetImageFileName(GetStringField('i.path'), 'ThumbsMoviePhotos', 'nophoto.gif', 0, PhotoHeight);
						movie:=movie+'<td class="box-photos" style="background:url('+BackgroundPeople+') repeat-x;">'+format('<a href="person:%d"><img class="person-photo" src="%s"></a>', [my_code, Filename]);
						if rate<>'' then
							movie := movie + '<br>' + rate;
						movie:=movie + format('<p><a href="person:%d">%s</a></p></td>', [my_code, GetStringField('p.name')]);

						PageItems:=PageItems+1;
					end;
				end
				else begin
					GetNextRecord;
					i:=i+1;
				end;
			end;
			PreviousCodes.Free;
			TotalItems := TotalItems + PageItems;
			
			all:=all+movie+'</tr></table></td></tr>';
			all := all + '</table>';

			kol := 0;
			lines := RegReadInteger('LinesPeople', DefaultLinesPeople);
			if (page > 0) and (i < RecordCount) then begin
				//set the maximum number of pages to 2000
				TotalItems := TotalItems + CountItemsForPages(page_width, 2000, RecordCount, i, lines, PhotoHeight, StandardPhotoWidth);
				kol := CountedPages;
			end;
			movie_top:=GetPatternTop;
			movie_top:= movie_top + '<p class="title">' + text + format(' (%d)', [TotalItems]);
			movie_top:=movie_top+'</p></td>'+ClosePatternTop;
			movie_top := movie_top + Format('<tr><td><table class="content"><tr><td style="background:url(%s) repeat-x;">&nbsp;</td></tr>', [WhiteBarFile]);
			movie_top:=movie_top+'<tr><td align="center"><table class="ref-boxes"><tr>';
			
			all := movie_top + all;
			
			s:='userref:'+IntToStr(TempReferenceCode)+','+TempText;
			if (kol > 0) or (page > 1) then begin
				all:=all+'<center><table class="navi"><td class="navi-border">'+format('<img src="%snavi-left.gif"></td><td style="background:url(%s) repeat-x;"><p>', [ImgPath, WhiteBarFile]);
				if (kol>0) or (page > 1) then
					all:=all+format('<a href="%s,%d">%s</a>   ', [s, 0, GetLangStr(1330)]);
				if page>1 then
					all:=all+format('<a href="%s,%d">%s</a>   ', [s, page-1, GetLangStr(1328)]);
				for i:=1 to page do begin
					if page=i then
						all:=all+format(' <b>%d</b> ', [i])
					else
						all:=all+format(' <a href="%s,%d">%d</a> ', [s, i, i]);
				end;
				for i:=(page+1) to (page+kol) do
					all:=all+format(' <a href="%s,%d">%d</a> ', [s, i, i]);			
				if kol>0 then
					all:=all+format('   <a href="%s,%d">%s</a> ', [s, page+1, GetLangStr(1329)]);
				all:=all+format('</p></td><td class="navi-border"><img src="%snavi-right.gif"></td></table></center>', [ImgPath]);
			end;
			all := all + GetPatternBottom;
		end;		
		
		sl.Free;
		result := all;
	end;
end;

function GetShots(Code, ImageMode: Integer; MyObject: String; AdditionalImageMode: Integer=0; AdditionalImageMode2: Integer=0): String;
var
	sl: TStringList;
	i, j, kol, RecordCount: Integer;
	s, FileName, ImageModes : String;
begin
	s := '';
	if AdditionalImageMode > 0 then
		ImageModes := Format('%d, %d', [ImageMode, AdditionalImageMode])
	else
		ImageModes := IntToStr(ImageMode);
	if AdditionalImageMode2 > 0 then
		ImageModes := Format('%s, %d', [ImageModes, AdditionalImageMode2]);
	sl := TStringList.Create;
	with sl do begin
		Clear;
		Add('select path, code from images');
		Add(format('where %s=%d and mode in (%s)', [MyObject, Code, ImageModes]));
		Add('order by sort_order');
	end;
	RecordCount:=ExecuteSQL(sl.text);
	if RecordCount>0 then begin
		kol := (GetHTMLWidth - 30) div ShotWidth;
		j := 0;
		s := '<tr><td style="background:url('+WhiteBarFile+') repeat-x;">&nbsp;</td></tr><tr><td><table class="ref-boxes" align="center"><tr>';
		//skip the first photo
		if MyObject = 'person' then begin
			GetNextRecord;
			RecordCount := RecordCount - 1;
		end;
		for i:=1 to RecordCount do begin
			j := j+1;
			FileName:=ImagesPath+GetStringField('path');
			if (MyFileExists(FileName)) then
				s:=s+format('<td class="box-shots"><a class="picture" href="ShowImage:%d"><img src="%s"></a></td>', [GetIntegerField('code'), FileName]);
			if j>=kol then begin
				j := 0;
				s:=s+'</tr><tr>';
			end;
			GetNextRecord;
		end;
		s := s + '</tr></table></td></tr>';
	end;
	sl.Free;
	result := s;
end;

//show movies by selected manual
function GetReference(ReferenceCode, reference: integer): string;
begin
	result:=GetReference2(ReferenceCode, reference, 0);
end;

//show movies by selected manual
function GetReference2(ReferenceCode, reference, page: integer): string;
var
  sl: TStringList;
  RecordCount, i: integer;
  s, all: string;
  AudioEditionMediaType: Integer;
begin
	result:='';
	TempReferenceCode:=ReferenceCode;
	TempReference:=reference;
	
	ProgramReference:='';
	sl:=TStringList.Create;

	all:='';
  if ReferenceCode>0 then begin
    //LastMode:=4;
      with sl do begin
        Clear;
        Add('select name from manuals');
        if ((Reference = 6) or (Reference = 7)) then
          Add(format('where code=%d and reference=%d', [ReferenceCode, 23]))
        else
          Add(format('where code=%d and reference=%d', [ReferenceCode, reference]));
      end;
      RecordCount:=ExecuteSQL(sl.text);
      if RecordCount<=0 then
        exit;
      ProgramReference:=GetStringField('name');

      //показываем фильмы по выбранному справочнику
      with sl do begin
        Clear;
		Add('select m.title, m.code as code, m.year, m.in_collection, m.rating, m.imdb_rating, m.series_nom, i.path, i.height, i.width');
        Add('from movies m');
        //custom fields
        if (reference>=13) and (reference<=16) then begin
        	i:=reference-12;
			Add('left outer join images i on i.movie=m.code and i.mode=1');
			Add(format('where m.custom%d=%d', [i, ReferenceCode]));
	        Add('order by m.title');
        end
        //video standard
        else if (reference=1) then begin
        	Add('left outer join editions e on e.movie=m.code');
			Add('left outer join images i on i.movie=m.code and i.mode=1');
  	      Add(format('where e.video_standard=%d and m.in_collection=1', [ReferenceCode]));
	        Add('order by m.year desc, m.title');
        end
        //media format
        else if (reference=2) then begin
        	Add('left outer join editions e on e.movie=m.code');
			Add('left outer join images i on i.movie=m.code and i.mode=1');
  	      Add(format('where e.media_format=%d and m.in_collection=1', [ReferenceCode]));
	        Add('order by m.year desc, m.title');
        end	
		
        // media types
        else if (reference = 3) then
        begin
			Add('left outer join images i on i.movie=m.code and i.mode=1');
			Add(format('where m.media_type=%d', [ReferenceCode]));
	        Add('order by m.year desc, m.title');          
        end
        //aspect ratio
        else if (reference=4) then begin
			Add('left outer join editions e on e.movie=m.code');
			Add('left outer join images i on i.movie=m.code and i.mode=1');
			Add(format('where e.screen_ratio=%d and m.in_collection=1', [ReferenceCode]));
	        Add('order by m.title');
        end
        //resolution
        else if (reference=5) then begin
			Add('left outer join editions e on e.movie=m.code');
			Add('left outer join images i on i.movie=m.code and i.mode=1');
			Add(format('where e.resolution=%d and m.in_collection=1', [ReferenceCode]));
	        Add('order by m.title');
        end
        else if (reference=6) or (reference=7) then
        begin
          AudioEditionMediaType := 7 - reference;
        	Add('left outer join editions e on e.movie=m.code');
    			Add(format('inner join audio_manuals em on em.edition=e.code and em.media_type=%d', [AudioEditionMediaType]));
    	    Add('inner join manuals mg on mg.code=em.reference');
		    	Add('left outer join images i on i.movie=m.code and i.mode=1');
    			Add(format('where mg.code=%d and m.in_collection=1', [ReferenceCode]));
	        Add('order by m.title');
        end			
        //location
        else if (reference=10) then begin
			Add('left outer join editions e on e.movie=m.code');
        	Add('inner join loans l on l.edition=e.code');
			Add('left outer join images i on i.movie=m.code and i.mode=1');
			Add(format('where l.location=%d', [ReferenceCode]));
			Add('and (l.return_date='''' or l.return_date is null) and m.in_collection=1');
	        Add('order by m.title');
        end
        // MPAA
        else if (reference = 11) then
        begin
			Add('left outer join images i on i.movie=m.code and i.mode=1');
			Add(format('where m.mpaa=%d and m.in_collection=1', [ReferenceCode]));
	        Add('order by m.year desc, m.title');
        end
        // video codec
        else if (reference = 19) then
        begin
        	Add('left outer join editions e on e.movie=m.code');
			Add('left outer join images i on i.movie=m.code and i.mode=1');
			Add(format('where e.video_codec=%d and m.in_collection=1', [ReferenceCode]));
	        Add('order by m.year desc, m.title');
        end
        //disc label
        else if (reference=20) then begin
			Add('left outer join editions e on e.movie=m.code');
			Add('left outer join images i on i.movie=m.code and i.mode=1');
			Add(format('where e.disc_label=%d and m.in_collection=1', [ReferenceCode]));
	        Add('order by m.title');
        end
		//sequence
		else if (reference=22) then begin
			Add('left outer join images i on i.movie=m.code and i.mode=1');
			Add(format('where m.series=%d', [ReferenceCode]));
	        Add('order by m.series_nom');
        end
        else begin
			Add(format('inner join movies_manuals mm on mm.movie=m.code and mm.reference=%d', [reference]));
    	    Add('inner join manuals mg on mg.code=mm.ref_code');
			Add('left outer join images i on i.movie=m.code and i.mode=1');
			Add(format('where mg.code=%d and m.in_collection=1', [ReferenceCode]));
	        Add('order by m.title');
        end;
      end;
      RecordCount:=ExecuteSQL(sl.text);
      if RecordCount>0 then begin
        //movie:=format('<h1>Movies by genre %s</h1><ol>', [genre]);
        case reference of
			//video standard
			1: s:=format(GetLangStr(1134), [ProgramReference]);
        	//media format
        	2: s:=format(GetLangStr(1526), [ProgramReference]);
			// media type
			3: s := GetLangStr(3279) + ': ' + ProgramReference;
        	//aspect ratio
        	4: s:=format(GetLangStr(645), [ProgramReference]);
        	//resolution
        	5: s:=format(GetLangStr(633), [ProgramReference]);
        	//subtitles
        	6: s:=format(GetLangStr(634), [ProgramReference]);
        	//audio track
        	7: s:=format(GetLangStr(632), [ProgramReference]);
        	//genre
        	8: s:=format(GetLangStr(313), [ProgramReference]);
        	//country
        	9: s:=format(GetLangStr(314), [ProgramReference]);
        	//location
        	10: s:=format(GetLangStr(569), [ProgramReference]);
			//mpaa
			11: s:=GetLangStr(3277) + ': ' + ProgramReference;
			//studios
			12: s:=format(GetLangStr(1527), [ProgramReference]);
        	//custom 1-4
        	13: s:=GetLangStr(540)+': '+ProgramReference;
        	14: s:=GetLangStr(541)+': '+ProgramReference;
        	15: s:=GetLangStr(542)+': '+ProgramReference;
        	16: s:=GetLangStr(543)+': '+ProgramReference;
        	//custom list 1-2
        	17: s:=GetLangStr(544)+': '+ProgramReference;
        	18: s:=GetLangStr(545)+': '+ProgramReference;
			// video codec
			19: s := GetLangStr(3280) + ': ' + ProgramReference;
        	//disc label
        	20: s:=format(GetLangStr(1001), [ProgramReference]);
			//sequence
			22: s:=GetLangStr(3327)+ ': ' + ProgramReference;
			else
				s:='';
        end;
	all := ProcessMovieReference(sl, s, page);
	end; //if
  end;
  sl.Free;
  result:=all;

end;

function GetYear(YearCode: integer): string;
begin
	result:=GetYear2(YearCode, 1);
end;

//show movies by selected year
function GetYear2(YearCode, page: integer): string;
var
  sl: TStringList;
  all: string;
begin
	TempReference:=1971;
	TempReferenceCode:=YearCode;
	result:='';
	sl:=TStringList.Create;

	all:='';
  if YearCode>0 then begin
      with sl do begin
        Clear;
        Add('select m.title, m.code as code, m.year, m.in_collection, m.imdb_rating, m.rating, i.path, i.width, i.height');
        Add('from movies m');
		Add('left outer join images i on i.movie=m.code and i.mode=1');
        Add(format('where m.year=%d and m.in_collection=1', [YearCode]));
        Add('order by m.year desc, m.title');
      end;
	all := ProcessMovieReference(sl, format(GetLangStr(315), [YearCode]), page);
  end;
  sl.Free;
  result:=all;
end;

function GetMyRating(Rating: integer): string;
begin
	result := GetMyRating2(Rating, 1);
end;

//show movies by selected year
function GetMyRating2(Rating, page: integer): string;
var
  sl: TStringList;
  all: string;
  rating_s: string;
begin
	TempReference:=MY_RATING_REFERENCE;
	TempReferenceCode:=Rating;
	result:='';
	sl:=TStringList.Create;

  with sl do
  begin
    Clear;
    Add('select m.title, m.code as code, m.Rating, m.in_collection, m.imdb_rating, m.rating, i.path, i.width, i.height');
    Add('from movies m');
    Add('left outer join images i on i.movie=m.code and i.mode=1');
    Add(format('where m.Rating=%d and m.in_collection=1', [Rating]));
    Add('order by m.Rating desc, m.title');
  end;
  if (Rating > 0) then
    rating_s := IntToStr(rating)
  else
    rating_s := GetLangStr(3885);
  rating_s := '"' + rating_s + '"';
	all := ProcessMovieReference(sl, format(GetLangStr(3884), [rating_s]), page);
  sl.Free;
  result:=all;
end;

function GetCast(MovieCode: Integer): String;
var
	sl, PreviousCodes: TStringList;
	RecordCount, i, person_code, prev_code, rating, PageWidth, col, total_col: Integer;
	s, img, character, rate, BirthDate, FileName: String;
begin
	sl := TStringList.Create;
	PreviousCodes := TStringList.Create;
	s := '';
    with sl do begin
		Clear;
        Add('select p.code, p.name, p.rating, p.birth_date, c.name, i.path from data d');
        Add('inner join persons p on p.code=d.person');
		Add('left outer join images i on i.person=d.person');
		Add('left outer join characters c on c.person=p.code and c.movie=d.movie');
        Add(format('where d.movie=%d and d.mode=3', [MovieCode]));
        Add('order by d.sort_order, i.mode desc, i.sort_order');
    end;
    RecordCount:=ExecuteSQL(sl.text);
    if RecordCount>0 then begin
		PageWidth := GetHTMLWidth - 250;
		total_col := PageWidth div 300;
		s := s + '<tr style="background:url('+WhiteBarFile+') repeat-x;"><td>&nbsp;&nbsp;</td></tr><tr><td><table class="cast"><tr>';
        i:=1;
		prev_code := 0;
		col := 1;
        while i<=RecordCount do begin
		  person_code := GetIntegerField('p.code');
		  rating:=GetIntegerField('p.rating');
		  if rating>0 then
			rate:=format(' <img src="%sstar.gif" width=16 height=16 border=0 align="absmiddle">%d', [ImgPath, rating])
		  else
			rate:='';
		  BirthDate:=GetStringField('p.birth_date');
		  if BirthDate<>'' then
			BirthDate:=Date2Str(BirthDate);
		  if PreviousCodes.IndexOf(IntToStr(person_code)) < 0 then begin
			  PreviousCodes.Add(IntToStr(person_code));
			  //photo
			  s := s + '<td class="cast-name">';
			  FileName := GetImageFileName(GetStringField('i.path'), 'Thumbs', 'nophoto.gif', DefaultThumbWidth, 0);
			  s:=s+format('<div><div class="thumb-cover-border"><a href="person:%d"><img class="thumb-cover" src="%s"></a>', [person_code, FileName]);
			//name
			  s := s+format('</div><div class="thumb-text"><a href="person:%d"><big><b>%s</b></big></a>%s<br>', [person_code, GetStringField('p.name'), rate]);
			  
			  //birth date
//			  if BirthDate <> '' then
//				s := s + BirthDate + '<br>';
			  
			  //character
			  character:=GetStringField('c.name');
			  s := s + character + '</div></td>';
			  //detect how many columns to create
			  col := col + 1;
			  if col > total_col then begin
				s := s + '</tr><tr>';
				col := 1;
			  end;
			  prev_code := person_code;
		  end;
		  i:=i+1;
          GetNextRecord;
        end;
		s := s + '</tr>';
		s := s + '</table></td></tr>';
	end;
	sl.Free;
	PreviousCodes.Free;
	Result := s;
end;

{function GetMovie(MovieCode, season: integer; FullDesc: boolean): string;
begin
	result:=GetMovie3(MovieCode, season, FullDesc, false, false);
end;

//show movie's info
function GetMovie3(MovieCode, season: integer; FullDesc, FullComments, FullPersons: boolean): string;
begin
	result:=GetMovie4(MovieCode, season, FullDesc, FullComments, FullPersons, false);
end;

function GetMovie4(MovieCode, season: integer; FullDesc, FullComments, FullPersons, FullAwards: boolean): string;
begin
	result := GetMovie5(MovieCode, season, FullDesc, FullComments, FullPersons, FullAwards);
end;}


//14.03.13
function GenerateHTMLForDescriptionSearching(AFullDescription: string;
  ASearchDescription: string; AMaxLength: Integer = 350): string;
var
  StartPos: Integer;
  EndPos: Integer;
  SearchPos: Integer;
begin
  Result := '';
  if ((ASearchDescription <> '') and
      (AFullDescription <> '')) then
  begin
    SearchPos := Pos(LowerCase(ASearchDescription), LowerCase(AFullDescription));
    if (SearchPos > 0) then
    begin
      // calculate start pos
      StartPos := SearchPos - ((AMaxLength - Length(ASearchDescription)) div 2);
      if (StartPos <= 0) then
        StartPos := 1
      else
      begin
        // in other case search first space from StartPos position
        if (MyPos(' ', AFullDescription, StartPos) > 0) then
          StartPos := MyPos(' ', AFullDescription, StartPos) + 1;
      end;
      // find end pos of the text
      EndPos := StartPos + AMaxLength;
      if (EndPos > Length(AFullDescription)) then
        EndPos := Length(AFullDescription)
      else
      while ((Length(AFullDescription) > 0) and
             (AFullDescription[EndPos] <> ' ')) do
      begin
        Dec(EndPos);
      end;
      //
      Result := Copy(AFullDescription, StartPos, EndPos - StartPos);
      Result := StringReplaceIgnoreCase(Result, ASearchDescription,
        '<font style="background-color: yellow">' + ASearchDescription + '</font>');
      Result := Trim(StringReplaceIgnoreCase(Result, '<br>', ' '));
      if (StartPos <> 1) then
        Result := '...' + Result;
      if (EndPos <> Length(AFullDescription)) then
        Result := Result + '...';
    end;
  end;
  if (Result <> '') then
    Result := '<div style="margin:5;">"' + Result + '"</p>';
end;

function StringReplaceIgnoreCase(AText: string; AReplaceWhat: string; AReplaceTo: string): string;
var
  TextPos: integer;
begin
  Result := AText;
  AReplaceWhat := LowerCase(AReplaceWhat);
  TextPos := Pos(AReplaceWhat, LowerCase(Result));
  while (TextPos > 0) do
  begin
    Delete(Result, TextPos, Length(AReplaceWhat));
    Insert(AReplaceTo, Result, TextPos);
    TextPos := MyPos(AReplaceWhat, LowerCase(Result), TextPos + Length(AReplaceTo));
  end;
end;

//показ уменьшенной карточки фильма
function GetThumbMovie2(code, mode: integer; title, year: string; InCollection, rating: integer; AFullDescription: string = ''; ASearchDescription: string = ''): string;
var
  sl: TStringList;
  s, rate, FileName, genres, directors, actors, img, seasons: string;
  fl, showCoversInList, FullList, ThisChecked, ShowCurrent, ShowDiscNr: boolean;
  i, j, kol, dir, amount, RecordCount: integer;
	ThumbsPath, FileIn, FileOut, CheckMode: string;
	BigOpen, BigClose, SmallOpen, SmallClose: string;
	kinopoisk_rating, imdb_rating, current_rating, current_site, disc_number: String;
	imdb_rating_number, kinopoisk_rating_number, current_rating_number: double;
begin
	result:='';
	sl:=TStringList.Create;
	amount:=mode;
	s:='';
	ThumbsPath:=ImagesPath+Thumbs+'\';
	i := RegReadInteger('ShowCoversInList', 1);
	if i = 1 then
		showCoversInList := True
	else
		showCoversInList := False;
	i := RegReadInteger('MinimaList', 0);
	if i = 1 then
		FullList := False
	else
		FullList := True;
	if (RegReadInteger('ShowDiscNrInList', 0) = 1) then
		ShowDiscNr := True
	else
		ShowDiscNr := False;
    fl:=false;
    genres:='';
    directors:='';
    actors:='';
	ThisChecked := False;
	imdb_rating := '';
	kinopoisk_rating := '';
	current_rating := '';
	current_site := '';
	imdb_rating_number := 0;
	kinopoisk_rating_number := 0;
	current_rating_number := 0;
	disc_number := '';
	
	if RegReadInteger('ShowCurrentRatingInList', 1) = 1 then
		ShowCurrent := True
	else
		ShowCurrent := False;

    //получаем дополнительную информацию о фильме, если он из коллекции
    if (InCollection=1) then begin
		if showCoversInList then begin
			//обложка
			with sl do begin
				Clear;
				Add('select path from images');
				Add(format('where movie=%d and mode=1', [code]));
				Add('order by sort_order');
			end;
			RecordCount:=ExecuteSQL(sl.text);
			if RecordCount>0 then begin
				FileIn:=ImagesPath+GetStringField('path');
				FileName:=ThumbsPath+GetStringField('path');

				if MyFileExists(FileIn) then begin
					if not MyFileExists(FileName) then begin
						ConvertThumb3(FileIn, FileName, Thumbs, RegReadInteger('ThumbWidth', DefaultThumbWidth), 0, False);
					end;
					if not MyFileExists(FileName) then 
						FileName:=FileIn;
				end
				else
					FileName:=FileIn;
				if MyFileExists(FileName) then
					fl:=true;
			end;
			if not fl then begin
				FileIn:=ImgPath+'no-cover.gif';
				FileName := ThumbsPath+'no-cover.gif';
				if MyFileExists(FileIn) then begin
					if not MyFileExists(FileName) then
						ConvertThumb3(FileIn, FileName, Thumbs, RegReadInteger('ThumbWidth', DefaultThumbWidth), 0, False);
					if not MyFileExists(FileName) then
						FileName := FileIn;
				end;
				fl:=true;
			end;
		end;

		if ShowCurrent then begin
			current_site := RegReadString('MovieScript', '');
			i := Pos(' (', current_site);
			if i>0 then
				delete(current_site, i, length(current_site)-i+1);
			if (current_site <> '') and (current_site <> 'kinopoisk') and (current_site <> 'imdb') then begin
				with sl do begin
					Clear;
					Add('select rating from movies_codes');
					Add(format('where movie=%d and script=''%s''', [code, current_site]));
				end;
				RecordCount := ExecuteSQL(sl.text);
				if RecordCount > 0 then begin
					current_rating_number := GetFloatField('rating');
					if current_rating_number > 0 then
						current_rating := '<NOBR>' + current_site + ': ' + FloatToStr(current_rating_number) + '</NOBR>; ';
				end;
			end;
		end;
		
		if (RegReadInteger('ShowIMDBRatingInList', 0) = 1) or GroupOperation or ((current_site = 'imdb') and ShowCurrent) then begin
			with sl do begin
				Clear;
				Add('select checked, imdb_rating from movies');
				Add(format('where code=%d', [code]));
			end;
			RecordCount:=ExecuteSQL(sl.text);
			if RecordCount > 0 then begin
				if (GetIntegerField('checked') = 1) then
					ThisChecked := True;
				imdb_rating_number := GetFloatField('imdb_rating');
				if (imdb_rating_number > 0) then
					imdb_rating := Format('<NOBR><img align="absmiddle" src="%simdb-ico.png"> ', [PicturesPath]) + FloatToStr(imdb_rating_number) + '</NOBR>; ';
			end;
		end;
		
		if (RegReadInteger('ShowKinopoiskRatingInList', 0) = 1) or ((current_site = 'kinopoisk') and ShowCurrent) then begin
			with sl do begin
				Clear;
				Add('select rating from movies_codes');
				Add(format('where movie=%d and script=''kinopoisk''', [code]));
			end;
			RecordCount := ExecuteSQL(sl.text);
			if RecordCount > 0 then begin
				kinopoisk_rating_number := GetFloatField('rating');
				if (kinopoisk_rating_number > 0) then
					kinopoisk_rating := Format('<NOBR><img align="absmiddle" src="%skinopoisk-ico.png"> ', [PicturesPath]) + Format('%.1f', [kinopoisk_rating_number]) + '</NOBR>; ';
			end;
		end;
		
		//disc number (only first edition)
		if ShowDiscNr then begin
			with sl do begin
				Clear;
				Add('select disc_nom from editions');
				Add(format('where movie=%d', [code]));
				Add('order by sort_order');
			end;
			RecordCount := ExecuteSQL(sl.text);
			if RecordCount > 0 then begin
				s := GetStringField('disc_nom');
				if (s <> '') and (s <> '0') then
					disc_number := Format('<NOBR>%s: %s</NOBR>', [GetLangStr(391), s]);
			end;
		end;
		
     	if amount>0 then begin 
			//жанры
			with sl do begin
				Clear;
				Add('select m.code, m.name from movies_manuals mm');
				Add('join manuals m on m.code=mm.ref_code');
				Add(format('where mm.movie=%d and m.reference=8', [code]));
			end;
			RecordCount:=ExecuteSQL(sl.text);
			for j:=1 to RecordCount do begin
				genres:=genres+format('<a href="genre:%d">%s</a>, ', [GetIntegerField('m.code'), GetStringField('m.name')]);
				GetNextRecord;
			end;
			if genres<>'' then
				genres:=copy(genres, 1, length(genres)-2);

			//режиссеры и актеры
			with sl do begin
				Clear;
				Add('select distinct p.code, p.name, p.in_collection, d.mode from data d');
				Add('inner join persons p on p.code=d.person');
				Add(format('where d.movie=%d and d.mode in (1,3)', [code]));
				//Add('and d.sort_order<10');//27.07.07
				Add('order by d.mode, d.sort_order');
			end;
			RecordCount:=ExecuteSQL(sl.text);
			i:=0;
			j:=0;
			dir:=0;
			while (i<RecordCount) and (j<amount) do begin
				if GetIntegerField('p.in_collection')=1 then
					img:=format('<img src="%sperson.gif" align="absmiddle">', [ImgPath])
				else
					img:='';
				if GetIntegerField('d.mode')=1 then begin
					if dir<=3 then begin
						directors:=directors+img+format('<a href="person:%d">%s</a>, ', [GetIntegerField('p.code'), GetStringField('p.name')]);
						dir:=dir+1;
					end;
				end
				else begin
					actors:=actors+img+format('<a href="person:%d">%s</a>, ', [GetIntegerField('p.code'), GetStringField('p.name'), j]);
					j:=j+1;
				end;
				i:=i+1;
				GetNextRecord;
			end;
		end;
		if directors<>'' then
			directors:=copy(directors, 1, length(directors)-2);

		if actors<>'' then
			actors:=copy(actors, 1, length(actors)-2);
    // Fade 16.08.2011 - For Search Thumbs do not add CheckBox picture
		if ((mode <> 7) and(GroupOperation)) then begin
			if ThisChecked then
				CheckMode:=format('<a href="group_check_off:%d"><img src="%scheck.gif" align="absmiddle" border="0"></a>',  [code, PicturesPath])
			else
				CheckMode:=format('<a href="group_check_on:%d"><img src="%scheckout.gif" align="absmiddle" border="0"></a>',  [code, PicturesPath]);
		end
		else
			CheckMode:='';
      
		if year<>'' then
			year:=format(' (%s)', [year]);

		if rating>0 then
			rate:=format(' <img src="%sstar.gif" width=16 height=16 border=0 align="absmiddle">%d', [ImgPath, rating])
		else
			rate:='';
		BigOpen:='';
		BigClose:='';
		SmallOpen:='<small>';
		SmallClose:='</small>';
		if GetCutePreview or (mode=7) then begin
			BigOpen:='<big>';
			BigClose:='</big>';
			SmallOpen:='';
			SmallClose:='';
		end;
		if showCoversInList then begin
			s:=format('<div><div class="thumb-cover-border"><a href="movie:%d"><img class="thumb-cover"  style="width: %dpx;" src="%s"', [code, RegReadInteger('ThumbWidth', DefaultThumbWidth), FileName]);
			if not GetCutePreview and (mode<>7) then
				s:=s+' width="50" border="0" align="left"';
			s:=s+'></a></div>';
		end;
		s := s+format('<div class="thumb-text">%s<a href="movie:%d">%s<b>%s</b>%s</a>%s%s%s<br>', [CheckMode, code, BigOpen, title, BigClose, SmallOpen, year, rate]);
	
		//site ratings
		if FullList and ((imdb_rating <> '') or (kinopoisk_rating <> '') or (current_rating <> '')) then begin
			s := s + current_rating + imdb_rating + kinopoisk_rating;
			s := copy(s, 1, length(s)-2) + '<br>';
		end;
		
		//disc number
		if (disc_number <> '') then
			s := s + disc_number + '<br>';
		
		//Genres
		if (genres<>'') and FullList then begin
			if mode<>1 then
				genres:=GetLangStr(179)+': '+genres;
			s:=s+genres+'<br>';
		end;
		//Directors
		if FullList and (mode<>1) and (directors<>'') then
			s:=s+GetLangStr(181)+': '+directors+'<br>';
		//Actors
		if FullList and (actors<>'') then begin
			if mode<>1 then
				actors:=GetLangStr(164)+': '+actors;
			s:=s+actors+'<br>';
		end;
		s := s+SmallClose;
    end
    else begin
		if year<>'' then
			year:=format(' (%s)', [year]);
		s:=format('<a href="movie:%d"><b>%s</b>%s</a>', [code, title, year]);
    end;

	//seasons
	seasons:='';
	with sl do begin
		Clear;
		Add('select distinct season from episodes');
		Add(format('where movie=%d', [code]));
		Add('order by season');
	end;
	RecordCount:=ExecuteSQL(sl.text);
	for i:=1 to RecordCount do begin
		seasons:=seasons+format('<a href="userref:114,%d;%d">%d</a> ', [code, GetIntegerField('season'), GetIntegerField('season')]);
		GetNextRecord;
	end;
	if FullList and (seasons<>'') then begin
		seasons:=GetLangStr(517)+' '+seasons;
		delete(seasons, length(seasons), 1);
		s:=s+seasons;
	end;
	
	s := s + GenerateHTMLForDescriptionSearching(AFullDescription, ASearchDescription);
	s := s+'</div></div>';
	if mode=7 then
		s:='<tr><td class="thumb">'+s+'</td></tr>';
	result:=s;
	sl.Free;
end;

function GetThumbMovie(code, mode: integer; title, year: string; InCollection: integer): string;
begin
	result:=GetThumbMovie2(code, mode, title, year, InCollection, 0);
end;

function GetThumbMovie3(code, mode: integer; title: string): string;
var
  sl: TStringList;
  s, rate, FileName, genres, directors, actors, img, seasons: string;
  fl, CutThumb: boolean;
  i, j, kol, dir, amount, RecordCount, CoverWidth, CoverHeight: integer;
	ThumbsPath, FileIn, FileOut, CheckMode: string;
begin
	result:='';
  sl:=TStringList.Create;
  amount:=mode;
  {
  if mode=1 then
    amount:=3
  else
    amount:=7;
	}
  s:='';

  ThumbsPath:=ImagesPath+'Thumbs2\';

  fl:=false;
  genres:='';
  directors:='';
  actors:='';


    //обложка
    with sl do begin
      Clear;
      Add('select * from images');
      Add(format('where movie=%d and mode=1', [code]));
	  Add('order by sort_order');
    end;
    RecordCount:=ExecuteSQL(sl.text);

	  CoverWidth := RegReadInteger('ThCoverWidth', DefaultMultiCoverWidth);
	  CoverHeight := RegReadInteger('ThCoverHeight', DefaultMultiCoverHeight);
  
	  if (CoverWidth <= 0) and (CoverHeight <= 0) then begin
		  CoverWidth := DefaultMultiCoverWidth;
		  CoverHeight := DefaultMultiCoverHeight;
	  end;

    if RecordCount>0 then
    begin
		  i := RegReadInteger('CutThumb', 1);
		  if i = 1 then
				CutThumb := True
		  else
				CutThumb := False;
      FileIn:=ImagesPath+GetStringField('path');
      FileName:=ThumbsPath+GetStringField('path');
      if MyFileExists(FileName) then
        fl:=true
      else if MyFileExists(FileIn) then
        ConvertThumb2(FileIn, FileName, CoverWidth, CoverHeight, CutThumb);
      if MyFileExists(FileName) then
        fl:=true;
    end;
    if not fl then
    begin
      FileIn:=ImgPath+'no-cover.gif';
      FileName:=ThumbsPath+'no-cover.jpg';
      //ShowMessage('FileName='+FileName);
      //ShowMessage('FileIn='+FileIn);
      if ((not MyFileExists(FileName)) and
          (MyFileExists(FileIn))) then
      begin
        ConvertThumb2(FileIn, FileName, CoverWidth, CoverHeight, CutThumb);
      end;
      fl:=true;
    end;

    if GroupOperation then
    begin

      with sl do begin
        Clear;
        Add('select checked from movies');
        Add(format('where code=%d', [code]));
      end;
      RecordCount:=ExecuteSQL(sl.text);
      if (RecordCount>0) and (GetIntegerField('checked')=1) then
        CheckMode:=format('<a href="group_check_off:%d"><img src="%scheck.gif" align="absmiddle" border="0"></a>',  [code, PicturesPath])
      else
        CheckMode:=format('<a href="group_check_on:%d"><img src="%scheckout.gif" align="absmiddle" border="0"></a>',  [code, PicturesPath]);
    end
    else
      CheckMode:='';

    s:=format('<table><tr><td align="center"><div class="thumb-big-cover-border"><a href="movie:%d"><img class="thumb-big-cover" src="%s"></a></div></td></tr><tr><td>', [code, FileName])+CheckMode+format('<a href="movie:%d"><b>%s</b></a></td></tr></table>', [code, title]);


	if mode=7 then
	  s:='<tr><td>'+s+'</td></tr>';

	if amount=3 then
		s:='<div class="preview">'+s+'</div>';
  result:=s;
  sl.Free;
end;


//показ уменьшенной карточки человека
function GetThumbPerson(code, mode: integer): string;
var
  sl: TStringList;
  s, rate, FileName, img, PersonName, BirthDate, DeathDate: string;
  fl, PersonStatsInCollection, showCoversInList, FullList: boolean;
  i, j, kol, amount, RecordCount, DirectorCount, WriterCount, ActorCount, ComposerCount, years: integer;
  InCollection, rating: integer;
  ThumbsPath, FileIn, FileOut: string;
  BigOpen, BigClose, SmallOpen, SmallClose: string;
  CheckMode: string;
begin
	result:='';
  sl:=TStringList.Create;

  if mode=1 then
    amount:=3
  else
    amount:=7;
  s:='';
  
	i := RegReadInteger('ShowCoversInList', 1);
	if i = 1 then
		showCoversInList := True
	else
		showCoversInList := False;
	i := RegReadInteger('MinimaList', 0);
	if i = 1 then
		FullList := False
	else
		FullList := True;

  ThumbsPath:=ImagesPath+Thumbs+'\';

    fl:=false;

		with sl do begin
			Clear;
			Add('select p.code, p.name, p.in_collection, p.birth_date, p.death_date, p.rating, i.path from persons p');
			Add('left outer join images i on i.person=p.code and i.mode=6');
			Add(format('where p.code=%d', [code]));
			Add('order by i.sort_order');
		end;
		RecordCount:=ExecuteSQL(sl.text);
		PersonName:=GetStringField('p.name');
		InCollection:=GetIntegerField('p.in_collection');
		rating:=GetIntegerField('p.rating');

		if rating>0 then
			rate:=format(' <img src="%sstar.gif" width=16 height=16 border=0 align="absmiddle">%d', [ImgPath, rating])
		else
			rate:='';

    BirthDate:=GetStringField('p.birth_date');
    if BirthDate<>'' then
    	BirthDate:=Date2Str(BirthDate);
    DeathDate:=GetStringField('p.death_date');
    if DeathDate<>'' then
    	DeathDate:=Date2Str(DeathDate);

    //получаем дополнительную информацию о фильме, если он из коллекции
    if InCollection=1 then begin
      //обложка
	  if ShowCoversInList then begin
		  if GetStringField('i.path')<>'' then begin
	//      	FileName:=ImagesPath+GetStringField('i.path');
		 
			  FileIn:=ImagesPath+GetStringField('i.path');
			FileName:=ThumbsPath+GetStringField('i.path');
			if MyFileExists(FileIn) then begin
				if not MyFileExists(FileName) then begin
					//ShowMessage('Convert '+FileIn+' to '+FileName);
							ConvertThumb3(FileIn, FileName, Thumbs, RegReadInteger('ThumbWidth', DefaultThumbWidth), 0, False);
						end;
				if not MyFileExists(FileName) then 
					FileName:=FileIn;
			end
			else
				FileName:=FileIn;

			if MyFileExists(FileName) then
			  fl:=true;
		  end;
		  if not fl then begin
			FileIn:=ImgPath+'nophoto.gif';
			FileName := ThumbsPath + 'nophoto.gif';
			ConvertThumb3(FileIn, FileName, Thumbs, RegReadInteger('ThumbWidth', DefaultThumbWidth), 0, False);
			fl:=true;
		  end;
	  end;
      if RegReadInteger('PersonStatsInCollection', 0) = 1 then
		PersonStatsInCollection := True
	  else
		PersonStatsInCollection := False;
	if FullList then begin
      //кол-во фильмов, как актер
	  with sl do begin
        Clear;
        Add('select distinct d.movie as amount from data d');
		Add('join movies m on d.movie=m.code');
        Add(format('where d.person=%d and d.mode=3', [code]));
		if PersonStatsInCollection then
			Add('and m.in_collection=1');
      end;
      ActorCount:=ExecuteSQL(sl.text);
	  //number of movies as director
	  with sl do begin
        Clear;
        Add('select distinct d.movie as amount from data d');
		Add('join movies m on d.movie=m.code');
        Add(format('where d.person=%d and d.mode=1', [code]));
		if PersonStatsInCollection then
			Add('and m.in_collection=1');
      end;
      DirectorCount:=ExecuteSQL(sl.text);
	  //number of movies as writer
	  with sl do begin
        Clear;
        Add('select distinct d.movie as amount from data d');
		Add('join movies m on d.movie=m.code');
        Add(format('where d.person=%d and d.mode=2', [code]));
		if PersonStatsInCollection then
			Add('and m.in_collection=1');
      end;
      WriterCount:=ExecuteSQL(sl.text);
	  //number of movies as composer
	  with sl do begin
        Clear;
        Add('select distinct d.movie as amount from data d');
		Add('join movies m on d.movie=m.code');
        Add(format('where d.person=%d and d.mode=4', [code]));
		if PersonStatsInCollection then
			Add('and m.in_collection=1');
      end;
      ComposerCount:=ExecuteSQL(sl.text);
	end;
    // Fade 16.08.2011 - For Search Thumbs do not add CheckBox picture
    if ((Mode <> 2) and
        (GroupOperation)) then
    begin

      with sl do begin
        Clear;
        Add('select checked from persons');
        Add(format('where code=%d', [code]));
      end;
      RecordCount:=ExecuteSQL(sl.text);
      if (RecordCount>0) and (GetIntegerField('checked')=1) then
        CheckMode:=format('<a href="group_person_check_off:%d"><img src="%scheck.gif" align="absmiddle" border="0"></a>',  [code, PicturesPath])
      else
        CheckMode:=format('<a href="group_person_check_on:%d"><img src="%scheckout.gif" align="absmiddle" border="0"></a>',  [code, PicturesPath]);
    end
    else
      CheckMode:='';


	BigOpen:='';
	BigClose:='';
	SmallOpen:='<small>';
	SmallClose:='</small>';
	if GetCutePreview or (mode=7) then begin
		BigOpen:='<big>';
		BigClose:='</big>';
		SmallOpen:='';
		SmallClose:='';
	end;
	if showCoversInList then begin
      s:=format('<div><div class="thumb-cover-border"><a href="person:%d"><img class="thumb-cover" style="width: %dpx;" src="%s"', [code, RegReadInteger('ThumbWidth', DefaultThumbWidth), FileName]);
	  if not GetCutePreview and (mode<>7) then
		s:=s+' width=50 border="0" align=left';
    // fade group operations
	  s := s + '></a></div>';
	end;
	  s:=s+format('<div class="thumb-text">' + CheckMode + '<a href="person:%d">%s<b>%s</b>%s</a>%s%s<br>', [code, BigOpen, PersonName, BigClose, SmallOpen, rate]);
      if BirthDate<>'' then begin
      	//ShowMessage(BirthDate);
      	s:=s+BirthDate;
		if DeathDate <> '' then
			s := s + ' - ' + DeathDate;
      	s:=s+'<br>';
	  end;
	if FullList then begin
	  if ActorCount > 0 then
		s:=s+format('%s: %d; ', [GetLangStr(1449), ActorCount]);
	  if DirectorCount>0 then
		s:=s+format('%s: %d; ', [GetLangStr(1447), DirectorCount]);
	  if WriterCount>0 then
		s:=s+format('%s: %d; ', [GetLangStr(1448), WriterCount]);
	  if ComposerCount>0 then
		s:=s+format('%s: %d; ', [GetLangStr(1450), ComposerCount]);
	  if (ActorCount>0) or (DirectorCount>0) or (WriterCount>0) or (ComposerCount>0) then
		delete(s, length(s) - 1, 2);
	end;

      s:=s+SmallClose;
    end
    else begin
      s:=format('<a href="person:%d"><b>%s</b></a>', [code, PersonName]);
    end;

  s := s+'</div></div>';
  s:='<tr><td class="thumb">'+s+'</td></tr>';
  result:=s;
  sl.Free;
end;

function GetFileSize(AFilePath: string): Integer;
var
  FileStream: TFileStream;
begin
  Result := 0;
  if (MyFileExists(AFilePath)) then
  begin
    FileStream := TFileStream.Create(AFilePath, fmOpenRead or fmShareDenyNone);
    try
      Result := FileStream.Size;
    finally
      FileStream.Free();
    end;
  end;
end;

// Fade. Add fix for files whose size is more than 1 Мб
function NeedToCreateThumbFile(AThumbFilePath: string): Boolean;
const
  // max file size
  MAX_FILE_SIZE = 1 * 1024 * 1024;
begin
  Result := True;
  if (MyFileExists(AThumbFilePath)) then
  begin
    Result := Result and (GetFileSize(AThumbFilePath) >= MAX_FILE_SIZE);
    if (Result) then
      DeleteFile(AThumbFilePath);
  end;
end;

function GetThumbPerson3(code, mode: integer): string;
var
  sl: TStringList;
  CheckMode: string;
  s, rate, FileName, img, PersonName, BirthDate: string;
  fl, CutThumb: boolean;
  i, j, kol, amount, RecordCount, DirectorCount, WriterCount, ActorCount, years: integer;
  InCollection, rating, PhotoWidth, PhotoHeight: integer;
  ThumbsPath, FileIn, FileOut: string;
begin
	result:='';
  sl:=TStringList.Create;

  if mode=1 then
    amount:=3
  else
    amount:=7;
  s:='';

  ThumbsPath:=ImagesPath+'Thumbs2\';

    fl:=false;

		with sl do begin
			Clear;
			Add('select p.code, p.name, p.in_collection, p.birth_date, p.rating, i.path from persons p');
			Add('left outer join images i on i.person=p.code and i.mode=6');
			Add(format('where p.code=%d', [code]));
			Add('order by i.sort_order');
		end;
		RecordCount:=ExecuteSQL(sl.text);
		PersonName:=GetStringField('p.name');

		InCollection:=GetIntegerField('p.in_collection');

    // Calculate Photo neccessary dimensions
	  PhotoWidth := RegReadInteger('ThPhotoWidth', DefaultMultiCoverWidth);
	  PhotoHeight := RegReadInteger('ThPhotoHeight', DefaultMultiCoverHeight);
	  if (PhotoWidth <= 0) and (PhotoHeight <= 0) then begin
		  PhotoWidth := DefaultMultiCoverWidth;
		  PhotoHeight := DefaultMultiCoverHeight;
	  end;

    //получаем дополнительную информацию о фильме, если он из коллекции
    if InCollection=1 then
    begin

		if GetStringField('i.path')<>'' then
		begin
			i := RegReadInteger('CutPhotoThumb', 1);
				if i = 1 then
					CutThumb := True
				else
					CutThumb := False;
//      	FileName:=ImagesPath+GetStringField('i.path');
        FileIn:=ImagesPath+GetStringField('i.path');
        FileName:=ThumbsPath+GetStringField('i.path');
        if MyFileExists(FileName) then
          fl:=true
        else if MyFileExists(FileIn) then
          ConvertThumb2(FileIn, FileName, PhotoWidth, PhotoHeight, CutThumb);
        if MyFileExists(FileName) then
          fl:=true;
		end;
	end;

    if GroupOperation then
    begin

      with sl do begin
        Clear;
        Add('select checked from persons');
        Add(format('where code=%d', [code]));
      end;
      RecordCount:=ExecuteSQL(sl.text);
      if (RecordCount>0) and (GetIntegerField('checked')=1) then
        CheckMode:=format('<a href="group_person_check_off:%d"><img src="%scheck.gif" align="absmiddle" border="0"></a>',  [code, PicturesPath])
      else
        CheckMode:=format('<a href="group_person_check_on:%d"><img src="%scheckout.gif" align="absmiddle" border="0"></a>',  [code, PicturesPath]);
    end
    else
      CheckMode:='';

      if not fl then begin
        FileIn:=ImgPath+'nophoto.gif';
        //FileName:=ThumbsPath+'no-cover.jpeg';
        FileName:=ThumbsPath+'no-photo.jpeg';
        if ((NeedToCreateThumbFile(FileName)) and
            (MyFileExists(FileIn))) then
        begin
          ConvertThumb2(FileIn, FileName, PhotoWidth, PhotoHeight, CutThumb);
        end;
        fl:=true;
      end;

      s:=format('<table><tr><td align="center"><div class="thumb-big-cover-border"><a href="person:%d"><img class="thumb-big-cover" src="%s"></a></div></td></tr><tr><td>' + CheckMode + '<a href="person:%d"><b>%s</b></a></td></tr></table>', [code, FileName, code, PersonName]);
    //else
      //s:=format(CheckMode + '<a href="person:%d"><b>%s</b></a>', [code, PersonName]);
  //s:='<tr><td>'+s+'</td></tr>';
  result:=s;
  sl.Free;
end;

//показ домашней страницы
function GetHome: string;
begin
	result:=GetHomeModern(HomeMovieTab, HomePersonTab);
end;

//показ домашней страницы

function GetSearchTop(RecMin, RecMax, RecCount: integer): string;
begin
	result:=GetPatternTop + '<p class="title">'+GetLangStr(1293)+format(': %d-%d %s %d', [RecMin, RecMax, GetLangStr(1461), RecCount])+'</p></td>'+ClosePatternTop+'<tr><td>';
end;

function GetSearchBottom(RecMin, RecMax, RecCount: integer): string;
var
	s: string;
	RecPage, i, kol: integer;
begin
	//s:=format('Results from %d to %d. Total records %d', [RecMin, RecMax, RecCount]);
	s:='';
	RecPage:=GetNumberSearchResults;
	if RecPage>0 then begin
		kol:=RecCount div RecPage;
		if kol*RecPage<>RecCount then
			kol:=kol+1;
		s:=s+'<tr><td><center><table class="navi"><td class="navi-border">'+format('<img src="%snavi-left.gif"></td><td style="background:url(%s) repeat-x;"><p>', [ImgPath, WhiteBarFile]);
		for i:=1 to kol do begin
			if (RecMin-1) div RecPage=i-1 then
				s:=s+format('<a href="search:%d-%d"><b>%d</b></a> ', [(i-1)*RecPage+1, i*RecPage, i])
			else
				s:=s+format('<a href="search:%d-%d">%d</a> ', [(i-1)*RecPage+1, i*RecPage, i]);
		end;
		s:=s+format('</p></td><td class="navi-border"><img src="%snavi-right.gif"></td></table></center></td></tr>', [ImgPath]);
		
	end;
	result:='</td></tr>' + s + GetPatternBottom;
end;

//remove all thumbs files
procedure DeleteThumbs(FileName: string);
begin
	DeleteFile(ImagesPath+'Thumbs\'+FileName);
	DeleteFile(ImagesPath+'Thumbs2\'+FileName);
	DeleteFile(ImagesPath+'ThumbsCovers\'+FileName);
	DeleteFile(ImagesPath+'ThumbsHomeMovies\'+FileName);
	DeleteFile(ImagesPath+'ThumbsMainPhoto\'+FileName);
	DeleteFile(ImagesPath+'ThumbsMoviePhotos\'+FileName);
	DeleteFile(ImagesPath+'ThumbsPersonMovies\'+FileName);
	DeleteFile(ImagesPath+'ThumbsPhotos\'+FileName);
	DeleteFile(ImagesPath+'ThumbsScreenshots\'+FileName);
end;

begin
	ImgPath := PicturesPath + 'Themes\Modern\';
	WhiteBarFile := ImgPath + 'white-bar.gif';
	WhiteBarFile := ReplaceStr(WhiteBarFile, '(', '%28');
	WhiteBarFile := ReplaceStr(WhiteBarFile, ')', '%29');
	WhiteBarFile := ReplaceStr(WhiteBarFile, ' ', '%20');
	BackgroundMovies := ImgPath + 'background-movies.gif';
	BackgroundMovies := ReplaceStr(BackgroundMovies, '(', '%28');
	BackgroundMovies := ReplaceStr(BackgroundMovies, ')', '%29');
	BackgroundMovies := ReplaceStr(BackgroundMovies, ' ', '%20');
	BackgroundPeople := ImgPath + 'background-people.gif';
	BackgroundPeople := ReplaceStr(BackgroundPeople, '(', '%28');
	BackgroundPeople := ReplaceStr(BackgroundPeople, ')', '%29');
	BackgroundPeople := ReplaceStr(BackgroundPeople, ' ', '%20');
	ActiveTab := 1;
	PersonActiveTab := 1;
  // 22.04.2011 - default sizes for multi image showing
  MultiShowRowHeight := RegReadInteger('ThumbCellHeight', DefaultMultiCellHeight);
  MultiShowImageWidth := RegReadInteger('ThumbCellWidth', DefaultMultiCellWidth);
  MiltiShowDistanceBetweenCovers := 12;  
  SetHintWindowSize(290, 130);
	HomeMovieTab := 1;
	HomePersonTab := 1;

	DeleteFile(ImagesPath+'Thumbs2\no-cover.jpg');
end.
