var thisProto = document.location.protocol;
var thisHost = document.location.host;
var sugBaseUri = thisProto+'//'+thisHost+"/suggestion/";

function initPBAutoComplete(){
  
  // Unbind autocomplete if exists...
  $("#haut_ou, #PJ_ou").unautocomplete();

  // autocompletion sur OU
  $("#haut_ou, #PJ_ou").autocomplete(
    sugBaseUri+"suggestion_ou",
    {
      parse: function(d) {
        var rows = [];
        if (d!=null){
          for(var i=0; i<d.length; i++){
            rows[i] = {
              data:d[i],
              value:d[i].corrige+' '+d[i].cp,
              result:d[i].corrige+' '+d[i].cp
            };
          }
        }
        return rows;
      },

      formatItem: function(row, i, n) {
        var rc = String(row.corrige);
        var val = (rc.length > 40 )? rc.substring(0,40 )+'...' : rc;
        var sOut  = '<div class="nom" title="'+rc+'">'+val + '</div>';
        if(row.cp != ""){
          sOut += '<div class="cp">('+ row.cp + ')</div>';
        }
        return sOut;
      }
    }); 

    // Options communes...
    $('#haut_ou, #PJ_ou ').setOptions({
    dataType: 'json', minChars: 1, max: 15,
    autoFill: false, mustMatch: false,  matchContains: true,
    cacheLength:0, width:328, selectFirst:false,
    matchSubset:true, scrollHeight: 220,  delay: 50
    });
  //-------------
  /*var txtFocus = ( 'undefined' != typeof(inputFocus) )? inputFocus : 'quoiqui';
  $("#"+txtFocus).focus().blur().focus();*/


}
//------------------------
function in_array( array, value ){
  if( array.length > 0 ){
    for(var i=0; i<array.length;i++){
      if(array[i] == value){
        return true;
      }
    }
  }
  return false;
}
//------------------------
function get_ac_aladin_stats(){
  
  var ouVal    = '';
  var ouNumCar = 0;
  var lastKeyCode;
  var tabKeyOk = [8,46];
  $('#haut_ou, #PJ_ou').keydown(
      function( event ){
        lastKeyCode = event.keyCode;
      }
    ).keyup(
      function(){
        if( ( lastKeyCode > 46 && lastKeyCode < 91) || in_array( tabKeyOk, lastKeyCode)){
          if( $(this).attr('id') == 'PJ_ou' || $(this).attr('id') == 'haut_ou' ){
            ouNumCar += 1;
            ouVal = $(this).val();
          }
        }
      }
    );

  var formulaireId = (document.getElementById('formAccueil')) ? '#formAccueil' : '#formHaut';
  
  // Envoi des stats à la soumission du formulaire...
  $(formulaireId).submit(
    function(){      
      $("#ouSaisi").attr("value", escape(ouVal));
      $("#ouNbCar").attr("value", ouNumCar);
    }
  );
}
// -------------------------------
$(document).ready( function() {
  initPBAutoComplete();
  get_ac_aladin_stats();
});