// Autor: Alfonso Nishikawa
// Fecha: Mayo-2009
// 
// controls_dice.js v2009-08-13
//
// Crea un control autocompleter local que siempre muestra todas las opciones

// Expande:
// script.aculo.us controls.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008

Autocompleter.BaseExt = Class.create(Autocompleter.Base, {
  baseInitialize: function($super,element, update, options) {
    $super(element, update, options) ;
    this.options.elemsperpage = options.elemsperpage || 5 ;
  },

  onKeyPress: function(event) {
    if(this.active)
      switch(event.keyCode) {
       case Event.KEY_TAB:
       case Event.KEY_RETURN:
         this.selectEntry();
         Event.stop(event);
       case Event.KEY_ESC:
         this.hide();
         this.active = false;
         Event.stop(event);
         return;
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
         return;
       case Event.KEY_UP:
         this.markPrevious();
         this.render();
         Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         this.render();
         Event.stop(event);
         return;
       case Event.KEY_HOME:
    	 this.markFirst() ;
    	 this.render();
    	 Event.stop(event) ;
    	 return ;
       case Event.KEY_END:
    	 this.markLast();
    	 this.render();
    	 Event.stop(event);
    	 return ;
       case Event.KEY_PAGEUP:
    	 this.markPageUp();
    	 this.render() ;
    	 Event.stop(event);
    	 return ;
       case Event.KEY_PAGEDOWN:
    	 this.markPageDown() ;
    	 this.render() ;
    	 Event.stop(event) ;
         return;
      }
    else
      if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
        (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;

    this.changed = true;
    this.hasFocus = true;

    if(this.observer) clearTimeout(this.observer);
      this.observer = setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  },

  markPrevious: function() {
	    if(this.index > 0) this.index--;
	    else this.index = this.entryCount-1;
	    if (this.entryCount <= this.index + this.options.elemsperpage) {
	           this.getEntry(this.entryCount - 1).scrollIntoView(false); }
	    else { this.getEntry(this.index + this.options.elemsperpage).scrollIntoView(false); }
	  },

  markNext: function() {
	    if(this.index < this.entryCount-1) this.index++;
	      else this.index = 0;
	    if (this.entryCount <= this.index + this.options.elemsperpage)
	         { this.getEntry(this.entryCount - 1).scrollIntoView(false); }
	    else { this.getEntry(this.index + this.options.elemsperpage).scrollIntoView(false); }
	  },
	  
  markFirst: function() {
		this.index =  0 ;
		this.getEntry(this.index).scrollIntoView(false);
	  },

  markLast: function() {
		this.index = this.entryCount - 1;
		this.getEntry(this.index).scrollIntoView(false) ;
	  },
	  
  markPageUp: function() {
		this.index -= this.options.elemsperpage ;
		if (this.index < 0 ) { this.index = 0; }
	    if (this.entryCount <= this.index + this.options.elemsperpage)
	         { this.getEntry(this.entryCount - 1).scrollIntoView(false); }
        else { this.getEntry(this.index + this.options.elemsperpage).scrollIntoView(false); }
	  },
	  
  markPageDown: function() {
        this.index += this.options.elemsperpage ;
        if (this.index >= this.entryCount) { this.index = this.entryCount - 1 ; }
	    if (this.entryCount <= this.index + this.options.elemsperpage)
	         { this.getEntry(this.entryCount - 1).scrollIntoView(false); }
	    else { this.getEntry(this.index + this.options.elemsperpage).scrollIntoView(false); }
      },

  hide: function() {
 	    this.stopIndicator();
   	    if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
   	    if(this.iefix) Element.hide(this.iefix);
   	    if(this.entryCount>0) { this.getEntry(0).scrollIntoView(false) ; }
  	  },

    }) ;

Ajax.AutocompleterExt = Class.create(Autocompleter.BaseExt, {
	  initialize: function(element, update, url, options) {
	    this.baseInitialize(element, update, options);
	    this.options.asynchronous  = true;
	    this.options.onComplete    = this.onComplete.bind(this);
	    this.options.defaultParams = this.options.parameters || null;
	    this.url                   = url;
	  },

	  getUpdatedChoices: function() {
	    this.startIndicator();

	    var entry = encodeURIComponent(this.options.paramName) + '=' +
	      encodeURIComponent(this.getToken());

	    this.options.parameters = this.options.callback ?
	      this.options.callback(this.element, entry) : entry;

	    if(this.options.defaultParams)
	      this.options.parameters += '&' + this.options.defaultParams;

	    new Ajax.Request(this.url, this.options);
	  },

	  onComplete: function(request) {
	    this.updateChoices(request.responseText);
	  }
	});

// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//           (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
//           (c) 2005-2008 Jon Tirsen (http://www.tirsen.com)
// Contributors:
//  Richard Livsey
//  Rahul Bhargava
//  Rob Wills
//

Autocompleter.LocalFullChoices = Class.create(Autocompleter.Base, {
  initialize: function(element, update, array, options) {
    this.baseInitialize(element, update, options);
    this.options.array = array;
  },

  getUpdatedChoices: function() {
//document.getElementById('estado').innerHTML = document.getElementById('estado').innerHTML + '(updatedchoices tiny)';
    this.startIndicator();
    this.updateChoices(this.options.selector(this));
  },

  setOptions: function(options) {
    this.options = Object.extend({
      choices: 10,
      partialSearch: true,
      partialChars: 2,
      ignoreCase: true,
      fullSearch: false,
      selector: function(instance) {
        var ret       = []; // Beginning matches

        for (var i = 0; i < instance.options.array.length; i++) {
          ret.push("<li>" + instance.options.array[i] + "</li>");
        }
        return "<ul>" + ret.join('') + "</ul>";
      }
    }, options || { });
  },
  
  show: function() {
    if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
    if(!this.iefix &&
      (Prototype.Browser.IE) &&
      (Element.getStyle(this.update, 'position')=='absolute')) {
      new Insertion.After(this.update,
       '<iframe id="' + this.update.id + '_iefix" '+
       'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
       'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
      this.iefix = $(this.update.id+'_iefix');
    }
    if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
    // Había problemas al mostrar las sugerencias con .activate(), así que cuando
    //  se muestren las sugerencas ahora, activamos la observación de blur
    Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
  },

  hide: function() {
    this.stopIndicator();
    if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
    if(this.iefix) Element.hide(this.iefix);
    // Si no se desactiva aqué la observación de blur, al mostrar las sugerencias
    //  con .activate() sélo funciona una de cada dos o tres veces
    Event.stopObserving(this.element, 'blur');
  },
  updateElement: function(selectedElement) {
  // Redefinimos este método porque daba problemas a la hora de copiar el elemento
  // seleccionado al input 
    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';
    if (this.options.select) {
      var nodes = $(selectedElement).select('.' + this.options.select) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else {
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
    }
    this.element.value = value;
    this.oldElementValue = this.element.value;
    this.element.focus();
    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
  },

  markPrevious: function() {
    if(this.index > 0) this.index--;
      else this.index = this.entryCount-1;
    this.getEntry(this.index).scrollIntoView(false);
  },

});

// ============================================================================
// ============================================================================
// ============================================================================
// Autor: Alfonso Nishikawa
// Fecha: Julio-2009
// Crea un control autocompleter local que siempre muestra todas las opciones
// y que siempre es visible

// Expande: Autocompleter.LocalFullChoices
// script.aculo.us controls.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008

// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//           (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
//           (c) 2005-2008 Jon Tirsen (http://www.tirsen.com)
// Contributors:
//  Richard Livsey
//  Rahul Bhargava
//  Rob Wills
//

Autocompleter.AlwaysVisible = Class.create(Autocompleter.Base, {
  initialize: function(element, update, array, options) {
    this.baseInitialize(element, update, options);
    this.options.array = array;
	this.activate();
  },

  onObserverEvent: function() {
    this.changed = false;
    this.tokenBounds = null;
    this.getUpdatedChoices();
    this.oldElementValue = this.element.value;

    if (this.element.value != null && this.element.value != '') {
        if (this.entryCount <= this.index + 6) {
            this.getEntry(this.entryCount - 1).scrollIntoView(false);
        }
        else {
            this.getEntry(this.index + 6).scrollIntoView(false);
        }
        this.render();
    }

  },

  getUpdatedChoices: function() {
    this.updateChoices(this.options.selector(this));
    if (elemento_encontrado) this.index = elegido;
	elemento_encontrado=false ;
  },

  setOptions: function(options) {
    this.options = ({
      choices: 10,
      partialSearch: true,
      partialChars: 2,
      ignoreCase: true,
      fullSearch: false,
      selector: function(instance) {
        var ret       = []; // Beginning matches
        var entry     = instance.getToken();
        elemento_encontrado = false ;
		if (typeof(cache_listado_generado)=='undefined') cache_listado_generado=false ;
        for (var i = 0; i < instance.options.array.length; i++) {
          var elem = instance.options.array[i] ;
		  if (cache_listado_generado!=true) ret.push("<li>" + elem + "</li>");
          if (entry.length!=0 && !elemento_encontrado && elem.substr(0,entry.length) == entry) {
		  	elemento_encontrado = true ;
			elegido = i ;
		  }		  
        }
        if (cache_listado_generado != true) {
			cache_listado = "<ul>" + ret.join('') + "</ul>";
			cache_listado_generado = true;
		}
		return cache_listado;
      }
    });
  },

  show: function() {
  },

  hide: function() {
  },
  updateElement: function(selectedElement) {
  // Redefinimos este método porque daba problemas a la hora de copiar el elemento
  // seleccionado al input

    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';
    if (this.options.select) {
      var nodes = $(selectedElement).select('.' + this.options.select) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else {
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
    }
    this.element.value = value;
    this.oldElementValue = this.element.value;
    this.element.focus();
    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
  },

  markPrevious: function() {
    if(this.index > 0) this.index--;
      else this.index = this.entryCount-1;

    if (this.entryCount <= this.index + 6) {
        this.getEntry(this.entryCount - 1).scrollIntoView(false);
    }
    else {
        this.getEntry(this.index + 6).scrollIntoView(false);
    }
  },

  markNext: function() {
    if(this.index < this.entryCount-1) this.index++;
      else this.index = 0;

    if (this.entryCount <= this.index + 6) {
        this.getEntry(this.entryCount - 1).scrollIntoView(false);
    }
    else {
        this.getEntry(this.index + 6).scrollIntoView(false);
    }
  },
  
  updateChoices: function(choices) {
    if(!this.changed && this.hasFocus) {
      this.update.innerHTML = choices;
      Element.cleanWhitespace(this.update);
      Element.cleanWhitespace(this.update.down());

      if(this.update.firstChild && this.update.down().childNodes) {
        this.entryCount =
          this.update.down().childNodes.length;
        for (var i = 0; i < this.entryCount; i++) {
          var entry = this.getEntry(i);
          entry.autocompleteIndex = i;
          this.addObservers(entry);
        }
      } else {
        this.entryCount = 0;
      }

      this.stopIndicator();
      this.render();
    }
  },

  
});