// ----------------------------------------------------------------------------
// Lauyan Software Javascript Search Engine 2.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é";
LBL_QUERY_RESULT = "résultat(s) trouvé(s) pour :&nbsp";
LBL_ITREFERENCE  = "Référence";
LBL_ITPRICE = 'Prix';
LBL_PRICEERROR = "Erreur de prix";
MIN_WORD_LEN = 2;
DISPLAY_SRCH_INFO = 1;
USE_UTF8 = 0;
REMOVE_ACCENTS = 1;
BOLD_LINKS = 0;
ONLINE_WEBSITE = 1;
ALLWORDSONLY = 0;
SHOWREFERENCES = 0;
BORDERCOLOR = "#990033";
SORTCOMPARE = 2;
itNamesArray = new Array("ART023 ART023",
"ART223 saisissez description article ici ",
"ART224 saisissez description article ici ",
"ART225 saisissez description article ici ",
"Art023 Art023",
"ART190",
"ART401 saisissez description article ici ",
"ART208 saisissez description article ici ",
"ART199 ultra-compact sans sacrifier aux performances vague mini-notebook deferle depuis plusieurs mois face fort engouement public effet comment resister taille mini look surtout simplicite pratiques intuitifs mini-notebooks proposent caracteristiques differentes selon leur systeme d'exploitation processeur encore ergonomie ",
"ART188 c'est l'appellation d'un petit portable d'une taille proche feuille train devenir normale ",
"ART187",
"ART195 ART195 ART195",
"ART476 ART476 ART025 ART001",
"ART164",
"art214 art213 art214 art215",
"Art130 iris iriscan anywhere scanner feuilles 216 297 600 ppp usb utilisable sans pc ",
"ART130 scanner anglicisme mot francais numeriser est peripherique d'acquisition permettant documents c'est-a-dire transformer document papier image numerique distingue generalement trois categories scanners plats placant plat contre vitre s'agit type plus courant main possedant taille reduite ces doivent etre deplaces manuellement semi sur bandes successives afin entier defilement faisant defiler devant fente lumineuse fixe maniere telecopieurs fax plus integre dans appareils tels imprimantes multi fonctions existe egalement capables supports particuliers diapositives ",
"ART191 ART191 ART216 ART217 ART218 ART219",
"ART192 ART192 ART220",
"ART193 ART193 ART221",
"ART057 multi fonction photocopieuse telecopieur imprimante noir blanc jet d'encre copie jusqu'a ppm impression 100 feuilles kbits hi-speed usb ",
"ART211 shuttle 5020ta -tout atom d510 ghz ram disque dur 250 gma 3150 lan sans fil 802 11b microsoft windows Édition familiale premium moniteur Écran lcd ecran large tft materiel garanti ans constructeur ",
"ART175 fujitsu a19-5 eco Écran lcd tft  ",
"ART055",
"ART168",
"ART414",
"ART403 ART401 ART080 ART403 role premier d'un onduleur est proteger ordinateur variations interruptions tension suivant lieu d'habitation coupures d'electricite baisses surtensions seront plus moins frequentes sans defauts entrainent l'arret redemarrage soudain machine ses peripheriques ceci consequence faire perdre travaux cours endommager materiel informatique voir detruire habitiez region peu reculee secteur fournie n'est pas toujours exempte defaut vouliez ainsi donnees c'est dire etre sur interrompu pendant travail l'investissement reste plutot raisonnable meme particulier surtout relativise l'achat complet plupart onduleurs actuels incluent systemes protection contre foudre nombre d'elements connectes ecran modem imprimante scanner etc celui-ci devra posseder capacite batterie d'autant importante voici quelques ordres grandeur puissances prevoir voltampere afin brancher differents additionner fonctionnement autonomie minutes environ ",
"Art150 Art150 300 utilisation standard  ",
"Art151 Art151 500 utilisation frequente relativement importante ",
"Art154 Art154 utilisation journaliere avec donnees grande capacite  ",
"12-001 remplacez texte description article peut etre aussi long souhaitez pouvez laisser lignes blanches aerer presentation egalement demarrer sous-paragraphe commencant ligne caractere comme illustre ci-dessous exemple titre formater utilisant elements syntaxe suivant mettre mots italique attirer l'attention soulignant mots gras combiner styles precedents placer dessus image l'editeur d'images cela cliquer sur modifier puis rendez-vous l'onglet ajouter ceci utile rupture stock promotion  ",
"19-001 saisissez texte paragraphe ici ");
itUrlsArray = new Array("../promotions/page1.html",
"../promotions/page2.html",
"../promotions/page3.html",
"../promotions/page4.html",
"../ordinateursdebur/page1.html",
"../ordinateursdebur/page2.html",
"../ordinateursdebur/page3.html",
"../ordinateursdebur/page4.html",
"../ordinateursporta/page1.html",
"../ordinateursporta/page2.html",
"../ordinateursporta/page3.html",
"../logiciels/page1.html",
"../logiciels/page2.html",
"../logiciels/page3.html",
"../logiciels/page4.html",
"../imprimantes/page1.html",
"../imprimantes/page2.html",
"../imprimantes/page3.html",
"../imprimantes/page4.html",
"../imprimantes/page5.html",
"../imprimantes/page6.html",
"../magasin/index.html",
"../accessoires/page1.html",
"../accessoires/page2.html",
"../accessoires/page3.html",
"../accessoires/page4.html",
"../accessoires/page5.html",
"../accessoires/page6.html",
"../accessoires/page7.html",
"../accessoires/page8.html",
"../ciac/index.html",
"../tousvents/index.html");
itTitlesArray = new Array("A saisir tour + écran 21.5 multimédia a moins de 500€ TTC",
"Mini Portable en SUPER Promotion (jusqu'au 31 juillet uniquement)",
"Portable 15-17",
"Imprimante Laser Couleur",
"A saisir tour + écran 21.5 multimédia a moins de 500€ TTC",
"Ordinateur de bureau avec écran 20",
"Le pc le moins cher (sans moniteur)",
"Tout en un 23'' full HD",
"Mini Notebook",
"Notebook",
"Portable haut de gamme",
"AutoCAD LT 2011",
"Microsoft Office Professionnel 2010 complet",
"QuarkXPress V8",
"Bureautique",
"Scanner Portable",
"Scanner à plat",
"Laser couleur au meilleur prix (n'oubliez pas les cartouches en réserve)",
"Laser N&B au meilleur prix",
"Jet d'encre couleur au meilleur prix",
"Fax multi fonction",
"Shuttle X 5020TA",
"Ecran 19''",
"Clavier & Souris sans fil",
"Souris sans fil Noir",
"Câble USB",
"Onduleurs",
"Disques Durs Externe Moyenne capacité  320Go",
"Disques Durs Externe Grande capacité  500Go",
"Disques Durs Externe très grande capacité  1.5 To",
"Liste des postes du centre (format HTML)",
"Tousvents");
itDescArray = new Array("",
"Saisissez la description  de votre article ici",
"Saisissez la description  de votre article ici",
"Saisissez la description  de votre article ici",
"",
"",
"Saisissez la description  de votre article ici",
"Saisissez la description  de votre article ici",
"Ultra-compact sans sacrifier aux performances, la vague mini-notebook déferle depuis plusieurs mois face à un fort engouement du public. En effet, comment résister à la taille mini, au look et surtout à la simplicité du mini-notebook ? Pratiques et intuitifs, les mini-notebooks proposent des caractéristiques différentes, selon leur système d'exploitation, leur processeur ou encore leur ergonomie.",
"C'est l'appellation d'un petit portable d'une taille proche d'une feuille A4.  C'est en train de devenir la taille normale d'un portable.",
"",
"",
"",
"",
"",
"IRIS IRIScan Anywhere 2 - Scanner à feuilles - 216 x 297 mm - 600 ppp - USB Utilisable sans pc",
"Un scanner (anglicisme pour le mot français numériser) est un périphérique d'acquisition permettant de numériser des documents, c'est-à-dire de transformer un document papier en image numérique.  On distingue généralement trois catégories de scanners :  -Les scanners à plats permettant de numériser un document en le plaçant à plat contre une vitre. Il s'agit du type de scanner le plus courant. -Le...",
"",
"",
"",
"Multi fonction (photocopieuse / télécopieur / imprimante) - Noir et blanc - jet d'encre - copie (jusqu'à) : 4.5 ppm - impression (jusqu'à) : 5.5 ppm - 100 feuilles - 14.4 Kbits/s - Hi-Speed USB",
"Shuttle X 5020TA -Tout en un 1 x Atom D510 / 1.66 GHz   RAM 2 Go -  Disque dur 1 x 250 Go - GMA 3150   LAN sans fil : 802.11b/g/n  Microsoft Windows 7 Édition Familiale Premium  Moniteur Écran LCD 15.6 écran large TFT Matériel garanti 2 ans constructeur",
"Fujitsu A19-5 ECO - Écran LCD - TFT - 19",
"",
"",
"",
"Le rôle premier d'un onduleur est de protéger votre ordinateur des variations et interruptions de tension.  Suivant votre lieu  d'habitation, les coupures d'électricité, les baisses de tension ou les surtensions seront plus ou moins fréquentes.   Sans onduleur, les défauts de tension entraînent l'arrêt et le redémarrage soudain de votre machine et de ses périphériques.   Ceci a pour conséquence de...",
"300 Go pour une utilisation standard",
"500 Go pour une utilisation fréquente et relativement importante",
"1.5 To pour une utilisation journalière et avec des données a grande capacité",
"Remplacez ce texte par la description de votre article. Votre texte peut être aussi long que vous le souhaitez et vous pouvez  laisser des lignes blanches pour aérer la présentation.  Vous pouvez également démarrer un sous-paragraphe en commençant une ligne par le caractère + comme illustré ci-dessous :  + Exemple de titre de sous-paragraphe  Vous pouvez également formater votre texte en utilisant...",
"Saisissez le texte du paragraphe ici");
itImgArray = new Array("../promotions/bv000003.thumb.jpg",
"../promotions/bv000001.thumb.jpg",
"../promotions/bv000002.thumb.jpg",
"../promotions/bv000004.thumb.jpg",
"../ordinateursdebur/bv000003.thumb.jpg",
"../ordinateursdebur/bv000014.thumb.jpg",
"../ordinateursdebur/bv000001.thumb.jpg",
"../ordinateursdebur/bv000002.thumb.jpg",
"../ordinateursporta/bv000014.thumb.jpg",
"../ordinateursporta/bv000001.thumb.jpg",
"../ordinateursporta/bv000002.thumb.jpg",
"../logiciels/bv000001.thumb.jpg",
"../logiciels/bv000014.thumb.jpg",
"../logiciels/bv000004.thumb.jpg",
"../logiciels/bv000002.thumb.jpg",
"../imprimantes/bv000005.thumb.jpg",
"../imprimantes/bv000004.thumb.jpg",
"../imprimantes/bv000014.thumb.jpg",
"../imprimantes/bv000002.thumb.jpg",
"../imprimantes/bv000001.thumb.jpg",
"../imprimantes/bv000003.thumb.jpg",
"../magasin/bv000014.thumb.jpg",
"../accessoires/bv000014.thumb.jpg",
"../accessoires/bv000001.thumb.jpg",
"../accessoires/bv000002.thumb.jpg",
"../accessoires/bv000003.thumb.jpg",
"../accessoires/bv000004.thumb.jpg",
"../accessoires/bv000005.thumb.jpg",
"../accessoires/bv000006.thumb.jpg",
"../accessoires/bv000007.thumb.jpg",
"",
"../tousvents/bv000032.thumb.jpg");
itRefArray = new Array("ART023 ART023",
"ART223",
"ART224",
"ART225",
"Art023 Art023",
"ART190",
"ART401",
"ART208",
"ART199",
"ART188",
"ART187",
"ART195 ART195 ART195",
"ART476 ART476 ART025 ART001",
"ART164",
"art214 art213 art214 art215",
"Art130",
"ART130",
"ART191 ART191 ART216 ART217 ART218 ART219",
"ART192 ART192 ART220",
"ART193 ART193 ART221",
"ART057",
"ART211",
"ART175",
"ART055",
"ART168",
"ART414",
"ART403 ART401 ART080 ART403",
"Art150 Art150",
"Art151 Art151",
"Art154 Art154",
"12-001",
"19-001");
itPricesArray = new Array(418.00,
325.00,
435.00,
215.00,
418.00,
1095.00,
450.00,
995.00,
335.00,
480.00,
995.00,
795,
0.00,
1395.00,
58.00,
192,
118,
215.00,
115.00,
98,
98.00,
595,
155.00,
45,
35.00,
10.00,
120.00,
115.00,
145.00,
190.00,
0.00,
0.00);
var itemsCount = 32;
var catalogdirs = new Array("/promotions/",
"/ordinateursdebur/",
"/ordinateursporta/",
"/logiciels/",
"/imprimantes/",
"/magasin/",
"/accessoires/",
"/ciac/",
"/tousvents/");
var catalognames = new Array("Promotions du Mois",
"Ordinateurs de bureau",
"Ordinateurs Portables",
"Logiciels",
"Imprimantes,fax & scanners",
"Shuttle",
"Accessoires",
"Cliac (Massy)",
"CFIP intranet");

			
function SubmitSearch(n)
{
	var p = document.getElementsByName("jse_query");
	if( p < 0) return false;
	if( p && p[n] && p[n].value != "" ) 
	{
	  if( (p[n].value).replace(/^\s+|\s+$/g, '') != "" ) 
	  {
		var idx = 0;
		p = document.getElementsByName("minprice");
		if( p && p[idx] )
		{
			if( p[idx].value != "" && isNaN(p[idx].value) )
			{
				if( LBL_PRICEERROR != "" )
					alert( LBL_PRICEERROR );
				return false;
			}
		}
		p = document.getElementsByName("maxprice");
		if( p && p[idx] )
		{
			if( p[idx].value != "" && isNaN(p[idx].value) )
			{
				if( LBL_PRICEERROR != "" )
					alert( LBL_PRICEERROR );
				return false;
			}
		}
		p = document.getElementsByName("jse_form");
		if( p && p[n] )
			p[n].submit();
		return true;
	  }
	}
	return false;
}
function switchSearchLang(lang,emptycart)
{
	var params = "";
	var currURL = document.location.href;
	var newURL = (currURL.lastIndexOf('_frame/search2') >= 0) ? "search2":"search";
	if( lang != "" )
		newURL += "-"+lang;
	newURL += ".html";
	var paramIndex = currURL.lastIndexOf('?');
	if( paramIndex > -1 )
		newURL += "?" + currURL.substr( paramIndex + 1 );
	if( emptycart && typeof(CleanShopcart) != "undefined" )
		CleanShopcart();
	document.location.href = newURL;
	return false;
}
			
// 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 getQueryParam()
{
  var query = getParam("jse_query");
  query = query.replace(/[\++]/g, " ");  // replace any '+' with spaces
  query = query.replace(/\</g, "&lt;");
  query = query.replace(/[\"+]/g, " ");
	return query;
}

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 SortCompare2(a, b)
{
	if( SORTCOMPARE == 1 ) 
	{
	    if (a[3] < b[3]) return 1;
	    else if (a[3] > b[3]) return -1;
	    else return 0;
	}
	else if( SORTCOMPARE == 0 )
	{
	    if (a[3] > b[3]) return 1;
	    else if (a[3] < b[3]) return -1;
	    else return 0;
	}
	return -1;
}

function jseSearch2( internal )
{
  // 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 = getQueryParam();
  var sortp = getParam("sort");
  if( sortp == "0" ) {
	SORTCOMPARE = 0;
  } else if( sortp == "1" ) {
	SORTCOMPARE = 1;
  } else if( sortp == "2" )
	SORTCOMPARE = 2;
  var catfilterp = getParam("cat");
  var minPrice = getParam("minprice");
  var maxPrice = getParam("maxprice");
 
  // display the search form
  var lnktarget = "";
	query = formatChars(query);
  if( query.length == 0 ) return;
  
  var found=0, t=0, k=0, score=0, i=0;
  var keyword = "", tmp = "";
  var searchWords = new Array();

  // split search query by spaces
  searchWords = query.split(" ");
  // init result table information
  res_table = new Array(itemsCount);
  for( t=0; t<itemsCount; 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] = 0;  // price
  }

  var significantwords = 0;

  // begin search ...
  for( i=0; i<searchWords.length; i++ )
  {
    keyword = searchWords[i];
    if( keyword.length > MIN_WORD_LEN ) // skip small words
	{
	  significantwords++;
	  for(var q=0; q<itemsCount; q++ )
	  {
		// catalog filter verification
	    if( catfilterp != "" && catfilterp != "allcat" && itUrlsArray[q].indexOf(catfilterp) == -1 ) 
			continue;
		// min and max price filter
	    if( minPrice > 0 && itPricesArray[q] < minPrice )
			continue;
	    if( maxPrice > 0 && itPricesArray[q] > maxPrice )
			continue;
		// search for keywords (an exact word doubles the score)
		score = 0;
		tmp = formatChars(itDescArray[q]);
	    if( tmp.indexOf(keyword) != -1 ) score++;
	    if( tmp.indexOf(' '+keyword+' ') != -1 ) score+=2;
		  tmp = formatChars(itTitlesArray[q]);
	  	if( tmp.indexOf(keyword) != -1 ) score++;
		  if( tmp.indexOf(' '+keyword+' ') != -1 ) score+=2;
		  tmp = formatChars(itNamesArray[q]);
	    if( tmp.indexOf(keyword) != -1 ) score++;
	    if( tmp.indexOf(' '+keyword+' ') != -1 ) score+=2;
			
	    if( score > 0 ) // && itPricesArray[q] > 0 )  // add this test in order not to display 0.00 prices 
	    {
		  if( res_table[q][1] <= 0 ) 
			found++;	// increment only if not already found with a previous keyword
	      res_table[q][0] = q;
	      res_table[q][1] = 1; // itPricesArray[q];
	      res_table[q][2]++;
	      res_table[q][3] = itPricesArray[q];
	    }
	  }
	}
  }
  if( found == 0 ) {
    document.write("<br><p class='wg-paragraph'><b>" + STR_NO_RESULT + "</b></p>");
  } 
  else 
  {
	if( ALLWORDSONLY )
	{
		//  if all words only then we recount and filter amoung the results to get the total of found items
		found = 0;
		for( var z=0; z<itemsCount; z++ )
			if( res_table[z][1] > 0 ) // display only results with a positive score
			if( !ALLWORDSONLY || (ALLWORDSONLY && res_table[z][2] == significantwords) )
				found++;
	}
	if( internal == null || internal != 1 ) {
		document.writeln( "<span class='wg-paragraph'>" + found + " " + LBL_QUERY_RESULT + "<strong>" +query+"</strong></span>" );
	}
	// sort by words found and scores
	if( SORTCOMPARE >= 0 && SORTCOMPARE <= 1 )
		res_table.sort(SortCompare2);	
    // display the results
	document.writeln("<table border='1' class='wg-paragraph' bordercolor='"+BORDERCOLOR+"' style='border-collapse:collapse;margin:4px;' cellspacing='2' cellpadding='2' >");

	for( var q=0; q<itemsCount; q++ )
	{
      if( res_table[q][1] > 0 ) // display only results with a positive score
	  if( !ALLWORDSONLY || (ALLWORDSONLY && res_table[q][2] == significantwords) )
	  {
        t = res_table[q][0];    // get page index
		document.writeln("<tr valign='top'><td>");
		if( itImgArray[t] != "" ) {
			document.writeln("<a href=\"" + itUrlsArray[t] + lnktarget + "\">" + "<img src='"+itImgArray[t]+"' border='0' width=\"48\" height=\"48\" /></a>" );
		}
		document.writeln("</td><td>");
		if( 1 ) { //BOLD_LINKS ) {
          document.writeln("<b><a href=\"" + itUrlsArray[t] + lnktarget + "\">" + itTitlesArray[t] + "</a></b><br>" );
        } else
          document.writeln("<a href=\"" + itUrlsArray[t] + lnktarget + "\">" + itTitlesArray[t] + "</a><br>" );
		if( SHOWREFERENCES && itRefArray[t] != "" ) {
			var ref = itRefArray[t].split(' ');
			if( ref && ref[0] != "" ) 
				document.writeln( LBL_ITREFERENCE+" : "+ref[0]+"<br>" );
		}
        if( itDescArray[t].length > 2 )
			document.writeln( itDescArray[t]);
		document.writeln("</td><td nowrap>");
		if( itPricesArray[t] != ""  && itPricesArray[t] > 0 )
			document.writeln( LBL_ITPRICE+"<br><b>"+AddMonetarySymbol(moneyFormat(itPricesArray[t]))+"</b>" );
		else
			document.writeln( "&nbsp;" );
		document.writeln("</td></tr>");
      }
	}
	document.writeln("</table>");			
  }
  document.writeln("<br>");
}
