/**
 * @FileFR » Gestion d'un champ de texte avec autocompletion
 * @FileEN » Management of a textbox with autocompletion
 */

/**
 * @ClassFR AutoComplete » Gestion d'un champ de texte avec autocompletion
 * @ClassEN AutoComplete » Management of a textbox with autocompletion
 */

var ENTER  = 13;
var SHIFT  = 16;
var CTRL   = 17;
var ALT    = 18;
var CAPS   = 20;
var ESC    = 27;
var PGUP   = 33;
var PGDOWN = 34;
var END    = 35;
var HOME   = 36;
var KEYLT  = 37;
var KEYUP  = 38;
var KEYRT  = 39;
var KEYDN  = 40;
function getHTTPObject()
{
   var xmlhttp;
   /*@cc_on
   @if (@_jscript_version >= 5)
   try
   {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
   }
   catch (e)
   {
      try
      {
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (E)
      {
         xmlhttp = false;
      }
   }
   @else
      xmlhttp = false;
   @end @*/
   if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
   {
      try
      {
         xmlhttp = new XMLHttpRequest();
      }
      catch (e)
      {
         xmlhttp = false;
      }
   }
   return xmlhttp;
}

/**
 * @FunctionFR AutoComplete » Constructeur du champ de texte avec autocompletion
 * @FunctionEN AutoComplete » Contructor of the textbox with autocompletion
 * @ParamFR asText String / » Texte saisi dans le champs de texte
 * @ParamEN asText String / » Typing text in the textbox
 * @ParamFR asCode String / » Code correspondant à la requête dans le fichier autocomplete.inc.php
 * @ParamEN asCode String / » Code corresponding to the query in the file autocomplete.inc.php
 */
function AutoComplete(asText, asCode)
{
   this.code2 = asText;
   this.text = window.document.getElementById(asText);

   this.div  = window.document.getElementById(asText+"AutoComplete");
   var laCode = asCode.split('-');
   this.code = laCode[0];
   this.parameters = '';
   if (laCode.length > 1)
   {
      asCode = asCode.substring(laCode[0].length+1, asCode.length);
      this.parameters = asCode;
   }
   this.http = getHTTPObject();
   var _this = this;
   this.highlighted = 0;
   this.text.onkeyup   = function(evt) { _this.onKeyup(evt); };
   //this.text.onblur    = function()    { _this.onBlur(); };
   this.text.onkeydown = function(evt) { _this.onKeyDown(evt); };
   this.text.onfocus   = function(evt) { _this.onKeyup(evt); };

}


/**
 * @FunctionFR AutoComplete.prototype.onBlur » Ferme la popup d'autocompletion quand le champ de type n'est plus sélectionné
 * @FunctionEN AutoComplete.prototype.onBlur » Close the autocompletion popup when the textbox is not more selected
 */
AutoComplete.prototype.onBlur= function()
{
   this.div.className = "autoCompleteHide";
}


/**
 * @FunctionFR AutoComplete.prototype.onKeyup » Ouvre la popup d'autocompletion
 * @FunctionEN AutoComplete.prototype.onKeyup » Open the autocompletion popup
 */
AutoComplete.prototype.onKeyup = function(evt)
{
   var key = getKeyCode(evt);

   switch(key)
   {
      //The control keys were already handled by onkeydown, so do nothing.
      case ENTER:
      case SHIFT:
      case CTRL:
      case ALT:
      case CAPS:
      case ESC:
      case PGUP:
      case PGDOWN:
      case END:
      case HOME:
      case KEYLT:
      case KEYUP:
      case KEYRT:
      case KEYDN:
         return;
      default:
         // clear the popup div.
         while (this.div.hasChildNodes())
         {
            this.div.removeChild(this.div.firstChild);
         }
         if (this.text.value.length>=1)
         {
           var lsResults = "";
           this.http.open("GET", "includes/autocompletion.php?asCode="+this.code+(this.parameters != '' ? "&asParameter="+this.parameters : '')+"&asText="+this.text.value, true);
           var _this = this;
           this.http.onreadystatechange = function() { _this.onLoad(); };
           this.http.send(null);
           working = true;
           break;                 
         }
         /*
         if(this.text.value.length==0)
         {
				// GOTO
            document.getElementById('Categorie4Id').value   = ''; // Ville
				document.getElementById('Categorie4Name').value = ''; // Ville
            document.getElementById('Categorie5Id').value   = ''; // QuartierProximite
            document.getElementById('Categorie6Id').value   = ''; // Quartier
            document.getElementById('Categorie7Id').value   = '100'; // Proximite
            document.getElementById('recherche-QUARTIER_PROXIMITE').style.display  = 'none';
            document.getElementById('separateur-QUARTIER_PROXIMITE').style.display = 'none';
            document.getElementById('recherche-QUARTIER').style.display            = 'none';
            document.getElementById('separateur-QUARTIER').style.display           = 'none';
            document.getElementById('recherche-PROXIMITE').style.display           = 'none';
            document.getElementById('separateur-PROXIMITE').style.display          = 'none';
            recherche2();
         }
         */
   }
}

/**
 * @FunctionFR AutoComplete.prototype.onLoad » Remplit la popup d'autocompletion
 * @FunctionEN AutoComplete.prototype.onLoad » Fill the autocompletion popup
 */
AutoComplete.prototype.onLoad = function()
{
   if (this.http.readyState == 4)
   {
      if (this.http.status == 200)
      {
         lsResults = this.http.responseText;
         if (lsResults)
         {
            this.highlighted = 0;
            var loTable = document.createElement('table');
            loTable.cellPadding = 2;
            loTable.cellSpacing = 0;
            var loTbody = document.createElement('tbody');
            var laLines = lsResults.split("#+#");
            var laResults = new Array(laLines.length);
            var laOrder = new Array(laLines.length);
            for (var i = 0 ; i < laLines.length ; i++)
            {
               var laColumns = laLines[i].split("#-#");
               laResults[laColumns[0]] = new Array();
               laOrder[i] = laColumns[0];
               for (var j = 1 ; j < laColumns.length ; j++)
               {
                  laResults[laColumns[0]][laResults[laColumns[0]].length] = laColumns[j];
               }
            }
            for (var i = 0 ; i < laOrder.length ; i++)
            {
               var loTr = document.createElement('tr');
               if (i == this.highlighted)
               {
                  loTr.className = "selected";
               }
               else
               {
                  loTr.className = "";
               }
               var loSpan = document.createElement('span');
               loSpan.innerHTML = laOrder[i];
               loTr.appendChild(loSpan);
               this.div.appendChild(loTable);
               loTable.appendChild(loTbody);
               loTbody.appendChild(loTr);
               for (var k = 0 ; k < laResults[laOrder[i]].length ; k++)
               {
                  var loTd = document.createElement('td');
                  loTd.innerHTML = laResults[laOrder[i]][k];
                  loTr.onmousedown = AutoComplete.prototype.onMouseDown;
                  loTr.onmouseover = AutoComplete.prototype.onMouseOver;
                  loTr.onmouseout  = AutoComplete.prototype.onMouseOut;
                  loTr.AutoComplete = this;
                  loTr.appendChild(loTd);
               }
            }
            this.div.className = "autoCompleteShow";
         }
         else
         {
            this.div.className = "autoCompleteHide";
         }
      }
      else
      {
         this.div.className = "autoCompleteHide";
      }
   }
}

/**
 * @FunctionFR AutoComplete.prototype.onMouseDown » Renseigne le champ de textbox et ferme la popup d'autocompletion
 * @FunctionEN AutoComplete.prototype.onMouseDown » Fill the textbox and close the autocompletion popup
 */
AutoComplete.prototype.onMouseDown = function()
{   
   if (document.getElementById(this.AutoComplete.text.id+"Id") != null)
   {  
      var loTextId = document.getElementById(this.AutoComplete.text.id+"Id");
      loTextId.value = this.firstChild.innerHTML;
   }
   
   this.removeChild(this.firstChild);
   if (document.getElementById(this.AutoComplete.text.id+"Name") != null)
   {
      var loTextName = document.getElementById(this.AutoComplete.text.id+"Name");
      lsChaine = this.firstChild.innerHTML;
      loTextName.value = ((lsChaine.replace(/<b>/gi, "")).replace(/<\/b>/gi, ""));
      // loTextId.value = this.firstChild.innerHTML;
   }  
   lsChaine = this.firstChild.innerHTML;
   this.AutoComplete.text.value = ((lsChaine.replace(/<b>/gi, "")).replace(/<\/b>/gi, ""));
   // this.AutoComplete.text.value = this.firstChild.innerHTML;
   this.AutoComplete.div.className = "autoCompleteHide";
   if (document.getElementById(this.AutoComplete.text.id+"Id")) {
      loTextId.onblur();
   }
}

/**
 * @FunctionFR AutoComplete.prototype.onMouseOver » Change le style du choix où est le curseur
 * @FunctionEN AutoComplete.prototype.onMouseOver » Change the style of the choice where is the cursor
 */
AutoComplete.prototype.onMouseOver = function()
{
   if (this.className == "")
   {
      this.className = "onMouseOver";
   }
}

/**
 * @FunctionFR AutoComplete.prototype.onMouseOut » Enlève le style du choix où était le curseur
 * @FunctionEN AutoComplete.prototype.onMouseOut » Remove the style of the choice where was the cursor
 */
AutoComplete.prototype.onMouseOut = function()
{
   if (this.className == "onMouseOver")
   {
      this.className = "";
   }
}

/**
 * @FunctionFR AutoComplete.prototype.changeHighlight » Change le style du choix sélectionné
 * @FunctionEN AutoComplete.prototype.changeHighlight » Change the style of the selected choice
 */
AutoComplete.prototype.changeHighlight = function()
{
   var laTrs = this.div.getElementsByTagName('TR');
   if (this.highlighted < 0)
   {
      this.highlighted = 0;
   }
   if (this.highlighted >= laTrs.length)
   {
      this.highlighted = laTrs.length - 1;
   }
   for (i in laTrs)
   {
      var loTr = laTrs[i];
      if (this.highlighted == i)
      {
         loTr.className = "selected";
      }
      else
      {
         loTr.className = "";
      }
   }
}

/**
 * @FunctionFR AutoComplete.prototype.validateHighlighted » Renseigne le champ de textbox avec le choix sélectionné et ferme la popup d'autocompletion
 * @FunctionEN AutoComplete.prototype.validateHighlighted » Fill the textbox with the slected choice and close the autocompletion popup
 */
AutoComplete.prototype.validateHighlighted = function()
{  
   var laTrs = this.div.getElementsByTagName('TR');
   for (i in laTrs)
   {
      var loTr = laTrs[i];
      if (this.highlighted == i)
      {
         if (document.getElementById(this.text.id+"Id") != null)
		   {  
		      var loTextId = document.getElementById(this.text.id+"Id");
		      loTextId.value = loTr.firstChild.innerHTML;
		   }
		   
		   loTr.removeChild(loTr.firstChild);
		   if (document.getElementById(this.text.id+"Name") != null)
		   {
		      var loTextName = document.getElementById(this.text.id+"Name");
		      lsChaine = loTr.firstChild.innerHTML;
		      loTextName.value = ((lsChaine.replace(/<b>/gi, "")).replace(/<\/b>/gi, ""));
		   }  
		   lsChaine = loTr.firstChild.innerHTML;
		   this.text.value = ((lsChaine.replace(/<b>/gi, "")).replace(/<\/b>/gi, ""));
		   this.div.className = "autoCompleteHide";
         if (document.getElementById(this.text.id+"Id") != "undefined") {
            loTextId.onblur();
         }
      }
   }
}

/**
 * @FunctionFR AutoComplete.prototype.onKeyDown » Lance l'évènement en fonction de la touche pressée
 * @FunctionEN AutoComplete.prototype.onKeyDown » Launch the event in function of the key pressed
 */
AutoComplete.prototype.onKeyDown = function(evt)
{
   var key = getKeyCode(evt);

   switch(key)
   {
      case ENTER:
      //case KEYRT:
      this.validateHighlighted();
      break;

      case ESC:
      //case KEYLT:
      this.onBlur();
      break;

      case KEYUP:
      this.highlighted--;
      this.changeHighlight();
      break;

      case KEYDN:
      this.highlighted++;
      this.changeHighlight();
      break;
   }
}

/**
 * @FunctionFR getKeyCode » Retourne le code de la touche de l'évènement
 * @FunctionEN getKeyCode » Return the code of the key of the event
 * @ParamFR aoEvt Object / » Evenement javascript
 * @ParamEN aoEvt Object / » Javascript event
 * @ReturnFR String » Code de la touche de l'évènement
 * @ReturnEN String » Code of the key of the event
 */
function getKeyCode(aoEvt)
{
   if(aoEvt)         // Moz
   {
      return aoEvt.keyCode;
   }
   if(window.event)  // IE
   {
      return window.event.keyCode;
   }
}

