// Copyright (c) 2006 - 2008 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.4

var MAG = Object.extend({}, MAG || {});

Autocompleter.SelectBox = Class.create();
Autocompleter.SelectBox.prototype = Object.extend(new Autocompleter.Base(), {

	_on_over: false,
	initialize: function(select, options) {

	if(select.onchange) this.onchange = select.onchange;
	
	if($(select)._prototypeEventID)
	{
		var events_for_element = Event.cache[$(select)._prototypeEventID];
		Object.keys(events_for_element).each(function(evt_name){
			this["sel_"+evt_name] = events_for_element[evt_name];
		}.bind(this));
	}

	MAG["select_"+$(select).id] = this;

	var inputClasses = Element.classNames(select);
	this.element = new Element('input', {
		id: $(select).id + '_combo',
		type: 'text',
		'class': inputClasses
	});
	new Insertion.Before(select, this.element)

	this.update = "<div id=\"" + $(select).id + "_options\" class=\"auto_complete\"></div>"
	new Insertion.Before(select, this.update)

    this.baseInitialize($(select).id + "_combo", $(select).id + "_options", options);
    this.tokenBounds = [-1, 0];
    this.select = select;

	$(this.element.id).setAttribute('readonly','readonly');
	this.element.readOnly = true;

	Element.hide(select);
	Element.addClassName(this.element.id, this.options.css) ;

	this.setSelectOptions();

	Event.observe(this.element, "click", this.activate.bindAsEventListener(this));

	if ($(select).selectedIndex >= 0) this.element.value = $(select).options[$(select).selectedIndex].innerHTML;

	var self = this;
	this.options.afterUpdateElement = function(text, li) {
		if(li.hasClassName('optgroup')) return;
		var optionList = $(select).getElementsByTagName('option');
		var nodes = $A(optionList);

		var opt = nodes.find( function(node){
			return (node.value == li.id);
		});
		$(select).selectedIndex=opt.index;
		
		if(self.sel_change) {
			self.sel_change.each(function(f){
				f.handler.call($(select));
			});
		}
		
		if(typeof self.onchange == 'function') {
			self.onchange.bind(self.select).call();
		}
	}

	Event.observe(this.update, 'mouseover', function(){this._on_over=true;}.bind(this));
	Event.observe(this.update, 'mousemove', function(){this._on_over=true;}.bind(this));
    Event.observe(this.update, 'mouseout', function(){this._on_over=false;this.element.focus();}.bind(this));
  },

  setSelectOptions: function()
  {
		this.selectOptions = [];
		var optionList = $(this.select).getElementsByTagName('option');
		var nodes = $A(optionList);
		var tmp_parent = null;
		for(i=0; i<nodes.length;i++){
			var parent_element = nodes[i].parentNode;
			if(parent_element != tmp_parent) {
				tmp_parent = parent_element;
				if(parent_element.tagName === 'OPTGROUP') {
					this.selectOptions.push("<li class=\"optgroup\">" + parent_element.getAttribute('label') + '</li>');
					var html_class = 'optgroup_option';
				} else {
					var html_class = 'option';
				}
			}
			this.selectOptions.push("<li class=\""+html_class+"\" id=\"" + nodes[i].value + "\">" + nodes[i].innerHTML + '</li>');
			if (nodes[i].getAttribute("selected")) this.element.value = nodes[i].innerHTML;
		}
  },

  getUpdatedChoices: function() {
  		this.updateChoices(this.setValues());
  },

  setValues : function(){
		return ("<ul>" + this.selectOptions.join('') + "</ul>");
  },

  setOptions: function(options) {
    this.options = Object.extend({
		css			: 'combo'	 //css class for new element
	}, options || {});
  },

  reSet: function()
  {
  	this.setSelectOptions();
  	$(this.update).update(this.setValues());
  	if($(this.select).selectedIndex >= 0) this.element.value = $(this.select).options[$(this.select).selectedIndex].innerHTML;
  	else this.element.value = '';
  },

  onClick: function(event) {
  	var element = Event.findElement(event, 'LI');
  	if(element.hasClassName('optgroup')) return;
    this.index = element.autocompleteIndex;
    this.selectEntry();
    this.hide();
  },

  onBlur: function(event) {
  	if(this._on_over===true) return;

  	// needed to make click events working
    setTimeout(this.hide.bind(this), 250);
    this.hasFocus = false;
    this.active = false;
  }
});

Event.observe(window, 'load', function(e){
	$$('select').each(function(sel){
		new Autocompleter.SelectBox(sel);
	});
});