/*
  - MooTools version required: 1.2
  - MooTools components required: Element.Event, Element.Style, Selectors, Request.JSON and dependencies.
  
  Credits:
  - Idea: Facebook
  - Adapted from a TextboxList + Autocomplete 0.2 script by Guillermo Rauch <http://devthought.com/>
  - Realised thanks to the help of Josh Moont <http://twitter.com/moonty>
  
  Changelog:
  - 0.1: initial release
*/

/* Copyright: Jeremy DESVAUX <http://jdmweb.com/> - Keep this message! */



//============== Settings ==================//

//Url of the json page from where to fetch the data
var JSONUrl = "/mysql2json/example.php";

//Url you want to go to when the user clicks on of the list elements. (Or when he presses enter)
var GOTOUrl = "/";

//Id and Name of the input where the user types
var UserInput = "searchTxtHome";

//Id and Name of the results container
var ResContainer = "facebook-auto";

//==========================================//
//Edit below this line at your own risks



var FacebookList = new Class({

  Extends: TextboxList,
  
  options: {    
    onBoxDispose: function(item) { this.autoFeed(item.retrieve('text')); },
    onInputFocus: function() { this.autoShow(); },    
    onInputBlur: function(el) { 
      this.lastinput = el;
      this.blurhide = this.autoHide.delay(200, this);
    },
    autocomplete: {
      'opacity': 0.8,
      'maxresults': 15,
      'minchars': 1
    }
  },
  
  initialize: function(element, autoholder, options) {
    arguments.callee.parent(element, options);
    this.references = [];
	this.data = [];
	this.loc = [];
	this.logos = [];	
	this.autoholder = $(autoholder).set('opacity', this.options.autocomplete.opacity);
	this.autoresults = this.autoholder.getElement('ul');
	var children = this.autoresults.getElements('li');
	children.each(function(el) { this.add(el.innerHTML); }, this); 
  },
  
  autoShow: function(search) {
    this.autoholder.setStyle('display', 'block');
	
    this.autoholder.getElement('.default').setStyle('display', 'none');
    this.autoholder.getElement('.feed').setStyle('display', 'none');
    if(! search || ! search.trim() || (! search.length || search.length < this.options.autocomplete.minchars)) 
    {
      this.autoholder.getElement('.default').setStyle('display', 'block');
	  this.resultsshown = false;
    } else {
      this.resultsshown = true;
      this.autoresults.setStyle('display', 'block').empty();
	  
      this.data.filter(function(str) { return str ? str.test(search, 'i') : false; }).each(function(result, ti) {
        
		if(ti >= this.options.autocomplete.maxresults) return;
        var that = this;
        var el = new Element('li').addEvents({
          'mouseenter': function() { that.autoFocus(this);},
          'click': function(e) { 
            new Event(e).stop();
            that.autoAdd(this); 
          }
        }).set('html', '<div style="height:30px;clear:both;">' + this.autoHighlight(result, search) +'</div>').inject(this.autoresults);
        el.store('result', result);
        if(ti == 0) this.autoFocus(el);
      }, this);
    }
    return this;
  },
  
  autoHighlight: function(html, highlight) {
    return html.replace(new RegExp(highlight, 'gi'), function(match) {
      return '<em>' + match + '</em>';
    });
  },
  
  autoHide: function() {    
    this.resultsshown = false;
    this.autoholder.setStyle('display', 'none');    
    return this;
  },
  
  autoFocus: function(el) {
    if(! el) return;
    if(this.autocurrent) this.autocurrent.removeClass('auto-focus');
    this.autocurrent = el.addClass('auto-focus');
    return this;
  },
  
  autoMove: function(direction) {    
    if(!this.resultsshown) return;
    this.autoFocus(this.autocurrent['get' + (direction == 'up' ? 'Previous' : 'Next')]());
    return this;
  },
  
  autoFeed: function(id,text,area,pic) {
	
	this.references.include(id);
    this.data.include(text);
	this.loc.include(area);
    this.logos.include(pic);
    return this;
  },
  
  autoAdd: function(el) {
	 //alert(this.data);
    if(!el || ! el.retrieve('result')) return;
	//var vid = this.references[this.data.indexOf(el.retrieve('result'))]++;
    location.href=GOTOUrl+this.references[this.data.indexOf(el.retrieve('result'))];
    this.autoHide();
    return this;
  },
  
  createInput: function(options) {
    var li = arguments.callee.parent(options);
    var input = li.retrieve('input');
    input.addEvents({
      'keydown': function(e) {
        this.dosearch = false;
        switch(new Event(e).code) {
          case Event.Keys.up: return this.autoMove('up');
          case Event.Keys.down: return this.autoMove('down');        
          case Event.Keys.enter: 
            if(! this.autocurrent) break;
            this.autoAdd(this.autocurrent);
            this.autocurrent = false;
            this.autoenter = true;
            break;
          case Event.Keys.esc: 
            this.autoHide();
            if(this.current && this.current.retrieve('input'))
              this.current.retrieve('input').set('value', '');
            break;
          default: this.dosearch = true;
        }
      }.bind(this),
      'keyup': function() {
        if(this.dosearch) this.autoShow(input.value);
      }.bind(this)
    });
    input.addEvent(Browser.Engine.trident ? 'keydown' : 'keypress', function(e) { 
      if(this.autoenter) new Event(e).stop()
      this.autoenter = false;
    }.bind(this));
    return li;
  }
  
});

window.addEvent('domready', function() {
  
  // init
  var tlist2 = new FacebookList(UserInput, ResContainer);
  
  // fetch and feed
  new Request.JSON({'url': JSONUrl, 'onComplete': function(j) {
	for (var p in j) {
		tlist2.autoFeed(j[p]['value'], j[p]['caption'], j[p]['picture']);
	}
  }}).send();
  
});