var search_value = "";
var barre_recherche_id = "i_cp";


function free_div(){
	$('#suggestions').empty().hide();
}


function autocomplete(input,str2)
{
  var txt = input.value;
  input.value = str2.toLowerCase();
  if (document.selection)
  {
    var textselect = str2.substring(txt.length, str2.length);
    var rng = input.createTextRange();
    if (rng.findText(textselect))
    {
      rng.select();
    }
  }
  else
  {
    input.setSelectionRange(txt.length,str2.length);
  }
}

function onchoose(prop)
{
  search_value = prop;
  div = $("#suggestions");
  free_div();
  input = document.getElementById(barre_recherche_id);
  input.value = prop;
}


function proposer_cp(input, evt)
{
	
  var elm = evt.keyCode;
  var complete = true;
  var div = document.getElementById('suggestions');
  if ((elm == 8) || (elm == 37) || (elm == 39) || (elm == 27) || (elm == 46) || (elm == 35) || (elm == 36)) {
      if (elm == 8) free_div();
      input.focus();
      return 1;
  }
  free_div();
  var txt = input.value;
  str2 = txt;
  search_value = txt;
  if (txt.length < 2)
  {
    input.focus();
    return 1;
  }
    bool = true;
    if (bool)
    {
     $.ajax({
        url: "associations_autocompletion/cp_search.php",
        data: "query="+str2,
        success: function(html){
          if (!bool) return;
          bool = false;
          var str = html;
          if (str == "") return;
          st = str.split('\n');

          if (st[0])
          {
            var lol = st[0];
            var lol2 = lol.split("   ");
            str2 = lol2[0];
          }
          if ((complete) && (str2 != txt)) autocomplete(input, str2);

          var i = 0;
          while (st[i])
          {
            prop = st[i].split("   ")[0];
            
            $('#suggestions').append('<div onclick="onchoose(\''+prop+'\')">'+st[i]+'</div>');
						$('#suggestions').show();
            i++;
          }
        }
      });
    }
  input.focus();
  return 0;
}


$().ready(function(){
	 $('#i_cp').click(function(){
	 	free_div();
	 })
	 .keyup(function(e){
	 	proposer_cp(this,e);
	});
	
});