/* ---  Custom Select  ---
	Require prototype.js
*/

var customSelect = Class.create({
	container: null,
	button: null,
	selectedText: null,
	list: null,
	input: null,
	
	initialize: function(container,list,input){
		this.container = $(container);
		this.selectedText = this.container.childElements().first();
		this.button = this.container.childElements().last();
		this.container = container;
		this.list = $(list);
		this.input = $(input);
		
		this.button.observe('click', this.toggleList.bindAsEventListener(this));
		this.selectedText.observe('click', this.toggleList.bindAsEventListener(this));
		
		this.list.childElements().each(function(li){
			if(li.hasClassName('selected')){this.choseElement(this,li);}
			li.observe('click',this.choseElement.bindAsEventListener(this, li));
		},this);
		
		document.observe('click', this.closeListElement.bindAsEventListener(this, this.list));
	},
	

	toggleList: function(e){
	
		/* s'il y a un autre customselect d'ouvert, on le ferme d'abord*/
		$$('.customSelect ul').each(function(ul){
			if(ul.identify() != this.list.identify() && ul.getStyle('display') == 'block'){
				ul.setStyle({
				display:'none'
				});
			}
		},this);
		/*toggle ouvre - ferme */
		if(this.list.getStyle('display') != 'block'){
			this.list.setStyle({
				display:'block'
			});	
		}
		else{
			this.list.setStyle({
				display:'none'
			});
		}
		e.stop();
		
	},
	
	
	choseElement: function(e, li){
		this.list.setStyle({
			display:'none'
		});	
		this.selectedText.innerHTML = li.childElements()[0].innerHTML;
		//alert((this.list.identify().length));
		this.input.value = li.identify().substring((this.list.identify().length)+1, li.identify().length);
	},
	
	closeListElement: function(e, ul){
		
		if(ul.getStyle('display') != 'none' ){
			ul.setStyle({		
				display:'none'
			});
		}
	}
});