/**
* @file elSelect.js
* @author Sergey Korzhov aka elPas0
* @site  http://www.cult-f.net
* @date December 12, 2007
* @extended/rewritten by Thomas Krohn
*
*/
var nichtschliessen=false;
var comefromthek=false;
var dcounter=0;

function zeigeAlphabet(w,maxcount,cc) {
	var alphabet=("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
	var optioncount=1;
	var optionleft=0;
	var start=3;
	var addiere=2;
	var zusdummy=0;
	var spalte=1
	document.nichtschliessen=true
	
	document.comefromthek=true
	for (var i=2;i<1000;i++) {
		if ($('selhide'+i)) {
			if ($('selhide'+i).getProperty('bname')!=w) {
				$('selhide'+i).setStyle('display','none')
			}else{
				$('selhide'+i).setStyle('display','block')
				if ( (document.all)&&((typeof document.body.style.maxHeight == "undefined")) ) { //IE6
			   	$('selhide'+i).setStyle("top",(((optioncount+1)*18)+(start*12)+addiere-2)+"px") //Ie6 eben
 	  			$('selhide'+i).setStyle("left",(optionleft.toInt())+"px")
				}else{
			   	$('selhide'+i).setStyle("top",(optioncount*18)+(start*12)+addiere+"px")
   				$('selhide'+i).setStyle("left",optionleft.toInt()+"px")
   			}
   			if ( optioncount > maxcount-start-zusdummy ) {
    			optioncount=0
    			optionleft+=205
    			start=3
    			zusdummy=1
    			addiere=20
    			spalte++;
    		}else{
    			optioncount++;  //zï¿½hlen
    		}
    	}
		}else{
			if ( optioncount==0 ) {
				optionleft-=205
				spalte--
				maxcount--
			}
			$("selectom"+cc).setStyle('background-color','#f7f7f7')
			if (spalte==1) {
				optioncount--
				if ( (document.all)&&((typeof document.body.style.maxHeight == "undefined")) ) { //IE6
		   		$("selectom"+cc).setStyle("left","5px")
		   		$("selectom"+cc).setStyle("height",(((optioncount)*18)+addiere-19)+"px") //Ie6 eben
	  			$("selectom"+cc).setStyle("width",(optionleft.toInt()+204)+"px")
				}else{
		   		$("selectom"+cc).setStyle("height",((optioncount-1)*18)+addiere+"px")
	  			$("selectom"+cc).setStyle("width",(optionleft.toInt()+204)+"px")
  			}
			} else {
				if ( (document.all)&&((typeof document.body.style.maxHeight == "undefined")) ) { //IE6
		   		$("selectom"+cc).setStyle("background-color","transparent") //Ie6 eben
		   		$("selectom"+cc).setStyle("background-image","url(/fileadmin/templates/images/selalph_bg.gif)") //Ie6 eben
		   		$("selectom"+cc).setStyle("margin-top","50px")
		   		$("selectom"+cc).setStyle("margin-left","5px")
		   		$("selectom"+cc).setStyle("height",(((maxcount-zusdummy)*18)+(start*12)+addiere-19)+"px") //Ie6 eben
	  			$("selectom"+cc).setStyle("width",(optionleft.toInt()+200)+"px")
				}else{
		   		$("selectom"+cc).setStyle("height",((maxcount-start-zusdummy-1)*18)+(start*12)+addiere+"px")
	  			$("selectom"+cc).setStyle("width",(optionleft.toInt()+210)+"px")
  			}
  		}
			return;
		}
	}
}

var elSelect = new Class({
	options: {
		container: false,
		baseClass : 'elSelect',
		selection: false,
		maxoptions: 10000, //krohnadd
		sortiere:false,  //krohnadd zum alphabet
		breite:0  //krohnadded um auf die verscheiendenen breiten einzugehen
	},
	source : false,
	selected : false,
	_select : false,
	current : false,
	ajaxcall : 0,
	catmenucounter : 0,
	selectedOption : false,
	dropDown : false,
	optionsContainer : false,
	hiddenInput : true,
	//krohnadd
	timmieout:1,
	optioncount:-1,
	optioncounter:0,
	startcountd:0,
	optionleft:0,
	sorterID:'',
	erstespalte:true,
	alphabet:'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
	/*
	pass the options,
	create html and inject into container
	*/
	initialize: function(options){
		this.setOptions(options);
		
		if ( !this.options.container ) return;
		
		if(!$(this.options.container))
			return;
		
		this.selected = false;
		this.source = $(this.options.container).getElement('select');
		if ($type(this.source)!='element' ) return;
		
		this.buildFrameWork();
				
		//---------------------------------------------------------------
		if ($(this.source).getElements('option').length > this.options.maxoptions) {  //nicht angegeben dann standard
			this.alphabet='';
			$(this.source).getElements('option').each( this.machalphabet, this ) //krohns Zusatzfunktion zum Alphabeterzeugen
			$(this.source).getElements('option').each( this.addOptionSpalt, this ) //krohns Zusatzfunktion
			
		} else //normal
		//---------------------------------------------------------------
		
		
		
		$(this.source).getElements('option').each( this.addOption, this )

		//$(this.options.container).setHTML('')
		$(this.options.container).set('html','')
		
		this._select.injectInside($(this.options.container))								
		
		this.bindEvents()
		//falls ein sortierer da ist
		if (this.sorterID!='') {
			zeigeAlphabet('A',this.options.maxoptions,this.sorterID)
			document.comefromthek=false  //noch aussschalten
		}
	},
	
	buildFrameWork : function() {
		this._select = new Element('div').addClass( this.options.baseClass )
		this.current = new Element('div').addClass('selected').injectInside($(this._select))
		this.selectedOption = new Element('div').addClass('selectedOption').injectInside($(this.current))
		//added krohn ie6 setzt dropdown falsch ohne das
		dcounter++;
		if ($(this.source)) {
			
			if ( (document.all)&&((typeof document.body.style.maxHeight == "undefined"))&&($(this.source).getElements('option').length > this.options.maxoptions) ) { //spalten dropdown anders platzieren
				
				//alert('test1');
								
				this.dropDown = new Element('div').addClass('dropDown').injectInside($(this.current));
			}
		}
		//added krohn end
		new Element('div').addClass('clear').injectInside($(this._select))
		this.optionsContainer = new Element('div').addClass('optionsContainer').injectInside($(this._select))
		
		var t = new Element('div').addClass('optionsContainerTop').injectInside($(this.optionsContainer));
		var o = new Element('div').injectInside($(t));
		var p = new Element('div').injectInside($(o));
		var t = new Element('div').addClass('optionsContainerBottom').injectInside($(this.optionsContainer));
//ohhh mann
		t.setProperty("id","selectom"+dcounter)
		
		if (!this.options.sortiere) {  //es ist keine Sortierspalte
			//alert('ok');
			if ( $(this.source).getElements('option').length > (this.options.maxoptions+2) ) { //mehr als eine Spalte
				t.setStyle('background-color','#f7f7f7')
				if ( (document.all)&&((typeof document.body.style.maxHeight == "undefined")) ) { //spalten dropdown anders platzieren
					this.dropDown.setStyle('height','0px')
					t.setStyle('top','-16px')
					t.setStyle('margin-left','5px')
					t.setStyle('margin-top','20px')
					t.setStyle('width', ((Math.ceil($(this.source).getElements('option').length/7)*205)-6)+'px');
					//t.setStyle('width',(((Math.round(( ($(this.source).getElements('option').length+2) / this.options.maxoptions)))*205)-6)+'px')
					t.setStyle('height',(((this.options.maxoptions+1)*18)+21)+'px')
				}else{
					t.setStyle('margin-left','4px')
					t.setStyle('margin-top','0px')
					t.setStyle('width', ((Math.ceil($(this.source).getElements('option').length/7)*205)-4)+'px');
					//t.setStyle('width',(((Math.round(( ($(this.source).getElements('option').length) / this.options.maxoptions)))*205)-4)+'px')
					t.setStyle('height',(((this.options.maxoptions+1)*18)+20)+'px')
				}
				t.setStyle('top','0px')
			}else{  //eine Spalte
				t.setStyle('display','none');
			}
		} else if ( (document.all)&&((typeof document.body.style.maxHeight == "undefined")) ) { //spalten dropdown anders platzieren in der sortierliste
			this.dropDown.setStyle('height','0px')
		}

		var o = new Element('div').injectInside($(t))
		var p = new Element('div').injectInside($(o))

//		this.optionsContainer.setStyle('width','600px');  //added krohn
		if ( (document.all)&&((typeof document.body.style.maxHeight == "undefined")) ) { //spalten dropdown anders platzieren
			//alert('test2');
			this.optionsContainer.setStyle('margin-top','-14px');
		}

		this.hiddenInput = new Element('input').setProperties({
			type  : 'hidden',
			name  : this.source.getProperty('name')
		}).injectInside($(this.options.container));
	},
	
	bindEvents : function() {
		document.addEvent('click', function() {		    		  
				if ( this.optionsContainer.getStyle('display') == 'block') 
					this.onDropDown()
			}.bind(this));
			
		$(this.options.container).addEvent( 'click', function(e) { new Event(e).stop(); } )		
		//war this.current.addEvent('click', this.onDropDown.bindWithEvent(this) )
		//krohn add
		if (this.options.breite > 0) {
			this._select.setStyle('width', (this.options.breite+5)+'px' );
			//this.selectedOption.setStyle('width', (this.options.breite-30+5)+'px' ); //fï¿½r den Button
			this.selectedOption.setStyle('width', '85px' ); //fï¿½r den Button
		}
		this._select.addEvent('click', this.onDropDown.bindWithEvent(this) )
		this._select.addEvent('mouseout', this.onSelMouseout.bindWithEvent(this) )
		this._select.addEvent('mouseover', this.onSelMouseover.bindWithEvent(this) )
		/*debug
		this._select.setStyle('border', '1 solid #FF0000' )
		this.selectedOption.setStyle('border', '1 solid #00FF00' )
		*/
	},
	
	//add single option to select
	addOption: function( option ){
		if (!option.text) {return;}  //leere Optionen fï¿½hren im Moz zu Durchsichtigkeit
    var o = new Element('div').addClass('option').setProperty('value',option.value)
	  if ( option.disabled ) { o.addClass('disabled') } else {
			o.addEvents( {
				'click': this.onOptionClick.bindWithEvent(this),
				'mouseout': this.onOptionMouseout.bindWithEvent(this),
				'mouseover': this.onOptionMouseover.bindWithEvent(this)
			})
		}
		
		if ( $defined(option.getProperty('class')) && $chk(option.getProperty('class')) ) 
			o.addClass(option.getProperty('class'))

	
		if ( option.selected ) { 
			if ( this.selected) this.selected.removeClass('selected');
			this.selected = o
			o.addClass('selected')
			//this.selectedOption.setText(option.text);
			this.selectedOption.set('text',option.text);
			this.hiddenInput.setProperty('value',option.value);
		}
		//o.setText(option.text)
		o.set('text',option.text);
		o.injectBefore($(this.optionsContainer).getLast())
	},

	//krohn add single option to select in more Cols
	machalphabet: function( xoption ){
		var c=xoption.text.substr(0,1);
		if (this.alphabet=='' && c!='A') // das ist noch kein alphabet
			return
		if (this.alphabet.indexOf(c)<0) {
			this.alphabet=this.alphabet+c;
		}
	},
	addOptionSpalt: function( option ){
		if (!option.text) {return;}  //leere Optionen fï¿½hren im Moz zu Durchsichtigkeit
    var o = new Element('div').addClass('option').setProperty('value',option.value)
		var inserte='';
		if ( (this.optioncount==-1) ) { //start
			this.optioncount=0;
			if (this.options.sortiere) { // sortieren
				this.startcountd=3;
				var inserte = new Element('div').addClass('alphabetsel').setProperty('value','scriptA')
				if ( (document.all)&&((typeof document.body.style.maxHeight == "undefined")) ) { //dropdown anders platzieren im IE6
					inserte.setStyle("position","absolute") //Ie6 eben
					inserte.setStyle("top","17px") //Ie6 eben
					inserte.setStyle("left","0px") //Ie6 eben
					var ausgabedummy="<table height=50 border=0 cellspacing=0 cellpadding=0 style='width:150px;'><tr style='width:150px;'><td style='width:150px;'>";
				}else{
					var ausgabedummy="<table height=50 border=0 cellspacing=0 cellpadding=0 style='width:200px;'><tr style='width:100px;'><td style='width:200px;'>";
				}
				if (this.alphabet=="")
					this.alphabet=("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
				for(var i=0;i<this.alphabet.length;i++) 
					ausgabedummy+="<span onclick=\"zeigeAlphabet('"+this.alphabet.substr(i,1)+"',"+this.options.maxoptions+",'"+dcounter+"');\">&nbsp;"+this.alphabet.substr(i,1)+"&nbsp;</span> ";
				ausgabedummy+="</td></tr></table>";
				//inserte.setHTML(ausgabedummy)
				inserte.set('html',ausgabedummy)
			}else{
				this.startcountd=0;
			}
		}
		if (this.options.sortiere) { // sortieren
			this.sorterID=dcounter   //fï¿½r spï¿½ter um zu sortieren
			if (this.erstespalte)
				var topplus=(this.startcountd*12)+2
			else
				var topplus=(this.startcountd*12)+20				
		} else {
			var topplus=3
		}


		if ( (document.all)&&((typeof document.body.style.maxHeight == "undefined")) ) { //dropdown anders platzieren im IE6
	   	o.setStyle("top",(((this.optioncount+1)*18)+topplus-2)+"px") //Ie6 eben
   		o.setStyle("left",(this.optionleft.toInt())+"px")
		}else{
	   	o.setStyle("top",(this.optioncount*18)+topplus+"px")
   		o.setStyle("left",this.optionleft.toInt()+"px")
		}
   	o.setStyle("position","absolute")

    if ( this.optioncount > this.options.maxoptions-this.startcountd ) {
    	this.optioncount=0;
    	this.optionleft+=205;
    	if (this.options.sortiere)
    		this.startcountd=3;
    	this.optioncounter++;
    	this.erstespalte=false
    }else{
    	this.optioncount++;  //zï¿½hlen
    	this.optioncounter++;
    }
		if (option.disabled) { o.addClass('disabled') } else {
			o.addEvents( {
				'click': this.onOptionClick.bindWithEvent(this),
				'mouseout': this.onOptionMouseout.bindWithEvent(this),
				'mouseover': this.onOptionMouseover.bindWithEvent(this)
			})
		}
		
		if ( $defined(option.getProperty('class')) && $chk(option.getProperty('class')) ) 
			o.addClass(option.getProperty('class'))

	
		if ( option.selected ) { 
			if ( this.selected) this.selected.removeClass('selected');
			this.selected = o
			o.addClass('selected')
			//this.selectedOption.setText(option.text);
			this.selectedOption.set('text',option.text);
			this.hiddenInput.setProperty('value',option.value);
		}
		if ( (option.text.substr(0,1)=='A')||(!this.options.sortiere) ) {
			o.setStyle("display","block")
			lastox=o.getStyle("left")
			lastoy=o.getStyle("top")
		}else{
			o.setStyle("display","none")
		}
		if (this.options.sortiere) {
			o.setProperty('id','selhide'+this.optioncounter)
			o.setProperty('bname',option.text.substr(0,1))
		}
		//o.setText(option.text)
		o.set('text',option.text);
		if (inserte!='') {
			inserte.injectBefore($(this.optionsContainer).getLast())
		}
		o.injectBefore($(this.optionsContainer).getLast())
	},
	
	onDropDown : function( e ) {				    
			//krohn add browserschot
			window.clearTimeout(this.timmieout);
			this.timmieout=false;
			if (document.comefromthek) {
				document.comefromthek=false
				return
			}
			var isIE=(document.all)?true:false;
			var isOP=(window.opera)?true:false;
			var isNS4=(document.layers)?true:false;
			if (isIE)
				if (typeof document.body.style.maxHeight != "undefined") {
				  var isIE6=false;
				} else {
				  var isIE6=true;
			}			
			//krohn add browserschot end
			if ( this.optionsContainer.getStyle('display') == 'block') {
				//krohn klein machen
				this.optionsContainer.setStyle('display','none')
			} else {				
				//krohn gross machen
				if (document.lastopened) {document.lastopened.setStyle('display','none');document.lastopened=null;}
				document.lastopened=this.optionsContainer;
				this.optionsContainer.setStyle('padding-top','2px')  //klitzekleine anpassung fï¿½r aussehen  
				this.optionsContainer.setStyle('display','block')
			
				this.selected.addClass('selected')
				//needed to fix min-width in ie6
				var width =  this.optionsContainer.getStyle('width').toInt() > this._select.getStyle('width').toInt() ?
															this.optionsContainer.getStyle('width')
															:
															this._select.getStyle('width')														
															
				this.optionsContainer.setStyle('width', width)
				this.optionsContainer.getFirst().setStyle('width', width)
				this.optionsContainer.getLast().setStyle('width', width)
			}
	},
	onOptionClick : function(e) {
		var event = new Event(e)
		if ( this.selected != event.target ) {
			if ($('diverror' + this.hiddenInput.getProperty('name'))) {
				$('diverror' + this.hiddenInput.getProperty('name')).setStyle('display', 'none');
				this._select.setStyle('background-image', 'url(fileadmin/templates/images/nav/news/select-bg.gif)');
			}
			
			this.selected.removeClass('selected')
			event.target.addClass('selected')
			this.selected = event.target
			this.selectedOption.set('text',this.selected.get('text'));
			this.hiddenInput.setProperty('value',this.selected.getProperty('value'));												
			
    //fill hidden field with value of selected option        
    $(this.options.selection).value = this.selected.getProperty('value');                
    
    // TGA: ï¿½nderung, damit der Supplier-Selektor der Produktlistenansicht funktioniert    
    switch (this.options.ajaxcall){
      // Produkt-Liste + Fallback - Produktmatrix
    	case 1:	
    		xajax_displayRecordsBySupplier($(this.options.selection).value);
    		break;
    	// Fallback - Produktmatrix
    	// Auswahl Category/Market
    	case 9:
    		xajax_displayRecordsByCategoryOrMarket($('selection').value, $('selection-2').value);
    		break;
    	// Auswahl Supplier
    	case 10:	
    		xajax_displayRecordsBySupplier($('selection').value, $('selection-2').value);
    		break;
    	// News
    	case 2:
    		tx_ttnewsxajax_displayNewsByCatM($('selectioncategory').value,$('selectionsupplier').value);
    		break;
    	// News
    	case 3:
    		tx_ttnewsxajax_displayNewsBySupplier($('selectioncategory').value, $('selectionsupplier').value);
    		break;
    	// News
    	case 4:
    		tx_ttnewsxajax_displayNewsByCategory($(this.options.selection).value, $(this.options.catmenucounter).value);
    		break;
    	// Events
    	case 7:    
    	  tx_bgmevent_pi1xajax_refreshSelBoxen($(this.options.selection).id,$('sel_supp').value,$('sel_region').value,$('sel_market').value);
    		tx_bgmevent_pi1xajax_filterResult($('sel_supp').value, $('sel_region').value,$('sel_market').value);
    		break;	
    	// Formulare
    	case 8:    		
    		tx_ebvregistration_pi1xajax_setLocations($('tx_ebvregistration_pi1[nearest_country_input]').value);
    		break;
    	// Locations Fallback    	
      case 11:                        
        if ($('group1').checked)
          checkbox = $('group1');       
        else
          checkbox = $('group2');                                                                         
          
        tx_bgmxmlcontacts_pi1xajax_setLocations($('selection-2').value, checkbox.value);        
        break;
       // Formulare
      case 12:    		
    	tx_ebvregistration_pi1xajax_setCountry($('tx_ebvregistration_pi1[location_input]').value);
    	break;
      case 13:
    	  loadContent($(this.options.selection).value);
    	  break;
      default:    	
    }        	    
    
    // TGA: Aenderung, damit der Kategorien-Select funktioniert, da auf onChange nicht reagiert wird    
    if ($(this.options.selection).value.indexOf('html', 0) > 0 || $(this.options.selection).value.indexOf('php', 0) > 0)
    	window.open($(this.options.selection).value,'_parent');
		}
		//krohn delete war this.onDropDown()
		this.timmieout=setTimeout( function() { if (document.lastopened) {document.lastopened.setStyle('display','none');document.lastopened=null;} }, 200 ); //krohnadded weil ja hier nur zumachen
		window.clearTimeout(this.timmieout);		
		this.timmieout=false;
		document.nichtschliessen=true;
	},
	onOptionMouseover : function(e){
		var event = new Event(e)
		this.selected.removeClass('selected')
		event.target.addClass('selected')
		window.clearTimeout(this.timmieout);
		this.timmieout=false;
		document.nichtschliessen=true;
	},
	onOptionMouseout : function(e){
		var event = new Event(e)
		event.target.removeClass('selected')
	},
	//Krohn add
	onSelMouseout : function(e){
		var event = new Event(e)
		window.clearTimeout(this.timmieout);
		this.timmieout=false;
		document.nichtschliessen=false;
		this.timmieout=setTimeout( function() { 
			if ( (document.lastopened)&&(!document.nichtschliessen) ) {document.lastopened.setStyle('display','none');document.lastopened=null;} 
			}, 3000 );
	},
	onSelMouseover : function(e){
		var event = new Event(e)
		window.clearTimeout(this.timmieout);
		this.timmieout=false;
		document.nichtschliessen=true;
	}
	
});
elSelect.implement(new Events);
elSelect.implement(new Options);

