/*
  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 JSONData = new Class({
  options: {
  },

  initialize: function() {
    this.name = [];
    this.data = [];
  },

  add: function(pname, pdata) {    
    this.name.include(pname);
    this.data.include(pdata);
  },

  sendData: function() {
    //return JSON.encode(this.data.associate(this.name));
    return this.data.associate(this.name);
  }
});

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': 10,
      'minchars': 3
    },
    cargaid: true,
    alowadd : false,
    multiple : true
  },
	

	
	
  initialize: function(element, autoholder, options) {
    this.parent(element, options);
    this.data = [];
    this.iddata = [];
    this.newdata = [];
    this.showdata = [];
    this.showiddata = [];
		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);
		
		if( this.options.alowadd){
			this.alowadd = this.options.alowadd
		}
		
    if (this.options.comentario) {
      var div_comentario = new Element('div', {
        'class': 'default',
        'text': this.options.comentario
      });
      div_comentario.inject(this.autoholder, 'top');
    }

    // Miramos si pasamos el parámetro de la url de la carga de datos inicial
    if (this.options.urldatainicial) {
      var this_fb = this;
      var jSonRequest = new Request.JSON({
						url: options['urldatainicial'], 
								onComplete: function(jsonListado){	
															jsonListado.rows.each(function(lista) {																																	
																this_fb.autoFeed(lista);																												  		
													  	});															  	
													  	//jsonListado.rows.each(this_fb.autoFeed, this_fb);							  					      												        						      	
														}
					}).send();
      

        /*j.each(function(item, index){
         alert(index + " = " + item);
        }); */
      
    }
  },

  autoShow: function(search) {
    var numres=0;
    this.autoholder.setStyle('display', 'block');
    this.autoholder.getChildren().setStyle('display', 'none');
    if(! search || ! search.trim() || (! search.length || search.length < this.options.autocomplete.minchars) ||
      ( (this.options.multiple == false) && (this.showiddata.length > 0) ) )
    {
      if (this.autoholder.getElement('.default'))
        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;

        numres++;
        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', this.autoHighlight(result, search)).inject(this.autoresults);
        el.store('result', result);
        if(ti == 0) this.autoFocus(el);
      }, this);

      if (numres == 0) {
        this.autocurrent = false;
      }
    }

    //this.setEstado(this.autocurrent);
    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) {    
    if (($type(text) == 'object')) {
    	this.iddata.include(text.id);
      this.data.include(text.titulo);            
    }
    else if ( ($type(text) == 'array') && (text.length == 2) && (this.options.cargaid == true) ) {
      this.iddata.include(text[0]);
      this.data.include(text[1]);
    }
    else {
      this.data.include(text);
    }
    return this;
  },

	autoLoad: function (text){		
		if (text != null){
			var that = this;						
			var milista = text.split(','); 			
			milista.each(function(item){									
						that.autoShow(item);	
						$$("li.auto-focus").each(function(el){
							that.fireEvent('onInputBlur',el);		
							el.fireEvent('mouseenter');	
							el.fireEvent('click',el);			
						});	
			});
		}	
	},

	autoCarga: function(pid){
		this.autoShow(pid);		
		var that = this;		
		$$("li.auto-focus").each(function(el){
			that.fireEvent('onInputBlur',el);		
			el.fireEvent('mouseenter');	
			el.fireEvent('click',el);			
		});		
	},


  autoAdd: function(el) {        
    if(!el || ! el.retrieve('result')) return;
   
    var val = el.retrieve('result');
    var input = this.lastinput || this.current.retrieve('input');
    if (this.showdata.indexOf(val) != -1) {
      input.set('value', '').focus();
      return;
    }

    var pos = this.data.indexOf(val);    
    this.showdata.include(val);
    this.showiddata.include(this.iddata[pos]);
		this.add(val);
		//alert("hemos añadido " + val);
    //delete this.data[this.data.indexOf(el.retrieve('result'))];
    this.data.erase(val);
    this.iddata.erase(this.iddata[pos]);
    this.autoHide();

    input.set('value', '').focus();

    if ( (this.options.multiple == false) && (this.showiddata.length > 0) ) {
      $$("input.maininput").setStyle('visibility', 'hidden');
      // BERNABEU
      $$("input.maininput").setStyle('display', 'none');
    }
    return this;
  },

  autoAddNuevo: function(el) {
    if(!el) return;

    var val = el.get('value');

    // Miramos si no esta en la lista de palabras
    if (this.data.indexOf(val) == -1)
      this.newdata.include(val);

    if (this.showdata.indexOf(val) != -1) {
      var input = this.lastinput || this.current.retrieve('input');
      input.set('value', '').focus();
      return;
    }

    this.showdata.include(val);
    this.add(val);
    this.generarPalabras();

    var input = this.lastinput || this.current.retrieve('input');
    input.set('value', '').focus();

    return this;
  },
  cambiarEstado: function() {
    var el = $("estado");
    var val = el.get('value');

    if (val == "off")
      val = "on";
    else
      val = "off";

    el.set('value', val);
  },

  setEstado: function(val) {
    var el = $("estado");

    if (val)
      el.set('value', "on");
    else
      el.set('value', "off");
  },

  generarPalabras: function() {
    var el = $("palabras");
    var words = "";

    this.newdata.each(function(item, index){
      var word = item;

      if (words != "") words += " - ";

      words += word + " (" + word.length + ")";
    });

    el.set('value', words);
  },

  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:

            //this.setEstado(this.autocurrent);

            if(! this.autocurrent && this.alowadd) {
              
              this.autoAddNuevo(input);
              this.autoenter = true;
              break;
            }						
            this.autoAdd(this.autocurrent);
            this.autocurrent = false;
            this.autoenter = true;
            //$$("input.maininput") .set('value', '');

            break;
          case Event.Keys.esc:
            this.autoHide();
            //if(this.current && this.current.retrieve('input'))
            //  this.current.retrieve('input').set('value', input.value);
            //this.current = false;
            this.autocurrent = false;

            break;
          default: this.dosearch = true;
        }
        //this.setEstado(this.autocurrent);
      }.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;
  },
	
	
	
	
	vaciaBox: function(){
		var mischildren = $$('.closebutton');
			mischildren.each(function(el){							
					el.fireEvent('click',el);
			});
	},

  createBox: function(text, options) {
    var li = this.parent(text, options);
    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);
					
				
          // Elemento a quitar
          var val = li.get("text");
          this.newdata.erase(val);

          var pos = this.showdata.indexOf(val);
          var idval = this.showiddata[pos];

          this.showiddata.erase(idval);
          this.showdata.erase(val);
					this.iddata.include(idval);
					this.data.include(val);					
          //this.generarPalabras();

          this.dispose(li);

          if ( (this.options.multiple == false) && (this.showiddata.length == 0) ) {
            $$("input.maininput").setStyle('visibility', 'visible');
            // BERNABEU
            $$("input.maininput").setStyle('display', 'inline');

            var input = this.lastinput || this.current.retrieve('input');
            input.set('value', '').focus();
          }
        }.bind(this)
      }
    })).store('text', text);
  }

});
