// ----------------------------------------------------------------------------
// 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 = 1;
DISPLAY_SRCH_INFO = 1;
USE_UTF8 = 0;
REMOVE_ACCENTS = 1;
BOLD_LINKS = 0;
ONLINE_WEBSITE = 1;
ALLWORDSONLY = 0;
SHOWREFERENCES = 0;
BORDERCOLOR = "#FF8704";
SORTCOMPARE = 0;
itNamesArray = new Array("1-001 introduction au monde affaires en chine occuper un poste managerial ou l'etranger et savoir gerer la communication inter-culturelle avec professionnels chinois ",
"3-001 methodes et outils realiser un audit d`usine performant cours premium ",
"2-001 toutes methodes et tous outils necessaires reussir recherche de produits selection fournisseurs en chine attention n'inclus pas le suivi production ni controle qualite  ",
"2-002 methodes et outils optimiser la phase initiale de sourcing ne pas faire d'impairs lors signature du contrat operer un suivi achat production qualite plus professionnels tout en construisant relation stable avec fournisseurs chinois cours premium  ",
"4-001 presentation du qc controle qualite de ses methodes et differentes techniques basiques gestion la produits consommation courante pendant production avant l'envoi marchandise en export cours debutants  ",
"4-002 presentation du qc controle qualite de ses methodes et differentes techniques gestion la produits l'industrie lourde pendant production avant l'envoi marchandise en export cours premium  ",
"5-001 tout ce devez savoir sur le shanghai pratique un court sejour ou installation en douceur et rassurante ",
"5-002 tout ce devez savoir sur le guangzhou pratique un court sejour ou installation en douceur et rassurante ",
"4-003 disponible tres prochainement cours premium ",
"D-001 travailler avec fabricants competents et en phase standards internationaux ce concerne l'organisation de leur usine est aujourd'hui devenu condition sine qua non acheteurs charge la selection partenaires chinois notamment dans le secteur industriel changer fournisseur ou remettre niveau partenaire travail sourcing s'il survient cadre du remplacement d'un habituel un nouveau cout peut s'averer tres important effet si l'on considere fait fabricant produit donne va impliquer l'acheteur fort investissement temps ressources humaines celui-ci doit egalement tenir compte risques mise œuvre nouvelle d'une communication d'abord moins fluide pourra etre l'origine problemes delais qualite produits enfin lies aux differents ajustements procedures seront incontournables debut cooperation c'est raison laquelle plus d'acheteurs doivent opter formule adaptee lorsque budget permet aussi auditer l'usine identifier lacunes majeures defauts critiques son systeme lui suggerer d'effectuer remise l'aide consultant externe specialise certains considerent vrai dire cette solution nouveaux fournisseurs lesquels ils souhaitent anticiper futurs sur leurs dont cause pourrait facteur organisation faire idee precise actions effectives peuvent menees d'usine voici condense etude cas pratique lire suite ajoutez l'article panier ");
itUrlsArray = new Array("../catalogue/page1.html",
"../catalogue/page2.html",
"../catalogue/page3.html",
"../catalogue/page4.html",
"../catalogue/page5.html",
"../catalogue/page6.html",
"../catalogue/page7.html",
"../catalogue/page8.html",
"../catalogue/page9.html",
"../magasin1/index.html");
itTitlesArray = new Array("Conduite Efficace du Business en Chine",
"Audit d`Usine en Chine",
"Réussir son Sourcing en Chine",
"Sourcing, Achats et Relations Fournisseurs",
"QC des Produits de Consommation Courante",
"QC des Produits de l'Industrie Lourde",
"Vivre à Shanghai",
"Vivre à Guangzhou (Canton)",
"QA des Usines : Qualité Générale, QC Produits, Process Qualité",
"Cas pratique : Remise à Niveau d'une Usine Chinoise");
itDescArray = new Array("Introduction au monde des affaires en Chine : occuper un poste managerial en Chine ou à l'étranger et savoir gérer la communication inter-culturelle avec les professionnels Chinois",
"Methodes et Outils pour realiser un audit d`usine performant. Cours PREMIUM.",
"Toutes les méthodes et tous les outils nécessaires pour réussir votre recherche de produits et votre sélection de fournisseurs en Chine.  ATTENTION : N'inclus pas le suivi de production ni le contrôle qualité.",
"Méthodes et outils pour optimiser la phase initiale de sourcing, ne pas faire d'impairs lors de la signature du contrat, et opérer un suivi achat / production / qualité des plus professionnels, tout en construisant une relation stable avec vos fournisseurs chinois.  Cours PREMIUM.",
"Présentation du QC (contrôle qualité), de ses méthodes, et des différentes techniques basiques de gestion de la qualité des produits de consommation courante, pendant la production et avant l'envoi de la marchandise en export. Cours pour débutants.",
"Présentation du QC (contrôle qualité), de ses méthodes, et des différentes techniques de gestion de la qualité des produits de l'industrie lourde, pendant la production et avant l'envoi de la marchandise en export. Cours PREMIUM.",
"Tout ce que vous devez savoir sur le Shanghai pratique pour un court séjour ou une installation en douceur et rassurante.",
"Tout ce que vous devez savoir sur le Guangzhou pratique pour un court séjour ou une installation en douceur et rassurante.",
"Disponible très prochainement.  Cours PREMIUM.",
"Travailler avec des fabricants compétents et en phase avec les standards internationaux en ce qui concerne l'organisation de leur usine, est aujourd'hui devenu une condition sine qua non pour les acheteurs en charge de la sélection de partenaires chinois, notamment dans le secteur industriel.    Changer de fournisseur ou remettre à niveau votre partenaire ?  Le travail de sourcing, s'il survient d...");
itImgArray = new Array("../catalogue/bv000037.thumb.jpg",
"../catalogue/bv000001.thumb.jpg",
"../catalogue/bv000019.thumb.jpg",
"../catalogue/bv000028.thumb.jpg",
"../catalogue/bv000004.thumb.jpg",
"../catalogue/bv000005.thumb.jpg",
"../catalogue/bv000003.thumb.jpg",
"../catalogue/bv000002.thumb.jpg",
"../catalogue/bv000006.thumb.jpg",
"../magasin1/bv000014.thumb.jpg");
itRefArray = new Array("1-001",
"3-001",
"2-001",
"2-002",
"4-001",
"4-002",
"5-001",
"5-002",
"4-003",
"D-001");
itPricesArray = new Array(400.00,
1200.00,
950.00,
1400.00,
800.00,
1200.00,
300.00,
300.00,
2000.00,
50.00);
var itemsCount = 10;
var catalogdirs = 0;
var catalognames = 0;

			
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>");
}
