const
	script_name='CINeol';
	language='Spanish';
	version=17;
	author='Ordago_86/Vlad';
	MinProgramBuild=5500;
	PCount = 12;
	//MaxPicturesCount = 3;
var
	DownloadMovieBigCover, DownloadMovieShortCast, DownloadMovieFullCast, 
	DownloadMovieBigDescription, DownloadMovieComments, 
	DownloadMovieStudios,	DownloadMovieAwards, DownloadMovieEarnings, 
	DownloadMovieAdditionalInfo, DownloadMovieSeasonsList: boolean;
	MaxShotsCount: integer;

	title, MovieName, s, s2, s3, s4, year, director, name, character, BasicURL, description, country, salary: string;
	movie_code, movie_site_url, title_code, imdb_code, awards: string;
	duration: integer;
	titles: array of string;
	titles_count: integer;
	i, j: integer;
	code: string;
	imdb_rating, rating: double;
	front_cover_url: string;
	posters_exists: boolean;
	original_title, mpaa, mpaa_rating: string;
	prefixes: array [1..PCount] of string;
	monthes: array [1..12] of string;
	resolution, barcode, aspect_ratio, features, media_format, video_codec: string;
	gen_amazon_url: string;

function GetStr(str: String; s1: String; s2: String): String;
var
  I: Integer;
  J: Integer;
begin
  // Вырезает кусок строки между s1 и s2
	Result := '';
	I := Pos(s1, str);
	if I > 0 then
	begin
		J := MyPos(s2, str, I + Length(s1));
		if J > 0 then
  		Result := Copy(str, I + Length(s1), J - I - Length(s1));
	end;
end;	

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 MovieSearch: integer;
var
	i, j: integer;
	title, s, s2, small_cover, description: string;
begin
	s:='';
	titles_count:=0;
	i:=pos('<title>Resultados de la b', all);
	if i>0 then begin
	  s:=GetStr(all, '<h2>Películas</h2>', '<div class="publicidad-google-468">');
	  if s<>'' then begin
		i:=Pos('<div class="item">', s);
		while i>0 do begin
		   titles_count:=titles_count+1; 
		   j:=MyPos('</div>', s, i);
		   s2:=copy(s, i, j-i);
		   title_code:=ParseString(s2, 'pelicula/(.*?)"',1);
		   title:= ParseString(s2,'<h3>(.*?)</a>',1);
		   title:=RemoveTags(title);
		   title:= MovePrefixLeft(title);
		   small_cover := ParseString(s2, '<img src="galeria/carteles/mini_(\d+).jpg" ', 1);
		   if small_cover <> '' then
			small_cover := 'http://www.cineol.net/galeria/carteles/'+small_cover+'.jpg';
		   description := ParseString(s2, '<li class="director">(.*?)</li>', 1);
		   description := RemoveTags(description);
		   description := ClearExtraBlankCharacters(description);
		   SetSearchResult2(title,title_code, '', '', description, small_cover);
		   delete(s, 1, j);
		   i:=Pos('<div class="item">', s);
		end;
	  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:='';
	ShowMessage('Este script no tiene esta opcion. Disculpa las molestias, intentaremos aсadir esta opciуn en futuras versiones.');
	result:=res;
end;

//Get search URL by movie name
function GetSearchURLbyName(MovieName, AYear, ABarcode: string): string;
var
	url: string;
begin
	url:=format('http://www.cineol.net/search.php?search=%s&select=1&button=Buscar', [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
  result:=format('http://www.cineol.net/pelicula/%s',[code]);
//  result:=format('http://www.cineol.net/pelicula.php?idpelicula=%s',[code]);
end;

//returned link to front cover
function GetAmazonImages: string;
var
	res, all, url, s, s2, s3, amazon_url: string;
	i, j: integer;
begin
	//discard info in brackets
	if original_title='' then Result:=''
	else begin
		s:=original_title;
		all:=GetHTMLPageContentFromRequest(gen_amazon_url);
		//search image by title
		amazon_url:='';
		i:=pos('<Item>', all);
		while (i>0) and (amazon_url='') 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);
				s3:=DecodeHTML(s3);
				if s3<>'' then 
				begin
					//if title=s3 then begin //!!!
					if pos(UpperCase(original_title), UpperCase(s3))=1 then 
					begin
						amazon_url:=ParseString(s2, '<LargeImage><URL>(.*?)</URL>', 1);
					end;
				end;
			end;
		i:=MyPos('<Item>', all, i+1);
		end;
		if amazon_url<>'' then begin
			SetImageName('', amazon_url, '', 1);
			res:=amazon_url;
		end;
		result:=res;
	end;
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);
	i := pos(' [', name);
	if i>0 then
		name := copy(name, 1, i-1);
	Result := name;
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 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 SavePhoto(url, FileName: string): boolean;
var
	fs: TFileStream;
	s: string;
begin
	s:=DownloadURL(url);
	if (length(s)>0) and (s<>'-1') then begin
		try
			fs:=TFileStream.Create(FileName, fmCreate);
			fs.Write(s, Length(s));
			fs.Free;
			result:=true;
		except
			result:=false;
		end;
	end
	else
		result:=false;
end;

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

procedure ExtractPersonName(text_block: string; person_mode: integer);
var
	s2, name, code: string;
	i, j: integer;
begin
     j:= pos('</a>', text_block);
     while j>0 do begin
        s2:= copy(text_block, 1, j-1);
		name:=RemoveTags(s2);
		//remove the separator
		i:= pos('/ ', name);
		if i>0 then
			delete(name, 1, i+1);
		i:= pos('(', name);
		if i>0 then
			delete(name, i-1, length(name)-i+2);
        code:= ParseString(s2,' href="gente/(.*?)"',1);
        if name<>'' then
            setPersonName(name, '', person_mode, code);
		delete(text_block, 1, j+4);
        j:= Pos('</a>', text_block);
     end;
end;


function GetInfo(url: string; images_only: boolean): string;
var 
	keyword, s, s2, s3, plot_outline: string;
	i, j, k, l: integer;
	day, month: string;
begin

	result:='';
	BasicURL:=url;
	all:=DownloadURL(url);

	if all='-1' then
		result:='-1'
	else
		result:=all;
	
	title:='';
	year:='';
	movie_code:=ParseString(url, '/pelicula/(.*?)$', 1);
	movie_site_url:=GetMovieSiteURL(movie_code);
	
  // Titulo de la pelicula
	title:=ParseString(all, '<title>(.*?) - Pelicula :: CINeol</title>', 1);
	title:=ClearBrackets(title);
	
  // Titulo Original  
  original_title:=GetStr(all, '<li><strong>Título Original</strong>: ', '</li>');
  
	if DownloadMovieBigCover then begin
		gen_amazon_url:=format('http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&SubscriptionId=0J0N83PT9M72BYH98YR2&Operation=ItemSearch&Keywords=%s&SearchIndex=Video&ResponseGroup=Request,Images,Tracks,ItemAttributes', [original_title]);
		gen_amazon_url:=ReplaceStr(gen_amazon_url, ' ', '+', -1);
		AddRequestForHTMLPageContent(gen_amazon_url, False);
	end;
  
  
  // Año de la pelicula
  year := ParseString(all, '<strong>Año:</strong> (\d+)</li>', 1);
  
	// Generos
	s:= GetStr(all, '<li><strong>Género:</strong> ', '</li>');
	// Estudio los generos
	s:=RemoveTags(s);
	j:= pos('/',s);
	i:=1;
	while j>0 do begin
		name:= copy(s,i,j-i);
		if name<>'' then
			SetGenre(name);
		delete(s, 1, j);
		j:= Pos('/',s);
	end;
	if s<>'' then
		SetGenre(s);
  
  // Pais
  s:= GetStr(all, '<li><strong>País:</strong> ', '</li>');
  if s<>'' then begin
     // Estudio los paises
     j:= pos('/',s);
     i:=1;
     while j>0 do begin
        name:= copy(s,i,j-i);
        if name<>'' then begin
           s3:=copy (name,1,1);
           if s3 = ' ' then begin
              i:=i+1;
              name:=copy(s2,i,j-i);
           end;   
           if name<>'' then
              SetCountry(name);
        end;
        delete(s, 1, j);
        j:= Pos('/',s);
     end;
     if s<>'' then begin
        s3:=copy (s,1,1);
           if s3 = ' ' then begin
              i:=i+1;
              name:=copy(s,i,j-i);
           end;   
           if s<>'' then
              SetCountry(s);
     end;
  end;
  
  // Duración
  s:=ParseString(all, '<li><strong>Duración</strong>: .*?(\d+)</time> minutos</li>', 1);
  if s<>'' then begin
    try
		duration:=StrToInt(s);
		except
		end;
  end;
 
  
  // Sinopsis
  s:=ParseString(all, '<h2>Sinopsis</h2>(.*?)</p>', 1);
  description:=RemoveTags(s);
  
(*  //Premios
  i:= pos('Premios</SPAN>:<BR>', all);
  if i>0 then begin
	j:=MyPos('</TD>', all, i+1);
	awards:=copy(all, i+19, j-i-19);
  end;
 *)
  // Dirección
	s:=GetStr(all, '<li><strong>Dirección: </strong>', '</li>');
	ExtractPersonName(s, 1);
  
  // Guionistas
  s:=GetStr(all, '<li><strong>Guión:</strong> ', '</li>');
  ExtractPersonName(s, 2);

  
  // Imagen
  s:=ParseString(all, '<img src="galeria/carteles/(.*?)"', 1);
  if s<>'' then
     front_cover_url:='http://www.cineol.net/galeria/carteles/'+s;
  
  // Musica
  s:=GetStr(all, '<li><strong>Música:</strong> ', '</li>');
  ExtractPersonName(s, 4);
  
  // Interpretes
	s:=GetStr(all, '<h2>Intérpretes</h2>', '<div class="clearing">');
	i:= Pos(' href="gente/', s);
    while i>0 do begin
        j:= MyPos('</tr>', s, i);
        s2:= copy(s, i, j-i);
        name:=ParseString(s2, '">(.*?)</a', 1);
        code:=ParseString(s2, ' href="gente/(.*?)"', 1);
        character:=GetStr(s2, '</a></td><td>', '</td>');
		if name<>'' then
			SetPersonName(name, character, 3, code);
		delete(s, 1, j);
        i:= Pos(' href="gente/', s);
	end;
  
  // Valoracion
(*  i:=pos('iconota',all);
  if i>0 then begin
     i:=MyPos('&nbsp;<font size="1">',all,i);
     j:=MyPos('</B>',all,i);
     s:=copy(all,i+21,j-i-21);
     s:=ReplaceStr(s, '.', ',', -1);
     try
				rating:=StrToFloat(s);
				except
		 end;
  end;*)
  
end;


//returned images links
procedure GetImages;
var
	i, i2, k, page, frames_count: integer;
	s, s2, all2, frame_url: string;
begin
  // Imagenes
  if DownloadMovieBigCover then
	GetAmazonImages;
  if (front_cover_url<>'') and (front_cover_url<>'http://www.cineol.net/galeria/carteles/nada.jpg') then
	SetImageName('', front_cover_url, '', 1);
  frames_count:=0;
  s:=ParseString(all, '<div class="galeria">(.*?)</div>', 1);
  i:=pos('src="galeria/fotos/thumb90',s);
  while (i>0) and (frames_count<MaxShotsCount) do begin
	j:=MyPos('</a>', s, i+1);
	s2:=copy(s, i, j-i);
	frame_url:=ParseString(s2, 'src="galeria/fotos/thumb90_(.*?)"', 1);
	frame_url:='http://www.cineol.net/galeria/fotos/'+frame_url;
	SetImageName('', frame_url, '', 3);
	delete(s, 1, j);
	i:=pos('src="galeria/fotos/thumb90', s);
  end;
end;

//get movie site url
function GetMovieSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else
		result:='http://www.cineol.net/pelicula/'+code;
//		result:='http://www.cineol.net/pelicula.php?idpelicula='+code;
end;

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


begin

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

prefixes[1]:='El';
prefixes[2]:='La';
prefixes[3]:='Los';
prefixes[4]:='Las';
prefixes[5]:='Les';
prefixes[6]:='Des';
prefixes[7]:='Unas';
prefixes[8]:='Un';
prefixes[9]:='Unos';
prefixes[10]:='Una';

end.