/*
  Moogets - TextboxList + Autocomplete 0.2
  - MooTools version required: 1.2
  - MooTools components required: Element.Event, Element.Style, Selectors, Request.JSON and dependencies.

  Credits:
  - Idea: Facebook

  Changelog:
  - 0.1: initial release
  - 0.2: added click support, removed $attributes use, code cleanup
*/

/* Copyright: Guillermo Rauch <http://devthought.com/> - Distributed under MIT - Keep this message! */
var tlist2 ; // create a text box list 


var FacebookList = new Class({

  Extends: TextboxList,

  options: {
    onBoxDispose: function(item) { this.autoFeed(item.get('text'));},
    onInputFocus: function() {  this.autoShow(); },
    onKeyPressGetCity: function(itemText) {this.fireEvent('getList', itemText);},
    onInputBlur: function(el) {
      this.lastinput = el;
      this.blurhide = this.autoHide.delay(200, this);
    },
    autocomplete: {
      'opacity': 1.0,
      'maxresults': 5,
      'minchars': 1 
    }
  },

  initialize: function(element, autoholder, options) {
    this.parent(element, options);
    this.data = [];
      this.data.include("No Results Found");
    this.searchValues = [];
      this.countSearchVales = 0;
		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.getChildren().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;
      this.searchAjax = true;
    } else {
      this.resultsshown = true;
      this.autoresults.setStyle('display', 'block').empty();
     this.autoholder.getElements('div').setStyle('display', 'block');
       this.autoholder.getElements('div').setStyle('z-index', '200');
      this.autoholder.getElement('.default').setStyle('display', 'none');



      var rg = new RegExp('^' + search.escapeRegExp(), 'i');
      this.data.filter(function(str) { return str ? str.match(rg) : false; }).each(function(result, ti) {
        if(ti >= this.options.autocomplete.maxresults) return;
        var that = this;
        if(result != "No Results Found") {
            var textIn = result.split(",");
            var toxttoshow = "";

              if(textIn[1].length > 1) {
                  toxttoshow = textIn[0] + "," + textIn[1];
              } else {
                   toxttoshow = textIn[0];
              }

             var el = new Element('li').addEvents({
              'mouseenter': function() { that.autoFocus(this); },
              'click': function(e) {
                new Event(e).stop();
                that.autoAdd(this);
              }
            }).set('html', this.autoHighlight(toxttoshow, search)).inject(this.autoresults);
              el.set('id', textIn[2]);
              el.store('result', result);
            if(ti == 0) this.autoFocus(el);
            
        }
      }, this);


       if(this.searchValues.length > this.countSearchVales) {
           
            var children = this.autoresults.getElements('li');
            if(children.length == 0) {
                var el = new Element('li').addEvents({
                  'mouseenter': function() { /*that.autoFocus(this);*/ },
                  'click': function(e) {
                    new Event(e).stop();
                  }
                }).set('html', this.autoHighlight("Loading...", "")).inject(this.autoresults);
                  el.store('result', "Loading...");
            }
           //this.countSearchVales++;
        } else {
            var children = this.autoresults.getElements('li');
            if(children.length == 0) {
                var el = new Element('li').addEvents({
                  'mouseenter': function() { /*that.autoFocus(this);*/ },
                  'click': function(e) {
                    new Event(e).stop();
                  }
                }).set('html', this.autoHighlight("No Results Found", "")).inject(this.autoresults);
                  el.store('result', "No Results Found");
            }
        }

    }
    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(text) {
    //var textIn = text.split("-");
      this.data.include(text);
    //this.data.include(textIn[0]+"-"+textIn[2]);
    //this.datadescrition[textIn[2]] = textIn[0]+"-"+textIn[1];
    return this;
  },

  autoAdd: function(el) {
    if(!el || ! el.retrieve('result')) return;
    var rt= this.add(el.retrieve('result'));
    if(rt!=null){ // check whether new via city is added or not
    	delete this.data[this.data.indexOf(el.retrieve('result'))]; // city name is removed from auto complete list
    }
    this.autoHide();
    var input = this.lastinput || this.current.retrieve('input');
    input.set('value', '').focus();
    return this;
  },

 // if($$('li li.bit-box').length > 0) { this.setStyle('display', 'none');}

  createInput: function(options) {
    var li =  this.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.searchValues.length > 0 && this.searchValues.length[this.searchValues.length -1] != input.value.charAt(0)) {
             this.searchAjax = true;
         }

          this.fireEvent('onKeyPressGetCity', input.value);
          this.searchAjax = false;
        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;
  },

 incrementSearchValue: function() {
   this.countSearchVales++;
 },

  createBox: function(text, options) {	 
    var li =  this.parent(text, options);
   // var textIn = text.split("-");
    return li.addEvents({
      'mouseenter': function() { this.addClass('bit-hover') },
      'mouseleave': function() { this.removeClass('bit-hover') }
    }).adopt(new Element('a', {
      'href': '#',
      'class': 'closebutton',
      'events': {
        'click': function(e) {
          new Event(e).stop();
         if(! this.current) this.focus(this.maininput);
          this.dispose(li);  
        }.bind(this)
      }
    })).store('text', text);    
  }

});



window.addEvent('domready', function() {


        tlist2 = new FacebookList('via_cities_input', 'facebook-auto');
        var url = "";


      tlist2.addEvent('getList', function(text) {

          if(text.trim().length > 0) {

              url = base_path + "via_city_json/"+text.charAt(0).trim();

           var searchValueNotFound = true;

             if(this.searchValues.length != 0) {

              for(var i=0; i < this.searchValues.length; i++) {
    
                  var rg = new RegExp('^'  + this.searchValues[i].escapeRegExp(), 'i');

                  if(text.charAt(0).search(/[a-zA-Z]/) == -1 || text.charAt(0).match(rg)) {
                      searchValueNotFound = false;
                  }

              }

             if(searchValueNotFound) {
                   this.searchValues.push(text.charAt(0));
                   if(this.searchAjax) {
                       new Request.JSON({'url': url, 'onSuccess': function(j) {
                            if(j !== null && j.length > 0) {
                                j.each(tlist2.autoFeed, tlist2);
                            }
                            tlist2.incrementSearchValue();
                            var textVal = $$('#facebook-list input.maininput')[0].get('value');
                            tlist2.autoShow(textVal);

                        } /*, 'onRequest': function() {show_hide_path_load_img(true);}, 'onFailure': function() {show_hide_path_load_img(false);} */}).send();

                       searchValueNotFound = true;
                   }
             }




         } else {

             if(text.charAt(0).search(/[a-zA-Z]/) != -1) {

                  this.searchValues.push(text.charAt(0));
                  if(this.searchAjax) {
                        new Request.JSON({'url': url, 'onSuccess': function(j) {
                            if(j !== null && j.length > 0) {
                                j.each(tlist2.autoFeed, tlist2);
                            }
                            tlist2.incrementSearchValue();
                            var textVal = $$('#facebook-list input.maininput')[0].get('value');
                            tlist2.autoShow(textVal);
                        } /*, 'onRequest': function() {show_hide_path_load_img(true);}, 'onFailure': function() {show_hide_path_load_img(false);}*/ }).send();

                  }

             }
             



         }


          }

      });

});

