//Event.observe(document, "dom:loaded", function (event) {
//	$$('.main-menu > li.products > a').each(function (element) {
//		element.observe('mouseover', function(event) {
//			$$('.header-foldout').each(function(item) { 
//				item.toggle();
//			});
//		});
//		element.observe('mouseout', function(event) {
//			$$('.header-foldout').each(function(item) { 
//				item.toggle();
//			});
//		});
//	});
//});


Prototype.Browser = {
	IE:     !!(window.attachEvent && !window.opera),
	Opera:  !!window.opera,
	WebKit: document.childNodes && !document.all && !navigator.taintEnabled,
	Gecko:  (document.getBoxObjectFor != null),
	MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
};

Object.extend(Prototype.Browser, {
     WebKit419: Prototype.Browser.WebKit && (Prototype.BrowserFeatures.XPath),
     WebKit420: Prototype.Browser.WebKit && (!Prototype.BrowserFeatures.XPath),
     IE6:      Prototype.Browser.IE && (typeof window.XMLHttpRequest == "undefined"),
     IE7:      Prototype.Browser.IE && (typeof window.XMLHttpRequest == "object") && (parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7),
     IE8:	   Prototype.Browser.IE && (typeof window.XMLHttpRequest == "object") && ! (parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7)
});

/*
(function() {
  var arrayProto = Array.prototype,
  
  function inArray(item) {
    var length = this.length;
    for (i=0; i < length; i++) {
      if (this[i] == item) return true;
    }
    return false;
  }
  
  Object.extend(arrayProto, {
	  inArray: inArray
  });
})();*/

var ImageSlide = Class.create({
	
	//currently active item, count from 0
	items: [],
	currentItem: 0,
	navigation: [],
	pe: false,
	inProgress: false,
	autoplay: false,
	
	/**
	 * Initialize class
	 *
	 * @container: html-parent-container, usually with class fce-imageslide
	 */
	initialize: function(container) {
		this.container  = container;
		this.height = 0;
		this.items = this.container.select('ul.images>li');
		this.itemCount = this.items.size();
		
		if(this.container.hasClassName('autoplay') || this.container.hasClassName('imageslider-simple')) {
			this.autoplay = true;
		}
		
		this.items.each(function (item, index) {
			imgTag = item.select('img').first();
			//preload all images
			preloadImage = new Image();
			preloadImage.src = imgTag.readAttribute('src');
			
			//search for image with greatest height
			if (Prototype.Browser.IE) {
				regExp = new RegExp(/\<img.*height[^\d]+(\d+)/i);
				match = regExp.exec(item.innerHTML);
				tempHeight = match[1];
			} else {
				tempHeight = imgTag.readAttribute('height');
			}
			this.height = (tempHeight > this.height) ? tempHeight : this.height;
			
			//display first image
			if (index == this.currentItem) {
				item.show();
			}
		}.bind(this));
		//FG, this is a hotfix, please change 
		if (this.container.hasClassName('imageslider')) {
			this.container.setStyle({height: this.height + 'px'});
		}

		if (this.itemCount > 1) {
			this.navigation = this.container.select('ul.navigation>li');
			this.navigation.each(function (item, index) {
				item.observe('click', function(event) {
					elementClicked = event.element().tagName.toLowerCase() == 'li' ? event.element() : event.element().up('li');
					this.currentItem = this.navigation.indexOf(elementClicked);
					if(this.autoplay) {
						this.pe.stop();
					}
					this.showItem(this.currentItem);
				}.bindAsEventListener(this));
			}.bind(this));
			
			//startPeriodicalExecuter
			if(this.autoplay) {
				this.pe = new PeriodicalExecuter(function(pe) {
					this.nextItem();
				}.bind(this), 5);
			}
		}
	},
	
	nextItem: function () {
		this.items[this.currentItem].fade();
		this.currentItem = (this.currentItem + 1) % this.itemCount;
		this.items[this.currentItem].appear();
		
		if (this.navigation.size() > 0) {
			this.navigation.invoke('removeClassName', 'act');
			this.navigation[this.currentItem].addClassName('act');
		}
	},
	
	showItem: function (itemPos) {
		inProgress = false; 
		this.items.each(function (item) {
			if (item.inProgress) {
				inProgress = true;
			}
		});
		
		if (! inProgress) {
			this.items.each(function (item, index) {
				item.inProgress = true;
				if (index == itemPos) {
					item.appear({
						afterFinish: function() {
							item.inProgress = false;
						}.bind(item)
					});
				} else {
					item.fade({
						afterFinish: function() {
							item.inProgress = false;
						}.bind(item)
					});
				}
			}.bind(this));			
			if (this.navigation.size() > 0) {
				this.navigation.invoke('removeClassName', 'act');
				this.navigation[itemPos].addClassName('act');
			}
		}
	}
});
var SliderBox = Class.create({
	size: 5,
	inaction: false,
	
	slide: function (move, position) {
		if (!this._contentToScroll_prev() && move > 0 ) {
			move = 0;
		} else if (!this._contentToScroll_next() && move < 0) {
			move = 0;
		}

		new Effect.Morph(this.container.down('.slider'), {
			style: 'left: '+(parseInt(this.container.down('.slider').getStyle('left'))+move)+'px',
			duration: 0.5,
			afterFinish: function () {
				this.verticalSlider.setValue(position);
				this.setTriggerVisibility();
				this.inaction = false;
			}.bind(this)
		});
	},
	
	scrollerSlide: function (value) {
		this.container.select('.slider').first().setStyle({ left: ((value*this.itemWidth)*-1)+'px'});
		this.setTriggerVisibility();
	},
	
	_setPosLeft: function(posLeft) {
		this.boxPosLeft = posLeft;
		this.container.select('.slider').first().setStyle({
			left: posLeft + 'px'
		});
	},
	
	_getPosLeft : function () {
		this.boxPosLeft = this.container.select('.slider').first().getStyle('left').replace('px','');
		return this.boxPosLeft; 
	},
	
	_contentToScroll_prev: function (pos) {
		if (! Object.isNumber(pos)) {
			pos = this._getPosLeft();
		}
		
		if (pos >= 0) {
			return false;
		} 
		return true;
	},
	
	_contentToScroll_next: function (pos) {
		if (! Object.isNumber(pos)) {
			pos = this._getPosLeft();
		}
		
		//calculate with of inner items minus width of container
		var width = 0-(this.sliderWidth-this.container.getWidth());
		if ((pos - this.itemWidth) < width) {
			return false;
		}
		return true;
	},
	
	setTriggerVisibility : function () {

		//prev trigger
		if (this._contentToScroll_prev()) {
			this.triggerPrev.up().removeClassName('disabled disabled-prev');
		} else {
			this.triggerPrev.up().addClassName('disabled disabled-prev');
		}
		
		// next trigger
		if (this._contentToScroll_next()) {
			this.triggerNext.up().removeClassName('disabled disabled-next');
		} else {
			this.triggerNext.up().addClassName('disabled disabled-next');
		}
	},
	
	slide_prev: function () {
		if (!this.inaction && !this.triggerPrev.up().hasClassName('disabled')) {
			this.inaction = true;
			var current = parseInt(this.container.down('.slider').getStyle('left'));
			var targetIndex = Math.round(this.verticalSlider.value) - 1;
			if(parseInt(this.verticalSlider.value) != this.verticalSlider.value) {
				targetIndex = Math.floor(this.verticalSlider.value)
			}
			var target = -(this.itemWidth * targetIndex);
			this.slide(target - current, targetIndex);
			if( this.container.select('.slider-count').first() && this.container.select('.slider-count').first().innerHTML != 1) {
				this.sliderCount = this.sliderCount - 1;
				this.container.select('.slider-count').first().update(this.sliderCount);
			}
		}
	},
	
	slide_next: function () {
		if (!this.inaction && !this.triggerNext.up().hasClassName('disabled')) {
			this.inaction = true;
			var current = parseInt(this.container.down('.slider').getStyle('left'));
			var targetIndex = Math.round(this.verticalSlider.value) + 1;
			if(parseInt(this.verticalSlider.value) != this.verticalSlider.value) {
				targetIndex = Math.ceil(this.verticalSlider.value)
			}
			var target = -(this.itemWidth * targetIndex);
			this.slide(target - current, targetIndex);
			if(this.container.select('.slider-count').first() && this.container.select('.slider-count').first().innerHTML != this.container.select('.pages-count').first().innerHTML) {
				this.sliderCount = this.sliderCount + 1;
				this.container.select('.slider-count').first().update(this.sliderCount);
			}
		}
	},
	
	indexOfItem: function (item) {
		if (!item) {
			item = this.container.down('.slider .article.active');
		}
		
		retVal = 0;
		this.items.each(function (curitem, index) {
			if (curitem == item) {
				retVal = index;
			}
		});
		return retVal;
	},
		
	jumpToActiveItem: function () {
		activeElement = this.container.down('.slider .article.active');
		if (!activeElement) {
			activeElement = this.items.first();
		}
		pos = 0 - activeElement.positionedOffset().left;
		while (! this._contentToScroll_next(pos+this.itemWidth)) {
			pos = pos + this.itemWidth;
		}
		this._setPosLeft(pos);
	},
	
	rearrangeArticleContent: function() {
		var articles = this.container.select('.article');
		articles.each(function(item) {
			var link = item.select('.article-image a').first().clone();
			link.childElements().each(function(linkchild) {
				linkchild.remove();
			});
			var contents = new Array();
			item.childElements().each(function(elem) {
				contents.push(elem.remove());
			});
			
			item.insert(link);
			contents.each(function(elem) {
				item.childElements().first().insert(elem);
			});
		});
	},
	
	sizeHandle: function() {
		var handleMaxWidth = parseInt(this.verticalSliderContainer.up().getWidth());
		var sliderWidth = this.container.down('div.slider').childElements().length * parseInt(this.container.down('div.slider').childElements().first().getWidth());
		var sliderWrapperWidth = parseInt(this.container.down('.articles-content').getWidth());
		var handleWidth = sliderWrapperWidth / sliderWidth * handleMaxWidth;
		
		if(handleWidth > handleMaxWidth) {
			handleWidth = handleMaxWidth;
		}
		
		this.verticalSliderContainer.down().setStyle({ width: handleWidth+'px' })
	},
	
	initialize: function(container) {

		try {
			this.sliderCount = 0;
			this.container = container;
			this.items = container.select('.slider .article');
			this.itemWidth = this.items.first().getWidth();
			this.itemCount = this.items.size();
			this.sliderWidth = this.itemWidth*this.itemCount;
			this.currentItem = 0;
	
			this.triggerPrev = container.down('.slider-box-trigger-prev');
			this.triggerPrev.observe('click', this.slide_prev.bind(this));
			
			this.triggerNext = container.down('.slider-box-trigger-next');
			this.triggerNext.observe('click', this.slide_next.bind(this));
	
			this.verticalSliderContainer = container.down('.slider-box-trigger-slider');
			this.sizeHandle();
			
			if (this.itemCount-this.size >= 0) {
				this.jumpToActiveItem();
				
				this.verticalSlider = new Control.Slider(this.verticalSliderContainer.down('.handle'), this.verticalSliderContainer, {
					range: $R(0,this.itemCount-this.size),
					sliderValue: this.indexOfItem(),
					onSlide: this.scrollerSlide.bind(this),
					onChange: this.scrollerSlide.bind(this)
				});
			} else {
				//this.container.down('.articles-navigation').hide();
				this.verticalSliderContainer.up('div').addClassName('slider-box-trigger-slider-deact');
			}
			
			this.setTriggerVisibility();
		} catch (e) {
			if (Object.isFunction(console.log)) {
				console.log(e);
			}
		}
	}
});

var CheckShifter = Class.create({
	
	name: 0,
	value: false,
	container: null,
	prefixClass: '',
	activeClass: 'checked',
	lastActive: null,
	targetGroup: null,
	
	initialize: function(container, options) {
		this.container = container;
		//set name
		regExp = new RegExp(/value\-([^\-]+)$/i);
		match = regExp.exec(this.container.readAttribute('class'));
			
		this.name = parseInt(match[1]);		
		if (options) {
	 		if (options.value) {
	 			this.setValue(options.value);			
	 		}
	 		
	 		if (options.prefixClass) {
	 			this.prefixClass = options.prefixClass + '-';
	 		}
	 		
	 		if (options.activeClass) {
	 			this.activeClass = options.activeClass;
	 		}
		}
		this.container.observe('click', this.click.bindAsEventListener(this));
		this.lastActive = false;
		
		this.targetGroup = container.readAttribute('class').split(' ').first();
	},
	
	isChecked: function () {
		return this.value;
	},

	switchShifter: function() {
		this.setValue(! this.value);		
		return this;
	},
	
	resetContainer: function(){
		var parentContainer = $$('.brunner-products-container').first();
		var containerElements = new Array();
		fc.mapping.get(this.targetGroup).each(function(item) {
			containerElements.push(parentContainer.down('.brunner-products-'+item))
		});
		
		containerElements.each(function (item) {					
			item.select('ul>li').invoke('removeClassName', this.prefixClass + this.activeClass);							
		}.bind(this));
			
//		this.resetValue();
		return this;
	},
	
	getValue: function () {
		return this.value;
	},
	
	// not used anymore
	resetValue: function(){				
//		var parentContainer = this.container.up(2);		
//		containerElements.push(parentContainer.down('.brunner-products-scopes'));
//		containerElements.push(parentContainer.down('.brunner-products-typeschair'));
//		containerElements.push(parentContainer.down('.brunner-products-typestable'));
//		containerElements.push(parentContainer.down('.brunner-products-accessories'));		
		
		if (! this.container.readAttribute('class').startsWith('facility')) {			
			//remove all
			if (! this.container.readAttribute('class').startsWith('scope')) {					
//				this.container.up(2).childElements().each(function (item) {
				containerElements.each(function (item) {					
					if(! item.readAttribute('class').endsWith('scopes')){
						item.select('ul>li').invoke('removeClassName', this.prefixClass + this.activeClass);							
					}					
				}.bind(this));	
			} else {
				parentContainer.select('ul>li').invoke('removeClassName', this.prefixClass + this.activeClass);
			}
		}			
	},
	
	setValue: function (value) {
		this.value = value;
		if (this.value) {
			this.container.addClassName(this.prefixClass + this.activeClass);
		} else {
			this.container.removeClassName(this.prefixClass + this.activeClass);
		}
		return this;
	},

	click: function (event) {
		this.lastActive = true;
		if(fc.rule.get(this.targetGroup) == 'single') {
			this.resetContainer();
		}
		this.switchShifter();	
		this.container.fire('fs:filterSwitched', { value: this.getValue() });
	}
});

var Serie = Class.create({
	
	container: null,
	activeClass: 'active',
	enabled: true,
	
	_scopes: null,
	_accessories: null,
	
	_types: null,
	_facilities: null,

	_typeschair: null,
	_typestable: null,			
	_facilitiesall: null,
	_facilitieschair: null,
	_facilitiestable: null,
	
	initialize: function (container, options) {
		this.container = container;
		
		this._scopes = new Array();
		this._accessories = new Array();
		this._typeschair = new Array();
		this._typestable = new Array();			
		this._facilitiesall = new Array();
		this._facilitieschair = new Array();
		this._facilitiestable = new Array();
		
		if (options) {
			if (options.initValue) {
				this.enabled = options.initValue;
			}
			
	 		if (options.activeClass) {
	 			this.activeClass = options.activeClass;
	 		}
	 		
	 		if (options.scopes) {
	 			this._scopes = options.scopes;
	 		} else {
	 			this._scopes = [];
	 		}

	 		if (options.facilitiesall) {
	 			this._facilitiesall = options.facilitiesall;
	 		} else {
	 			this._facilitiesall = [];
	 		}
	 		if (options.facilitieschair) {
	 			this._facilitieschair = options.facilitieschair;
	 		} else {
	 			this._facilitieschair = [];
	 		}
	 		if (options.facilitiestable) {
	 			this._facilitiestable = options.facilitiestable;
	 		} else {
	 			this._facilitiestable = [];
	 		}
	 		if (options.typeschair) {
	 			this._typeschair = options.typeschair;
	 		} else {
	 			this._typeschair = [];
	 		}
	 		if (options.typestable) {
	 			this._typestable = options.typestable;
	 		} else {
	 			this._typestable = [];
	 		}	 			 		
	 		
/*	 		
	 		if (options.types) {
	 			this._types = options.types;
	 		} else {
	 			this._types = [];
	 		}
	 		
	 		if (options.facilities) {
	 			this._facilities = options.facilities;
	 		} else {
	 			this._facilities = [];
	 		}
*/	 		
	 		if (options.accessories) {
	 			this._accessories = options.accessories;
	 		} else {
	 			this._accessories = [];
	 		}	
		}
	},
	
	isActive: function() {
		return this.enabled; 
	},
	
	setActive: function() {
		this.container.addClassName(this.activeClass);
		this._setEnabled(true);
	},
	
	setInActive: function() {
		this.container.removeClassName(this.activeClass);
		this._setEnabled(false);
	},
	
	toggleActiveState: function() {
		this.container.toggleClassName(this.activeClass);
		this._setEnabled(!this.isActive());
	},
	
	_setEnabled: function(enabled) {
		this.enabled = enabled;
	},
	
	_getName: function() {
		return this.container.down('a').innerHTML;
	},
	
	checkAgainstFilters: function(filters) {
		//am i visible
//		if(this.container.down('a').innerHTML == 'alite') {
//			console.log(this);
//		}
		
		var visibleGlobal = true;
		var filterMatches = null;
		var mustHave = new Array();
		
		filters.each(function (filter) {			
			var filterMatches = this['_'+filter.key];
			var filterConjunctionAND = (fc.filterConjunction.get(filter.key) == 'AND') ? true : false;
			//CHECK GENERALLY
			//if filter is set but this serie has no filter set, it is invisble
			if (!filterMatches.size() && filter.value.size()) {
				visibleGlobal = false;
				return;
			}

			//if no filter is set to this property (e.g. scope, type or facility) 
			//this property does not affect the result
			if (! filter.value.size()) {
				visibleGlobal = visibleGlobal & true;
				return;
			}

			// CHECK AGAINST SPECIFIC VALUES
			
			if(filterConjunctionAND) {
				var visibleFilter = true;
			}
			else {
				var visibleFilter = false;
			}
			// at this point we know that filterMatches is an array and filter.value also.
			// no if-condition needed
			for (var i=0; i < filter.value.length; i++) {
				if(filterConjunctionAND) {
					var tmpVisibleFilter = false;
				}
				//if (filterMatches.inArray(filter.value[i])) {
				if (filterMatches.detect(function (n) { return n == filter.value[i]; })) {
					//and - condition
					if(filterConjunctionAND) {
						tmpVisibleFilter = true;
					}
					else {
						visibleFilter = true;
					}
					// or-condition
					//visibleFilter = true;
				}
				if(filterConjunctionAND) {
					if(!tmpVisibleFilter) {
						visibleFilter = false;
						break;
					}
				}
			}
			visibleGlobal = visibleGlobal & visibleFilter;
			return;
		}.bind(this));
//		this.getSelectedSeries();		
		if (visibleGlobal) {
			this.container.removeClassName('disabled');
		} else {
			this.container.addClassName('disabled');
		}
	}	
});

var FilterSelect = Class.create({
	name: 0,
	container: null,
	filters: null,
	group: null,
	
	initialize: function(container, options) {
		this.container = container;
		//set name
		regExp = new RegExp(/\.*\-([^\-]+)$/i);
		match = regExp.exec(this.container.readAttribute('class'));
		this.name = match[1];

		this.filters = [];
		checkSwifterTags = this.container.select('ul>li');
		checkSwifterTags.each(function(item) {
			this.filters.push(new CheckShifter(item));
		}.bind(this));
		this.getGroup();
	},

	getSelection: function () {
		selection = [];
		for (var i = 0, len = this.filters.length; i < len; ++i) {
			if( this.filters[i].isChecked()) {	
				selection.push(this.filters[i].name);
			}
		}
		return selection;
	},
	
	isGroup: function(targetGroup) {
		if(this.group == targetGroup) {
			return true;
		}
		else if(fc.alias.get(this.group) && fc.alias.get(this.group) == targetGroup) {
			return true;
		}
		return false;
	},
	
	getGroup: function() {
		fc.mapping.each(function(item) {
			var hit = item.value.any(function(n) { return  n == this.name; }.bind(this));
			if(hit) { this.group = item.key; }
		}.bind(this));
	},
	
	resetGroup: function() {
		if(fc.rule.get(this.group) == 'multiple') {
			return;
		}
		for(var i = 0; i < this.filters.length; i++) {	
			if(this.filters[i].lastActive) {				
				this.filters[i].lastActive = false;
				continue;			
//				this.filters[i].value = true;
			}
			this.filters[i].value = false;
//			console.log('i: '+i+' group: '+this.group+' name: '+this.name+' value: '+this.filters[i].value);
		}
	}
});


var ProductFinder = Class.create({
	container: null,
	series: null,
	filterSelects: null,
	request: null,

	initialize: function(container, options) {
		this.container = container;
		this.series = [];
		seriesTags = this.container.down('.brunner-products-series').select('li.serie');
		seriesTags.each(function(item) {
			//get serieUid from className
			regExp = new RegExp(/serie\-(\d+)/i);
			match = regExp.exec(item.readAttribute('class'));
			serieUid = match[1];

			//find serieUid in productMapping
			options = productMapping.findAll(function(item) {
				return item.uid == serieUid;
			}).first();
			
			this.series.push(new Serie(item, options));
		}.bind(this));
		
		this.filterSelects = [];
		//OR
		this.filterSelects.push( new FilterSelect(this.container.down('.brunner-products-scopes')));
		this.filterSelects.push( new FilterSelect(this.container.down('.brunner-products-typeschair')));
		this.filterSelects.push( new FilterSelect(this.container.down('.brunner-products-typestable')));
		this.filterSelects.push( new FilterSelect(this.container.down('.brunner-products-accessories')));
		//AND
		this.filterSelects.push( new FilterSelect(this.container.down('.brunner-products-facilitiesall')));
		this.filterSelects.push( new FilterSelect(this.container.down('.brunner-products-facilitieschair')));
		this.filterSelects.push( new FilterSelect(this.container.down('.brunner-products-facilitiestable')));

		this.container.observe('fs:filterSwitched', this.onFilterSwitched.bind(this));
	},
	
	getSelectedSeries: function(){
		//array for all selected series
		var selectedSeries = new Array();
		var selectedTypes = new Array();
		var selectedAccessories = new Array();
		var selectedScopes = new Array();
		//get the parent container
		var parentContainer = this.container.down('.brunner-products-series');
	
		var typeContainer = new Array();
		typeContainer.push(this.container.down('.brunner-products-typeschair'));
		typeContainer.push(this.container.down('.brunner-products-typestable'));

		var accessorieContainer = new Array();
		accessorieContainer.push(this.container.down('.brunner-products-accessories'));
		
		var scopeContainer = new Array();
		scopeContainer.push(this.container.down('.brunner-products-scopes'));
		
		regExp = new RegExp(/type\-(\d+)/i);
		
		typeContainer.each(function(item) {		
			typesTags = item.select('ul>li');
			typesTags.each(function(item) {
				if(item.readAttribute('class').endsWith('checked')){
					match = regExp.exec(item.readAttribute('class'));
					typeUid = match[1];
					selectedTypes.push(typeUid);
				}	
			}.bind(this));
		}.bind(this));
		
		//regex to extract teh series name and id
		regExp = new RegExp(/serie\-(\d+)/i);
		seriesTags = parentContainer.select('ul>li');
		seriesTags.each(function(item) {		
			if(! item.readAttribute('class').endsWith('disabled')){
				match = regExp.exec(item.readAttribute('class'));
				serieUid = match[1];
				selectedSeries.push(serieUid);
			}	
		}.bind(this));

		regExp = new RegExp(/accessorie\-(\d+)/i);
		
		accessorieContainer.each(function(item) {		
			accessorieTags = item.select('ul>li');
			accessorieTags.each(function(item) {
				if(item.readAttribute('class').endsWith('checked')){
					match = regExp.exec(item.readAttribute('class'));
					accessorieUid = match[1];
					selectedAccessories.push(accessorieUid);
				}	
			}.bind(this));
		}.bind(this));

		regExp = new RegExp(/scope\-(\d+)/i);
		
		scopeContainer.each(function(item) {		
			scopeTags = item.select('ul>li');
			scopeTags.each(function(item) {
				if(item.readAttribute('class').endsWith('checked')){
					match = regExp.exec(item.readAttribute('class'));
					scopeUid = match[1];
					selectedScopes.push(scopeUid);
				}	
			}.bind(this));
		}.bind(this));

		var serie = Object.toJSON($H({serie: selectedSeries}));
		var scope = Object.toJSON($H({scope: selectedScopes}));
		var type = Object.toJSON($H({type: selectedTypes}));
		var accessorie = Object.toJSON($H({accessorie: selectedAccessories}));

		if(this.request) {
			this.request.transport.abort();
		}

		this.request = new Ajax.Request('/index.php?id=120&no_cache=1&ajaxRequest=1', {
			  method: 'post',
			  parameters : { series : serie, types : type, accessories : accessorie, scopes : scope},
			  onCreate: function(response) {
				var container = $$('.brunner-products-search-result').first();
				container.childElements().each(function(item) { item.remove(); });
				
				var loader = new Element('div');
				loader.setStyle({ background: 'url(uploads/tx_brunnerproducts/ajax-loader.gif) no-repeat center top transparent', height: '36px' });
				container.insert(loader);
			  }.bind(this),
			  onSuccess: function(response) {
				  var searchResult = response.responseText;
				  searchResult = searchResult.substr(0, searchResult.length - 1);
				  objResult = searchResult.evalJSON();
				  this.setSearchResult(objResult);  				  
			  }.bind(this),
			  onFailure: function(response) {
			  }.bind(this)
		});
		return	selectedSeries;
	},

	setSearchResult: function(objResult){
		var output = '';
		var ajaxTemplate = new Template('<li class="serie"><a href="#{url}"><img width="175" height="175" src="#{imagePath}#{image}" alt="#{image}">#{title}</a></li>');

		var container = $$('.brunner-products-search-result').first();
		container.childElements().each(function(item) { item.remove(); });
		
		for(var i = 0; i <= objResult.length; i++) {
			if(i % 5 == 0 && i > 0 || objResult.length == i) {
				var ul = new Element('ul');
				ul.innerHTML = output;
				output = '';
				container.insert(ul);
				if(objResult.length == i) {
					break;
				}
			}

			var item = objResult[i];
			item.imagePath = imagePath;
			output += ajaxTemplate.evaluate(item);
		}
	},
	
	onFilterSwitched: function (event) {
		var targetGroup = event.target.readAttribute('class').split(' ').first();
		try {
			options = new Hash();
			//go through all container
			for (var i = 0, len = this.filterSelects.length; i < len; ++i) {
				//name of the container(scopes), value(scopes-id)
				if(this.filterSelects[i].isGroup(targetGroup)) {
					this.filterSelects[i].resetGroup();
				}
				options.set(this.filterSelects[i].name, this.filterSelects[i].getSelection());	
			}
			//check series against filters
			this.series.each(function (item) {
				item.checkAgainstFilters(options);
			});
//			console.dir(options._object);
//			this.getSelectedSeries();
		} catch (e) {
			console.log(e)
		}
		
		pf.getSelectedSeries();
	}
});

var FilterConfiguration = Class.create({
	mapping: null,
	rule: null,
	alias: null,
	filterRules: null,
	
	initialize: function() {
		this.mapping = new Hash();;
		this.mapping.set('scope', ['scopes']);
		this.mapping.set('facility', ['facilitiesall', 'facilitieschair', 'facilitiestable']);
		this.mapping.set('type', ['typeschair', 'typestable', 'accessories']);
		
		this.rule = new Hash();
		this.rule.set('scope', 'single');
		this.rule.set('facility', 'multiple');
		this.rule.set('type', 'single');

		this.filterConjunction = new Hash();
		this.filterConjunction.set('accessories', 'OR');
		this.filterConjunction.set('facilitiesall', 'AND');
		this.filterConjunction.set('facilitieschair', 'AND');
		this.filterConjunction.set('facilitiestable', 'AND');
		this.filterConjunction.set('scopes', 'OR');
		this.filterConjunction.set('typeschair', 'OR');
		this.filterConjunction.set('typestable', 'OR');
		
		this.alias = new Hash();
		this.alias.set('scope', null);
		this.alias.set('facility', null);
		this.alias.set('type', null);
		this.alias.set('accessorie', 'type');
		
		this.parseAlias();
	},
	
	parseAlias: function() {
		this.alias.each(function(alias) {
			if(this.mapping.index(alias)) {
				return;
			}
			else if(!this.mapping.get(alias.value) || !this.rule.get(alias.value)) {
				return;
			}

			this.mapping.set(alias.key, this.mapping.get(alias.value));
			this.rule.set(alias.key, this.rule.get(alias.value));
		}.bind(this));
	}
});

var fc = new FilterConfiguration();
var productMapping = '';
var pf = '';

Event.observe(document, "dom:loaded", function (event) {
	if(productMapping.isJSON()) {
		productMapping = productMapping.evalJSON();
	}
	
	if ($$('.brunner-products-container').first()) {
		pf = new ProductFinder($$('.brunner-products-container').first());
		//$$('.brunner-products-container').fire('fs:filterSwitched');
	}
	
	$$('.imageslider').each(function (container) {
		new ImageSlide(container);
	});
	
	if(pf != '') {
		pf.setSearchResult(productMapping);
	}
	
	$$('.slider-box').each( function (container) {
		new SliderBox(container);
	});

	
	var twinCheckboxes = $$('a.formhandler-twin-checkbox');
	twinCheckboxes.each(function(item) {
		if (item.down('input').value == 1) {
			item.addClassName('formhandler-twin-checkbox-checked');
		} else {
			item.removeClassName('formhandler-twin-checkbox-checked');
		}
	});
	
	twinCheckboxes.each(function(item, index) {
		item.observe('click', function(event) {
			elementClicked = event.element().tagName.toLowerCase() == 'a' ? event.element() : event.element().up('a');
			otherElement = twinCheckboxes[index ? 0 : 1];
			if (elementClicked.hasClassName('formhandler-twin-checkbox-checked')) {
				elementClicked.down('input').value = 0;
				otherElement.down('input').value = 1;
				elementClicked.removeClassName('formhandler-twin-checkbox-checked');
				otherElement.addClassName('formhandler-twin-checkbox-checked');
			} else {
				otherElement.down('input').value = 0;
				elementClicked.down('input').value = 1;
				otherElement.removeClassName('formhandler-twin-checkbox-checked');
				elementClicked.addClassName('formhandler-twin-checkbox-checked');
			}
		}.bindAsEventListener(this));
	});
});

function getSelectedSeries(){
	pf.getSelectedSeries();
//	$('test').value = pf.getSelectedSeries().toString();
//return test;	
};

String.prototype.basename = function(){
	var re = new RegExp("/\\/", "g");
	var str = this.replace(re, "/");
	var filename=str.split("/");
	return filename[(filename.length - 1)];
	
};





























