//BEHAVIOR PRINCIPAL
var nCore_selectBox = Behavior.create({
	initialize: function()
	{
		if(Object.isUndefined(this.element.selectBoxClass)) this.element.selectBoxClass = new nCore_selectBoxClass(this.element);
	}
});




//CLASE PRINCIPAL
var nCore_selectBoxClass = Class.create();

nCore_selectBoxClass.prototype.initialize = function(element)
{
	this.element = element;
	this.extendOptions();
	this.getConfig();
			
	this.baseClass = this.element.className;		
	this.selectBox = new nCore_selectBoxDiv(this);
				
	this.element.hide();		
	Element.insert(this.element,{'before':this.selectBox.div});
	this.selectBox.startObservers();
	
	if(!this.config) this.setSelectedIndex(this.element.selectedIndex);
	else if(this.config.relateFrom != undefined) 
	{
		if(this.relateFrom.selectBoxClass != undefined)
		{
			this.updateFromRelation(this.relateFrom.value);
			if(this.config.selectedValue != undefined) this.setSelectedValue(this.config.selectedValue);
			if(this.config.selectedIndex != undefined) this.setSelectedIndex(this.config.selectedIndex);
		}
	}
	else this.setSelectedIndex(this.element.selectedIndex);
	
	return this;
}

nCore_selectBoxClass.prototype.extendOptions = function()
{
	this.element.options.each = function(iterator)
	{
		if(iterator == undefined) return;
		var x = 0;
		for(x=0;x<this.length;x++) iterator(this[x],x);
		
	}.bind(this.element.options);
}

nCore_selectBoxClass.prototype.getConfig = function()
{
	if(this.element.next() == undefined) this.config = false;
	else
	{
		var config = this.element.next();
		if(config.readAttribute("name") == "SELECT_config")
		{
			console.log("CONFIG");
			console.log(config.value);
			eval("this.config = " + config.value);				
			config.remove();
				
			if((this.config.relateTo != undefined) && ($(this.config.relateTo) != undefined)) this.relateTo = $(this.config.relateTo);
			else this.relateTo = false;
			
			if((this.config.relateFrom != undefined) && ($(this.config.relateFrom) != undefined)) this.relateFrom = $(this.config.relateFrom);
			else this.relateFrom = false;
		}
		else this.config = false;
	}
	
	var onchange = this.element.readAttribute("onchange");
	if(onchange != null)
	{
		if(!onchange.blank()) eval("this.userOnChange = function(){" + onchange + "}.bind(this.element);");
		else this.userOnChange = false;
	}
	else this.userOnChange = false;
}

nCore_selectBoxClass.prototype.updateFromArray = function(values)
{
	var x = 0;
	for (x=this.element.options.length - 1;x>=0;x--) {this.element.options[x] = null}
	values.each(function(value,index){ this.element.options[index] = new Option(value.label,value.value, false, false);}.bind(this));		
	this.update();
}

nCore_selectBoxClass.prototype.updateFromRelation = function(index)
{
	if(this.config) if(this.config.fromRelation != undefined) if(this.config.fromRelation.length) this.config.fromRelation.each(function(relation)
	{
		if(relation.relatedIndex == index) this.updateFromArray(relation.values);
	}.bind(this));
}


nCore_selectBoxClass.prototype.setSelectedValue = function(value)
{
	if(!this.element.options.length) return;
	var returnedOption = false;
	var x = 0;
	for(x=0;x<this.element.options.length;x++)
	{
		var el = this.element.options[x];
		if(el.value == value)
		{
			returnedOption = el;
			this.setSelectedIndex(x);
		}
	}
	return returnedOption;
}
	
nCore_selectBoxClass.prototype.setSelectedIndex = function(index,fromSelectTag)
{
	//si no tiene opciones no selecciono una goma
	if(!this.element.options.length)
	{
		this.selectBox.div.innerHTML = "";
		return;
	}
		
	if(fromSelectTag == undefined) fromSelectTag = false;
		
	if(!fromSelectTag)
	{
		var SELECT = this.element;
		var opcion = SELECT.options[index];		
		SELECT.selectedIndex = index;
		this.onchange();
	}
	else
	{
		var SELECT = this.element;
		var opcion = SELECT.options[index];
		this.selectBox.div.innerHTML = opcion.text;

		if(((this.relateTo != undefined) && (this.relateTo !== false)) && ($(this.relateTo) != undefined))
		{
			if(this.relateTo.selectBoxClass != undefined) this.relateTo.selectBoxClass.updateFromRelation(this.element.value);
		}
	}
}	
	
nCore_selectBoxClass.prototype.onchange = function(e)
{
	this.setSelectedIndex(this.element.selectedIndex,true);
}

nCore_selectBoxClass.prototype.update = function(index)
{
	if(index == undefined) index = 0;
	this.selectBox.openCombo(true);
	this.setSelectedIndex(index);
}












//clase del DIV del selectBox
var nCore_selectBoxDiv = Class.create();

nCore_selectBoxDiv.prototype.initialize = function(owner)
{
	this.owner = owner;
	//this.div = $div({'class': this.owner.baseClass});
	this.div = $div();
	this.div.addClassName(this.owner.baseClass);
	this.timeOut = 30;
	this.owner.opened = false;
	this.openCombo(true);
}

nCore_selectBoxDiv.prototype.closeCombo = function()
{
	if(!this.owner.opened) return;
	
	if(this.contents) this.contents.remove();
	if(this.updater) this.updater.stop();
	this.div.removeClassName(this.owner.baseClass + "__open");
	this.owner.opened = false;
}

nCore_selectBoxDiv.prototype.openCombo = function(cache)
{
	var SELECT = this.owner.element;
	if(cache == undefined) cache = false;		
	if((this.opened) && (!cache)) return;
		
	if((this.contents == null) || (cache))
	{
		var salida = $div({});
		//var fondo = $div({'class':this.owner.baseClass + "__back"});
		//var lista = $ol({'class':this.owner.baseClass + "__list"});
		var fondo = $div();
		fondo.addClassName(this.owner.baseClass + "__back");
		var lista = $ol();
		lista.addClassName(this.owner.baseClass + "__list");
		
		var x = 0;
		for(x=0;x<SELECT.options.length;x++)
		{
			//var li = $li({'class':this.owner.baseClass + "__listElement"},SELECT.options[x].text);
			var li = $li(SELECT.options[x].text);
			li.addClassName(this.owner.baseClass + "__listElement");
			li.owner = this;
			li.index = x;				
			lista.appendChild(li);
		}
			
		salida.appendChild(lista);
		/*var contraSalida = $div({'class':this.owner.baseClass + "__contents"});
		var contenedor = $div({'class':this.owner.baseClass + "__overAllContents"});
		var scroll = $div({'class':this.owner.baseClass + "__scrollBody"});
		var scrollTrack = $div({'class':this.owner.baseClass + "__scrollTrack"});*/
		
		var contraSalida = $div();
		var contenedor = $div();
		var scroll = $div();
		var scrollTrack = $div();

		contraSalida.addClassName(this.owner.baseClass + "__contents");
		contenedor.addClassName(this.owner.baseClass + "__overAllContents");
		scroll.addClassName(this.owner.baseClass + "__scrollBody");
		scrollTrack.addClassName(this.owner.baseClass + "__scrollTrack");
		
		scroll.appendChild(scrollTrack);
		contenedor.appendChild(scroll);
		contenedor.appendChild(salida);
		contenedor.style.position = "relative";
			
		contraSalida.appendChild(contenedor);
		contraSalida.appendChild(fondo);
	}
	else
	{
		var contraSalida = this.contents;
		var salida = contraSalida.childNodes[0].childNodes[1];
		var lista = salida.childNodes[0];
			
		var contenedor = contraSalida.childNodes[0];
		var scroll = contenedor.childNodes[0];
		var scrollTrack = scroll.childNodes[0];
		var fondo = contraSalida.childNodes[contraSalida.childNodes.length-1];
	}
		
	Element.extend(salida);
	Element.extend(lista);
	Element.extend(contenedor);
	Element.extend(scroll);
	Element.extend(scrollTrack);
		
	this.contents = contraSalida;
		
	if(!cache)
	{
		var body = $$("body")[0];
		var posicionREFF = getAbsolutePosition(this.div);
		contraSalida.style.position = "absolute";
		contraSalida.style.left = posicionREFF[0] + "px";
		contraSalida.style.top = (posicionREFF[1] + posicionREFF[2].height) + "px";
		
		body.appendChild(contraSalida);
		
		//eventos y observadores				
		this.createUpdater();
		contraSalida.observe('mouseout', this.createUpdater.bind(this));
		contraSalida.observe('mouseover', this.resetUpdater.bind(this));
			
		for(x=0;x<lista.childNodes.length;x++)
		{
			var li = lista.childNodes[x];
			li = $(li);
			if(li.observers == undefined)
			{
				li.observe('click',this.elementClick.bind(this));
				li.observe('mouseover',this.elementMouseOver.bind(this));
				li.observe('mouseout',this.elementMouseOut.bind(this));
				li.observers = true;
			}
			
			if(li.hasClassName(this.owner.baseClass + "__listElementSELECTED")) { if(li.index != SELECT.selectedIndex) li.removeClassName(this.owner.baseClass + "__listElementSELECTED"); }				
			else if(li.index == SELECT.selectedIndex) li.addClassName(this.owner.baseClass + "__listElementSELECTED");
			if(li.hasClassName(this.owner.baseClass + "__listElementHover")) li.removeClassName(this.owner.baseClass + "__listElementHover");
		}
		//eval("Event.addBehavior({'li." + this.owner.baseClass + "__listElement' : nCore_selectBoxElement });");
		this.div.removeClassName(this.owner.baseClass + "__hover");
		this.div.addClassName(this.owner.baseClass + "__open");
		
		this.scrollBar = new Control.ScrollBar(lista.identify(),scroll.identify(),{proportional:true});
		if(this.owner.element.options.length)
			if(lista.childNodes[this.owner.element.selectedIndex] != undefined)
				this.scrollBar.scrollTo(lista.childNodes[this.owner.element.selectedIndex],true);
		
		this.owner.opened = true;
	}
}
	
nCore_selectBoxDiv.prototype.resetUpdater = function()
{
	if(this.updater) this.updater.stop();
	this.timeOutLast = 0;
}
	
nCore_selectBoxDiv.prototype.createUpdater = function()
{
	var SELECT = this.owner.element;
	if(this.updater) this.updater.stop();
	this.timeOutLast = 0;
	this.updater = new PeriodicalExecuter(function(pe)
	{			
		this.owner.timeOutLast++;
		if(this.owner.timeOutLast >= this.owner.owner.timeOut)
		{				
			pe.stop();
			this.owner.owner.closeCombo();
		}
	}, 1);
	this.updater.owner = this;
}

nCore_selectBoxDiv.prototype.startObservers = function()
{
	this.div.observe("mouseover",this.onmouseover.bind(this));
	this.div.observe("mouseout",this.onmouseout.bind(this));
	this.div.observe("click",this.onclick.bind(this));
}

nCore_selectBoxDiv.prototype.onmouseover = function(e)
{
	if(this.owner.opened)
	{
		this.resetUpdater();
		return;
	}
		
	var SELECT = this.owner.element;
	this.div.addClassName(this.owner.baseClass + "__hover");
}
	
nCore_selectBoxDiv.prototype.onmouseout = function(e)
{
	if(this.owner.opened)
	{
		this.createUpdater();
		return;
	}
	
	var SELECT = this.owner.element;
	this.div.removeClassName(this.owner.baseClass + "__hover");
}
	
nCore_selectBoxDiv.prototype.onclick = function(e)
{
	if(this.owner.opened)
	{
		this.closeCombo();
	}
	else this.openCombo();
}
	
nCore_selectBoxDiv.prototype.elementClick = function(e)
{
	if(e.element().index != this.owner.element.selectedIndex) this.owner.setSelectedIndex(e.element().index);
	e.element().up().childElements().each(function(element){
			if(element.hasClassName("__listElementSELECTED")) element.removeClassName("__listElementSELECTED");
	});

	this.closeCombo();
	if(this.owner.userOnChange !== false) this.owner.userOnChange();
}
	

nCore_selectBoxDiv.prototype.elementMouseOver = function(e)
{
	e.element().addClassName(this.owner.baseClass + "__listElementHover");
}
	
nCore_selectBoxDiv.prototype.elementMouseOut = function(e)
{
	e.element().removeClassName(this.owner.baseClass + "__listElementHover");
}