/*-----------------------------------
	sbsearch.js
	moteur de recherche client
	Author : simalis 
			 modif by JI
	Last modif : 09 04 2004
------------------------------------*/

path = document.getElementById("sbsearch").src;
path = path.substring(0,path.lastIndexOf("/"))+"/";

engine = '<table>'+
		 '<form name="sbsearch" method="post" action="'+path+'search.htm" target="popsearch" onsubmit="if(document.sbsearch.input_sbsearch.value==\'\'){return false;}else{ps=window.open(\''+path+'search.htm?disp=0\',\'popsearch\',\'width=400,height=600,top=\'+((screen.height-600)/2)+\',left=\'+((screen.width-400)/2));ps.focus();return false;}">'+
		 '<tr><td></td><td class="fd_layer">Recherche</td></tr>'+
		 '<tr><td></td><td><input type="text" name="input_sbsearch" id="input_sbsearch" size="15" class="fd_layer"></td><td rowspan=2 valign=top><input type="image" src="'+path+'ok.gif"  class="fd_layer"></td></tr>'+
		 '<tr><td></td><td><select name="sbsearch_layer" class="fd_layer" style="display: none" onchange="chgFilter(this)"><option value="all">Toutes les couches</option></select></td></tr>'+		
		 '</form></table>';

document.writeln(engine); 

//******************* Classe trecords***********************//
function trecords(){
	this.index=(trecords.count++)
	this.file=''
	this.link=''
	this.rowid=''
	this.description=''
	return this
}
trecords.prototype.set=function(file,link,rowid,description) {
	this.file=file
	this.link=link
	this.rowid=rowid
	this.description=description
}
trecords.prototype.searchstring=function() { 
	if(layerSearch(this.link)==1){
		return this.description;
	}else{
		return " ";
	}
}
trecords.prototype.count=0


function add(num_file,num_desc,str_id,str_desc) {
	al=records.length
	records[al]=new trecords()
	records[al].set(num_file,num_desc,str_id,str_desc)
}
 
records = new Array()
finds=0
sites=0
version="6"
andresult=false
SortResults=true
display_start=0
nb_enreg_affiche=20
displast=nb_enreg_affiche
tag_page_precedente = "<img src='pg_precedent.gif' border=0>"
tag_page_suivante   = "<img src='pg_suivant.gif'   border=0>";
mapName = "svgmap";
w = null;

function triBulleOptimise(tableau)
{
    var longueur=tableau.length
    var inversion = 1

    while(inversion)
    {
		inversion = 0
        for(i=0;i<longueur-1;i++)
        {
            //alert ("1) " + records[tableau[i].rec].description + ", 2) " + records[tableau[i+1].rec].description )
            if(records[tableau[i].rec].description>records[tableau[i+1].rec].description)
            {
    	        s=tableau[i]
    	        tableau[i]=tableau[i+1]
    	        tableau[i+1]=s
                inversion=1
            }
        }
        longueur--
    }
}

function bsort() {
        triBulleOptimise(results)
}


function searchAll(keyword){

	var timeA=new Date()
	var nw=0
	finds=0
	sites=0

	keywords = new Array();
	var x = parseIt(keyword)
	if(x == -1) return
	total_keywords=x

	
	w.document.write('<link rel="stylesheet" href="xsearch.css">')
	AddBody()

	if (keyword.length>50) keyword=keyword.substring(0,60)+"..."

	results=new Array()
	var str = ""
	for (nw=0; nw<keywords.length; nw+=1){ str = str + " " + keywords[nw]; search(keywords[nw]);}
	if (andresult) {
		for (a=0; a<results.length; a+=1) {
			if (results[a].val>0) {
				if (results[a].val<=(total_keywords-1)<<1) {
					results[a].val=0
					sites-=1
				}
			}
		}
	}
	if (SortResults && keywords!='[all]') bsort()

	// Now we build the output page
	displast=display_start
	displast+=nb_enreg_affiche
	if (displast>sites) displast=sites

	var timeB=new Date()

	if (finds==0) { display_start=-1; displast=0 }
	w.document.write("<h3><b>Résultats de la recherche \""+keyword+"\"</b><br><br><br>&nbsp;"+"<font size=-3>Temps: "+((timeB-timeA)/1000)+" secondes.</font></h3>" ) //+"<font size=-3>Temps: "+((timeB-timeA)/1000)+" secondes.</font></h3>")

	if (displast>sites && finds!=0) displast=sites+1
	
	if (finds==0) {
		w.document.write("<h3><font color=green>Pas de résultat pour <b>''"+keyword+"''</b></font></h3>"+
						"<p>Votre recherche - <b>"+keyword+"</b> - ne correspond à aucun document de la base.</p>"+
						"<LI>Vérifiez que tous les mots sont orthographiés correctement.</li>"+
						"<LI>Essayez d'utiliser moins de mots.</li>"+
						"<LI>Essayez d'utiliser des mots plus généraux.</li>"+
						"<LI>Essayez d'utiliser d'autres mots.</li></span>"+
						"</p>")
		DisplayXSearch()
		w.document.close()
		return
	}
	
	q2=display_start
	q3=displast
	var preced = "";
	for (q=display_start; q<q3; q+=1) {
		//alert ("for display : " + results[q].rec + " " + results[q].val)
		if(q=="-1")q = 0;
		if (results[q].val>0) {
			rc=results[q].rec
				affichage = ""; 
				arrAff    = records[rc].description.split('#');
				if (records[rc].description != preced)
    			{	
    				for(i=0;i<arrAff.length;i++){
    					if(arrAff[i].substring(0,1)=="*")affichage+=arrAff[i].substring(1,arrAff[i].length)+" ";
    				}
    				
					//Sans découpage
    				if(records[rc].file=="0"){
    					hrefString = "<a class='link1' href='#' onclick='javascript:window.opener.putIt(\""+records[rc].rowid+"\");window.opener.document.all[\""+mapName+"\"].setSrc(\""+getFile(records[rc].file)+"\")'>";
    				}
    				
					//Mode SVG
    				if(getMode(records[rc].file)=="S"){ 
    					//hrefString = "<a class='link1' href='#' onclick='javascript:window.opener.putIt(\""+records[rc].rowid+"\");window.opener.document.all[\""+mapName+"\"].setSrc(\""+getFile(records[rc].file)+"\")'>";
						hrefString = "<a href='#' onclick='javascript:window.opener.putIt(\""+records[rc].rowid+"\");window.opener.changeSvgSrc(\"" + getFile(records[rc].file)+"\");'>";
    				}

					//Mode HTML
    				if(getMode(records[rc].file)=="H"){
    					hrefString = "<a class='link1' href='#' onclick='javascript:window.opener.location.href=\""+getFile(records[rc].file)+"?k="+keywords+"&search_id="+records[rc].rowid+"\"'>";
    				}
    				w.document.write("<table border=0><tr><td><span class='xresult'>"+hrefString+"["+layerName(records[rc].link)+"] - "+purge(affichage)+"</a></span></td></tr></table>")
    			}
    			preced = records[rc].description;
   			    q2++

   		}
	}

	if (finds>nb_enreg_affiche) {
		w.document.write("<BR>")
		pages=Math.round(finds/nb_enreg_affiche)
		if (finds%nb_enreg_affiche<6)	pages++

		// Créé la chaîme de paramètres
		paramstring=searchname+"?keywords="+keyword+"&and="+andresult+"&sort="+SortResults

		w.document.write("<center><span class='xsmall'>")
		if (display_start>0) w.document.write("<a class='link2' href='"+paramstring+"&disp="+(display_start-nb_enreg_affiche)+"'>"+tag_page_precedente+"</a>")
		w.document.write("&nbsp;&nbsp;&nbsp;")

		for (i=1; i<=pages; i+=1){
			if ((((i-1)*nb_enreg_affiche)+1)<=sites) w.document.write("<a class='link2' href='"+paramstring+"&disp="+(((i-1)*nb_enreg_affiche))+"'>"+i+"</a>&nbsp&nbsp ")
		}
		w.document.write("&nbsp;&nbsp;&nbsp;")
		if (displast<sites) w.document.write("<a class='link2' href='"+paramstring+"&disp="+(displast)+"'>"+tag_page_suivante+"</a>")
		w.document.write("</span></center>")
	}
	DisplayXSearch()
	w.document.close()
}

function putIt(rowid){
	if(document.all['search_id'])document.all['search_id'].value = rowid;
 
}

function Cat() {
	w.document.open()
	w.document.clear()
	w.document.write('<link rel="stylesheet" href="xsearch.css">')
	AddBody()
	DisplayXSearch()
	w.document.close()
}

function purge(txt){ 
var reg=new RegExp("#", "g"); 
return txt.replace(reg," ");
}

var AndKeyWord = " "
var OrKeyWord = "OR"

function stripBlank (key, ind)
{
  if (ind+1 < key.length)
  {
    if (key.substring(ind,ind+2).indexOf('  ')>0)
    {
    	key = key.substring(0,ind) + stripBlank (key,ind+1)
    }
  }
  else 
    return key
}

function stripInput(key) {
  //alert ("voilou" + stripBlank (key));
  while(key.substring(0, 1) == ","  || key.substring(0,1) == " " )
    key = key.substring(1, key.length);
  while(key.substring(key.length-1,key.length) == "," || key.substring(key.length-1,key.length) == " ")
    key = key.substring(0, key.length - 1);
    
  // to do : les doubles blancs et carac spéciaux
  
  return key;
}

// PROBLEME AVEC LA GESTION DE L'ESPACE
/*
function parseIt(key) {
  key = stripInput(key) + " ";
  var y = 0;
	var andkey2 = AndKeyWord + ' ';
	var andkey1 = ' ' + andkey2;
	var orkey2 = OrKeyWord + ' ';
	var orkey1 = ' ' + orkey2;
  while(key.indexOf(" ") > 0) {
	// Utilisation du symbole "" pour regrouper plusieurs mots en un seul mot clé.
    if (key.substring(0,1) == '"') {
      var pos = key.indexOf('"',2);
      keywords[y] = key.substring(1,pos);
      keywords[y] = stripInput(keywords[y]);
      y++;
      key = key.substring(pos + 1, key.length);
    }
    else {
  // Utilisation de la commande AND (conjonction de mots clés).
      var pos = key.indexOf(andkey1);
      if ((pos > 0) && (key.indexOf(' ') >= pos)) {
        pos = key.indexOf(' ', pos + 5);
        keywords[y] = key.substring(0, pos);
        keywords[y] = stripInput(keywords[y]);
        y++;
        key = key.substring(pos + 1, key.length);
        if (key.substring(0,4)==andkey2) {
          pos = keywords[y - 1].indexOf(' ') + 5;
          key = keywords[y - 1].substring(pos, keywords[y - 1].length) + ' ' + key;
        }
      }
      else {
  // Utilisation de la Commande OR (Disjonction de mots clés).
        var pos = key.indexOf(orkey1);
        if ((pos > 0) && (key.indexOf(' ') >= pos)) {
          pos = key.indexOf(' ');
          keywords[y] = key.substring(0, pos);
          keywords[y] = stripInput(keywords[y]);
          if (keywords[y] != keywords[y - 1])
            y++;
          key = key.substring(pos + 1, key.length);
          pos = key.indexOf(orkey2);
          key = key.substring(pos + 3, key.length);
          pos = key.indexOf(' ');
          keywords[y] = key.substring(0, pos);
          keywords[y] = stripInput(keywords[y]);
          y++;
          key = key.substring(pos + 1, key.length);
          if (key.substring(0,3) == orkey2)
					  key = keywords[y - 1] + ' ' + key;
        }
        else {
          var pos = key.indexOf(" ");
          keywords[y] = key.substring(0, pos);
          keywords[y] = stripInput(keywords[y]);
          y++;
          if (y > 50)
					  return -1;
          key = key.substring(pos + 1, key.length);
        }
      }
    }
  }
  return y - 1;
}
*/

function parseIt(key) {
	key=stripInput(key)+"#"
	var y=0

	while(key.indexOf("#") > 0) {
		if (key.substring(0,1)=='"') {
			var pos=key.indexOf('"',2)
			keywords[y]=key.substring(1,pos)
			keywords[y]=stripInput(keywords[y])
			y++
			key=key.substring(pos+1,key.length)
		} else {
			var pos=key.indexOf(' AND ')
			if ((pos>0) && (key.indexOf(' ')>=pos)) {
				pos=key.indexOf('#',pos+5)
				keywords[y]=key.substring(0,pos)
				keywords[y]=stripInput(keywords[y])
				y++
				key=key.substring(pos+1,key.length)
				if (key.substring(0,4)=='AND ') {
					pos=keywords[y-1].indexOf('#')+5
					key=keywords[y-1].substring(pos,keywords[y-1].length)+'#'+key
				}
			} else {
		  		var pos=key.indexOf(' OR ')
		  		if ((pos>0) && (key.indexOf('#')>=pos))	{
					pos=key.indexOf('#')
					keywords[y]=key.substring(0,pos)
					keywords[y]=stripInput(keywords[y])
					if (keywords[y]!=keywords[y-1])	y++
					key=key.substring(pos+1,key.length)
					pos=key.indexOf('OR ')
					key=key.substring(pos+3,key.length)
					pos=key.indexOf('#')
					keywords[y]=key.substring(0,pos)
					keywords[y]=stripInput(keywords[y])
					y++
					key=key.substring(pos+1,key.length)
					if (key.substring(0,3)=='OR ') key=keywords[y-1]+'#'+key
				} else {
					var pos = key.indexOf("#")
					keywords[y]=key.substring(0,pos)
					keywords[y] = stripInput(keywords[y])
					y++
					if(y > 50) return -1
					key=key.substring(pos+1,key.length)
				}
			}
		}
	}
	return y-1
}

var keywords = new Array()

var results

function AddBody() {
	var keytext='"'+searchname+'?keywords="+'
	var andtext='"&and="+'

	w.document.write('<script>function doSearch(){'+
						'searchwords=document.searchform.searchwords.value; '+
						'while (searchwords.indexOf(" ")>-1){ pos=searchwords.indexOf(" ");'+
						'searchwords=searchwords.substring(0,pos)+"+"+searchwords.substring(pos+1); }'+
						'document.location='+keytext+' searchwords+'+andtext+'"0"}'+
						'<'+'/'+'script>'
						)

	templateBody()
	//document.write("<form name='searchform' method='post' action='javascript:doSearch()'><table border='0' width='100%'><tr><td align='center'><font face='Arial, Helvetica, sans-serif' size='3'><input name='searchwords' type='text' size='30'>&nbsp;&nbsp;<a href='javascript:doSearch()'>"+ButtonCode+"</a></font></td></tr></table></form><hr size=1>")
	if (usebannercode) bannerCode()
}

function DisplayXSearch() {
	// Cette ligne peut être effacée, mais, s'il vous plaît, n'ajoutez rien comme 
	// copyright <votre nom> parce que c'est interdit, et
	// si vous enlevez ou changez cette ligne, assurez vous qu'il y ait une mention
	// et un lien à www.dynamic-core.net de sorte que d'autre personnes puissent également
	// se faire la main sur ce moteur de recherche GRATUIT.. Merci.
	//document.write("<h3><center>Réalisé par <a href=http://www.dynamic-core.net>XSearch "+version+"</a> - Moteur de recherche JavaScript gratuit<h4>Traduction française Vincent Vaudey - <a href=mailto:xseditor@free.fr>xseditor@free.fr</a></h4></center></h3>")
	templateEnd()
}

function isInParam (arrWord, search_parm) // JI 09042004
{
	var valbool = 1;
	for (ind=0; ind<arrWord.length; ind++)
		if (search_parm.indexOf(arrWord[ind]) < 0)
			valbool = 0;
	return valbool;
}

function search(keyword) {

    if (keyword==" " || keyword=="")return false
    
	var hit=0
	var addcomplete=0

	var posAND = 0
	var posOR = 0	 
	
	var arrWord = new Array();// JI 09042004

	if (keyword.indexOf(' '+OrKeyWord+' ')>0)
	{
		posOR = keyword.indexOf(' '+OrKeyWord+' ')
		firstword=keyword.substring(0,keyword.indexOf(' ')).toLowerCase()
		lastword=keyword.substring(posOR+(OrKeyWord.length+2),keyword.length).toLowerCase()
	}
	else // JI 09042004
		if (keyword.indexOf(AndKeyWord)>0)
		{
			tempKeyword = keyword.toLowerCase();
			arrWord = tempKeyword.split(AndKeyWord);
		}
		
	for (q=0; q<records.length; q++) { 
		addcomplete=0
		search_parm=" "+records[q].searchstring()+" "
		search_parm=search_parm.toLowerCase()
		
		if (posOR) 
		{
			if ((search_parm.indexOf(firstword) != -1) || (search_parm.indexOf(lastword)!= -1 )) 
			{
				hit++
				finds++
				if(hit<2) 
				{ 
						sites++
						results[finds-1]=new Array()
						results[finds-1].val=0
						results[finds-1].val +=2
						results[finds-1].rec=q
				} 
			}
		}
		else 
		{
			if (arrWord.length) // JI 09042004
				if (isInParam (arrWord, search_parm)) 
				{
					hit++
					finds++
					if(hit<2) 
					{ 
							sites++
							results[finds-1]=new Array()
							results[finds-1].val=0
							results[finds-1].val +=2
							results[finds-1].rec=q
					}
				}
					
			keyword=keyword.toLowerCase()
			if ((search_parm.indexOf(" "+keyword+" ") != -1) || (keyword=="[all]")) 
			{
				hit++
				finds++
				if(hit<2) 
				{ 
						sites++
						results[finds-1]=new Array()
						results[finds-1].val=0
						results[finds-1].val+=2
						results[finds-1].rec=q
				} 
			} 
			else 
			{
				// recherche sur des moitiés de résultats (par exemple recherche:java trouve:javascript)
				if (search_parm.indexOf(keyword) != -1)	
				{
					hit++
					finds++
					if(hit < 2) 
					{
						sites++
						results[finds-1]=new Array()
						results[finds-1].val=0
						results[finds-1].val+=1
						results[finds-1].rec=q
						x=search_parm.indexOf(keyword)+keyword.length
						pos=search_parm.substring(1,x-keyword.length)
						
						while (pos.indexOf(" ")!=-1) 
						{
							y=pos.indexOf(" ")
							pos=pos.substring(y+1,pos.length)
						}
						if (pos.length<=2) addcomplete++
	
						pos=search_parm.substring(x,search_parm.length)
						fullresult=search_parm.substring(x,x+pos.indexOf(" "))
						
						if (fullresult.length<=2) addcomplete++
						if (addcomplete>1) results[finds-1].val+=1
					}
				}
			}
		}
		hit=0
	} 
}                                       

var searchwords = ''
var newload = true

function initXsearch(win,searchwords) {
	w = win;
	searchAll(searchwords)
	
}

/* ---------------------------------------- Paramètres de configuration  ------------------------------------ */
	searchname = 'search.htm'
	usebannercode=true
	ButtonCode = "<img src='searchbutton.gif' border=0>" 
	
	function templateBody() {
		w.document.write('<html><head><title>SVG Builder</title><'+
		'script language="Javascript">'+
		'<'+'/'+'script'+'></head><body bgcolor="#ffffff" text="#000000" link="#000099" vlink="#996699" alink="#996699">' +
		'<Center><font face="Arial" size="3"><table border=0><tr><td>');
	}

	function templateEnd() {
		w.document.write('</td></tr></table></font></body></html>');
	}
	function bannerCode() {
	}	

/* fin des paramètres de configuration */

/* Entrées SVG Builder */

/*Description des fichiers*/
function file(txt) {
	arrTxt=txt.split('|');
	id_file=arrTxt[0];
	mode=arrTxt[1];
	label=arrTxt[2];
	nb=arrFile.length
	arrFile[nb]=new description_file()
	arrFile[nb].set(id_file,mode,label)
}
function description_file(){
	this.id_file=0
	this.mode=''
	this.label=''
	return this
}
description_file.prototype.set=function(id_file,mode,label) {
	this.id_file=id_file
	this.mode=mode
	this.label=label 
}

function getMode(n){
	l = "";
	for(i=0;i<arrFile.length;i++){ 
		if(arrFile[i].id_file==n) return arrFile[i].mode;
	}
	return l;
}

function getFile(n){
	l = "";
	for(i=0;i<arrFile.length;i++){ 
		if(arrFile[i].id_file==n) return arrFile[i].label;
	}
	return l;
}

	arrFile = new Array()

/*Description des couches*/ 
function desc(txt) {
	
	arrTxt=txt.split('|');
	id_couche=arrTxt[0];
	label=arrTxt[1];
	searchable=arrTxt[2];
	nb=arrCouche.length
	arrCouche[nb]=new description_couche()

	if(document.getElementById('sbsearch_layer').style.display=="none")document.getElementById('sbsearch_layer').style.display = "list-item";
	
	//Remplissage de la liste
	o=new Option(label,id_couche);
	liste=document.getElementById("sbsearch_layer");
   	liste[liste.options.length]=o;	

	arrCouche[nb].set(id_couche,label,searchable)
	
}

//Définit le filtrage sur une couche
function chgFilter(list){	
	for(i=0;i<arrCouche.length;i++){
		if(list.value!="all"){
			if(list.value!=arrCouche[i].id_couche)arrCouche[i].searchable=0;
			else arrCouche[i].searchable=1;
		}else{
			arrCouche[i].searchable=1;
		}
	}
}

function description_couche(){
	this.id_couche=0
	this.label=''
	this.searchable=''
	return this
}
description_couche.prototype.set=function(id_couche,label,searchable) {
	this.id_couche=id_couche
	this.label=label 
	this.searchable=searchable 
}

function layerName(n){
	l = "";
	for(i=0;i<arrCouche.length;i++){
		if(arrCouche[i].id_couche==n) return arrCouche[i].label;
	}
	return l;
}

function layerSearch(n){
	l = "";
	for(i=0;i<arrCouche.length;i++){
		if(arrCouche[i].id_couche==n) return parseInt(arrCouche[i].searchable);
	}
	return l;
}

	arrCouche = new Array()

	ejs_list = new Array;
	ejs_list_valeur = new Array;
	ejs_place = document.location.href.indexOf("?",0);
	
	if(ejs_place >= 0)
	{
		ejs_query_string = document.location.href.substring(ejs_place+1, document.location.href.length);
		ejs_place_and = ejs_query_string.indexOf("&",0);
		if(ejs_place_and >= 0)
			ejs_list = ejs_query_string.split("&");
		else
			ejs_list[0] = ejs_query_string;
		for (ejs_i=0;ejs_i<ejs_list.length;ejs_i++)
		{
			ejs_temp = ejs_list[ejs_i].split("=");
			ejs_variable = ejs_temp[0];
			ejs_valeur = ejs_temp[1];
			ejs_plus_place = ejs_valeur.indexOf("+",0);
			while (ejs_plus_place >-1)
			{
				ejs_temp2 = ejs_valeur.substring(0,ejs_plus_place) + ' ' + ejs_valeur.substring(ejs_plus_place+1,ejs_valeur.length);
				ejs_valeur = ejs_temp2;
				ejs_plus_place = ejs_valeur.indexOf("+",ejs_plus_place+2);
			}
			ejs_list_valeur[ejs_variable] = ejs_valeur;
 		}	
	} 
	
function get(ejs_get)
	{		 
	if(ejs_list_valeur[ejs_get])		
		return(unescape(ejs_list_valeur[ejs_get]));
	else
		return("");
	}

function svg_item_search(){
	document.write("<input type='hidden' id='search_id' name='search_id' value=''>");	
	if(search_id)document.getElementById('search_id').value = get("search_id");
	document.getElementById('input_sbsearch').value = get("k"); 
}

svg_item_search();