var betterSelects = new Class({
	initialize: function(formId){
		this.formularObj = $(formId);
		this.loadSelects();
	},
	loadSelects : function()
	{
		var self = this;
		if (this.formularObj == null) return false;
		this.formularObj.getElements('[class=dropdown]').each(function(single)
		{
			single.firstOption = single.getElement('option');
		    single.selectObj = new htmlSelects(single);
		   	single.addEvent('change', function(){
			   self.changeSelect(single, this);
			   single.selectObj.fireEvent('change');
			});
			single.asyncUpdate = new asyncUpdate(single);
		});
	},
	changeButton: function(button)
	{
		this.formularObj.getElements('[class=dropdown]').each(function(single)
		{
		    single.selectObj.button.setStyle('background', 'url('+button+')');
  		})
	},
	changeSelect: function (select)
	{
	    //console.log(select.get('value'));
		var childEl = select.getProperty('childSelect');
		if (childEl != 'null')
		{
		    childEl = $(childEl);
			//childEl.fireEvent('change');
			childEl.asyncUpdate.update(select.get('value'));
		    this.changeSelect(childEl);
		}
	}
});
var betterSelects2 = new Class({
	initialize: function(formId){
		this.formularObj = $(formId);
		this.loadSelects();
	},
	loadSelects : function()
	{
		var self = this;
		if (this.formularObj == null) return false;
		this.formularObj.getElements('[class=dropdown]').each(function(single)
		{
		//	single.firstOption = single.getElement('option');
		    single.selectObj = new htmlSelects(single);
		});
	},
	changeButton: function(button)
	{
		this.formularObj.getElements('[class=dropdown]').each(function(single)
		{
		    single.selectObj.button.setStyle('background', 'url('+button+')');
  		})
	}
});

var asyncSelects = new Class({
	Implements: [Options,Events],
	options: {filter: null, 'url': '/requests/options.php'},
	initialize: function(formId, options){      
		this.setOptions(options);
		this.formularObj = $(formId);
		this.filter = new Hash();
		if (this.options.filter != null)
		{
			var self = this;
			$each(this.options.filter,function(value, key)
			{
				self.filter.set(key, value);
			});
			/* 
			this.options.filter.each(function(value, key)
			{
				this.filter.set(key, value);
			})
			*/
		}
		this.loadSelects();
	},
	loadSelects : function()
	{
		var self = this;
		var first = false;
		if (this.formularObj == null) return false;
		//this.formularObj.getElements('[class=dropdown]').each(function(single)
		this.formularObj.getElements('select.dropdown').each(function(single)
		{
			if (first == false) first = single;
			if (single.getElement('option') != null) {
				single.firstOption 	= single.getElement('option');
				single.firstValue 	= single.getElement('option').get('text');
			}
			//console.log(single.firstOption);
			//console.log(single.firstValue);
		   	single.addEvent('change', function(){
			   self.changeSelect(single, this);
			});
			
		   	single.addEvent('loading', function(){
				single.setOpacity('0.2');
			});
		   	single.addEvent('update', function(){
				//alert (single.get('value'));
				single.setOpacity('1');
				//alert (single.getProperty('name'));
       			single.fireEvent('change');
			});
			single.updateUrl = self.options.url;
			single.asyncUpdate = new asyncUpdate(single);
		});
		this.loadSelect(first);
	},
	loadSelect: function(select)
 	{
		this.filter.set(select.getProperty('searchtype'), select.get('value'));
		select.asyncUpdate.update(select.get('value'), this.filter);
	},
	changeSelect: function (select)
	{
	    //console.log(select.get('value'));
	    select.getElements('[class=selected]').removeClass('selected');
		select[select.selectedIndex].addClass('selected');
		var childEl = select.getProperty('childSelect');
		//console.log(childEl);
		if (childEl != 'null')
		{
			//alert ('test' + ' - '+childEl+' - '+select.getProperty('name'));
		    childEl = $(childEl);
			//childEl.fireEvent('change');
			this.filter.set(childEl.getProperty('searchtype'),'all');
			this.filter.set(select.getProperty('searchtype'), select.get('value'));
			childEl.asyncUpdate.update(select.get('value'), this.filter);
		    //this.changeSelect(childEl);
		} else {
			this.fireEvent('change', select);	
		}
	}
});

var storeRequests = new Class({
	initialize : function(){
		this.requests = {};
	},
	checkRequest: function (key)
	{
	    if (this.requests[key])
		{
		    //console.log('da'+key);
		    //console.log(this.requests[key]);
			return this.requests[key];
		}
	    else					return false; //console.log('nicht da'+key);
	},
	saveRequest: function(key, data)
	{
		this.requests[key] = data;
	}
});

var storeRequests = new storeRequests();

var asyncUpdate = new Class({
	initialize : function(el){
		this.el = el;
		this.url = el.updateUrl;
		this.filter = {'test':'test1', 'test2':'test2'};
	},
	update: function(value, filter)
	{
		this.filter = filter;
		//alert (this.el.getProperty('name') + ' -- '+value);
	    data = this.getData(value);
		//this.el.getElement('.starter').setProperty('vAlue', value+'_all');
		
		//console.log('update '+this.el.getProperty('name'));
		var childEl = this.el.getProperty('childSelect');
	},
	getData: function(value)
	{
		//console.log (this.filter);
	    var self = this;
		self.el.empty();
		this.el.fireEvent('loading');
		var		            rValue = value;
		if (value == '' || value == 'all') {
			if (this.el.getProperty('searchtype') == 'manufacture') 
				rValue = 'all_all';
			else 
				rValue = 'all';
		}
		var parentSelect = this.el.getProperty('parentSelect');
		var childSelect = this.el.getProperty('childSelect');
		
		var request = {'type': this.el.getProperty('searchtype'), 
		'filter': this.filter,
		'parentSelect': parentSelect,
		'childSelect': childSelect};
		request = $merge(request, this.filter);
		var requestKey = this.el.getProperty('searchtype');
		this.filter.each(function(single){
			requestKey += '_'+single;
		})
		//var requestKey =	this.el.getProperty('searchtype')+'_'+rValue;
		//console.log(requestKey);
		var storeOptions = storeRequests.checkRequest(requestKey);
		if (storeOptions == false)
		{
			var jsonRequest = new Request.JSON({
				async: false,
				url: self.url, //"/requests/options.php",
				onComplete:	function(options)
				{

					storeRequests.saveRequest(requestKey, options);
					self.addOptions(options);
					/*
				   	self.el.firstOption.set('text',self.el.firstValue).inject(self.el);
				    if ($type(options) == 'array')
				    {
						options.each(function (single){
						  var newOption = new Element('option')
						  	.setProperty('value', single.id)
							  .set('text', single.name); //new Option(single.name, single.id, false, true);
		  					self.el.adopt(newOption); ///options[document.Testform.Auswahl.length] = NeuerEintrag;
		  					if (self.el.getProperty('currentValue') == single.id)
		  					{
								newOption.setProperty('selected', 'selected');
								newOption.addClass('selected');
							}

						})
						self.el.fireEvent('update');
					}
					*/
				}
			}).post(request);
		}
		else
		{
			//console.log('schon vorhanden'+requestKey);
			this.addOptions(storeOptions);
		}

	},
	addOptions: function(optionsArray)
	{
	    var self = this;
		if (this.el.firstOption != null)
			this.el.firstOption.set('text',this.el.firstValue).inject(this.el);
		if ($type(optionsArray) == 'array')
		{
			optionsArray.each(function (single){
			    self.addOption(single);
			})
			this.el.fireEvent('update');
		}
	},
	addOption: function(single)
	{
		//alert (single.id + ' ' + this.el.getProperty('currentValue'));
	    var self = this;
        var newOption = new Element('option')
			.setProperty('title', single.name)
			.setProperty('value', single.id)
			.set('text', single.name); //new Option(single.name, single.id, false, true);
		this.el.adopt(newOption); ///options[document.Testform.Auswahl.length] = NeuerEintrag;
		if (this.el.getProperty('currentValue') == single.id)
		{
			newOption.setProperty('selected', 'selected');
			newOption.addClass('selected');
			this.el.setProperty('_currentValue', single.id);
			this.el.removeProperty('currentValue');
		}
	}
	
	
	
})
var htmlSelects = new Class(
{
	Implements:[Events],
	initialize: function(selectObj)
	{
	    var self = this;
		selectObj.firstValue = selectObj.getElement('option').get('text');
		this.selectObj = selectObj;
		this.currentKey 	= selectObj.get('value');
		this.currentValue 	= selectObj.options[selectObj.selectedIndex].text;
		this.createHtml();
		this.addEvent('change', function(){self.isChanged()});
		selectObj.addEvent('update', function(){self.update()});
	},
	createHtml: function()
	{
	    var self = this;
	    var height = 21;
	    var buttonWidth = 29;
	    var borderWidth = 1;
	    var paddingLeft = 4;
	    var paddingTop 	= 4;
	    var wrapperWidth = this.selectObj.getCoordinates().width;
	        wrapperWidth 	= wrapperWidth-(2*borderWidth);
	    var titleWidth 		= (wrapperWidth-buttonWidth);
	        titleWidth 		= titleWidth-(1*borderWidth);
	        titleWidth 		= titleWidth-paddingLeft;
		this.selectObj.setStyle('display', 'block')
		this.selectObj.setStyle('position', 'absolute')
		this.selectObj.setStyle('left', '-99999px');
		var self = this;
		this.optionsWrapper = null;
		this.wrapper = new Element('div').injectAfter(this.selectObj);
		var cleaner = new Element('div').setStyle('clear:both').injectAfter(this.wrapper);
		this.title 	= new Element('p').injectInside(this.wrapper);
		this.button = new Element ('div').injectInside(this.wrapper);
		
		this.wrapper	.setStyle('border', borderWidth+'px solid #c8c8c8')
					.setStyle('margin-bottom', '6px')
					.setStyle('height', '21px')
					.setStyle('border', '1px solid #fff')
					.setStyle('width', wrapperWidth+'px');

		this.title	.setStyle('border-right', borderWidth+'px solid #c8c8c8')
					.setStyle('paddingLeft', paddingLeft)
					.setStyle('background', 'url(/img/buttons/input_bg.gif) no-repeat')
					.setStyle('color', '#aaaaaa')
					.setStyle('float', 'left')
					.setStyle('paddingTop', paddingTop)
					.setStyle('height', (height - paddingTop)+'px')
					.setStyle('width', titleWidth+'px')
					.setStyle('overflow', 'hidden')
					.setStyle('white-space', 'nowrap')
					.addEvent('click', function(e){e.stop();self.open()});

		this.button	.setStyle('width', buttonWidth+'px')
					.setStyle('float', 'left')
					.setStyle('height', '21px')
					.setStyle('background', 'url(/img/buttons/dropDown.gif) no-repeat')
					.addEvent('click', function(e){e.stop();self.open()})
		this.updateTitle();

		   	this.selectObj.addEvent('loading', function(){
				self.wrapper.setOpacity('0.9');
			});
		   	this.selectObj.addEvent('update', function(){
				self.wrapper.setOpacity('1');
			});
	},
	updateTitle :function ()
	{
	    this.title.setProperty('title', this.currentValue);
		this.title.set('text', this.currentValue.substring(0,20));
	},
	open: function()
	{
		if (this.status == 'open') 
		{			
			this.close();
		}			
		else {
			this.status = 'open';
			$$('.options_wrapper').empty();
			this.wrapper.oldBorder = this.wrapper.getStyle('border');
			this.wrapper.setStyle('border', '1px solid #8c8c8c');
			var borderWidth = 1;
			var self = this;
			var options = this.selectObj.getChildren();
			var coordinates = this.wrapper.getCoordinates();
			var optionsWidth = coordinates.width - (2 * borderWidth);
			//if(this.optionsWrapper != null) this.optionsWrapper.destroy();
			this.optionsWrapper = new Element('ul').inject(this.wrapper, 'after');
			this.optionsWrapper.addClass('options_wrapper')
			.setStyle('position', 'absolute')
			.setStyle('display', 'block')
			.setStyle('overflow', 'auto')
			.setStyle('border', borderWidth + 'px solid #ccc')
			.setStyle('top', coordinates.top + coordinates.height)
			.setStyle('left', coordinates.left)
			.setStyle('background', '#ffffff')
			.setStyle('background', '#ffffff')
			.setStyle('width', optionsWidth)
			.setStyle('max-height', '300px')
			.addEvent('mouseleave', function(){
				self.close()
			});
			options.each(function(single){
				var element = new Element('li').set('text', single.get('text'));
				element.setStyle('padding', '4px').setStyle('color', '#333333').setStyle('display', 'block').addEvent('mouseenter', function(){
					element.oldBg = element.getStyle('background');
					element.setStyle('background', '#ccc');
				}).addEvent('mouseleave', function(){
					element.setStyle('background', element.oldBg);
				}).addEvent('click', function(e){
					e.stop();
					self.select(single)
				});
				if (single.selected) 
					element.addClass('selected');
				self.optionsWrapper.adopt(element);
				
			})	
			
			// imitate the maxHeight of the firefox
			if (self.optionsWrapper.getCoordinates().height > '300')
					self.optionsWrapper.setStyle('height', '300px');
		}
	},
	select : function(el)
	{
		//console.log(this.selectObj.get('value') + '  '+el.get('value'));
		if (this.selectObj.get('value') == el.get('value')) return false;
	    //this.selectObj.getChildren().each(function(single){
		for(i=0;i<this.selectObj.length;++i){
		    var single = this.selectObj.options[i];
			//console.log(single.get('value')+' == '+el.get('value'));
			if (single.get('value') == el.get('value'))
			{
				single.selected = 'true';
				single.setProperty('sElecTed', 'selected');
				//console.log(single);
   			}
   			
			else
			{
				single.removeProperty('sElecTed');
				single.selected = false;
				//console.log(single);
			}
			
		};
		//})
		this.selectObj.fireEvent('change');
		this.fireEvent('change');
		this.close();
	},
	close : function()
	{
		this.status = 'close';
	    $$('.options_wrapper').empty();
	    this.wrapper.setStyle('border', this.wrapper.oldBorder);
		this.optionsWrapper.empty();// = 'test';
		this.optionsWrapper.setStyle('display', 'none');// = 'test';
	},
	isChanged: function ()
	{
		this.currentKey 	= this.selectObj.get('value');
		this.currentValue 	= this.selectObj.options[this.selectObj.selectedIndex].text;
		this.updateTitle();
		//console.log(this.selectObj.getEvents('change'));
	},
	update: function ()
	{
		this.currentKey 	= '';
		this.currentValue 	= this.selectObj.firstValue;
		this.updateTitle();
	}
})
