function setSliderTexts(pos,elementName,extendStr)
{
    if(document.getElementById('slider_minmax_min_' + elementName).tagName.toUpperCase() != 'INPUT')
	$('slider_minmax_min_' + elementName).set('html', pos.minpos + extendStr);
    if(document.getElementById('slider_minmax_max_' + elementName).tagName.toUpperCase() != 'INPUT')
	$('slider_minmax_max_' + elementName).set('html', pos.maxpos + extendStr);
	document.getElementsByName(elementName+'[min]')[0].value=pos.minpos;
	document.getElementsByName(elementName+'[max]')[0].value=pos.maxpos;	
}

function setSliderTextsFloor(pos, elementName) {
 
 	html = '';
 	
 	if(pos.minpos == pos.maxpos) {
 		if(pos.minpos == 0)
			html += 'nur Erdgeschoss';
		else if(pos.minpos == 5)
			html += 'ab 5. Etage';
 		else
		 	html += 'nur ' +pos.minpos + '. Etage';
 	}else{
		if(pos.minpos == 0)
			htmlmin = 'Erdgeschoss'
		else
			htmlmin = pos.minpos + '. Etage';
			
		html = htmlmin + ' bis ' + pos.maxpos + '. Etage';
		
		if(pos.maxpos == 5)
			html = 'ab ' + htmlmin;
	}
	
	$('slider_minmax_max_' + elementName).set('html', html);
	
	for(a=0;a<=5;a++) {
	 	ele=document.getElementsByName(elementName+'['+a+']')[0];
	 	if(ele.checked != (a>=pos.minpos && a<=pos.maxpos))
	 		ele.checked = !ele.checked;
			ele.fireEvent('change');
	}
	
	document.getElementsByName(elementName+'[min]')[0].value=pos.minpos;
	document.getElementsByName(elementName+'[max]')[0].value=pos.maxpos;	
}

/*
Class: Slider
        Creates a slider with two elements: a knob and a container. Returns the values.
Note:
        The Slider requires an XHTML doctype.
Arguments:
        element - the knob container
        knob - the handle
        options - see Options below
        maxknob - an optional maximum slider handle
Options:
		start - the minimum value for your slider.
		end - the maximum value for your slider.
        mode - either 'horizontal' or 'vertical'. defaults to horizontal.
        offset - relative offset for knob position. default to 0.
        knobheight - positions the max slider knob
		snap - whether the slider will slide in steps 
		numsteps - number of slide steps 
Events:
        onChange - a function to fire when the value changes.
        onComplete - a function to fire when you're done dragging.
        onTick - optionally, you can alter the onTick behavior, for example displaying an effect of the knob moving to the desired position.
                Passes as parameter the new position.
*/

// Set the visible texts for the current slidebar values and puts the values
// into the hidden fields for posting the data to the result page


var ImmoSlider = new Class({
	options: {
		onChange: Class.empty,
		onComplete: Class.empty,
		onTick: function(pos){
			this.moveKnob.setStyle(this.p, pos);			
		},
		start: 0,
		end: 100,
		offset: 0,
		knobheight: 23,
		knobwidth: 13,
		mode: 'horizontal',
		clip_w:0, 
		clip_l:0,
		isinit:true,
		snap: false,
		range: false,
		numsteps:null,
        i_step:0
	},
    initialize: function(el, knob,bkg, options, maxknob) {
		this.setOptions(options);
		this.element = $(el);
		this.knob = $(knob);
		this.previousChange = this.previousEnd = this.step = -1;
		this.bkg = $(bkg);
		if(this.options.steps==null){
			this.options.steps = this.options.end - this.options.start;
		}
        
		if(maxknob!=null)
			this.maxknob = $(maxknob);

		var mod, offset;
		switch(this.options.mode){
			case 'horizontal':
				this.z = 'x';
				this.p = 'left';
				mod = {'x': 'left', 'y': false};
				offset = 'offsetWidth';
				break;
			case 'vertical':
				this.z = 'y';
				this.p = 'top';
				mod = {'x': false, 'y': 'top'};
				offset = 'offsetHeight';
		}
		this.max = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
		this.half = this.knob[offset]/2;
		this.full = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
		this.min = $chk(this.options.range[0]) ? this.options.range[0] : 0;
		this.getPos = this.element['get' + this.p.capitalize()].bind(this.element);
		this.knob.setStyle('position', 'relative').setStyle(this.p, - this.options.offset);

		this.range = this.max - this.min;
		this.steps = this.options.steps || this.full;
		this.stepSize = Math.abs(this.range) / this.steps;
		this.stepWidth = this.stepSize * this.full / Math.abs(this.range) ;
		
//alert('StepSize: '+this.stepSize + "; StepWidth: " + this.stepWidth + "; range: "+this.range+"; steps: "+this.steps);
		if(maxknob != null) {
			this.maxPreviousChange = -1;
			this.maxPreviousEnd = -1;
			this.maxstep = this.options.end;
			this.maxknob.setStyle('position', 'relative').setStyle(this.p, + this.max - this.options.offset).setStyle('bottom', this.options.knobheight);
		}
		var lim = {};
		//status = this.z
		lim[this.z] = [- this.options.offset, this.max - this.options.offset];
		//lim[this.z] = [100, this.max - this.options.offset];

		this.drag = new Drag(this.knob, {
			limit: lim,
			modifiers: mod,
			snap: 0,
			onStart: function(){
					this.draggedKnob();
			}.bind(this),
			onDrag: function(){
					this.draggedKnob();
			}.bind(this),
			onComplete: function(){
					this.draggedKnob();
					this.end();
			}.bind(this)
		});
		if(maxknob != null) {  
			this.maxdrag = new Drag(this.maxknob, {
				limit: lim,
				modifiers: mod,
				snap: 0, 
				onStart: function(){
					this.draggedKnob(1);
				}.bind(this),
				onDrag: function(){
					this.draggedKnob(1);
				}.bind(this),
				onComplete: function(){
					this.draggedKnob(1);
					this.end();
				}.bind(this)
			});		
		}

		if (this.options.snap) {
			//this.drag.options.grid = Math.ceil(this.stepWidth);
			this.drag.options.grid = (this.full)/this.options.numsteps ;
			this.drag.options.limit[this.z][1] = this.full;
			//this.drag.options.grid = this.drag.options.grid - (this.knob[offset]/this.options.numsteps);
			status = "GRID - " + this.drag.options.grid  + "  , full = " + this.full// DEBUG

		}
		if (this.options.initialize) this.options.initialize.call(this);
    },
	setMin: function(stepMin){
		this.step = stepMin.limit(this.options.start, this.options.end);                
		this.checkStep();
		this.end();
		this.moveKnob = this.knob;
		this.bkg.style.clip = "rect(0px "+  (parseInt(this.toPosition(this.step)) +3) + "px 10px 0px)";
		status =this.bkg.style.clip + "  vl= " + parseInt(this.toPosition(this.step)) ; //Debug
		this.fireEvent('onTick', this.toPosition(this.step));
		return this;
	},
	setMax: function(stepMax){
		this.maxstep = stepMax.limit(this.options.start, this.options.end);
		this.checkStep(1);
		this.end();
		this.moveKnob = this.maxknob;
		var w= Math.abs(this.toPosition(this.step)- this.toPosition(this.maxstep)) + 3 ;
		var r = parseInt(this.clip_l + w); 
		this.bkg.style.clip = "rect(0px "+  r + "px 10px "+ this.clip_l + "px)";

		this.fireEvent('onTick', this.toPosition(this.maxstep));
		// For Init Only 
		if(this.options.isinit){
			var lim = {}; var mi,mx;
			mi = - this.options.offset; 
			mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset-4 ;
			lim[this.z] = [mi, mx];
			this.drag.options.limit = lim;
			this.options.isinit = false;
		}
		return this; 
	},
	clickedElement: function(event){
		var position = event.page[this.z] - this.getPos() - this.half;
		position = position.limit(-this.options.offset, this.max -this.options.offset);

		this.step = this.toStep(position);

		//this.moveKnob = this.knob;
		this.bkg.style.clip = "rect(0px "+  (parseInt(this.toPosition(this.step)) +3) + "px 10px 0px)"  
		//status =this.bkg.style.clip; //Debug
		this.checkStep();
		this.end();
		this.fireEvent('onTick', position);
	},

	draggedKnob: function(mx){
		var lim = {}; var mi,mx;
		if(mx==null) {
			this.step = this.toStep(this.drag.value.now[this.z]);
			this.checkStep();
		}else {
			this.maxstep = this.toStep(this.maxdrag.value.now[this.z]); 
			this.checkStep(1);
		}
	},
	checkStep: function(mx){
		var lim = {}; var mi,mx;
		var limm = {};
		if(mx==null) {if (this.previousChange != this.step){this.previousChange = this.step;}}
		else {if (this.maxPreviousChange != this.maxstep){this.maxPreviousChange = this.maxstep;}}

		if(this.maxknob!=null) {

			mi = - this.options.offset; 
			mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset-4 ;
			//mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset ;
			lim[this.z] = [mi, mx];
			this.drag.options.limit = lim;
		

			mi = parseInt(this.knob.getStyle('left'))-this.options.offset+22; 
			//mi = parseInt(this.knob.getStyle('left'))-this.options.offset; 
			
			mx= this.max - this.options.offset;
			limm[this.z] = [mi, mx];
			this.maxdrag.options.limit = limm; 

			if(this.step < this.maxstep){
				this.fireEvent('onChange', { minpos: this.step, maxpos: this.maxstep });
				//this.clip_l = parseInt(this.knob.getStyle('left'));
			}
			else{
				this.fireEvent('onChange', { minpos: this.maxstep, maxpos: this.step });
				//this.clip_l = (parseInt(this.maxknob.getStyle('left')) + 10) ;
			}	
			this.clip_l = parseInt(this.knob.getStyle('left')) + 10;
			//var w = Math.abs(parseInt(this.knob.getStyle('left')) - parseInt(this.maxknob.getStyle('left'))) + 3;	
			var w = Math.abs(parseInt(this.knob.getStyle('left')) - parseInt(this.maxknob.getStyle('left')));
			//if(w > 3) w = w+3;
			
			var r = parseInt(this.clip_l + w); 
			this.bkg.style.clip = "rect(0px "+  r + "px 10px "+ this.clip_l + "px)"  
			//status =this.bkg.style.clip  + " w= " + w //Debug
		}else {  
			this.fireEvent('onChange', this.step);
			this.bkg.style.clip = "rect(0px "+  (parseInt(this.drag.value.now[this.z]) +3)  + "px 10px 0px)"  
		}
	},
	end: function(){
		if (this.previousEnd !== this.step || (this.maxknob != null && this.maxPreviousEnd != this.maxstep)) {
			this.previousEnd = this.step;
			if(this.maxknob != null) {
				this.maxPreviousEnd = this.maxstep;
				if(this.step < this.maxstep)
					this.fireEvent('onComplete', { minpos: this.step + '', maxpos: this.maxstep + '' });
				else    
					this.fireEvent('onComplete', { minpos: this.maxstep + '', maxpos: this.step + '' });
			}else{  
				this.fireEvent('onComplete', this.step + '');
			}
		}
	},
	
	toStep: function(position){
        erg = Math.round((position + this.options.offset) / this.max * this.options.steps) + this.options.start;
        
        if(this.options.i_step > 0) {
            c = (erg - this.options.start) / this.options.i_step;
            erg = Math.round(c) * this.options.i_step + this.options.start;
        }

		return erg;
	},

	toPosition: function(step){
		return (this.max * step / this.options.steps) - (this.max * this.options.start / this.options.steps) - this.options.offset;
	}

});

ImmoSlider.implement(new Events);
ImmoSlider.implement(new Options);


// Changes the display of the city-list
var cityListViewEnabled=true;
function toggleCityView() {
	cityListViewEnabled=(cityListViewEnabled) ? false : true;	
	$("cityList").setStyles({'display' : (cityListViewEnabled?'':'none')});		
	$("immosearch_citybtn").setStyles({'background-image' : 'url(fileadmin/templates/images/immosearch_city_btn' + (cityListViewEnabled ? '_on.png' : '.png') + ')'});
}

function getSliderValsFromInputs(sliderOb, valName) {
        var min = document.getElementsByName(valName + '[min]')[0].value * 1;
	var max = document.getElementsByName(valName + '[max]')[0].value * 1;

        if(min > max)
            max = min;               

	sliderOb.setMin(min).setMax(max);
	$('hiddenfields_' + valName).setStyle('display', 'none');
}

// Change the sliders for rentIB oder purchasePrice when changing the option-value of the searchType-select
function toggleSearchType() {
	val=$('searchtype').getElements('option').filter(function(o){ return o.selected==true;});
	value=val[0].getAttribute('value');
	$('sliderdiv_rentIB').setStyle('display', (value != 1 ? '' : 'none'));
	$('sliderdiv_purchasePrice').setStyle('display', (value != 1 ? 'none' : ''));
}

function allDistrictChecked(checkboxes) {
    
    var x = 0;
    var unchecked = 0;
    checkboxes.each(function(e) {
	 	if(x > 0) {
            unchecked += (e.checked ? 0 : 1);		 	    
 	    }
        x++;
    });
    
    return (unchecked == 0);
}

	// ON LOAD
    var myCfe = {};
    var mySlideA;
    var mySlideB;
    var mySlideC;
    var mySlideD;
    var mySlideE;

	window.addEvent('domready', function() {
		
	 	/* path to a 1x1 pixel transparent gif */ 
		cfe.spacer = "fileadmin/media/js/cfe/gfx/spacer.gif"; 
		/* create a cfe replacement instance */ 
		myCfe = new cfe.replace();
		/* now you may set options [see cfe.autostart.sample for details] */
		/* initialize cfe */ 
		myCfe.init(); 

		$('cityList').setStyle('position','absolute');

		// The checkbox-events
		var i=0;
		var checkboxes = $('cityList').getElements('input').filter(function(o){return o.type=="checkbox";});

		checkboxes.each(function(e) {
		 	if(i > 0) {
			 	e.addEvent('click', function(x) {
			 	   
					if(this.checked == false) {				 	
						checkboxes[0].retrieve("cfe").uncheck();      // deselect the all-urban-districts - choice
                        
					}else if(allDistrictChecked(checkboxes)) {

                        // loop over all checkboxes
                        checkboxes.each(function(d) {
                          d.retrieve("cfe").uncheck();    // uncheck the cfe-urbandistrict-element
                          d.checked = false;              // uncheck the urbandistrcit-element
                        });

                        checkboxes[0].retrieve("cfe").check();
                        checkboxes[0].checked = true;
                        
					}else if(this.checked == true) {
                        checkboxes[0].retrieve("cfe").uncheck();
                        checkboxes[0].checked = false;					   
					}
				});
			}else{			 
                // add selectAll/deselectAll functionality to links
                e.addEvent("click", function(x)
                {                
                    mode=e.checked;             // store the current check-status to check the dependend urban-district-checkboxes
                    e.checked = true;           // check the element again to keep functionality

                    // loop over all checkboxes (except the first)
                    var t = 0;
                    checkboxes.each(function(d,mode) {
                       if(mode && t>0) {
                            d.retrieve("cfe").uncheck();     // uncheck the cfe-urbandistrict-element
                            d.checked = false;               // uncheck the urbandistrcit-element
                       } 
                       t++;
                    });    
                }.bind(myCfe));   
                
                if(e.checked)
                    e.fireEvent('click');                 
			}
			i++;
		});	
		
		mySlideA = new ImmoSlider($('slider_minmax_gutter_m'), $('slider_minmax_minKnobA'),$('slider_bkg_img'), {
			start: 1,
			end: 5,
			offset:5,
			onChange: function(pos)
			{
				setSliderTexts(pos,'rooms','');
			}
                        
		}, $('slider_minmax_maxKnobA'));
	
		getSliderValsFromInputs(mySlideA, 'rooms');
	
		mySlideB = new ImmoSlider($('slider_minmax_gutter_m'), $('slider_minmax_minKnobB'),$('slider_bkg_img'), {
			start: 15,
			end: 140,
			offset: 5,
            i_step:5,
			onChange: function(pos)
			{
				setSliderTexts(pos,'livingArea','m<sup>2</sup>');
			}
		}, $('slider_minmax_maxKnobB'));
		
		getSliderValsFromInputs(mySlideB, 'livingArea');
	
		mySlideC = new ImmoSlider($('slider_minmax_gutter_m'), $('slider_minmax_minKnobC'),$('slider_bkg_img'), {
			start: 150,
			end: 950,
			offset:5,
            i_step:20,
			onChange: function(pos)
			{
				setSliderTexts(pos,'rentIB',' &euro;');
			}
		}, $('slider_minmax_maxKnobC'));
	
		getSliderValsFromInputs(mySlideC, 'rentIB');	

		if($('floorboxes')) {
		 	$('floorboxes').setStyle('display','none');
			mySlideD = new ImmoSlider($('slider_minmax_gutter_m'), $('slider_minmax_minKnobD'),$('slider_bkg_img'), {
				start: 0,
				end: 5,
				offset:5,
				onChange: function(pos)
				{
					setSliderTextsFloor(pos,'floors');
				}
			}, $('slider_minmax_maxKnobD'));
		
			getSliderValsFromInputs(mySlideD, 'floors');	
		}

		mySlideE = new ImmoSlider($('slider_minmax_gutter_m'), $('slider_minmax_minKnobE'),$('slider_bkg_img'), {
			start: 20000,
			end: 60000,
			offset:5,
            i_step:250,
			onChange: function(pos)
			{
				setSliderTexts(pos,'purchasePrice',' &euro;');
			}
		}, $('slider_minmax_maxKnobE'));
	
		getSliderValsFromInputs(mySlideE, 'purchasePrice');			


        // toggle between the options buy/rent flat / business flat
		$('searchtype').addEvent('change', function() {
			toggleSearchType();
		});
		toggleSearchType();
	}); 
