const
	script_name='adultdvdempire';
	language='English';
	version=14;
	author='Vlad';
	MinProgramBuild=5200;
	Dbg = false;
	PCount = 12;
var
	title, MovieName, year, director, name, character, BasicURL, country, description, salary: string;
	movie_code, movie_site_url, title_code, imdb_code: string;
	titles: array of string;
	titles_count: integer;
	director_code, code: string;
	directors, writers, actors, characters, genres, imdb_codes: array of string;
	directors_codes, writers_codes, actors_codes: array of integer;
	directors_count, writers_count, actors_count, genres_count: integer;
	duration: integer;
	imdb_rating: single;
	front_cover_url, back_cover_url: string;
	posters_exists, boxes_exists, screenshots_exists: boolean;
	original_title, mpaa, mpaa_rating: string;
	prefixes: array [1..PCount] of string;
	resolution, barcode, aspect_ratio, features, media_format, video_codec: string;
	tagline, awards, scenes_url: String;
	DownloadMovieBigCover, DownloadMovieShortCast, DownloadMovieFullCast, 
	DownloadMovieBigDescription, DownloadMovieComments, 
	DownloadMovieStudios,	DownloadMovieAwards, DownloadMovieEarnings, 
	DownloadMovieAdditionalInfo, DownloadMovieSeasonsList, DownloadMovieTechnicalInfo: boolean;
	MaxShotsCount, MaxPostersCount: integer;
	
const
	SITE_MAIN_URL = 'http://www.adultdvdempire.com/';
	MOVIE_URL_END = '/1234-porn-movies.html';

function GetStr(str: String; s1: String; s2: String): String;
var
  I: Integer;
  J: Integer;
begin
  // Вырезает кусок строки между s1 и s2
	Result := '';
	I := Pos(LowerCase(s1), LowerCase(str));
	if I > 0 then
	begin
		J := MyPos(LowerCase(s2), LowerCase(str), I + Length(s1));
		if J > 0 then
  		Result := Copy(str, I + Length(s1), J - I - Length(s1));
	end;
end;	
	
function MovieSearch: integer;
var
	i, j, k, l: integer;
	s, s2, s3, small_cover, description, year: string;
begin
	s:='';
	titles_count:=0;
	
	i:=pos('<strong>0</strong> Matches Found', all);
	if (all='') or (i>0) then
		// Movie not found!
	else begin
		i:=pos('<div class="container">',all);
		delete(all, 1, i-1);
		i := Pos('Category="Paging"', all);
		if i>0 then
			delete(all, i, length(all)-i+1);
		i := Pos('<div class="container">',all);
		while i>0 do begin
			j:=MyPos('<div class="clear">', all, i+1);
			s:=copy(all, i, j-i);
			//cover
			small_cover := GetStr(s, '<img src="', '" ');
			//title and code
			s2 := GetStr(s, '<p class="title">', '</a>');
			title_code:=GetStr(s2, '<a href="/', '/');
			title:=RemoveTags(s2);
			title:=ClearExtraBlankCharacters(DecodeHTML(title));
			year := ParseString(s, '\((\d+)\)', 1);
			if year = '' then
				year := ParseString(s, '- year: (\d+)', 1);
			description := GetStr(s, 'Cast:', '</p>');
			description := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(description)));
			description := ReplaceStr(description, #13, '', -1);
			description := ReplaceStr(description, #10, '', -1);
			if (title<>'') and (pos('sex-toys', s)=0) then begin
				titles_count := titles_count + 1;
				SetSearchResult2(title, title_code, year, '', description, small_cover);
			end;
			delete(all, 1, j);
			i:=pos('<div class="container">',all);
		end;
	end;
	result:=titles_count;
end;

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

//Get search URL by movie name
function GetSearchURLbyName(MovieName, AYear, ABarcode: string): string;
var
	url: string;
begin
	url:=format('http://www.adultdvdempire.com/AllSearch/Search?q=%s&pageSize=100', [MovieName]);
	url:=ReplaceStr(url, ' ', '+', -1);
	result:=url;
end;

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

function GetMovieURL(code: string; images_only: boolean): string;
begin
	if images_only then
		result:=SITE_MAIN_URL + code + MOVIE_URL_END
	else
		result:=SITE_MAIN_URL + code + MOVIE_URL_END
end;

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

function ClearBrackets(name: string): string;
var
	i: integer;
begin
	// clear word in brackets at the end of name
	i := pos(' (', name);
	if i>0 then
		name := copy(name, 1, i-1);
	Result := name;
end;

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

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

function ClearExtraBlankCharacters(text: string): string;
begin
	// Clear all extra blank charackters
	while (length(text) > 0) and (ord(text[1]) in [1..20, 32]) do
		delete(text, 1, 1);
	while (length(text) > 0) and (ord(text[length(text)]) in [1..20, 32]) do
		delete(text, length(text), 1);
	Result := text;
end;

function GetInfo(url: string; images_only: boolean): string;
var
	s, s2, s3, keyword, general_url, small_photo: string;
	i, j: integer;
	ProcessedActors: TStringList;
begin
	result:='';
	movie_code:=ParseString(url, SITE_MAIN_URL+'(\d+)', 1);
	movie_site_url:=GetMovieSiteURL(movie_code);
	if movie_code = '' then
		exit;
	BasicURL:=url;
	general_url := SITE_MAIN_URL + 'general/' + movie_code + MOVIE_URL_END;
	s := 'scenes/' + movie_code;
	scenes_url := SITE_MAIN_URL + s + MOVIE_URL_END;
	all:=DownloadURL(general_url);
	if all='-1' then
		result:='-1'
	else
		result:=all;
		
	if Pos(s, all)>0 then begin
		AddRequestForHTMLPageContent(scenes_url, False);
	end;

	imdb_code:='';

	title:=ParseString(all, '<h1>(.*?)</h1>', 1);
	if (Pos('</strong> Matches Found', title) > 0) then
		title := '';
	i := Pos('<', title);
	if i>0 then
		delete(title, i, length(title)-i+1);
	if (RegReadInteger('AdultDVDEmpireRemoveNr', 0) = 1) then begin
		i := Pos('#', title);
		if i>0 then
			delete(title, i, 1);
	end;
	title := RemoveTags(title);
	title := ClearExtraQuotes(title);
	title := MovePrefixLeft(title);
	title := ClearExtraBlankCharacters(DecodeHTML(title));
	if title='' then
		exit;


	//movie year
	year:=ParseString(all, 'Year:  (\d+)', 1);

	s2 := GetStr(all, '<h2>Synopsis</h2>', '</div>');
	//tagline
	tagline := GetStr(s2, '<p class="Tagline">', '</p>');
	tagline := DecodeHTML(RemoveTags(tagline));
	if Pos('<p class="Tagline">', s2) > 0 then begin
		i := Pos('</p>', s2);
		delete(s2, 1, i+3);
	end;

	//plot
	description:=GetStr(s2, '<p>', '</p>');
	description:=RemoveTags(description);
	description:=ClearExtraBlankCharacters(description);
	description:=DecodeHTML(description);



	//movie duration (minutes)
	duration:=0;
	i:=0;
	s:=GetStr(all, 'Length</strong>', '<');
	s2:=ParseString(s, ' (\d+) hrs.', 1);
	if s2<>'' then
		try
			i:=StrToInt(s2);
		except
		end;
	s3:=ParseString(s, ' (\d+) mins.', 1);
	if s3<>'' then
		try
			duration:=StrToInt(s3);
		except
		end;
	duration := duration + i*60;

	
	//studio
	s:=GetStr(all, 'Studio</strong>', '</a>');
	s:=ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
	if s<>'' then
		SetStudio(s);
		
	//barcode
	barcode := GetStr(all, 'UPC Code</strong> ', '<');
		
	//front cover
	s := GetStr(all, '<div id="Boxcover">', '</div>');
	front_cover_url := GetStr(s, '<a href="', '"');
	if (Pos('.jpg', LowerCase(front_cover_url)) = 0) then
		front_cover_url := '';
	//back cover
	i := Pos('</a>', s);
	delete(s, 1, i+3);
	back_cover_url := GetStr(s, '<a href="', '"');
	if (Pos('.jpg', LowerCase(back_cover_url)) = 0) then
		back_cover_url := '';
		
	//female cast (with photos)
	ProcessedActors := TStringList.Create;
	s := GetStr(all, '<h2>Female Cast</h2>', '</ul>');
	i := Pos('<li>', s);
	while i>0 do begin
		j:=MyPos('</li>', s, i+1);
		s2:=copy(s, i, j-i);
		name := GetStr(s2, '<span>', '</span>');
		code := GetStr(s2, '<a href="/', '-pornstars.html');
		small_photo := GetStr(s2, '<img src=''', '''');
		small_photo := ReplaceStr(small_photo, 't.jpg', '.jpg', -1);
		if (name<>'') then begin
			SetPersonName(name, '', 3, code + '-pornstars', small_photo);
			ProcessedActors.Add(name);
		end;
		delete(s, 1, j);
		i := Pos('<li>', s);
	end;
	

	//persons
	s := GetStr(all, '<h2>Cast</h2>', '</ul>');
	i := Pos('<li>', s);
	while i>0 do begin
		j:=MyPos('</li>', s, i+1);
		s2:=copy(s, i, j-i);
		name:=GetStr(s2, '<a href=', '</a>');
		name := RemoveTags('<' + name);
		name:=ClearExtraBlankCharacters(DecodeHTML(name));
		code:=GetStr(s2, '<a href="/porn-videos/', '-pornstars.html');
		if code = '' then
			code := GetStr(s2, '<a href="/', '-pornstars.html');
		if code='' then begin
			code:=ParseString(s2, '<a href="/(.*?).html', 1);
			if (code<>'') and (name<>'') then
				SetPersonName(name, '', 1, code);
		end
		else
		if (name<>'') and (ProcessedActors.IndexOf(name) < 0) then
			SetPersonName(name, '', 3, code+'-pornstars');
		delete(s, 1, j);
		i:=Pos('<li>', s);
	end;
	ProcessedActors.Free;
	
	//awards
	s := GetStr(all, '<h2>Awards</h2>', '</ul>');
	s := ReplaceStr(s, '</li>', #13#10, -1);
	awards := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
	
	//categories aka genres
	s := GetStr(all, '<h2>Categories</h2>', '</p>');
	if s<>'' then begin
		while (Pos('<a href', s)>0) do begin
			s2 := GetStr(s, '<a href=', '/a>');
			s2 := GetStr(s2, '>', '<');
			s2 := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s2)));
			if s2<>'' then
				SetGenre(s2);
			delete(s, 1, Pos('<a href', s));
		end;
	end;

end;

//returned images links
procedure GetImages;
var
	s, s2, img_url: string;
	i, img_cnt: Integer;
begin
	if front_cover_url <> '' then
		SetImageName('', front_cover_url, '', 1);
	if back_cover_url <> '' then
		SetImageName('', back_cover_url, '', 2);
	s := GetHTMLPageContentFromRequest(scenes_url);
	s := GetStr(s, '<div class="screens"', '<hr />');
	img_cnt := 0;
	i := Pos('"screenshots" href="', s);
	while (i>0) and (img_cnt < MaxShotsCount) do begin
		img_url := GetStr(s, '"screenshots" href="', '"');
		if img_url<>'' then begin
			SetImageName('', img_url, '', 3);
			Inc(img_cnt);
		end;
		delete(s, 1, i);
		i := Pos('"screenshots" href="', s);
	end;
end;

function ShowScriptOptions: integer;
var
	s: string;
	f: TForm;
	b: TButton;
	cbRemoveNr: TCheckBox;
	my_value: integer;
	
procedure ButtonClick(Sender: TButton);
var
	zn: integer;
begin
	try
		if cbRemoveNr.Checked then
			zn := 1
		else
			zn := 0;
		RegWriteInteger('AdultDVDEmpireRemoveNr', zn);	
	except
	end;

	f.ModalResult := mrOk;
end;

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

	
	cbRemoveNr := TCheckBox.Create(f);
	cbRemoveNr.Name := 'cbRemoveNr';
	cbRemoveNr.Parent := f;
	cbRemoveNr.SetBounds(10, 10, 350, 20);
	cbRemoveNr.Caption := 'Remove # from titles';
	my_value := RegReadInteger('AdultDVDEmpireRemoveNr', 0);
	if my_value=1 then
		cbRemoveNr.Checked := True;
		
		

	b := TButton.Create(f);
	b.Name := 'btnOK';
	b.Parent := f;
	b.SetBounds(160, 130, 80, 25);
	b.Caption := '&OK';
	b.OnClick := @ButtonClick;

	f.ShowModal;
	f.Free;
end;

//get movie site url
function GetMovieSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:=SITE_MAIN_URL+code+MOVIE_URL_END;
end;

//get person site url
function GetPersonSiteURL(code: string): string;
begin
	result:=SITE_MAIN_URL+code+'.html';
end;

begin

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

end.