/**
  searchengine.js
  
  @author florian.beese@misterspex.de
  @version 1.0
  Copyright 2010 Mister Spex GmbH
*/

function SearchEngine(ident)
{
  var m_nSelSuggestion = -1;
  var m_nMaxSuggestion = 0;
  var m_sIdent = ident;
  var this_priv = this;
  var m_bSearchOnReturn = false;
  var m_nSuggestMinLen = 0;
  var m_nSuggestionFadeOutInterval = 10000;  //remove suggestions after 10000ms inactivity
  var m_nSuggestionFadeOutSpeed = 400;
  var m_nRequestDelay = 500;

  this.m_toSug = null;      //window timeout for execution of ajax to get suggestions
  this.m_toFadeOut = null;  //window timeout for fade out of the suggestion div after inactivity

  this.SetSuggestMinLength = function(nMinLen)
  {
    m_nSuggestMinLen = nMinLen;
  };

  this.SetFadeOutInterval = function(nFadeOut)
  {
    m_nSuggestionFadeOutInterval = nFadeOut;
  };

  this.SetFadeOutSpeed = function(nSpeed)
  {
    m_nSuggestionFadeOutSpeed = nSpeed;
  };

  this.SetRequestDelay = function(nDelay)
  {
    m_nRequestDelay = nDelay;
  };

  this.SearchOnReturn = function(bSearch)
  {
    m_bSearchOnReturn = bSearch;
  };

  this.AjaxSuggestionCallback = function(data)
  {
    if (data.Ident == m_sIdent && data.Suggestions.length)
    {
      this_priv.RemoveSuggestions();
      m_nSelSuggestion = -1;
      m_nMaxSuggestion = data.Suggestions.length - 1;
      var d = document.getElementById("SearchEngineFieldDiv");
      var table = document.createElement("table");
      table.id = "SearchEngineSuggestions";
      table.className = "panel";

      table.ose = this_priv;

      var caption = document.createElement("caption");
      caption.innerHTML = "Propositions pour votre recherche";
      table.appendChild(caption);

      //colgroup:
      var colgroup = document.createElement("colgroup");
      var col = document.createElement("col");
      col.className="query";
      colgroup.appendChild(col);
      col = document.createElement("col");
      col.className="type";
      colgroup.appendChild(col);
      table.appendChild(colgroup);

      //heading:
      var thead = document.createElement("thead");
      var tr = document.createElement("tr");
      var th1 = document.createElement("th");
      th1.innerHTML = "Termes";
      th1.id = "SearchResultsQuery";
      tr.appendChild(th1);
      var th2 = document.createElement("th");
      th2.innerHTML = "Type";
      th2.id = "SearchResultsType";
      tr.appendChild(th2);
      thead.appendChild(tr);
      table.appendChild(thead);

      var tbody = document.createElement("tbody");

/*
!!<table summary="Suchergebnisse" id="SearchResults" cellspacing="0">
!!<caption>Vorschläge zu Ihrer Suche</caption>
!!          <colgroup>
!!            <col class="query"/>
!!            <col class="type"/>
!!            <col class="amount"/>
!!          </colgroup>
!!          <thead>
!!            <tr>
!!              <th id="SearchResultsQuery">Begriff</th>
!!              <th id="SearchResultsType">Typ</th>
!!              <th id="SearchResultsAmount">Treffer</th>
!!            </tr>
!!          </thead>
!!          <tbody>
!!            <tr>
!!              <td headers="SearchResultsQuery">Oakley</td>
!!              <td headers="SearchResultsType">Produkt</td>
!!              <td headers="SearchResultsAmount">120 Ergebnisse</td>
!!            </tr>
!!          </tbody>
!!        </table>
*/

      for(var i=0;i<data.Suggestions.length;i++)
      {
        var tr = document.createElement("tr");
        var td1 = document.createElement("td");
        td1.headers = "SearchResultsQuery";
        td1.className = "SearchResultsQuery";
        var td2 = document.createElement("td");
        td2.headers = "SearchResultsType";
        td2.className = "SearchResultsType";

        td1.innerHTML = "<a href=\"/searchengine.y?FilterSearch="+encodeURI(data.Suggestions[i])+"\">" + data.Suggestions[i] + "</a>";
        td2.innerHTML = "<a href=\"/searchengine.y?FilterSearch="+encodeURI(data.Suggestions[i])+"\">" + data.Info[i] + "</a>";

        tr.id = "Sug"+i;
        tr.className="SearchEngineSuggestion";
        tr.searchValue = data.Suggestions[i];
        tr.nSel = i;
        tr.se = this_priv;

        /*tr.onmouseup = function()
        {
          this.se.SelectSuggestion(this.nSel);
          this.se.UseSuggestion(document.getElementById("SearchEngineInputField"));
          this.se.Search(document.getElementById("SearchEngineInputField"));
        };*/
        tr.onmouseover = function()
        {
          if (this.se.m_toFadeOut)
            window.clearTimeout(this.se.m_toFadeOut);
          this.se.SelectSuggestion(this.nSel);
        };
        tr.onmouseout = function()
        {
          this.parentTable.fadeOut();
        };
        tr.parentTable = table;

        tr.appendChild(td1);
        tr.appendChild(td2);
        tbody.appendChild(tr);
      }

      table.appendChild(tbody);
      d.appendChild(table);

      //timeout functions:
      table.fadeOut = function()
      {
        if (this.ose.m_toFadeOut)
          window.clearTimeout(this.ose.m_toFadeOut);
        if (this.ose.m_nSuggestionFadeOutSpeed>0)
          this.ose.m_toFadeOut = window.setTimeout(function(){
              $("#SearchEngineSuggestions").fadeOut(m_nSuggestionFadeOutSpeed);
          }, m_nSuggestionFadeOutInterval);
      };
      table.fadeOut();
    }
    else
      this_priv.RemoveSuggestions();
  };

  this.RemoveSuggestions = function()
  {
    var d = document.getElementById("SearchEngineFieldDiv");
    if (document.getElementById("SearchEngineSuggestions"))
        d.removeChild(document.getElementById("SearchEngineSuggestions"));
  };

  this.Search = function(inputField)  //should be overwritten...
  {
    alert("Overwrite Search()! No Operation performed!");
  };

  this.SelectSuggestion = function(nSel)
  {
    var d = document.getElementById(("Sug"+m_nSelSuggestion));
    if (d) d.className = "SearchEngineSuggestion";
    d = document.getElementById(("Sug"+nSel));
    if (d) d.className = "SearchEngineSuggestion SearchEngineSuggestionSelected";
    m_nSelSuggestion = nSel;
  };

  this.UseSuggestion = function(inputField)
  {
    var d = document.getElementById(("Sug"+m_nSelSuggestion));
    if (d)
    {
      inputField.value = d.searchValue;
      this.RemoveSuggestions();
      return true;
    }
    return false;
  };

  this.OnSearchClear = function()
  {  };

  this.AjaxSuggest = function(inputField, e)
  {
    var k = e.keyCode;
    if (k==36 || k==35 || k==37 || k==39) { /*do nothing for home,end,left,right*/ return; }

    var divEl = document.getElementById("SearchEngineSuggestions");

    //Clear Timeouts:
    if (this.m_toSug)
      window.clearTimeout(this.m_toSug);

    //set timeout for fadeout of suggestion div
    if (divEl) divEl.fadeOut();

    if ((k == 27 || k == 38 || k == 40) && divEl || k == 13 || k == 9)
    {
      //cancel any propagation:
      if (e.preventDefault) e.preventDefault();
      if (e.stopPropagation) e.stopPropagation();
      e.cancelBubble = true;
      e.returnValue = false;
      if (divEl)
        divEl.style.display="block";

      switch(k)
      {
        case 38: // up
          if (m_nSelSuggestion>-1)
            this.SelectSuggestion(m_nSelSuggestion-1);
          break;
        case 40: // down
          if (m_nSelSuggestion<m_nMaxSuggestion)
            this.SelectSuggestion(m_nSelSuggestion+1);
          break;
        case 9:  // tab
        case 13: // return
          if (!this.UseSuggestion(inputField) || m_bSearchOnReturn)
          {
            this.Search(inputField);
          }
          break;
        case 27: // escape
          this.RemoveSuggestions();
          break;
      }
    }
    else
    {
      if (inputField.value.length >= m_nSuggestMinLen)
      {
        this.m_toSug = window.setTimeout( function() {
          $.getJSON("/searchengine.y?SearchEngine="+m_sIdent+"&Val="+escape(inputField.value), this_priv.AjaxSuggestionCallback);
        }, m_nRequestDelay);
      }
      else
        this.RemoveSuggestions();
    }
  };

  this.CancelEvent = function(e)
  {
    if (e.keyCode == 13)
    {
      if (e.preventDefault) e.preventDefault();
      if (e.stopPropagation) e.stopPropagation();
      e.cancelBubble = true;
      e.returnValue = false;
    }
  };
}

