// Copyright (c) 2006 - 2007 Gabriel Lanzani (http://www.glanzani.com.ar)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// SEE CHANGELOG FOR A COMPLETE CHANGES OVERVIEW
// VERSION 0.3

//Modified by Mark Pentland (http://www.golden-orb.com)
//	Butchered this to make it work with pikipimp: icon support and independece from a select box.

Autocompleter.SelectBox = Class.create();
Autocompleter.SelectBox.prototype = Object.extend(new Autocompleter.Base(), {
  initialize: function(select, button, options) {
	
	options.onShow = function(element, update){ 
      if(!update.style.position || update.style.position=='absolute') {
        update.style.position = 'absolute';
        Position.clone(element, update, {setHeight: false, setWidth: false, offsetTop: element.offsetHeight});
      }
	  update.style.width = options.width;
      Effect.Appear(update,{duration:0.15});
    };
	
	this.blurEvent = this.blurClick.bindAsEventListener(this);
	
	this.update = "<div id=\"" + $(select).id + "_options\" class=\"cbo_autocomplete\"></div>"	
	new Insertion.Before(select, this.update)
		
		
    this.baseInitialize($(select).id , $(select).id + "_options", options);
    this.select = select;
	this.selectOptions = [];
		
	$(this.element.id).setAttribute('readonly','readonly');
	this.element.readOnly = true;
	if(this.options.debug)alert('input ' + this.element.id + ' and div '+ this.update.id + ' created, Autocompleter.Base() initialized');

	var optionList = options.options;
	for(var i=0;i<optionList.length;i++) {
		var optHTML = "";
		if(optionList[i]["icon"]!=null) {
			optHTML =  '<img src="' + optionList[i]["icon"] + '" border="0" align="absmiddle"/> ' + optionList[i]["caption"];
		} else {
			optHTML = optionList[i]["caption"];
		}
		this.selectOptions.push('<li id="' + select.id + "_" + optionList[i]["value"] + '" value="' + optionList[i]["value"] + '">' + optHTML + '</li>');
		if (this.options.selectedValue != null) {
			if(optionList[i]["value"] == this.options.selectedValue) {
				this.index = i;
				$(this.select).innerHTML = optHTML;
			}
		}
		if(this.options.debug)alert('option ' + optHTML + ' added to '+ this.update.id);
	}
	
	
	Event.observe(select, "click", this.activate.bindAsEventListener(this));
	Event.observe(button, "click", this.activate.bindAsEventListener(this));
	
	
	var _this = this;
	
	this.options.updateElement = function(selectedElement) {
		$(_this.select).innerHTML = selectedElement.innerHTML;
		if(_this.options.onClick != null) {
			_this.options.onClick(selectedElement.getAttribute("value"));
		}
	}
  },

  getUpdatedChoices: function() {
	  	Event.observe(document, "mousedown", this.blurEvent);
		var idx = this.index;
  		this.updateChoicesCbo(this.setValues());
		this.index = idx;
  },
  
  updateChoicesCbo: function(choices) {
    if(!this.changed && this.hasFocus) {
      this.update.innerHTML = choices;
      Element.cleanWhitespace(this.update);
      Element.cleanWhitespace(this.update.firstChild);

      if(this.update.firstChild && this.update.firstChild.childNodes) {
        this.entryCount = 
          this.update.firstChild.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();
    }
  },

  setValues: function(){
		return ("<ul>" + this.selectOptions.join('') + "</ul>");
  },
  
  setOptions: function(options) {
    this.options = Object.extend({
		//MORE OPTIONS TO EXTEND THIS CLASS
		redirect	: false, // redirects to option value
		debug		: false, //show alerts with information
		autoSubmit	: '' //form Id to submit after change
	}, options || {});
  },
  
  blurClick: function(event) {
	  Event.stopObserving(document, "mousedown", this.blurEvent);
	  this.onBlur();
  }
  
  
})