// ----------------------------------------------------------------------------
// Lauyan Software Javascript Search Engine 1.0
//
// This file is the JavaScript search engine for a website created by TOWeb
//
// Copyright (C) LAUYAN SOFTWARE 2006
// web: http://www.lauyan.com
// ----------------------------------------------------------------------------

STR_SEARCH_QUERY_MSG = "Résultats de la recherche pour";
STR_NO_RESULT = "Aucun résultat trouvé";
STR_SEARCH_BUTTON = "Rechercher";
STR_SCORE = "Score";
STR_TERMS = "Termes";
STR_SEARCH_SIZE = "40";
MIN_WORD_LEN = 2;
DISPLAY_SRCH_INFO = 1;
USE_UTF8 = 0;
REMOVE_ACCENTS = 1;
BOLD_LINKS = 1;
ONLINE_WEBSITE = 1;

namesArray = new Array(" librairie rome accueille jours sur 365 depuis 1934  ",
" librairie rome livre bruxelles presse international ",
" harold cleaver presentateur vedette bbc est confronte l'image ses proches ont lui l'intermediaire d'un roman ecrit son fils dans lequel apparait comme monstre d'egoisme menteur manipulateur foulee cette lecture doit interviewer president etats-unis tache laquelle livrera maniere tout fait hors norme posant questions inattendues musclees faisant meme cet interview l'apotheose carriere c'est aussi precisement moment qu'il choisit prendre large refugie seul petit abri montagne tyrol confronter chacune assertions ",
" foenkinos l'ecrivain phagocytant codes l'autofiction raconte comment personnage vit parallele decadence litteraire est panne d'idees depuis plusieurs annees manque d'argent vie maritale materiau romanesque pas franchement innovant adultere crise quarantaine relations voisinage ameliepoulinesque prend grace tour passe-passe technique relief saveur rafraichissantes  ",
" l'excellent editeur actes sud cree peu plus d'un nouvelle collection intitulee noirs accueillir premier volume millenium c'etait hommes n'aiment pas femmes depuis lors deuxieme troisieme volumes respectivement intitules fille revait bidon d'essence d'une allumette reine dans palais courants d'air l'ont rejoint titres assez etranges attirer l'œil cachent romans non moins remarquables bases sur deux personnages principaux mikael blomkvist lisbeth salander auxquels s'ajoutent cinquantaine secondaires dont aucun n'est laisse cote faisant l'auteur donne son recit presence bien superieure aux policiers habituels lesquels temoins flics autres seconds roles servent qu'a faire progresser l'action cadre est celui suede originaire larsson aborde l'histoire pays ainsi qu'une multitude sujets quotidiens actuels avec realisme acuite marquante ",
" mendelshon decrit minutieusement recherches qu'il menees pendant ans parvenir apprehender qu'avaient ete vie mort son grand-oncle schmiel jager femme leurs quatre filles raconte resultats progressifs quete bolechow pologne jerusalem israel tente decrire plus particulier generalite innommable l'holocauste  ",
" dans beaute solaire l'ile grecque spetses pere pavlina decouvre fille n'est pas lui partir cette trahison originaire vie famille louganis sera marquee sceau tragedie  ",
" dans avec vue sur royaume jean-pierre gattegno presente mise scene fois drole pathetique l'au-dela defunts sont transportes bord d'un skybus traverse l'eternite vitesse supersonique luxueuse hyper class specialement amenagee ecran hemispherique diffusant images terre raoul sevilla fils juifs saloniciens voyage cote alejandro waldheim criminel guerre nazi sevi camp terezin embarque eux vol sans destination lecteur vit rythme leurs introspections diffusees tentant comprendre liens ont unis mort ",
" c'est recit autobiographique concu comme poupees russes trois histoires s'entremelent dont principale n'apparait progressivement d'abord film l'auteur tourne kotelnitch trou russie profonde raconte l'histoire d'un paysan hongrois enrole dans forces wehrmacht capture l'armee rouge 1944 interne pendant cinquante-six ans hopital psychiatrique russe rapatrie budapest seulement sept enfin figure grand-pere maternel pere d'helene carrere d'encausse disparu sans doute execute collaboration est trame raison d'etre roman ",
" merveilleuse galerie portraits habitants d'un riche hotel particulier parisien madame michel concierge cache derriere l'archetype peu flatteur profession alors qu'elle est realite erudite fine lettree ",
" roman presente son auteur comme autobiographie shantaram raconte vie cavale d'un jeune homme australien fuir police fondre dans bombay vivra tant d'aventures l'on peine croire qu'un seul ait vivre toutes histoires contees qu'importe puisqu'au final lecteur regale recit aux innombrables rebondissements ",
" mario vargas llosa fait traverser monde part gre reapparitions nina mala objet cruel passion narrateur cessera derober lui profit d'hommes plus riches roman subtilement cosmopolite ",
" premier grand chef d'oeuvre 21e siecle prix goncourt 2006  ",
" fresque humaniste sur detresse immigres servie ecriture magnifique  ",
" nancy huston glisse dans peau quatre enfants ans generations successives livre eblouissant sur maniere dont forge identite situe l'interieur d'une lignee prix femina 2006  ",
" recit d'une incroyable fluidite sous forme monologues entrecroises fait appel notre memoire collective recente reapproprie l'histoire contemporaine replongeant dans drame heysel  ",
" histoire sensible reliant octogenaire rescape shoah adolescente souffrant difficultes familiales lire absolument  ",
" apres l'attentat hirondelles kaboul yasmina khadra poursuit son exploration moyen-orient met mots quotidien debut 21e siecle qu'est terrorisme s'empare monde transformer roman partant lui donner sens percutant incontournable  ",
" meilleures ventes  ",
" librairie rome livre bruxelles presse international ",
" blog-notes  ",
" depuis 1er fevrier 2003 librairie rome pris ses quartiers dans calme serenite louise village deux pas son ancienne adresse  ",
" revue presse  ",
" recherche  ");
urlsArray = new Array("../topic/index.html",
"../coupdecoeur/index.html",
"../coupdecoeur/page1.html",
"../coupdecoeur/page2.html",
"../coupdecoeur/page3.html",
"../coupdecoeur/page4.html",
"../coupdecoeur/page5.html",
"../coupdecoeur/page6.html",
"../coupdecoeur/page7.html",
"../coupdecoeur/page8.html",
"../coupdecoeur/page9.html",
"../coupdecoeur/page10.html",
"../coupdecoeur/page11.html",
"../coupdecoeur/page12.html",
"../coupdecoeur/page13.html",
"../coupdecoeur/page14.html",
"../coupdecoeur/page15.html",
"../coupdecoeur/page16.html",
"../meilleuresventes/index.html",
"../prixlitteraires2006/index.html",
"../blog/index.html",
"../coordonnees/index.html",
"../revuedepresse/index.html",
"../recherche/index.html");
titlesArray = new Array("La librairie de rome",
"Librairie de rome",
"LE SILENCE DE CLEAVER - T. PARKS - Actes Sud",
"QUI SE SOUVIENT DE DAVID FOENKINOS - D. FOENKINOS - Gallimard",
"TRILOGIE MILLENIUM - S. LARSSON - Actes Sud",
"LES DISPARUS - D. MENDELSHON - Flammarion",
"LA FILLE DES LOUGANIS - M. ARDITI - Actes Sud",
"AVEC VUE SUR LE ROYAUME - J.-P. GATTEGNO - Actes Sud",
"UN ROMAN RUSSE - E. CARRERE - P.O.L.",
"L'ELEGANCE DU HERISSON - M. BARBERY - Gallimard",
"SHANTARAM - G.-D. Roberts - Flammarion",
"TOURS ET DETOURS DE LA VILAINE FILLE - M. VARGAS LLOSA - Gallimard",
"LES BIENVEILLANTES - J. LITTEL - Gallimard",
"ELADORADO - L. GAUDE - Actes Sud",
"LIGNES DE FAILLE - N. HUSTON - Actes Sud",
"DANS LA FOULE - L. MAUVIGNE - Ed. de Minuit",
"L'HISTOIRE DE L'AMOUR - N. KRAUSS - Gallimard",
"LES SIRENES DE BAGDAD - Y. KHADRA - Julliard",
"Meilleures ventes",
"Librairie de rome",
"Blog-notes",
"Rentrée littéraire",
"Revue de presse",
"Recherche");
descArray = new Array("librairie de rome Livres Presse international english books librairie bruxelles roman",
"",
"&",
"&",
"&",
"&",
"&",
"&",
"&",
"&",
"&",
"&",
"&",
"&",
"&",
"&",
"&",
"&",
"",
"",
"",
"",
"",
"");
sublinksArray = new Array(24);
var linksCount = 24;


// getParam returns the value of the specified GET parameter
function getParam(paramName)
{
    paramStr = document.location.search;
    if( paramStr == "" )
        return "";
    if( paramStr.charAt(0) == "?" )
        paramStr = paramStr.substr(1);
    arg = (paramStr.split("&"));
    for( i=0; i<arg.length; i++ ) 
    {
      arg_values = arg[i].split("=")
      if( unescape(arg_values[0]) == paramName ) 
      {
         if( USE_UTF8 == 1 && self.decodeURIComponent ) // check if decodeURIComponent() is defined
            ret = decodeURIComponent(arg_values[1]);
         else
            ret = unescape(arg_values[1]);  // IE 5.0 and older does not have decodeURI
         return ret;
      }
    }
    return "";
}

function replaceAll(str,from,to) 
{
    var idx = str.indexOf(from);
    while( idx > -1 ) {
        str = str.replace(from, to); 
        idx = str.indexOf(from);
    }
    return str;
}

// lowercase, remove quotes and accents
function formatChars(str) 
{
    str = str.toLowerCase();
    if( REMOVE_ACCENTS ) 
    {
      var a = "àáâãäåòóôõöèéêëçìíîïùúûüÿñ";
      var b = "aaaaaaoooooeeeeciiiiuuuuyn";
      for( i=0; i<a.length; i++ )
        str = replaceAll( str, a.charAt(i), b.charAt(i) );
    }
    str = replaceAll( str, "'", " " );
    return str;
}

function SortCompare(a, b)
{
  if( a[2] == b[2] )
  {  
    if (a[1] < b[1]) return 1;
    else if (a[1] > b[1]) return -1;
    else return 0;
  }
  else if (a[2] < b[2]) return 1;
    else return -1;
}

function jseSearch()
{
  // get params
  var rootURL = '';
	var SelfURL = document.location.href;
  var paramIndex = SelfURL.indexOf("?");    
  if (paramIndex > -1)
     SelfURL = SelfURL.substr(0, paramIndex);
  paramIndex = SelfURL.indexOf("#");
  if (paramIndex > -1)
    SelfURL = SelfURL.substr(0, paramIndex);        
	if (ONLINE_WEBSITE) 
	{
		paramIndex = SelfURL.lastIndexOf('/');
		if (paramIndex > -1) 
		{
			rootURL = SelfURL.substr(0, paramIndex);
			paramIndex = rootURL.lastIndexOf('/');
			if (paramIndex > -1) {
				rootURL = SelfURL.substr(0, paramIndex+1);
			} else
			  rootURL = '';
		}
	}	
  SelfURL = SelfURL.replace(/\</g, "&lt;");
  SelfURL = SelfURL.replace(/\"/g, "&quot;");

  var query = getParam("jse_query");
  query = query.replace(/[\++]/g, " ");  // replace any '+' with spaces
  query = query.replace(/\</g, "&lt;");
  query = query.replace(/[\"+]/g, " ");

  // display the search form
  document.writeln("<form method=\"get\" action=\"" + SelfURL + "\">");
  document.writeln("<input type=\"text\" name=\"jse_query\" size=\"" + STR_SEARCH_SIZE + "\" value=\"" + query + "\" />");
  document.writeln("<input type=\"submit\" value=\"" + STR_SEARCH_BUTTON + "\" />");
  document.writeln("</form>");

  query = formatChars(query);
  if( query.length == 0 ) return;
  
  var found=0, t=0, k=0, score=0, subscore=0, i=0;
  var keyword = "", tmp = "";
  var searchWords = new Array();

  // split search query by spaces
  searchWords = query.split(" ");
  document.write( "" + STR_SEARCH_QUERY_MSG + " : <strong>" +query+"</strong><br>");

  // init result table information
  res_table = new Array(linksCount);
  for( t=0; t<linksCount; t++ )
  {
    res_table[t] = new Array(3);
    res_table[t][0] = 0;  // index
    res_table[t][1] = 0;  // score
    res_table[t][2] = 0;  // words found
    res_table[t][3] = ""; // sublinks (output string)
  }

  // begin search ...
  for( i=0; i<searchWords.length; i++ )
  {
    keyword = searchWords[i];
    if( keyword.length > MIN_WORD_LEN ) // skip small words
	  for(var q=0; q<linksCount; q++ )
	  {
	    t = q;
	    score = 0;
	
	    // search for keywords (an exact word doubles the score)
		  tmp = formatChars(descArray[t]);
	    if( tmp.indexOf(keyword) != -1 ) score++;
	    if( tmp.indexOf(' '+keyword+' ') != -1 ) score+=2;
		  tmp = formatChars(titlesArray[t]);
	  	if( tmp.indexOf(keyword) != -1 ) score++;
		  if( tmp.indexOf(' '+keyword+' ') != -1 ) score+=2;
	    if( namesArray[t].indexOf(keyword) != -1 ) score++;
	    if( namesArray[t].indexOf(' '+keyword+' ') != -1 ) score+=2;
	
		// search for keywords in sublinks (i.e. bookmarks)
	    k = q+1;
		  while( k <= linksCount )
		  {
		    tmp = descArray[k];
				if( tmp == null || tmp.charAt(0) != '&' ) break;
				subscore = 0;
				tmp = formatChars(descArray[k]);
				if( tmp.indexOf(keyword) != -1 ) subscore++;
				if( tmp.indexOf(' '+keyword+' ') != -1 ) subscore+=2;
				tmp = formatChars(titlesArray[k]);
				if( tmp.indexOf(keyword) != -1 ) subscore++;
				if( tmp.indexOf(' '+keyword+' ') != -1 ) subscore+=2;
				if( namesArray[k].indexOf(keyword) != -1 ) subscore++;
				if( namesArray[k].indexOf(' '+keyword+' ') != -1 ) subscore+=2;
				if( subscore > 0 )
				{
	        if( res_table[t][3].indexOf( "'" + urlsArray[k] + "'" ) == -1 )
	        {
/*	           		if( BOLD_LINKS ) { 
						res_table[t][3] += "<tr><td width='50'>&nbsp</td><td><b><a href='" + urlsArray[k] +"'>" + titlesArray[k] + "</a></b></td></tr>";
					} else	
*/	          res_table[t][3] += "<tr><td width='35'>&nbsp</td><td><a href='" + urlsArray[k] +"'>" + titlesArray[k] + "</a></td></tr>";
	        }
		      score += subscore;
		    }	
		    k++;
		  }
		  q = k-1;
		
	    if( score > 0 )
	    {
	      res_table[t][0] = t;
	      res_table[t][1] += score;
	      res_table[t][2]++;
	      found++;
	    }
	  }
  }
  if( found == 0 ) 
  {
    document.write("<p><b>" + STR_NO_RESULT + "</b></p>");
  } 
  else 
  {
    // sort by words found and scores
    res_table.sort(SortCompare);	
    // display the results
    for( q=0; q<found; q++ )
      if( res_table[q][1] > 0 ) // display only results with a positive score
	    {
        t = res_table[q][0];    // get page index
        if( BOLD_LINKS ) {
          document.writeln("<br><b>" + (q+1) + ". <a href=" + urlsArray[t] +">" + titlesArray[t] + "</a></b>" );
        } else
          document.writeln("<br><b>" + (q+1) + ".</b> <a href=" + urlsArray[t] +">" + titlesArray[t] + "</a>" );
        if( descArray[t].length > 2 )
          document.writeln("<br>" + descArray[t]);
        if( DISPLAY_SRCH_INFO ) 
				{
          document.write("<br><span style='font-size: 80%; font-style: italic;'>" + STR_TERMS + ": " + res_table[q][2] + " - " + STR_SCORE + ": " + res_table[q][1] );
					if (ONLINE_WEBSITE) {
					  document.writeln(" - URL: " + rootURL + urlsArray[t].substr(3) + "</span>");
					}	else
					  document.writeln(" - URL: " + urlsArray[t] + "</span>");
      	}
				if( res_table[q][3].length > 0 ) { 
      	  document.writeln( '<table>' + res_table[q][3] + '</table>' );
      	} else document.writeln("<br>");
      }
  }
  document.writeln("<br>");
}
