// ------------------------------------------------------------------
// fast search
// ------------------------------------------------------------------
var FAST_SEARCH_DATA = new Array();

// prepares the documents descriptions for the fast search
// combines descriptions and document names with the parent ones,
// but keeps the previous URL
function rebuildFastSearchData()
{
  // skipping if the critical arrays are not initialized
  if ( !DOCUMENTS_DESCRIPTIONS || !SITE_MAP )
    return false;
    
  buildFastSearchDataLevel( new Array() );
}

// appends the current site map level documents to the fast search data
// calls itself inside to perform the tree structure treatment
function buildFastSearchDataLevel( siteMapLevel )
{
  // obtaining the site map subarray in the current level container level
  var currentSiteMap;
  var expression = "currentSiteMap = SITE_MAP";
  for ( var levelI = 0; levelI < siteMapLevel.length; levelI++ )
    expression += "['" + siteMapLevel[levelI] + "']";
  eval( expression );
  
  // treating all documents in the current level
  if ( !isEmpty(currentSiteMap) )
  {
    // the previous level title and summary, which will be combined with the current level ones
    var parentTitle = "";
    var parentSummary = "";
    var path = siteMapLevel.join( "/" ) + "/";
    for ( var i = 0; i < FAST_SEARCH_DATA.length; i++ )
      if ( FAST_SEARCH_DATA[i]['path'] == path )
      {
        parentTitle = " - " + FAST_SEARCH_DATA[i]['title'];
        parentSummary = FAST_SEARCH_DATA[i]['summary'] + "\n";
        break;
      };
    
    for ( var documentName in currentSiteMap )
    {
      // configuring the current site map level
      var currentSiteMapLevel = new Array();
      for ( var levelI = 0; levelI < siteMapLevel.length; levelI++ )
        currentSiteMapLevel[levelI] = siteMapLevel[levelI];
      currentSiteMapLevel[currentSiteMapLevel.length] = documentName;

      var path = currentSiteMapLevel.join( "/" ) + "/";
      var title = "";
      var summary = "";
      var url = "";
      for ( var i = 0; i < DOCUMENTS_DESCRIPTIONS[LANGUAGE].length; i++ )
        if ( DOCUMENTS_DESCRIPTIONS[LANGUAGE][i]['path'] == path )
        {
          var lastFastSearchDataIndex = FAST_SEARCH_DATA.length;
          FAST_SEARCH_DATA[lastFastSearchDataIndex] = new Array();
          FAST_SEARCH_DATA[lastFastSearchDataIndex]['title'] = DOCUMENTS_DESCRIPTIONS[LANGUAGE][i]['title'] + parentTitle;
          FAST_SEARCH_DATA[lastFastSearchDataIndex]['summary'] = parentSummary + DOCUMENTS_DESCRIPTIONS[LANGUAGE][i]['summary'];
          FAST_SEARCH_DATA[lastFastSearchDataIndex]['url'] = DOCUMENTS_DESCRIPTIONS[LANGUAGE][i]['url'];
          FAST_SEARCH_DATA[lastFastSearchDataIndex]['path'] = path;
          break;
        };
        
      // moving deeper
      if ( !isEmpty(currentSiteMap[documentName]) )
        buildFastSearchDataLevel( currentSiteMapLevel );
    };
  };
  
  // done
  return content;
}

// searches for the string, given in the documents descriptions and returns
// the HTML-formatted string with the search results
function findInDocumentsDescriptions( searchString )
{
  if ( FAST_SEARCH_DATA.length < 1 )
    return "Загрузка. Подождите.";

  var results = "";
  var resultsCount = 0;
  var searchPattern = eval( "/(" + 
    searchString.
      replace(/^\s+/gi, "").
      replace(/\s+$/gi, "").
      replace(/\s+/gi, ".+") + ")/gi" 
  );
  
  // the first level is searching in titles
  var descriptionI;
  for ( descriptionI = 0; descriptionI < FAST_SEARCH_DATA.length; descriptionI++ )
  {
    var url = FAST_SEARCH_DATA[descriptionI]['url'];
    var title = FAST_SEARCH_DATA[descriptionI]['title'];
    var summary = FAST_SEARCH_DATA[descriptionI]['summary'];
    // checking the title to have the search string
    if ( !title.match( searchPattern ) )
      continue;
    title = title.replace( searchPattern, "<span class='highlighted'>$1</span>" );
    summary = summary.replace( searchPattern, "<span class='highlighted'>$1</span>" );
    results += "<a href='"+url+"'><h1>"+title+"</h1></a><p>"+summary+"</p>";
    resultsCount++;
    if ( resultsCount > MAX_SEARCH_RESULTS )
      break;
  };
  
  // the second - in summaries
  var descriptionI;
  for ( descriptionI = 0; descriptionI < FAST_SEARCH_DATA.length; descriptionI++ )
  {
    var url = FAST_SEARCH_DATA[descriptionI]['url'];
    var title = FAST_SEARCH_DATA[descriptionI]['title'];
    var summary = FAST_SEARCH_DATA[descriptionI]['summary'];
    // checking, if the search string is in summary, but not in title
    // due to titles are in the previous level
    if ( !summary.match( searchPattern ) )
      continue;
    else if ( title.match( searchPattern ) )
      continue;
    title = title.replace( searchPattern, "<span class='highlighted'>$1</span>" );
    summary = summary.replace( searchPattern, "<span class='highlighted'>$1</span>" );
    results += "<a href='"+url+"'><h1>"+title+"</h1></a><p>"+summary+"</p>";
    resultsCount++;
    if ( resultsCount > MAX_SEARCH_RESULTS )
      break;
  };
  
  // displaying the approximate search results count
  if ( descriptionI < FAST_SEARCH_DATA.length-1 && descriptionI > 0 )
  {
    var approximateResults = Math.ceil( resultsCount * FAST_SEARCH_DATA.length / descriptionI );
    var log10ApproximateResults = Math.floor( Math.log( approximateResults ) / Math.LN10 );
    var digitsApproximateResults = Math.pow( 10, log10ApproximateResults );
    approximateResults = Math.ceil( approximateResults / digitsApproximateResults ) * digitsApproximateResults;
    results += "<p>Найдено примерно "+approximateResults+" результатов. Показаны первые "+MAX_SEARCH_RESULTS+". Уточните поисковый запрос.</p>";
  };
  
  if ( results == "" )
    results = "По Вашему запросу ничего не найдено.";
  
  return results;
}
