/*	jquery.item-suggest 1.0 - 2009-01-16 -- by ddunlop.com
*	based on Peter Vulgaris's (www.vulgarisoip.com) jquery.suggest
*/

//(function($) {
  $.suggest = function(input, options) {
    var t = this;
    t.input = input;
    t.options = options;
    t.$input = $(input).attr("autocomplete", "off");
    t.$results = $('<div class="'+t.options.resultsClass+'"><ul></ul></div>');
   
    t.currentItem = -1;
    t.items = false;

    t.timeout = false;	// hold timeout ID for suggestion results to appear
    t.prevLength = 0;	// last recorded length of $input.val()
    t.cache = [];		// cache MRU list
    t.cacheSize = 0;	// size of cache in chars (bytes?)

    t.$results.appendTo('body');

    t.resetPosition();
    $(window)
    .load(function() { t.resetPosition() })		// just in case user is changing size of page while loading
    .resize(function() { t.resetPosition() });

    t.$input.blur(function() {
      setTimeout(function() {
        t.hideResults();
      }, 200);
    });

    // help IE users if possible
    try {
      t.$results.bgiframe();
    } catch(e) { }

    // I really hate browser detection, but I don\'t see any other way
    if ($.browser.mozilla)
    t.$input.keypress(function(e) { t.processKey(e); });	// onkeypress repeats arrow keys in Mozilla/Opera
    else
    t.$input.keydown(function(e) { t.processKey(e); });	// onkeydown repeats arrow keys in IE/Safari

  }

  $.extend($.suggest.prototype, {
    addMatchClass:function(txt,q) {
      return txt.replace(new RegExp(q, 'ig'), '<span class="'+this.options.matchClass+'">$&</span>');
    },
    resetPosition:function() {
      var offset = this.$input.offset();
      this.$results.css({
        top: (offset.top + this.input.offsetHeight) + 'px',
        left: offset.left + 'px'
      });
    },
    processKey:function(e) {
      // handling up/down/escape requires results to be visible
      // handling enter/tab requires that AND a result to be selected
      if ((/27$|38$|40$/.test(e.keyCode) && this.$results.is(':visible')) ||
      (/^13$|^9$/.test(e.keyCode) && this.currentItem>=0)) {

        if (e.preventDefault) e.preventDefault();
        if (e.stopPropagation) e.stopPropagation();

        e.cancelBubble = true;
        e.returnValue = false;

        switch(e.keyCode) {
          case 38: // up
          this.selectItem(this.currentItem-1);
          break;
          case 40: // down
          this.selectItem(this.currentItem+1);
          break;
          case 9:  // tab
          case 13: // return
          this.selectCurrentItem();
          break;
          case 27: //	escape
          this.hideResults();
          break;

        }
      } else if (this.$input.val().length != this.prevLength) {
        var t=this;
        if (t.timeout)
        clearTimeout(t.timeout);
        t.timeout = setTimeout(function() { t.suggest() }, t.options.delay);
        t.prevLength = t.$input.val().length;
      }
    },
    suggest:function() {
      var q = $.trim(this.$input.val());
      var addr = q.split(',');
      var last = $.trim(addr[addr.length-1]);
      this.resetPosition();

      if (last.length >= this.options.minchars) {
        this.items = [];
        for( var id_contact in contacts)
        {
          if(id_contact=='length')continue;
          var row = contacts[id_contact];
          var re = new RegExp(last,'gi');
          var in_name = row[0].match(re);
          var in_email = row[1].match(re);

          if(in_name || in_email)
          {
            if(row[0]==row[1]){
              this.items.push(row[0]);
            }else{
              this.items.push('"'+row[0]+'" <'+row[1]+'>');
            }
          }
        }
        if(this.items.length>0)
        {
          this.displayItems(last);
        }else{
          this.hideResults();
        }
      } else {
        this.hideResults();
      }
    },

    displayItems:function(q) {
      var t = this;
      var html = '';
      if (!t.items) return;


      for (var i = 0; i < t.items.length; i++) {
        var text = t.items[i].replace(/[<>\"\']/g , '');
        var item = t.options.formatItem?t.options.formatItem.call(t,text,q):t.formatItem(text,q);
        if(!item) t.items.splice(i,1); // remove false items
        else html+=item;
      }

      if (!t.items.length) {
        t.hideResults();
        return;
      }

      $('ul',t.$results).html(html)
      t.$results.show()
      $('ul',t.$results).children()
      .mouseover(function() {
        var $items = $('ul',t.$results).children();
        for(var i=0;i<$items.length;i++) if($items[i]==this) break;
        t.selectItem(i);
      })
      .click(function(e) {
        t.selectCurrentItem();
        return false;
      });
      
      $('ul',t.$results).append('<li class="footer"><a href="/addressbook.php">Адресная книга</a></li>');
    },
    formatItem:function(txt,q) {
      txt=$.trim(txt);
      if(txt) return '<li>'+this.addMatchClass(txt,q)+'</li>';
      return false;
    },
    hideResults:function() {
      this.$results.hide();
      this.currentItem=-1;
    },
    selectItem:function(i) {
      if(i<0) i=this.items.length-1;
      if(i>=this.items.length) i=0;
      this.currentItem=i;
      $('li',this.$results).removeClass(this.options.selectClass).eq(i).addClass(this.options.selectClass);
    },
    selectCurrentItem:function() {
      if (this.currentItem>=0) {
        var item = this.currentItem;
        var text = this.options.selectItemText?this.options.selectItemText.call(this,this.items[item]):this.$results.children().eq(item).text();
        var val = this.$input.val().split(',');
        var item_text = this.items[item];
        var name = this.items[item].match(/"[^"]*"/);
        if(name)
        {
          name = name.toString().replace(/["]/g,'');
        }
        var mail = this.items[item].match(/<[^>]*>/);
        if(mail)
        {
          mail = mail.toString().replace(/[<>]/g,'');
        }
        if(name && mail && name==mail){
          item_text = mail;
        }
        var index = val.length-1;

        val[index] = ' '+item_text+', ';
        
        text = val.join(',');

        // hacked by bakytn, unescaping
        text = text.replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/&quot;/g, '"')
            .replace(/&amp;/g, '&')
            .replace(/&#039;/g, '\'');

        this.$input.val(text);
        this.hideResults();

        if (this.options.onSelect)
        this.options.onSelect.call(this.$input[0],this.items[item]);
      }
    }
  });



  $.fn.suggest = function(options) {
    options = $.extend({
      delay:100,
      resultsClass:'ac_results',
      selectClass:'ac_over',
      matchClass:'ac_match',
      minchars:1,
      delimiter:'\n',
      createItems:false,
      formatItem:false,
      selectItemText:false,
      onSelect:false,
      maxCacheSize:65536
    },options);

    this.each(function() {
      new $.suggest(this, options);
    });

    return this;
  };
//})(jQuery);
