/* 
 * FactureBook : autocompleteIt Plugin
 * @author Mohamed BENARROUDJ <mohamed.benarroudj@laposte.net>
 * @copyright   2010 Mohamed BENARROUDJ - All rights reserved
 */
(function($)
{
  var ac_box      = false;
  var ac_callback = false;
  var cache       = new Array();
  
  init();
  
  // autocompleteIt 
  $.fn.autocompleteIt = function(url, cibleHtml, callback)
  {
      
    
      
    var ac_url   = url;
    var node     = $(this);
    var ac_timer = false;
    
    node.keyup(function(e)
    {
      // Enter / Top / Bottom key 
      if( ac_box )
      {
        // Enter pressed
        if( e.keyCode == 13 )
        {
          ac_box.find('li.ui-state-hover').trigger('click');
          return false;
        }
        
        // Top arrow
        if( e.keyCode == 38 )
        {
          var current = ac_box.find('li.ui-state-hover').removeClass('ui-state-hover');
          
          if( !current.length )
            ac_box.find('li:last').addClass('ui-state-hover');
          else
            current.prev().addClass('ui-state-hover');
          
          return false;
        }
        
        // Bottom arrow
        if( e.keyCode == 40 )
        {
          var current = ac_box.find('li.ui-state-hover').removeClass('ui-state-hover');
          
          if( !current.length )
            ac_box.find('li:first').addClass('ui-state-hover');
          else
            current.next().addClass('ui-state-hover');
          
          return false;
        }
      }
    
      // Hide autocompete if empty value
      if( !node.val().length )
      {
        disapear();
        return false;
      }
      
      // Retrieve query and check cache
      var q = node.val();
      
      if( typeof(cache[q]) != 'undefined' )
      {
        // Has autocomplete opened ?
        if( !ac_box )
        {
          $(document).bind('click', disapear);
          
          // append autocomplete box
          ac_box = $('<ul class="autocompleteIt ui-selectmenu-menu ui-widget ui-widget-content ui-corner-bottom ui-selectmenu-menu-dropdown ui-selectmenu-open"></ul>');
         
         //Cas particulier pour ajax_choix_merchant
            if(cibleHtml){
                //node.next().append(ac_box);
                    var cibleHtmlWidth = $('#'+cibleHtml).attr('width');
                    $('#'+cibleHtml).append(ac_box);
                    ac_box.css({'position':'relative','left':'0px', 'width':(cibleHtmlWidth-5)+'px', 'overflow-x':'hidden'}).show();

            }else{
                // Original => 
                $('body').append(ac_box);
                // Display good position    
                var position = node.offset();
                ac_box.css({'top':position.top+28+'px', 'left':position.left+'px', 'width':(node.innerWidth()-2)+'px'}).show();

            }
          
          // init callback
          ac_callback  = callback;
        }
        
        ac_box.html(cache[q]);
      }
      else
      {
        // Timer
        if( ac_timer ) clearTimeout(ac_timer);
        
        ac_timer = setTimeout(function()
        {
            // Load data
            $.post(url, {'q':q}, function(data)
            {
              // Has autocomplete opened ?
              if( !ac_box )
              {
                $(document).bind('click', disapear);

                // append autocomplete box
                ac_box = $('<ul class="autocompleteIt ui-selectmenu-menu ui-widget ui-widget-content ui-corner-bottom ui-selectmenu-menu-dropdown ui-selectmenu-open"></ul>');
               
                
                //Cas particulier pour ajax_choix_merchant
                if(cibleHtml){
                    //node.next().append(ac_box);
                    var cibleHtmlWidth = $('#'+cibleHtml).attr('width');
                    $('#'+cibleHtml).append(ac_box);
                    ac_box.css({'position':'relative','left':'0px', 'width':(cibleHtmlWidth-5)+'px', 'overflow-x':'hidden'}).show();
                    
                }else{
                    // Original => 
                    $('body').append(ac_box);
                    // Display good position    
                    var position = node.offset();
                    ac_box.css({'top':position.top+28+'px', 'left':position.left+'px', 'width':(node.innerWidth()-2)+'px'}).show();
                    
                }
    
                // init callback
                ac_callback  = callback;
              }

              var results_li   = '';
              var search       = new RegExp('('+q+')', 'i');

              // No result
              if( !data.length )
              {
                results_li = '<li class="ac_no-result">Aucun résultat pour <i>"'+q+'"</i></li>';
              }
              else
              {
                for(var i=0; i < (data.length - 1); i++)
                {
                  if( typeof(data[i].separator) != 'undefined' ) 
                    results_li += '<li class="ac_separator">'+data[i].separator+'</li>';
                  else
                    results_li += '<li id="choice-'+data[i].id+'"><a href="#">'+data[i].label.replace(search, "<b class=\"rechercheTrouve\">$1</b>")+'</a></li>';
                }
                
              if( typeof(data[i].separator) != 'undefined' ) 
                results_li += '<li class="ac_separator ui-corner-bottom">'+data[i].separator+'</li>';
              else
                results_li += '<li id="choice-'+data[i].id+'" class="ui-corner-bottom"><a href="#">'+data[i].label.replace(search, "<b class=\"rechercheTrouve\">$1</b>")+'</a></li>';
              }

              ac_box.html(results_li);

              // Set cache
              cache[q] = results_li;

            }, 'json');
        }, 100);
      }
    });
  };
  
  function disapear()
  {
    $(document).unbind('click', disapear);      
    
    if( ac_box )
    {
      ac_box.remove();
      ac_box = false;
    }
  }
  
  function init()
  {   
    $('.autocompleteIt').find('li:not(.ac_no-result,.ac_separator)').live('click', function()
    {  
      disapear();
      
      var node   = $(this);
      var id     = node.attr('id').split('choice-')[1];
      var label  = node.text();
      
      if( typeof(ac_callback) == 'function' )
      {
        ac_callback(id, label);
      }
      
      return false;
    });
    
    $('.autocompleteIt li').live('mouseenter', function(){ $(this).addClass('ui-state-hover') }).live('mouseleave', function(){ $(this).removeClass('ui-state-hover') });
  }

})(jQuery)

