const
	script_name='CINeol';
	language='Spanish';
	version=13;
	author='Ordago_86/Vlad';
	MinProgramBuild=5500;
	PCount = 13;
	//MAX_PHOTOS_COUNT = 3;
var
	DownloadPersonBiography, DownloadPersonAdditionalInfo: boolean;
	MaxPhotosCount: integer;
	
	persons_count: integer;
	persons: array of string;
	imdb_codes: array of string;
	imdb_code, person_code: string;
	name, code, year, description: string;
	person, BasicURL, biography, trivia, character, birth_date, birthplace, birth_name, salary, height, original_name, death_date, person_site_url: string;
	photo_url: string;
	monthes: array [1..12] of string;
	prefixes: array [1..PCount] of string;
	movie_html: string;
	person_height: integer;

function GetSearchURLbyName(PersonName: string): string;
var
	url: string;
begin
	url:=format('http://www.cineol.net/search.php?search=%s&select=2&button=Buscar', [PersonName]);
	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 begin
    showMessage('Archivo Descargado Erroneo');
		result:=-1
	end
	else begin
		result:=PersonSearch;
	end;
		
end;

function Parse(Src, SStart, SEnd: String): String;
var
	s, e: Integer;
begin
	if Length(SStart) <> 0 then s := Pos(SStart, Src)+Length(SStart)
	else s := 1;
	if Length(SEnd) <> 0 then e := Pos(SEnd, Src)
	else e := Length(Src)+1;
	if (s > 0) and (e > 0) then Result := Copy(Src, s, e-s)
	else Result := '';
end;

// ------------------------------------------
//    PERSON SEARCH
// ------------------------------------------
function PersonSearch: integer;
var
	url, s, s2: string;
	i,i2, j, k: integer;
begin
	persons_count:=0;

	i := pos('<div id="gente" class="bloque">', all);
	if i>0 then begin
		j := MyPos('<script', all, i+1);
		s := copy(all, i, j-i);
		i := Pos('<a href="gente/', s);
		while i>0 do begin
			persons_count := persons_count + 1;
			j := MyPos('</a>', s, i+1);
			s2 := copy(s, i, j-i);
			name := RemoveTags(s2);
			person_code := ParseString(s2, '<a href="gente/(.*?)"', 1);
			if name<>'' then
				setSearchResult(name, person_code);
			delete(s, 1, j+4);
			i := Pos('<a href="gente/', s);
		end;
	end;
	result:=persons_count;
end;


function GetPersonURL(code: string; images_only: boolean): string;
begin
	result:='http://www.cineol.net/gente/'+code;
end;

procedure GetPhotos;
var
	i, j, k, page, photo_count: integer;
	s, s2, frame_url: string;
begin
  // Imagenes
  photo_count := 0;

  s:=ParseString(all, '<h2>Galería de Fotos(.*?)</div>', 1);
  i:=Pos('<img src="galeria/fotos/thumb90', s);
  while (i > 0) and (photo_count < MaxPhotosCount) 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, '', 6);
	delete(s, 1, j);
	i:=pos('<img src="galeria/fotos/thumb90', s);
	Inc(photo_count);
  end;
end;

//returnes images links
procedure GetImages;
var 
	s: string;
begin
	if (photo_url<>'') and (photo_url<>'http://www.cineol.net/galeria/gente/nada.jpg') then
		SetImageName('', photo_url, '', 6);
	if MaxPhotosCount > 0 then
		GetPhotos;
    //GetGoogleImage;
end;

function GetGoogleImage: boolean;
var
	all, url: string;
	i, j: integer;
begin
	url:=format('http://images.google.com/images?svnum=20&hl=en&lr=&safe=on&c2coff=1&q=%%22%s%%22', [person]);
	url:=ReplaceStr(url, ' ', '+', -1);
	all:=DownloadURL(url);
	i:=pos('dyn.Img(', all);
	if i>0 then begin
		i:=MyPos('","', all, i+1);
		i:=MyPos('","', all, i+1);
		i:=MyPos('","', all, i+1) + 3;
		j:=MyPos('","', all, i+1);
		if j>0 then begin
			url:=copy(all, i, j-i);
			SetImageName('', url, '', 6);
		end;
	end;
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 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 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 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 ExtractMovies(text_block: string; person_mode: integer);
var
	i, j, n, m: integer;
	s, name, code, year, character: string;
begin
	i := Pos('<a href="pelicula/', text_block);
	while i > 0 do begin
		j:= MyPos('</li', text_block, i+1);
		s:= copy(text_block, i, j-i);
		name:= Parse(s, 'title="', '">');
		n:= pos('<a href="pelicula/', s) + 18;
		m:= MyPos('"', s, n);
		//code:= Parse(s, '<a href="pelicula/', '" title="');
		code:= copy(s, n, m-n);
		year:= Parse(s, '">(', ') ');
		character:= ParseString(s, '</a> \((.*?)\)', 1);
		name:=ClearBrackets(name);
		if name <> '' then begin
			SetMovieName(name, character, person_mode, code, year);
//			ShowMessage(person_mode);
		end;
		delete(text_block, 1, j+4);
		i := Pos('<a href="pelicula/', text_block);
	end;
end;

function GetInfo(url: string; images_only: boolean): string;
var
	s, s2, s3, s4, dia, mes, elyear,all2: string;
	i, j, k, l, n, mode: integer;
begin
	result:='';
	BasicURL:=url;

	person_code:=ParseString(url, 'http://www.cineol.net/gente/(.*?)$', 1);
	person_site_url:=GetPersonSiteURL(person_code);
	all:=DownloadURL(url);
	
	if all='-1' then
		result:='-1'
	else
		result:=all;

	// Nombre
	person:=ParseString(all, '<title>(.*?) - Biografía, filmografía y fotos :: CINeol</title>', 1);
	
	// Nombre real
	original_name:=ParseString(all, '<li><strong>Nombre real:</strong> (.*?)</li>', 1);
	original_name:=RemoveTags(original_name);
	
	// Imagen
	i:=pos('<img src="galeria/gente/',all);
	if i>0 then begin
		photo_url:=ParseString(all, '<img src="galeria/gente/(.*?)"', 1);
		photo_url:='http://www.cineol.net/galeria/gente/'+photo_url;
    	end;

	// Pais
	birthplace:=GetStr(all, '<li><strong>País nacimiento:</strong> ', '</li>');
	birthplace:=RemoveTags(birthplace);
  
  //birth date
  s:=GetStr(all, '<li><strong>Fecha de Nacimiento:</strong> ', '</li>');
  s := RemoveTags(s);
  if s<>'' then begin
	dia:=copy(s,1,2);
	mes:=copy(s,4,2);
	elyear:=copy(s,7,4);
	birth_date:=format('%s/%s/%s',[mes,dia,elyear]);
  end;
  
  //death date
  s:=GetStr(all, '<li><strong>Fecha de Fallecimiento:</strong> ', '</li>');
  s := RemoveTags(s);
  if s<>'' then begin
	dia:=copy(s,1,2);
	mes:=copy(s,4,2);
	elyear:=copy(s,7,4);
	death_date:=format('%s/%s/%s',[mes,dia,elyear]);
  end;
  
  // Biografia
  if DownloadPersonBiography then begin
	  s:=GetStr(all, '<h2>Biografía</h2>', '</p>');
	  i:=Pos('<p>', s);
	  delete(s, 1, i+3);
          while Pos('<br />', S) > 0 do begin 
		Insert(#13#10, s, Pos('<br />', s)); 
		Delete(s, Pos('<br />', s), 6);		
	  end;
	  biography := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
  end;
  
  if DownloadPersonAdditionalInfo then begin
	  // Citas
	  s:=GetStr(all, '<h2>Citas</h2>', '</p>');
	  i:=Pos('<p>', s);
	  delete(s, 1, i+3);
          while Pos('<br />', S) > 0 do begin 
		Insert(#13#10, s, Pos('<br />', s)); 
		Delete(s, Pos('<br />', s), 6);		
	  end;
	  description := RemoveTags(s);
	  
	  // Curiosidades
	  s:=GetStr(all, '<h2>Curiosidades</h2>', '</p>');
	  i:=Pos('<p>', s);
	  delete(s, 1, i+3);
          while Pos('<br />', S) > 0 do begin 
		Insert(#13#10, s, Pos('<br />', s)); 
		Delete(s, Pos('<br />', s), 6);		
	  end;
	  description:=ClearExtraBlankCharacters(description + RemoveTags(s));
  end;
  

  // Comenzamos con la filmografia
  i := pos('>Actor / actriz</h3>',all);
  j := pos('>Dirección</h3>',all);
  k := pos('>Guionista</h3>',all);
  l := pos('>B.S.O.</h3>',all);
  n := pos('>Producción</h3>', all);
  if n=0 then
	n := MyPos('<!-- CONTENIDO fin -->', all, i+1);
  //movies as composer
  if l>0 then begin
	s:=copy(all, l, n-l);
	ExtractMovies(s, 4);
  end
  else l := n;
  //movies as writer
  if k>0 then begin
	s:=copy(all, k, l-k);
	ExtractMovies(s, 2);
  end
  else k := l;
  //movies as director
  if j>0 then begin
	s:=copy(all, j, k-j);
	ExtractMovies(s, 1);
  end
  else j := k;
  //movies as actor
  if i>0 then begin
	s:=copy(all, i, j-i);
	ExtractMovies(s, 3);
  end;
end;

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

//get person site url
function GetPersonSiteURL(code: string): string;
begin
	if code='' then
		result:=''
	else	
    result:='http://www.cineol.net/gente/'+code;
end;

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

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;

begin
monthes[1]:='Enero';
monthes[2]:='Febrero';
monthes[3]:='Marzo';
monthes[4]:='Abril';
monthes[5]:='Mayo';
monthes[6]:='Junio';
monthes[7]:='Julio';
monthes[8]:='Agosto';
monthes[9]:='Septiembre';
monthes[10]:='Octubre';
monthes[11]:='Noviembre';
monthes[12]:='Diciembre';

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.