program breeze_program;

uses 'breeze_program_variables.pas', 'breeze_program_part1.pas', 'breeze_program_part2.pas', 'breeze_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: 135 - awards

const                 
	script_name='Breeze';
	language='';
	version=31;
	author='movienizer.com';
	
function GetTab(Active: Boolean; TabName, Link: String; First: Boolean=False): String;
var
	s: String;
begin
	s := '';
	if Active then begin
		s := '<div class="inactive-tabs" style="background-image: url(' + GetProperPath(ImgPath + 'active-tab-button.gif') + '); border-left: 1px solid #387fc1;' + Format(' font-size: %dpt;', [BasicFontSize + NormalModifier]) + '">' + TabName + '</div>';
	end
	else begin
		s := '<div class="inactive-tabs" style="' + Format('font-size: %dpt;', [BasicFontSize + NormalModifier]);
		if First then
			s := s + ' border-left: 1px solid #387fc1;';
		s := s + '"><a class="pic" href="' + Link + '">' + TabName + '</a></div>';
	end;
	Result := s;
end;

function GetTextTab(Active: Boolean; TabName, Link: String): String;
var
	s: String;
begin
	s := '';
	if Active then begin
		s := ' | ' + TabName;
	end
	else
		s := ' | ' + '<a href="' + Link + '">' + TabName + '</a>';
	Result := s;
end;
	
function GetMovieTabs(MovieCode, SeasonNr, SeasonCnt: Integer; Awards, Shots, Params, Posters, Trailers, Desc, Connections: Boolean; AdditionalSpace: Integer = 0): String;
var
	s, media_format, prev_media_format, prefix: String;
	i, k, my_tabs, PageWidth, SeasonTabs, PageTabs, RecordCount: Integer;
	sl: TStringList;
begin
	RemainingTabs := '';
	PageWidth := GetHTMLWidth - LeftColumnWidth - IconSpace;
	SeasonTabs := PageWidth div SeasonTabWidth;
	PageTabs := PageWidth div TabWidth;
	s := '';
	
	s := '<div style="margin-left: 200px; color: white; vertical-align: bottom; font-weight: bold; line-height: 46px;">';

	//general info tab
	s := s + GetTab(ActiveTab = 1, GetLangStr(161), Format('userref:%d,%d', [109, MovieCode]), True);
	PageTabs := PageTabs - 1;
	
	//screenshots	
	if (Shots) and (RegReadInteger('ShowShotTab', 1) = 1) then begin
		if (PageTabs > 0) then begin
			PageTabs := PageTabs - 1;
			s := s + GetTab(ActiveTab = 2, GetLangStr(1429), Format('userref:%d,%d', [110, MovieCode]));
		end
		else
			RemainingTabs := RemainingTabs + GetTextTab(ActiveTab = 2, GetLangStr(1429), Format('userref:%d,%d', [110, MovieCode]));
	end;
	//posters
	if (Posters) and (RegReadInteger('ShowPosterTab', 1) = 1) then begin
		if (PageTabs > 0) then begin
			PageTabs := PageTabs - 1;
			s := s + GetTab(ActiveTab = 7, GetLangStr(1425), Format('userref:%d,%d', [115, MovieCode]));
		end
		else
			RemainingTabs := RemainingTabs + GetTextTab(ActiveTab = 7, GetLangStr(1425), Format('userref:%d,%d', [115, MovieCode]));
	end;
	//trailers
	if (Trailers) and (RegReadInteger('ShowTrailerTab', 1) = 1) then begin
		if (PageTabs > 0) then begin
			PageTabs := PageTabs - 1;
			s := s + GetTab(ActiveTab = 9, GetLangStr(1458), Format('userref:%d,%d', [117, MovieCode]));
		end
		else
			RemainingTabs := RemainingTabs + GetTextTab(ActiveTab = 9, GetLangStr(1458), Format('userref:%d,%d', [117, MovieCode]));
	end;
	
	//awards
	if (Awards) and (RegReadInteger('ShowAwardsTab', 1) = 1) then begin
		if PageTabs > 0 then begin
			PageTabs := PageTabs - 1;
			s := s + GetTab(ActiveTab = 3, GetLangStr(574), Format('userref:%d,%d', [111, MovieCode]));
		end
		else
			RemainingTabs := RemainingTabs + GetTextTab(ActiveTab = 3, GetLangStr(574), Format('userref:%d,%d', [111, MovieCode]));
	end;
	
	//actors
	if (RegReadInteger('ShowActorTab', 1) = 1) then begin
		if (PageTabs > 0) then begin
			PageTabs := PageTabs - 1;
			s := s + GetTab(ActiveTab = 4, GetLangStr(68), Format('userref:%d,%d', [112, MovieCode]));
		end
		else
			RemainingTabs := RemainingTabs + GetTextTab(ActiveTab = 4, GetLangStr(68), Format('userref:%d,%d', [112, MovieCode]));
	end;
	//parameters
	if (Params) and (RegReadInteger('ShowParameterTab', 1) = 1) then begin
		if PageTabs > 0 then begin
			PageTabs := PageTabs - 1;
			s := s + GetTab(ActiveTab = 5, GetLangStr(1254), Format('userref:%d,%d', [113, MovieCode]));
		end
		else
			RemainingTabs := RemainingTabs + GetTextTab(ActiveTab = 5, GetLangStr(1254), Format('userref:%d,%d', [113, MovieCode]));
	end;
	
	//description
	if (Desc) and (RegReadInteger('ShowDescriptionTab', 1) = 1) then begin
		if PageTabs > 0 then begin
			PageTabs := PageTabs - 1;
			s := s + GetTab(ActiveTab = 10, GetLangStr(162), Format('userref:%d,%d', [118, MovieCode]));
		end
		else
			RemainingTabs := RemainingTabs + GetTextTab(ActiveTab = 10, GetLangStr(162), Format('userref:%d,%d', [118, MovieCode]));
	end;
	
	//connections
	if Connections and (RegReadInteger('ShowConnectionsTab', 1) = 1) then begin
		if PageTabs > 0 then begin
			PageTabs := PageTabs - 1;
			s := s + GetTab(ActiveTab = 11, GetLangStr(4155), Format('userref:%d,%d', [119, MovieCode]));
		end
		else
			RemainingTabs := RemainingTabs + GetTextTab(ActiveTab = 11, GetLangStr(4155), Format('userref:%d,%d', [119, MovieCode]));
	end;

	//seasons
	if (SeasonCnt > 0) and (RegReadInteger('ShowSeasonTab', 1) = 1) then begin
		if PageTabs > 0 then begin
			s := s + GetTab(ActiveTab = 6, GetLangStr(521), Format('userref:%d,%d', [114, MovieCode]));
		end
		else
			RemainingTabs := RemainingTabs + GetTextTab(ActiveTab = 6, GetLangStr(521), Format('userref:%d,%d', [114, MovieCode]));
	end;
	
	s := s + '</div>';
	if RemainingTabs <> '' then
		RemainingTabs := RemainingTabs + ' |';
	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; AdditionalSpace: Integer = 0): String;
var
	s, prefix: String;
	i, my_tabs, PageWidth, PageTabs: Integer;
begin
	RemainingTabs := '';
	PageWidth := GetHTMLWidth - LeftColumnWidth - IconSpace;
	PageTabs := PageWidth div TabWidth;
	s := '';
	s := '<div style="margin-left: 200px; color: white; vertical-align: bottom; font-weight: bold; line-height: 46px;">';

	//general info tab
	s := s + GetTab(PersonActiveTab = 1, GetLangStr(161), Format('userref:%d,%d', [140, PersonCode]), True);
	PageTabs := PageTabs - 1;
	i := PersonActiveTab;

	//photos
	if (Photos) then begin
		if PageTabs > 0 then begin
			s := s + GetTab(PersonActiveTab = 2, GetLangStr(1400), Format('userref:%d,%d', [141, PersonCode]));
			PageTabs := PageTabs - 1;
			i := PersonActiveTab - 1;
		end
		else
			RemainingTabs := RemainingTabs + GetTextTab(PersonActiveTab = 2, GetLangStr(1400), Format('userref:%d,%d', [141, PersonCode]));
	end;
	
	//biography
	if (Bio) then begin
		if PageTabs > 0 then begin
			s := s + GetTab(PersonActiveTab = 3, GetLangStr(282), Format('userref:%d,%d', [142, PersonCode]));
			PageTabs := PageTabs - 1;
			i := PersonActiveTab - 2;
		end
		else
			RemainingTabs := RemainingTabs + GetTextTab(PersonActiveTab = 3, GetLangStr(282), Format('userref:%d,%d', [142, PersonCode]));
	end;
	
	//facts
	if (Facts) then begin
		if PageTabs > 0 then begin
			s := s + GetTab(PersonActiveTab = 4, GetLangStr(1435), Format('userref:%d,%d', [143, PersonCode]));
			PageTabs := PageTabs - 1;
			i := PersonActiveTab - 3;
		end
		else
			RemainingTabs := RemainingTabs + GetTextTab(PersonActiveTab = 4, GetLangStr(1435), Format('userref:%d,%d', [143, PersonCode]));
	end;
	
	//awards
	if (Awards) then begin
		if PageTabs > 0 then begin
			s := s + GetTab(PersonActiveTab = 6, GetLangStr(574), Format('userref:%d,%d', [145, PersonCode]));
			PageTabs := PageTabs - 1;
			i := PersonActiveTab - 5;
		end
		else
			RemainingTabs := RemainingTabs + GetTextTab(PersonActiveTab = 6, GetLangStr(574), Format('userref:%d,%d', [145, PersonCode]));
	end;
	
	//filmography
	if (PageTabs > 0) then begin
		s := s + GetTab(PersonActiveTab = 5, GetLangStr(42), Format('userref:%d,%d', [144, PersonCode]));
		i := PersonActiveTab - 4;
	end
	else
		RemainingTabs := RemainingTabs + GetTextTab(PersonActiveTab = 5, GetLangStr(42), Format('userref:%d,%d', [144, PersonCode]));

	s := s + '</div>';
	
	if RemainingTabs <> '' then
		RemainingTabs := RemainingTabs + ' |';
	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 := ItemHeight;
			PicWidth := StandardWidth + NormalImageBorders;
			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;

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: 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, temp, header_img: 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;
  RatingIndex: Integer;
  current_site, sortby_string, mc_rating: String;
begin
	result:='';
	ProgramReference:='';
	TempReferenceCode:=code;
	TempReference:=666;
	TempText:=text;
	if code=100 then
		result := GetPatternTop + Format('<p class="page-header" style="font-size: %dpt;">', [BasicFontSize + PageHeaderModifier]) + format('%s</p>', [GetLangStr(1333)]) + ClosePatternTop + Format('<p class="header" style="font-size: %dpt;">', [BasicFontSize + SubHeaderModifier]) + ShowScriptOptions
	
	//episodes seen
	else if code in [150..151] then begin
		i := Pos(';', text);
		movie_code := 0;
		my_code := 0;
		if i>0 then begin
			TempList := TStringList.Create;
			s := copy(text, i+1, Length(text)-i);
			s2 := copy(text, 1, i-1);
			try
				movie_code := StrToInt(s);
				my_code := StrToInt(s2);
			except
			end;
			i := Pos('#' + s2 + '#', UnseenEpisodes);
			if i>1 then
				delete(UnseenEpisodes, i-1, length(UnseenEpisodes)-i+2)
			else if i=1 then
				UnseenEpisodes := '';
			UnseenEpisodes := ReplaceStr(UnseenEpisodes, '#', '');
			if code=151 then begin
				TempList.CommaText := UnseenEpisodes;
			end;
			my_i := code - 150;
			if my_code <> 0 then begin
				s := Format('UPDATE episodes SET seen=%d WHERE code=%d', [my_i, my_code]);
				ExecuteSQL(s);
				if (TempList.Count > 0) and MarkPreviousAsSeen then begin
					ExecuteSQL('BEGIN TRANSACTION');
					for i := 0 to TempList.Count - 1 do begin
						s := Format('UPDATE episodes SET seen=1 WHERE code=%s', [TempList[i]]);
						ExecuteSQL(s);
					end;
					ExecuteSQL('COMMIT');
				end;
			end;
			if movie_code > 0 then begin
				SetMode(1, movie_code);
				result := GetMovie5(movie_code, 0, false, false, false, false);
			end;
			TempList.Free;
		end;
	end
	//episode rating
	else if code = 152 then begin
		my_code := 0;
		i := Pos(';', text);
		if i>0 then begin
			s := copy(text, 1, i-1);
			delete(text, 1, i);
		end;
		i := Pos(';', text);
		if i>0 then begin
			s2 := copy(text, 1, i-1);
			delete(text, 1, i);
		end;
		i := 0;
		try
			i := StrToInt(text);
			my_code := StrToInt(s);
			movie_code := StrToInt(s2);
		except
		end;
		if i>0 then begin
			s := Format('UPDATE episodes SET seen=1 WHERE code=%d', [my_code]);
			ExecuteSQL(s);
			s := Format('UPDATE episodes SET rating=%d WHERE code=%d', [i, my_code]);
			ExecuteSQL(s);
		end;
		if movie_code > 0 then begin
			SetMode(1, movie_code);
			result := GetMovie5(movie_code, 0, false, false, false, false);
		end;
	end
	//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, i.sort_order');
			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;
				//imdb - kinopoisk - kinoteatr
				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]];
			TempList.Free;
			RecordCount:=ExecuteSQL(sl.text);
			if header_img <> '' then
				header_img := PicturesPath + 'awards/' + header_img;
			all := ProcessMovieReference(sl, TempText, page, header_img);
		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 >= 1) and (code <= 5)) then begin
			mc_rating := '';
			if code = 2 then begin
				RatingIndex := RegReadInteger('MyRatingTabRating', 1);
				if RatingIndex = 2 then begin
					current_site := RegReadString('MovieScript', '');
					i := Pos(' (', current_site);
					if i>0 then
						delete(current_site, i, length(current_site)-i+1);
				end;
				case RatingIndex of
					2: sortby_string := 'order by SiteRating desc, m.date_add desc, m.code, i.sort_order';
					3: sortby_string := 'order by m.imdb_rating desc, m.date_add desc, m.code, i.sort_order';
					else
						sortby_string := 'order by m.rating desc, m.date_add desc, m.code, i.sort_order';
				end;
				if RatingIndex = 2 then begin
					mc_rating := Format(', (select Rating from movies_codes where movie=m.code and script=''%s'' LIMIT 1) as SiteRating', [current_site]);
				end;
			end;
			with sl do begin
				Clear;
				Add(Format('select m.code as code, m.title, m.year, m.rating, m.imdb_rating, m.in_collection, i.path, i.height, i.width%s', [mc_rating]));
				Add('from movies m');
				if (code = 2) and (RatingIndex = 2) then
					Add('join movies_codes mc on mc.movie=m.code');
				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(sortby_string);
					4: Add('order by m.date_update desc, m.code, i.sort_order');
					5: Add('order by m.title_sort, m.year, i.sort_order');
					else
						if ShowLastUpdated then
							Add('order by m.date_update desc, m.code, i.sort_order')
						else
							Add('order by m.date_add desc, m.code, i.sort_order');
				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]];
			TempList.Free;
			if header_img <> '' then
				header_img := PicturesPath + 'awards/' + header_img;
			RecordCount:=ExecuteSQL(sl.text);
		end;
		
		//people from the homepage
		if (code in [6..9, 136, 200, 201]) then begin
			s2 := Text;
			//136 is for awards
			if code <> 136 then begin
				header_img := '';
				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');
					case code of
						7: Add('where p.date_update is not null');
						8: Add('where 1=1');
						9: Add('where p.birth_date like ''%' + Format('%s', [GetTodaysDate]) + '%''');
						200: Add('where p.birthplace like ''%' + s2 + '%''');
						201: Add('where p.death_date<>''''');
						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.date_update desc, p.code, i.mode desc, i.sort_order');
						8: Add('order by p.rating desc, p.date_add desc, p.code, i.mode desc');
						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;
			
			lines := RegReadInteger('BreezeLinesPeople', DefaultLinesPeople);
			page_width := GetHTMLWidth - WholePageBorder;
			CountedPages := 0;
			TotalItems := CountItemsForPages(page_width, page, RecordCount, 1, lines, HomePhotoHeight, HomePhotoWidth);
			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 LastCode<>my_code then begin
					LastCode:=my_code;
					PicHeight := GetIntegerField('i.height');
					PicWidth := HomePhotoWidth + NormalImageBorders;
					page_width_copy := page_width_copy - PicWidth;
					if (page_width_copy < 0) then begin
						all := all + movie + '<td></td></tr></table><table class="whole-page-images"><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="%shalfstar-left.gif" align="absmiddle" border="0">',  [ImgPath])
									else
								rate:=rate+format('<img src="%snot-halfstar-left.gif" align="absmiddle" border="0">',  [ImgPath])
								end
								else begin
									if my_i<=rating then
								rate:=rate+format('<img src="%shalfstar-right.gif" align="absmiddle" border="0">',  [ImgPath])
									else
								rate:=rate+format('<img src="%snot-halfstar-right.gif" align="absmiddle" border="0">',  [ImgPath])
								end;
							end;
						end;
						FileName := GetImageFileName(GetStringField('i.path'), ThumbsHomePhotos, 'nophoto.jpg', HomePhotoWidth, HomePhotoHeight, True);
						movie:=movie+'<td style="background-color: white; border: 1px solid ' + WhiteAreaBorderColor + '; width: 100px; padding: 5px;"><a class="pic"'+format(' href="person:%d"><img style="height: %dpx" border="0" src="%s"></a>', [my_code, HomePhotoHeight, FileName]);
						//movie := movie + '<div class="image-text">';
						movie:=movie + format('<div style="margin: 5 0;"><a href="person:%d">%s</a>', [my_code, GetStringField('p.name')]);
						if (code = 9) then begin
							DecodeDate(Date, kol, ii, my_i);
							movie := movie + ' (' + IntToStr(YearsBetween(GetStringField('p.birth_date'), IntToStr(kol))) + ')';
						end;
						movie := movie + '</div>';
						if rate<>'' then
							movie := movie + '<div style="vertical-align: bottom;">' + rate + '</div>';
						movie := movie + '</td>';

						PageItems:=PageItems+1;
					end;
				end
				else begin
					GetNextRecord;
					i:=i+1;
				end;
			end;
			TotalItems := TotalItems + PageItems;
			all := all+movie;
			if movie <> '' then
				//all := all + format('<td style="width: %dpx;"></td>', [page_width_copy  - BigImageBorders]);
				all := all + '<td></td>';
			all:=all+'</tr></table>';

			kol := 0;
			lines := RegReadInteger('BreezeLinesPeople', 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, HomePhotoHeight, HomePhotoWidth);
				kol := CountedPages;
			end;
			if header_img <> '' then
				header_img := '<img border="0" style="float: left; margin-right: 10; vertical-align: middle;" src="' + header_img + '">';
			movie_top:=GetReferenceTop;
			movie_top:= movie_top + Format('<p class="page-header" style="font-size: %dpt;">', [BasicFontSize + PageHeaderModifier]) + header_img + text + format(' (%d)', [TotalItems]);
			movie_top:=movie_top+'</p>'+ClosePatternTop;
			movie_top:=movie_top+'<table class="whole-page-images"><tr>';
			
			all := movie_top + all;
			
			s:='userref:'+IntToStr(TempReferenceCode)+','+TempText;
			if (kol > 0) or (page > 1) then begin
				all:=all+Format('<center><hr><p><big>', [page_width div 3, page_width div 3]);
				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+'</big></p></center>';
			end;
		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, page_width, page_width_copy, PicWidth, PicHeight: Integer;
	s, FileName, temp, 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 * 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
		page_width := GetHTMLWidth - WholePageBorder;
		page_width_copy := page_width;
		j := 0;
		temp := '';
		s := '<table style="margin: 10px;"><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;
			PicHeight := GetIntegerField('height');
			if PicHeight > 0 then
				PicWidth := Round(GetIntegerField('width') * (ShotHeight / PicHeight)) + SmallImageBorder
			else
				PicWidth := StandardShotWidth + SmallImageBorder;
			page_width_copy := page_width_copy - PicWidth;
			if (page_width_copy < 0) then begin
				s := s + temp + '</tr></table><table style="margin: 10px;"><tr>';
				temp := '';
				page_width_copy := page_width - PicWidth;
			end;
			FileName:=ImagesPath+GetStringField('path');
			if (MyFileExists(FileName)) then
				temp:=temp+'<td style="vertical-align: top; text-align: center;"><a class="pic" ' + format('href="ShowImage:%d"><img src="%s" style="height: %dpx;"></a></td>', [GetIntegerField('code'), FileName, ShotHeight]);
			GetNextRecord;
		end;
		s := s + temp;
//		if temp <> '' then
//			s := s + format('<td style="width: %dpx">&nbsp;</td>', [page_width_copy]);
		s := s + '</tr></table>';
	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_sort, i.sort_order');
        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_sort, i.sort_order');
        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_sort, i.sort_order');
        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_sort, i.sort_order');          
        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_sort, i.sort_order');
        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_sort, i.sort_order');
        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_sort, i.sort_order');
        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_sort, i.sort_order');
        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_sort, i.sort_order');
        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_sort, i.sort_order');
        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_sort, i.sort_order');
        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, i.sort_order');
        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_sort, i.sort_order');
        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, i.sort_order');
      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, i.sort_order');
  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, page_width, page_width_copy, col, total_col: Integer;
	PicWidth, PicHeight: Integer;
	s, img, character, rate, BirthDate, FileName, temp: String;
begin
	sl := TStringList.Create;
	s := '';
    with sl do begin
		Clear;
        Add('select p.code, p.name, p.rating, p.birth_date, c.name, i.path, i.width, i.height 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;
	PreviousCodes := TStringList.Create;
    RecordCount:=ExecuteSQL(sl.text);
    if RecordCount>0 then begin
		page_width := GetHTMLWidth - LeftColumnWidth - WholePageBorder - 40; //40 pixels reserved
        i:=1;
		prev_code := 0;
		col := 0;
		temp := '';
		s := s + '<table style="width: 100%;"><tr><td><table class="photos"><tr>';
		page_width_copy := page_width;
		while i<=RecordCount do begin
		  person_code := GetIntegerField('p.code');
		  rating:=GetIntegerField('p.rating');
		  if rating>0 then
			rate:=format('<br/><img src="%sstar-transp.gif" width=17 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
			  PicHeight := GetIntegerField('i.height');
			  if PicHeight > 0 then
				PicWidth := Round(GetIntegerField('i.width') * (SmallCoverHeight / PicHeight)) + SmallImageBorder * 2
			  else
				PicWidth := StandardCoverWidth + SmallImageBorder * 2;
			  page_width_copy := page_width_copy - PicWidth;
			  if (page_width_copy < 0) then begin
				s := s + temp + '<td></td></tr></table>';
				temp := '';
(*				if col=2 then begin
					s := s + '<div style="clear:both">';
					page_width := GetHTMLWidth - WholePageBorder;
				end;
*)				s := s + '<table class="photos"><tr>';
				page_width_copy := page_width - PicWidth;
			  end;
			  //photo
			  FileName := GetImageFileName(GetStringField('i.path'), ThumbsMoviePhotos, 'nophoto.jpg', 0, SmallCoverHeight);
			  temp:=temp+'<td class="one-photo">'+format('<a class="pic" href="person:%d"><img style="height: %dpx;" src="%s" border="0"></a>', [person_code, SmallCoverHeight, FileName]);
			//name
			  temp := temp+format('<p><a href="person:%d"><b>%s</b></a>%s</p>', [person_code, GetStringField('p.name'), rate]);
			  //birth date
//			  if BirthDate <> '' then
//				s := s + BirthDate + '<br>';

			  //character
			  character:=GetStringField('c.name');
			  if character <> '' then
				temp := temp + '<p>' + character + '</p>';
			  temp := temp + '</td>';
			  PreviousCodes.Add(IntToStr(person_code));
		  end;
		  i:=i+1;
          GetNextRecord;
        end;
		s := s + temp;
		if temp <> '' then begin
			s := s + Format('<td style="width: %dpx">&nbsp;</td>', [page_width_copy]);
		end;
		s := s + '<td></td></tr></table></td></tr></table>';
		//s := s + '</table></td></tr>';
	end;
	sl.Free;
	PreviousCodes.Free;
	Result := s;
end;

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

//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 := '<br>"' + Result + '"<br>';
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, ThumbWidth: 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:='';
	ThumbWidth := RegReadInteger('ListCoverWidth', DefaultThumbWidth);
	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, ThumbWidth, 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
				FileName:=ImgPath+'no-cover.jpg';
				fl:=true;
			end;
		end
		else
			FileName := '';
		
		//current site rating
		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;
		
		//imdb rating
		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;
		
		//kinopoisk rating
		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
				s := GetStringField('p.name');
				if GetIntegerField('p.in_collection')=1 then begin
					img:=format('<NOBR><img src="%sperson.gif" align="absmiddle" border="0" style="margin-right: 2px;">', [ImgPath]);
					s := ReplaceStr(s, ' ', '</NOBR> ');
				end
				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'), s]);
						dir:=dir+1;
					end;
				end
				else begin
					actors:=actors+img+format('<a href="person:%d">%s</a>, ', [GetIntegerField('p.code'), s, 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) and (mode <> 5)) 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(' <NOBR><img src="%sstar-transp.gif" width="17" height="16" border="0" align="absmiddle">%d</NOBR>', [ImgPath, rating])
		else
			rate:='';
		s := '<div style="background-color: white; padding: 5px; margin: 3; border: 1px solid ' + WhiteAreaBorderColor + '; font-size: ' + IntToStr(ListFontSize) + 'pt;">';
		if showCoversInList then begin
			s:= s + '<div style="float: left; margin: 0 5 5 0;"><a class="pic" ' + format('href="movie:%d"><img border="0" style="width: %dpx;" src="%s"', [code, ThumbWidth, FileName]);
			if not GetCutePreview and (mode<>7) then
				s:=s+' width="50" align="left"';
			s:=s+'></a></div>';
		end;
		s := s+format('%s<a href="movie:%d"><big><b>%s</b></big></a>%s%s<br>', [CheckMode, code, title, year, rate]);
		
		//site ratings
		if (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;

	//14.03.13
  s := s + GenerateHTMLForDescriptionSearching(AFullDescription, ASearchDescription);


	s := s+'</div>';
	//if mode=7 then
		//s:='<tr><td class="description">'+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
        ConvertThumb3(FileIn, FileName, Thumbs2, CoverWidth, CoverHeight, CutThumb);
      if MyFileExists(FileName) then
        fl:=true;
    end;
    if not fl then
    begin
      FileIn:=ImgPath+'no-cover.jpg';
      FileName:=ThumbsPath+'no-cover.jpg';
      //ShowMessage('FileName='+FileName);
      //ShowMessage('FileIn='+FileIn);
      if ((not MyFileExists(FileName)) and
          (MyFileExists(FileIn))) then
      begin
        ConvertThumb3(FileIn, FileName, Thumbs2, 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 class="pic" href="group_check_off:%d"><img src="%scheck.gif" align="absmiddle" border="0"></a>',  [code, PicturesPath])
      else
        CheckMode:=format('<a class="pic" href="group_check_on:%d"><img src="%scheckout.gif" align="absmiddle" border="0"></a>',  [code, PicturesPath]);
    end
    else
      CheckMode:='';

    s:='<div style="height: 100%; background-color: white; padding: 5px; margin: 5 5 0 5; border: 1px solid ' + WhiteAreaBorderColor + '; font-size: ' + IntToStr(ListFontSize) + 'pt;"><div style="float: left; margin: 0 5 5 0;"><a class="pic" href="movie:' + format('%d"><img src="%s" border="0">', [code, FileName])+'</a></div><div style="clear:both"></div><div>'+CheckMode+format('<a href="movie:%d"><b>%s', [code, title]) + '</b></a></div></div>';


	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, ThumbWidth: 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;
  
  ThumbWidth := RegReadInteger('ListCoverWidth', DefaultThumbWidth);

  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(' <NOBR><img src="%sstar-transp.gif" width=17 height=16 border=0 align="absmiddle">%d</NOBR>', [ImgPath, rating])
		else
			rate:='';

    BirthDate:=GetStringField('p.birth_date');
    if (BirthDate<>'') then begin
		if FullList then
			BirthDate:=Date2Str(BirthDate)
		else
			BirthDate:=copy(BirthDate, 1, 4);
	end;
		
	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, ThumbWidth, 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
			FileName:=ImgPath+'nophoto.jpg';
			fl:=true;
		  end;
	  end;
      if RegReadInteger('PersonStatsInCollection', 0) = 1 then
		PersonStatsInCollection := True
	  else
		PersonStatsInCollection := False;
      //кол-во фильмов, как актер
	  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);
    // 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 class="pic" href="group_person_check_off:%d"><img src="%scheck.gif" align="absmiddle" border="0"></a>',  [code, PicturesPath])
      else
        CheckMode:=format('<a class="pic" href="group_person_check_on:%d"><img src="%scheckout.gif" align="absmiddle" border="0"></a>',  [code, PicturesPath]);
    end
    else
      CheckMode:='';

      s:='<div style="background-color: white; padding: 5px; margin: 3; border: 1px solid ' + WhiteAreaBorderColor + '; font-size: ' + IntToStr(ListFontSize) + 'pt;">';
	  if ShowCoversInList then begin
		s := s + '<div style="float: left; margin: 0 5 5 0;"><a class="pic" href="person:' + format('%d"><img border="0" src="%s" style="width: %dpx;"', [code, FileName, ThumbWidth]);
		if not GetCutePreview and (mode<>7) then
			s:=s+' width=50 border="0" align=left';
		s := s + '></a></div>';
	  end;
    // fade group operations
	  //if not full list then use birth year instead of rating
	  if not FullList and (BirthDate <> '') then
		rate := ' (' + BirthDate + ')';
	  s:=s+format('<div style="margin-top: 5px;">' + CheckMode + '<a href="person:%d"><big><b>%s</b></big></a>%s', [code, PersonName, rate]);
	  if FullList then
		s := s + '<br>';
      if (BirthDate<>'') and FullList then begin
      	//ShowMessage(BirthDate);
      	s:=s+BirthDate;
		if DeathDate <> '' then
			s := s + ' - ' + DeathDate;
      	try
      		//years:=StrToDate(BirthDate);
      	except
      	end;
	  end;
	  if FullList then begin
		  s:=s+'<br>';
		  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="text-box">'+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');

      //обложка
	  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
				ConvertThumb3(FileIn, FileName, Thumbs2, 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 class="pic" href="group_person_check_off:%d"><img src="%scheck.gif" align="absmiddle" border="0"></a>',  [code, PicturesPath])
      else
        CheckMode:=format('<a class="pic" 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.jpg';
        //FileName:=ThumbsPath+'no-cover.jpeg';
        FileName:=ThumbsPath+'nophoto.jpg';
        if ((NeedToCreateThumbFile(FileName)) and
            (MyFileExists(FileIn))) then
        begin
          ConvertThumb3(FileIn, FileName, Thumbs2, PhotoWidth, PhotoHeight, CutThumb);
        end;
        fl:=true;
      end;

      s:='<div style="height: 100%; background-color: white; padding: 5px; margin: 5 5 0 5; border: 1px solid ' + WhiteAreaBorderColor + '; font-size: ' + IntToStr(ListFontSize) + 'pt;"><div style="float: left; margin: 0 5 5 0;">' + format('<a class="pic" href="person:%d"><img border="0" src="%s"></a></div><div style="clear:both"></div><div>' + CheckMode + '<a href="person:%d"><b>%s</b></a></div></div>', [code, FileName, code, PersonName]);
    //else
      //s:=format('<div class="cover-flow-text">%s<a href="person:%d"><b>%s</b></a></div>', [CheckMode, 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 + Format('<p class="page-header" style="font-size: %dpt;">', [BasicFontSize + PageHeaderModifier])+GetLangStr(1293)+format(': %d-%d %s %d', [RecMin, RecMax, GetLangStr(1461), RecCount])+'</p>'+ClosePatternTop;
end;

function GetSearchBottom(RecMin, RecMax, RecCount: integer): string;
var
	s: string;
	RecPage, i, kol, page_width: integer;
begin
	//s:=format('Results from %d to %d. Total records %d', [RecMin, RecMax, RecCount]);
	s:='';
	page_width:=GetHTMLWidth - WholePageBorder;
	RecPage:=GetNumberSearchResults;
	if RecPage>0 then begin
		kol:=RecCount div RecPage;
		if kol*RecPage<>RecCount then
			kol:=kol+1;
		s:=s+Format('<center><p>', [page_width div 3, page_width div 3]);
		for i:=1 to kol do begin
			if (RecMin-1) div RecPage=i-1 then
				s:=s+format('<b class="search-active">%d</b> ', [i])
			else
				s:=s+format('<a href="search:%d-%d">%d</a> ', [(i-1)*RecPage+1, i*RecPage, i]);
		end;
		s:=s+'</p></center>';
		
	end;
	result:= s;
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);
	DeleteFile(ImagesPath+ThumbsHomePhotos+'\'+FileName);
	DeleteFile(ImagesPath+ThumbsHomeShots+'\'+FileName);
	DeleteFile(ImagesPath+ThumbsEpisodeCovers+'\'+FileName);
end;

begin
	ImgPath := PicturesPath + 'Themes\Breeze\';
	WhiteBarFile := GetProperPath(ImgPath + 'white-bar.gif');
	BackgroundImg := GetProperPath(ImgPath + 'background.png');
	BackgroundMovies := GetProperPath(ImgPath + 'background-movies.gif');
	BackgroundPeople := GetProperPath(ImgPath + 'background-people.gif');
	StandardCoverWidth := Round(NoCoverWidth * (SmallCoverHeight / NoCoverHeight));
	ActiveTab := 1;
	PersonActiveTab := 1;
	// 22.04.2011 - default sizes for multi image showing
	MultiShowRowHeight := RegReadInteger('ThumbCellHeight', DefaultMultiCellHeight);
	MultiShowImageWidth := RegReadInteger('ThumbCellWidth', DefaultMultiCellWidth);
	MiltiShowDistanceBetweenCovers := 12;  
	SetHintWindowSize(305, 175);
	HomeMovieTab := 1;
	HomePersonTab := 1;
	BasicFontSize := RegReadInteger('BreezeFontSize', DefaultBasicFontSize);
	ListFontSize := BasicFontSize + ListModifier;
	SingleViewDeltaY := 0;

end.
