/*----------------------------------------------------------------------------
 * JavaScript for webhelp search
 *----------------------------------------------------------------------------
 This file is part of the webhelpsearch plugin for DocBook WebHelp
 Copyright (c) 2007-2008 NexWave Solutions All Rights Reserved.
 www.nexwave.biz Nadege Quaine
 http://kasunbg.blogspot.com/ Kasun Gajasinghe
 */
//string initialization
var htmlfileList = "htmlFileInfoList.js";
var htmlfileinfoList = "htmlFileInfoList.js";
var useCJKTokenizing = false;
var w = new Object();
var scoring = new Object();
var searchTextField = '';
var no = 0;
var noWords = 0;
var partialSearch = "There is no page containing all the search terms.
Partial results:";
var warningMsg = '
';
warningMsg+='
Please note that due to security settings, Google Chrome does not highlight';
warningMsg+=' the search results in the right frame.';
warningMsg+='This happens only when the WebHelp files are loaded from the local file system.
';
warningMsg+='Workarounds:';
warningMsg+='
';
warningMsg+='- Try using another web browser.
 ';
warningMsg+='- Deploy the WebHelp files on a web server.
 ';
warningMsg+='
 ';
txt_filesfound = 'Results';
txt_enter_at_least_1_char = "You must enter at least one character.";
txt_enter_more_than_10_words = "Only first 10 words will be processed.";
txt_browser_not_supported = "Your browser is not supported. Use of Mozilla Firefox is recommended.";
txt_please_wait = "Please wait. Search in progress...";
txt_results_for = "Results for: ";
/* This function verify the validity of search input by the user
  Cette fonction verifie la validite de la recherche entrre par l utilisateur */
function Verifie(searchForm) {
    // Check browser compatibility
    if (navigator.userAgent.indexOf("Konquerer") > -1) {
        alert(txt_browser_not_supported);
        return;
    }
    searchTextField = trim(document.searchForm.textToSearch.value);
    searchTextField = searchTextField.replace(/['"]/g,'');
	var expressionInput = searchTextField;
    $.cookie('textToSearch', expressionInput);
    if (expressionInput.length < 1) {
        // expression is invalid
        alert(txt_enter_at_least_1_char);
        // reactive la fenetre de search (utile car cadres)
        document.searchForm.textToSearch.focus();
    }
    else {
    var splitSpace = searchTextField.split(" ");
       var splitWords = [];
        for (var i = 0 ; i < splitSpace.length ; i++) {     
          var splitDot = splitSpace[i].split(".");
          
          if(!(splitDot.length == 1)){
            splitWords.push(splitSpace[i]);
          }
          
          for (var i1 = 0; i1 < splitDot.length; i1++) {
               var splitColon = splitDot[i1].split(":");
            for (var i2 = 0; i2 < splitColon.length; i2++) {
                var splitDash = splitColon[i2].split("-");
                 for (var i3 = 0; i3 < splitDash.length; i3++) {
                     if (splitDash[i3].split("").length > 0) {
                           splitWords.push(splitDash[i3]);
                       }
                 }
            }
          }
       }
       noWords = splitWords;
    	if (noWords.length > 9){
          // Allow to search maximum 10 words
    		alert(txt_enter_more_than_10_words);
    		expressionInput = '';
    		for (var x = 0 ; x < 10 ; x++){
    			expressionInput = expressionInput + " " + noWords[x]; 
    		}    		
    		Effectuer_recherche(expressionInput);
    		document.searchForm.textToSearch.focus();
    	} else {
	        // Effectuer la recherche
             expressionInput = '';
          for (var x = 0 ; x < noWords.length ; x++) {
                 expressionInput = expressionInput + " " + noWords[x]; 
             }
	        Effectuer_recherche(expressionInput);
	        // reactive la fenetre de search (utile car cadres)
	        document.searchForm.textToSearch.focus();        
    	}
    }
}
var stemQueryMap = new Array();  // A hashtable which maps stems to query words
/* This function parses the search expression, loads the indices and displays the results*/
function Effectuer_recherche(expressionInput) {
    /* Display a waiting message */
    //DisplayWaitingMessage();
    /*data initialisation*/
    var searchFor = "";       // expression en lowercase et sans les caracte    res speciaux
    //w = new Object();  // hashtable, key=word, value = list of the index of the html files
    scriptLetterTab = new Scriptfirstchar(); // Array containing the first letter of each word to look for
    var wordsList = new Array(); // Array with the words to look for
    var finalWordsList = new Array(); // Array with the words to look for after removing spaces
    var linkTab = new Array();
    var fileAndWordList = new Array();
    var txt_wordsnotfound = "";
    // --------------------------------------
    // Begin Thu's patch 
    /*nqu: expressionInput, la recherche est lower cased, plus remplacement des char speciaux*/
    //The original replacement expression is: 
    //searchFor = expressionInput.toLowerCase().replace(/<\//g, "_st_").replace(/\$_/g, "_di_").replace(/\.|%2C|%3B|%21|%3A|@|\/|\*/g, " ").replace(/(%20)+/g, " ").replace(/_st_/g, "").replace(/_di_/g, "%24_");
    //The above expression was error prone because it did not deal with words that have a . as part of the word correctly, for example, document.txt
    
    //Do not automatically replace a . with a space
    searchFor = expressionInput.toLowerCase().replace(/<\//g, "_st_").replace(/\$_/g, "_di_").replace(/%2C|%3B|%21|%3A|@|\/|\*/g, " ").replace(/(%20)+/g, " ").replace(/_st_/g, "").replace(/_di_/g, "%24_");
    
    //If it ends with a period, replace it with a space
    searchFor = searchFor.replace(/[.]$/,"");
    // End Thu's Patch
    // ------------------------------------------
    searchFor = searchFor.replace(/  +/g, " ");
    searchFor = searchFor.replace(/ $/, "").replace(/^ /, "");
    wordsList = searchFor.split(" ");
    wordsList.sort();
    //set the tokenizing method
    useCJKTokenizing = typeof indexerLanguage != "undefined" && (indexerLanguage == "zh" || indexerLanguage == "ja" || indexerLanguage == "ko");
    //If Lucene CJKTokenizer was used as the indexer, then useCJKTokenizing will be true. Else, do normal tokenizing.
    // 2-gram tokenizinghappens in CJKTokenizing, 
    //If doStem then make tokenize with Stemmer
    var finalArray;
    if (doStem){
	    if(useCJKTokenizing){
	        finalWordsList = cjkTokenize(wordsList);
          finalArray = finalWordsList;
	    } else { 
	        finalWordsList = tokenize(wordsList);
          finalArray = finalWordsList;
	    }
    } else if(useCJKTokenizing){
          finalWordsList = cjkTokenize(wordsList);
          finalArray = finalWordsList;
         } else{
    //load the scripts with the indices: the following lines do not work on the server. To be corrected
    /*if (IEBrowser) {
     scriptsarray = loadTheIndexScripts (scriptLetterTab);
     } */
    /**
     * Compare with the indexed words (in the w[] array), and push words that are in it to tempTab.
     */
    var tempTab = new Array();
	
    // ---------------------------------------
    // Thu's patch
    //Do not use associative array in for loop, for example:
    //for(var t in finalWordsList)
    //it causes errors when finalWordList contains 
    //stemmed words such as: kei from the stemmed word: key
    for(var t=0;t 0){
		var searchedWords = noWords.length;
		var foundedWords  = fileAndWordList[0][0].motslisteDisplay.split(",").length;
		//console.info("search : " + noWords.length + "   found : " + fileAndWordList[0][0].motslisteDisplay.split(",").length);
		if (searchedWords != foundedWords){
			linkTab.push(partialSearch);
		}
	  }
	  
      
      for (var i = 0; i < cpt; i++) {
			
			var hundredProcent = fileAndWordList[i][0].scoring + 100 * fileAndWordList[i][0].motsnb;
			var ttScore_first = fileAndWordList[i][0].scoring;
			var numberOfWords = fileAndWordList[i][0].motsnb;
			
            if (fileAndWordList[i] != undefined) {
                linkTab.push("" + txt_results_for + " " + "" + fileAndWordList[i][0].motslisteDisplay + "" + "
");
                linkTab.push("");
                for (t in fileAndWordList[i]) {
                    //linkTab.push("- "+fl[fileAndWordList[i][t].filenb]+"
 ");
				                        
                    var ttInfo = fileAndWordList[i][t].filenb;
                    // Get scoring
                    var ttScore = fileAndWordList[i][t].scoring;
                    var tempInfo = fil[ttInfo];
				    
                    var pos1 = tempInfo.indexOf("@@@");
                    var pos2 = tempInfo.lastIndexOf("@@@");
                    var tempPath = tempInfo.substring(0, pos1);
                    var tempTitle = tempInfo.substring(pos1 + 3, pos2);
                    var tempShortdesc = tempInfo.substring(pos2 + 3, tempInfo.length);
                    
                    // toc.html will not be displayed on search result
                    if (tempPath == 'toc.html'){
                        continue;
                    }
                    /*
                    //file:///home/kasun/docbook/WEBHELP/webhelp-draft-output-format-idea/src/main/resources/web/webhelp/installation.html
                    var linkString = "- " + tempTitle + "";
                    // var linkString = "
 - " + tempTitle + "";
                    */
                    var split = fileAndWordList[i][t].motsliste.split(",");
                    // var splitedValues = expressionInput.split(" ");
					// var finalArray = split.concat(splitedValues);					
					
                    arrayString = 'Array(';
                    for(var x in finalArray){
                      if (finalArray[x].length > 2 || useCJKTokenizing){
                    		arrayString+= "'" + finalArray[x] + "',";
                    	} 
                    }
                    arrayString = arrayString.substring(0,arrayString.length - 1) + ")";
                    var idLink = 'foundLink' + no;
                    var linkString = '
 - ' + tempTitle + '';
                    var starWidth = (ttScore * 100/ hundredProcent)/(ttScore_first/hundredProcent) * (numberOfWords/maxNumberOfWords);
                    starWidth = starWidth < 10 ? (starWidth + 5) : starWidth;
                    // Keep the 5 stars format
                    if (starWidth > 85){
						starWidth = 85;
					}
					/*
					var noFullStars = Math.ceil(starWidth/17);
					var fullStar  = "curr";
					var emptyStar = "";
					if (starWidth % 17 == 0){
						// am stea plina
						
					} else {
						
					}
					console.info(noFullStars);
					*/
                    // Also check if we have a valid description
                    if ((tempShortdesc != "null" && tempShortdesc != '...')) {
                    
                        linkString += "\n
" + tempShortdesc + "
";
                    }
                    linkString += " ";
                    
                    // Add rating values for scoring at the list of matches	
					linkString += "";
					linkString += "
";
					//linkString += "
" 
					//				+ ((ttScore * 100/ hundredProcent)/(ttScore_first/hundredProcent)) * 1 + "
";
	                linkString += "
";
					linkString += "";
	                linkString += "
";
	                
	                linkString += "
";
	                linkString += "
";
					linkString += "
 ";
                    //linkString += 'Rating: ' + ttScore + '';
                                           
                    linkTab.push(linkString);
                    no++;
                }
                linkTab.push("
");
            }
        }
    }
    var results = "";
    if (linkTab.length > 0) { 
        /*writeln ("" + txt_results_for + " " + ""  + cleanwordsList + "" + "
"+"
");*/
        results = "";
        //write("