// ----------------------------------------------------------------------------
// 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 = 4;
DISPLAY_SRCH_INFO = 1;
USE_UTF8 = 0;
REMOVE_ACCENTS = 1;
BOLD_LINKS = 1;
ONLINE_WEBSITE = 1;
ALLWORDSONLY = 0;
SHOWREFERENCES = 0;
BORDERCOLOR = "#FFFFFF";
SORTCOMPARE = 0;
itNamesArray = new Array();
itUrlsArray = new Array();
itTitlesArray = new Array();
itDescArray = new Array();
itImgArray = new Array();
itRefArray = new Array();
itPricesArray = new Array();
var itemsCount = 0;
var catalogdirs = new Array("/rachatsentreprises/",
"/materielsprofessionnels/",
"/alimentaire/",
"/barbrasserierestauration/",
"/hotel/",
"/modedecorationbeaute/",
"/tabacpresse/",
"/photovideo/",
"/hifiinformatique/",
"/cadeauxfleurs/",
"/tourismeloisirs/",
"/sante/",
"/boulangeriepatisserie/",
"/boucheriecharcuterie/",
"/services/",
"/autre/");
var catalognames = new Array("Rachats entreprises",
"Matériels professionnels",
"Alimentaire",
"Bar/Brasserie/Restauration",
"Hôtel",
"Mode/Décoration/Beauté",
"Tabac/Presse",
"Photo/Vidéo",
"Hifi/Informatique/autre",
"Cadeaux/Fleurs",
"Tourisme/Loisirs",
"Santé",
"Boulangerie/Patisserie",
"Boucherie/Charcuterie",
"Services",
"Autre");

			
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>");
}
