/**
 * Kluwer.nl scripts
 */

/**
 * Adaptor for RicoEffects.js FadeTo object
 */
if (!Effect.FadeTo) {
	Effect.FadeTo = function( element, opacity, duration, steps, options) {
		var o = {
			duration: duration / 1000
		};
		
		if (options.compleate) {
			o.afterFinish = options.compleate;
		}
		
		if (opacity == 1) {
			return new Effect.Appear(element, o);
		} 
		
		return new Effect.Fade(element, o);
	};
}

/**
 * Stub for JSItemTitleBar
 * hides KLNL-1413, KLNL-931
 */
if (window.JSItemTitleBar == undefined) {
	var JSItemTitleBar = Class.create({
		initialize: function (id) {
		}
	});
}

/**
 * Kluwer namespace
 */ 
if (!window.Kluwer) {
	var Kluwer = {};
}

/**
 * Kluwer.utils namespace
 */ 
if (!Kluwer.utils) {
	Kluwer.utils = {};
}

/**
 * Kluwer.animations namespace
 */ 
if (!Kluwer.animations) {
	Kluwer.animations = {};
}

/**
 * Kluwer.logic namespace
 */ 
if (!Kluwer.portlets) {
	Kluwer.portlets = {};
}

/**
 * Kluwer Exception
 */ 
if (!Kluwer.Exception) {
	Kluwer.Exception = function (message) {
		this.message = message;
		this.name = 'Kluwer.Exception';
	}
}

/**
 * Kluwer.utils.Pool
 *
 * @author Volodymyr Iatsyshyn
 * Componence Lviv
 */
Kluwer.utils.Pool = Class.create({
	items: null,
	size: 0,
	
	/**
	 * Pushes element to end of pool
	 * 
	 * @param {Object} aObject
	 * @public
	 */
	push: function (aObject) {
		this.items[this.size] = aObject;
		this.size++;
	},
	
	/**
	 * Pops element from end of pool
	 * 
	 * @type Object
	 * @public
	 */
	pop: function () {
		var result = null;
		if (this.size > 0) {
			this.size--;
			result = this.items[this.size - 1];
			this.items[this.size] = null;
		}
		
		return result;
	},
	
	/**
	 * Iterates over existing objects
	 *
	 * @param {Function} aIterator
	 */	
	each: function (aIterator) {
		for(var i = 0; i < this.size; ++i) {
			var block = this.items[i];
			if (block) {
				aIterator(block);
			}
		}
	},
	
	/**
	 * Removes object from pool
	 *
	 * @param {Integer} aIndex
	 */
	remove: function (aObject) {
		var i = 0;
		for(; i < this.size; ++i) {
			if (aObject == this.items[i]) {
				this.size--;
				break;
			}
		}
		
		for(; i < this.size; ++i) {
			this.items[i] = this.items[i + 1];
		}
		
		this.items[i + 1] = undefined;
	},
	
	initialize: function () {
		this.items = new Object();
		this.size = 0;
	}
});

/**
 * Kluwer.utils.BlockContainer
 *
 * @author Volodymyr Iatsyshyn
 * Componence Lviv
 */
Kluwer.utils.BlockContainer = Class.create({
	items: null,
	size: 0,
	capacity: 0,
	
	/**
	 * Finds existing block that is next for aIndex block
	 *
	 * @param {Integer} aIndex
	 * @type DOMElement
	 */
	findNext: function (aIndex) {
		if (aIndex < 0) {
			throw new Kluwer.Exception('Index out of range');
		}
		
		while(aIndex < this.capacity) {
			var obj = this.get(aIndex);
			if (obj) {
				return obj;
			}
			++aIndex;
		}
		
		return null;
	},
	
	/**
	 * Finds existing block that is next for aIndex block
	 *
	 * @param {Integer} aIndex
	 * @type DOMElement
	 */
	findPrevious: function (aIndex) {
		if (aIndex > this.capacity) {
			throw new Kluwer.Exception('Index out of range');
		}
		
		while(aIndex >= 0) {
			var obj = this.get(aIndex);
			if (obj) {
				return obj;
			}
			--aIndex;
		}
		
		return null;
	},
	
	/**
	 * Sets or adds object
	 *
	 * @param {Index} aIndex
	 * @param {Object} aObject
	 */
	set: function (aIndex, aObject) {
		if (aIndex > this.capacity) {
			this.capacity = aIndex;
		}
		
		if (!this.items[aIndex]) {
			this.size++;
		}
		
		this.items[aIndex] = aObject;
	},
	
	/**
	 * Get object
	 *
	 * @param {Integer} aIndex
	 * @type Object
	 */
	get: function (aIndex) {
		if (aIndex < 0 || aIndex > this.capacity) {
			throw new Kluwer.Exception('Index out of range');
		}
		
		return this.items[aIndex] ? this.items[aIndex] : null;
	},
	
	/**
	 * Removes and returns object
	 *
	 * @param {Integer} aIndex
	 * @type Object
	 */
	remove: function (aIndex) {
		var result = this.get(aIndex);
		if (result) {
			this.set(aIndex, null);
			this.size--;
		}
		
		return result;
	},
	
	clearAll: function () {
		for(var i = 0; i < this.capacity; ++i) {
			var block = this.get(i);
			if (block) {
				this.remove(i);
			}
		}
	},

	/**
	 * Iterates over existing objects
	 *
	 * @param {Function} aIterator
	 */	
	each: function (aIterator) {
		for(var i = 0; i < this.capacity; ++i) {
			var block = this.get(i);
			if (block) {
				aIterator(block , i);
			}
		}
	},
	
	initialize: function(aCapacity) {
		this.capacity = aCapacity;
		this.items = new Object();
		this.size = 0;
	}
});


Kluwer.animations.DnaBlocksMorphs = Class.create({
	container: null,
	blockClass: 'dnaBlock',
	blocksCount: 0,
	animationDuration: 1.0,
	blocks: null,
	pool: null,
	clear_pool: null,
	bound_to_select: false,
	
	/**
	 * Creates new block or gets it from pool
	 *
	 * @type DOMElement
	 * @private
	 */
	getNewBlock: function () {
		var block = null; //this.pool.pop();
		if (!block) {	
			block = $(document.createElement("div"));	
			block.addClassName(this.blockClass);
		}
		
		return block;
	},
	
	/**
	 * Refreshes and animates blocks
	 */
	animate: function() {
		var animations = new Array();
		this.clear_pool.each(function(item) {
			animations.push(new Effect.Morph(item, {
				style: {width: '0px'},
				sync: true,
				afterFinish: function () {
					try {
						this.clear_pool.remove(item);
						this.container.removeChild(item);
						this.pool.push(item);
					} catch (e) {
					}
				}.bind(this)
			}));
		}.bind(this));

		var size = Math.floor(1000 / this.blocks.size) / 10 + "%";
		this.blocks.each(function(item) {
			animations.push(new Effect.Morph(item, {
				style: {width: size},
				sync: true
			}));
		});
		
		var queue = Effect.Queues.get('global-dna');
		queue.each(function (effect) {
			effect.cancel();
		});
		
		var first = this.blocks.findNext(0);		
		new Effect.Parallel(animations, {
			duration: this.animationDuration,
			fps: 50,
			queue: { position: 'end', scope: 'global-dna' },
			afterFinish: function () {
				if (this.blocks.size > 1) {
					this.container.setStyle({backgroundColor: first.getStyle('background-color')});			
				}
			}.bind(this)
		});
		
		if (this.blocks.size < 2) {
			this.container.setStyle({backgroundColor: '#ffffff'});
		}		
	},
	
	/**
	 * Adds new color block to DNA
	 *
	 * @param {String} aColor - after rewriting it is a className : d1-d20
	 * @param {Integer} aIndex
	 */
	show: function (aColor, aIndex) {
		var block = this.getNewBlock();
		if (block && this.container) {
			//block.setStyle({backgroundColor: aColor, width: '0px'}).show();	
			block.addClassName(aColor).show();
			
			var next = this.blocks.findNext(aIndex);
			if (next) {
				this.container.insertBefore(block, next.nextSibling);
			} else {
				this.container.insertBefore(block, this.container.firstChild);
			}
			
			this.blocks.set(aIndex, block);
			this.animate();
		}
	},
	
	/**
	 * Removes color block from DNA
	 *
	 * @param {Integer} aIndex
	 */
	hide: function (aIndex) {
		var div = this.blocks.remove(aIndex);
		if (div) {
			div.setStyle({width: '0px'});
			this.clear_pool.push(div);
			this.animate();
		}
	},
	
	hideAll: function () {
		//this.blocks.clearAll();
		this.blocks.each(function (e,i){this.hide(i)}.bind(this));

	},

	/**
	 * Handler for CheckBox OnClick event
	 *
	 * @param {DOMElement} aObject
	 * @param {Integer} aIndex
	 */
	handler: function(aObject, aIndex) {
		if (!this.bound_to_select){
		var p = $(aObject.parentNode);
		//alert(aObject);
		if (aObject.checked || aObject.selected) {
			//p.addClassName(aObject.id);
			//this.show(p.getStyle('background-color'), aIndex);
			if (p.className == 'domen') {
				this.hideAll();
				this.show(aObject.id, aIndex);
			} else if (p.className == 'group') {
				this.hideAll();
				p.nextSiblings().each(function (e,index){
					if (e.className == 'group'){
						throw $break;
					}else if (e.className == 'domen') {
						this.show(e.getElementsByClassName('rubrieken')[0].id, index);
					}
				}.bind(this));
			}
		} else {
			//p.removeClassName(aObject.id);
			//this.hide(aIndex);
			//this.hideAll();
		}
		} else {
			aObject = aObject.options[aObject.selectedIndex];//get selected option
			//var id = aObject.id;
			if (aObject.className == 'rubrieken') {
				this.hideAll();
				this.show(aObject.id, aIndex);
			} else if (aObject.className == 'rubrieken group') {
				this.hideAll();
				aObject.nextSiblings().each(function (e, index) {
					if (e.className == 'rubrieken group'){
						throw $break;
					}else if (e.className == 'rubrieken') {
						this.show(e.id, index);
					}
				}.bind(this));
			}
		}
	},
	
	bind: function(aContainer, index) {
		var listenTo;
		if (aContainer.tagName.toLowerCase() == 'select'){
			this.bound_to_select = true;
			listenTo = 'change';
		} else {
			listenTo = 'click';
		}
		if (aContainer.observe){
			aContainer.observe(listenTo, this.handler.bind(this, aContainer, index));
		}else{
			Event.observe(aContainer.id, listenTo, this.handler.bind(this, aContainer, index));
		}
	},
 
	/**
	 * Inits DNA animations
	 *
	 * @param {String} aContainer
	 * @construtor
	 */
	initialize: function(aContainer, aBlocksCount) {
		this.container = $(aContainer);
		this.blocks = new Kluwer.utils.BlockContainer(aBlocksCount);
		this.pool = new Kluwer.utils.Pool();
		this.clear_pool = new Kluwer.utils.Pool();		
		this.blocksCount = aBlocksCount;
		
		for(var index = 0; index < aBlocksCount; ++index) 
		{
			var e = $('d' + index);
			if (e) {
				if (e.tagName.toLowerCase() == 'option'){
					e = e.parentNode;
					this.bind(e, index);
					this.handler(e, index);
					break;
				}
				this.bind(e, index);
				this.handler(e, index);
			}
		}	
	},
	
	refresh: function() {
		for(var index = 1; index < this.blocksCount; ++index) {
			var e = $('d' + index);
			var p = $(e.parentNode);
			if (e && p) {
			/*	if (p.hasClassName(e.id) && !e.checked) {
					p.removeClassName(e.id);
					this.hide(index);
				} else if (!p.hasClassName(e.id) && e.checked) {
					p.addClassName(e.id);
					this.show(p.getStyle('background-color'), index);				 
				}*/
				if (e.checked || e.selected) {
					this.show(e.id,0);
					break;
				}
			}
		}		
	}	
});

Kluwer.animations.SearchFormStateChange = Class.create({
	container: null,
	subcontainer: null,
	queue: 'search-form',
	
	initialize: function(aContainer, aSubcontainer, aButton) {
		this.container = $(aContainer);
		this.subcontainer = $(aSubcontainer);
		
		this.bindTo($(aButton));
	},
	
	bindTo: function (aButton) {
		aButton.observe('click', this.handler.bind(this));
	},
	
	handler: function () {
		Effect.Queues.get(this.queue).each(function(effect) { 
			effect.cancel(); 
		});	
			
		if (this.container.hasClassName('mini')) {
			new Effect.Fade(this.subcontainer, {
				duration: 0.3,
				fps: 50,
				queue: {position: 'end', scope: this.queue},
				afterFinish: function () {
					this.subcontainer.hide();
					this.container.removeClassName('mini').addClassName('open');
				}.bind(this)
			});
			
			new Effect.Parallel([
				new Effect.Appear(this.subcontainer, {sync: true}),
				new Effect.Morph(this.container, {
					sync: true,
					style: {height: '280px' }
				})
			], {
				queue: {position: 'end', scope: this.queue},
				duration: 0.8,
				fps: 50
			});
		} else {
			new Effect.Parallel([
				new Effect.Fade(this.subcontainer, {sync: true}), 
				new Effect.Morph(this.container, {
					style: {height: '120px' },
					sync: true,
					afterFinish: function () {
						this.subcontainer.hide();
						this.container.addClassName('mini').removeClassName('open');
					}.bind(this)
				})
			], {
				duration: 0.8,
				fps: 50,
				queue: {position: 'end', scope: this.queue}						
			});
			
			new Effect.Appear(this.subcontainer, {
				duration: 0.3,
				fps: 50,
				queue: {position: 'end', scope: this.queue}
			});
		}
	}
});

/**
 * Kluwer.portlets.SearchForm
 */
Kluwer.portlets.SearchForm = Class.create({
	container: null,
	blocksCount: 0,
	baseContainer: null,
	pool: null,
	checkboxes: null,
	rootContainer: null,
	
	category: null,
	rubriekSelected: false,
	
	animDna: null,
	//animStateChange: null,
	animSearchInput: null,
	animSearchButton: null,

	/**
	 * Inits SearchForm Porlet logic
	 *
	 * @param {String} aContainer
	 * @param {String} aButton
	 * @param {Integer} aBlocksCount
	 * @construtor
	 */
	initialize: function(aContainer, aButton, aBlocksCount, aRootContainer, aSearchInput, aSubmitButton) {
		$(aContainer).update('Rubrieken: <span></span>');
		
		this.rootContainer = $(aRootContainer);
		this.container = $(aContainer).firstDescendant();
		this.blocksCount = aBlocksCount;
		this.pool = new Kluwer.utils.Pool();
		
		$(aButton).observe('click', this.handler.bind(this));
		
		var searchContNoResultA = $$('#' + this.rootContainer.id + ' .searchContNoResult A')[0];		  
		if (searchContNoResultA) {
			searchContNoResultA.observe('click', this.miniStateHandler.bind(this));
			$(aButton).observe('click', this.miniStateHandler.bind(this));
		}

		this.checkboxes = $$('#' + $(aRootContainer).id + ' .rubrieken');
				
		this.animDna = new Kluwer.animations.DnaBlocksMorphs(aRootContainer, aBlocksCount);
		//this.animStateChange = new Kluwer.animations.SearchFormStateChange(aRootContainer, 'badge', aButton);
		this.animSearchInput = new Kluwer.animations.SearchFormInput(aSearchInput);
		//this.animSearchButton = new Kluwer.animations.SearchFormButton(aSubmitButton);
		
		this.checkboxes.each(function (e) {
			e.observe('click', this.setRubriekSelected.bind(this));
		}.bind(this));
		/*
		this.animSearchInput.element.observe('keyup', this.searchButtonIsEnabled.bind(this));
		this.animSearchInput.element.observe('cut', this.searchButtonIsEnabled.bind(this));
		this.animSearchInput.element.observe('copy', this.searchButtonIsEnabled.bind(this));
		this.animSearchInput.element.observe('paste', this.searchButtonIsEnabled.bind(this));
		this.animSearchInput.element.observe('mouseout', this.searchButtonIsEnabled.bind(this));
		$(aSubmitButton).observe('mouseover', this.searchButtonIsEnabled.bind(this));		
		
		this.searchButtonIsEnabled();*/
		this.clear();
		//this.render();
	},
	
/*	searchButtonIsEnabled: function () {
		this.animSearchButton.setEnabled(!this.animSearchInput.isEmpty() || !this.checkboxes.all(function (e) { return !$F(e); }));
	},*/
	
	setRubriekSelected: function () {
		this.rubriekSelected = true;
	},
	
	searchFormIsMinized: function() {
		return this.rootContainer.hasClassName('mini');
	},
	
	miniStateHandler: function () {
		var	searchContNoResult = $$('#' + this.rootContainer.id + ' .searchContNoResult')[0];
		var searchCont = $$('#' + this.rootContainer.id + ' .searchCont')[0];
		var searchContReadOnly = $$('#' + this.rootContainer.id + ' .searchContReadOnly')[0];

		searchContNoResult.hide();
		searchContReadOnly.hide();
		searchCont.show();
		if (!this.searchFormIsMinized()) {updateSearchFormState(enoughDetails,searchformResults)};
	},
	
	/**
	 * Handler for event
	 */
	handler: function() {
		if (this.searchFormIsMinized()) {
			this.clear();
		} else {
			this.render();
		}
	},
	
	/**
	 * Create new block or get it from pool
	 */
	createBlock: function () {
		var block = this.pool.pop();
		if (!block) {
			block = $(document.createElement('label'));
		}
		return block;
	},
	
	/**
	 * Render domains list
	 */
	render: function () {
		var i = 0;
		var text = '';
		var block = null;
		for(var index = 1; i < 8 && index < this.blocksCount; ++index) 
		{
			var e = $('d' + index);
			if (e && $F(e)) {
				i++;
				block = this.createBlock();
				text = '<span>' + e.next('label').innerHTML + '</span>';
				block.update(text + ' / ');
				this.container.appendChild(block);
			}
		}
		if (block) {
			if (i > 6) {
				block.update('...');
			} else {
				block.update(text);
			}
		}
	},
	
	/**
	 * Clear domains list
	 */
	clear: function () {
		this.container.childElements().each(function (e) {
			this.pool.push(e);
			this.container.removeChild(e);
		}.bind(this));		
	},
	
	setCategory: function(categoryCode) {
		this.category = categoryCode;
	},
	
	getSelectedRubriek: function () {
		for (i = 0; i < this.checkboxes.length; i++) {
			if (this.checkboxes[i].tagName.toLowerCase() == 'option'){
				var select = this.checkboxes[i].parentNode;
				return (select.selectedIndex > 0) ? select.options[select.selectedIndex].value : null;
			}
			var active = this.checkboxes[i].checked || this.checkboxes[i].selected;
			if (active) {
				return domainCodes[i];
			}
		}
		return null;
	},
	
	submitSearch: function (contextPath, domainList) {

		//var domainCodesString = "";
		// create the Nice url for overzicht page
		var overzichtUrl = contextPath + '/' + (this.animSearchInput.isEmpty() ? "browse.ep" : "search.ep");// + '?';
//		var keywordPresent = false;
		var rubriek = this.getSelectedRubriek();
		this.rubriekSelected = (rubriek != null);
		if (this.category != "undefined" && this.category != null || this.rubriekSelected) {
			//overzichtUrl += "filters=";
			var input = document.createElement('INPUT');
			input.type = "hidden";
			input.name = "filters";
			var filtersValue = "";
			if (this.category != "undefined" && this.category != null) {
				filtersValue += 'c' + this.category + (this.rubriekSelected ? " " : '');
			}
			if (this.rubriekSelected) {
				filtersValue += 'c' + rubriek;
			}
			input.value = filtersValue;
			document.searchFormForSubmission.appendChild(input);
		}
		if (!this.animSearchInput.isEmpty()) {
			//if (!overzichtUrl.endsWith('?')) overzichtUrl += '&';
			var input = document.createElement('INPUT');
			input.type = "hidden";
			input.name = "keyWords";
			
			//overzichtUrl += "keyWords="
	  	    //overzichtUrl += encodeURIComponent(document.searchForm.search.value).replace(/%20/g,'+').replace(/%2F/g,'/');
			input.value = document.searchForm.search.value;
			document.searchFormForSubmission.appendChild(input);
	  	    
//			keywordPresent = true;
		}	
//		alert(overzichtUrl);return;
		
		/*var cn=false;
	  	for (i = 0; i < domainList.length; i++) {
			var active = domainList[i].checked;
			if (active) {
				if(cn) domainCodesString += "+";
				domainCodesString += encodeURIComponent(domainCodes[i]);				
				cn=true;
			}
		}
		if (domainCodesString != "") overzichtUrl += domainCodesString;

/*		overzichtUrl += "//";
		if (!this.animSearchInput.isEmpty()) {
	  	    overzichtUrl += encodeURIComponent(document.searchForm.search.value).replace(/%20/g,'+').replace(/%2F/g,'/');
	  	    cn = true;
		}	

		overzichtUrl += "/index.html";*/

//		if (cn) {
			document.searchFormForSubmission.action = overzichtUrl;
			document.searchFormForSubmission.submit();
	/*	} else {
			document.searchForm.action = '#';
		}*/
	}
});

/**
 * Kluwer.animations.ExpandCollapseEnimation
 * Used by KL SearchFilter portlet
 */
Kluwer.animations.ExpandCollapseEnimation = Class.create({
	container: null,
	state: null,
	button: null,
	title: null,
	states: null,
	
	/**
	 * Inits SearchForm Porlet logic
	 *
	 * @param {String} aContainer
	 * @param {String} aButton
	 * @param {Integer} aBlocksCount
	 * @construtor
	 */
	initialize: function(aContainer, aButton, aTitle, aState, aStates) {
		this.container = $(aContainer);
		this.button = $(aButton);
		this.state = aState;
		this.states = aStates;
		this.title = $(aTitle);
		
		this.bind(this.button);
	},
	
	bind: function (aButton) {
		aButton.observe('click', this.handler.bind(this));
	},
	
	handler: function () {
		this.container.toggleClassName(this.states.container);
		this.button.toggleClassName(this.states.button);
		this.title.toggleClassName(this.states.title);
	}
});

/**
 * Kluwer.animations.SearchFormButton
 */
 
Kluwer.animations.Button = Class.create({
	activeCss: {backgroundPosition: '0px 50%'},
	normalCss: {backgroundPosition: '0px 0px'},
	disabledCss: {backgroundPosition: '0px 100%'},
	isEnabled: null,
	button: null,
	enabled: true,
	
	initialize: function (aButton, onClick) {
		this.button = $(aButton);
		
		this.button.observe('mouseover', this.handler.bind(this, true));
		this.button.observe('mouseout', this.handler.bind(this, false));
		
		if (onClick) {
			this.button.observe('click', this.clickHandler.bind(this, onClick));
		}
		
		this.handler(false);
	},
	
	handler: function (isOver) {
		if (!this.enabled) {
			this.button.setStyle(this.disabledCss);
			this.button.disabled = true;			
		} else if (isOver) {
			this.button.setStyle(this.activeCss);
		} else {
			this.button.setStyle(this.normalCss);
		}
		if (this.enabled) {
		   this.button.disabled = false;
		}
	},
	
	clickHandler: function(onClick) {
		if (this.enabled) {
			onClick(this.button);
		}
	},
	
	setEnabled: function (value) {
		var update = !this.enabled && value || !value;
		this.enabled = value;
		if (update)
			this.handler(false);
	}
});

/**
 * Kluwer.animations.EditButton
 */
 
Kluwer.animations.EditButton = Class.create({
	normalCss: {color:'#FFFFFF'},
	activeCss: {color:'#b9b9b9'},
	isEnabled: null,
	button: null,
	enabled: true,
	
	initialize: function (aButton, onClick) {
		this.button = $(aButton);
		if (onClick) {
			this.button.observe('click', this.clickHandler.bind(this, onClick));
		}
		this.handler(false);
	},
	
	handler: function (isOver) {
		if (!this.enabled) {
			this.button.setStyle(this.activeCss);
			this.button.disabled = true;			
		} else if (isOver) {
		    this.button.setStyle(this.normalCss);
		} else {
			this.button.setStyle(this.normalCss);
		}
		if (this.enabled) {
		   this.button.disabled = false;
		}
	},
	
	clickHandler: function(onClick) {
		if (this.enabled) {
			onClick(this.button);
		}
	},
	
	setEnabled: function (value) {
		var update = !this.enabled && value || !value;
		this.enabled = value;
		if (update)
			this.handler(false);
	}
});
/* Alias */
/*Kluwer.animations.SearchFormButton = Kluwer.animations.Button;*/

Kluwer.animations.SearchFormInput = Class.create({
	element: null,
	INPUT_HINT_TEXT: 'Vul een titel, auteur of trefwoord in',
	INPUT_ACTIVE_CLASS: 'searchInputActive',
	hints : new Array(),
	
	initialize: function (aElement) {
		this.element = $(aElement);
		
		this.bind();
		this.initState();
		this.initHints();
	},
	
	isEmpty: function() {
		var value = $F(this.element);
		return value == '' || value.replace(/\s+$/, '') == this.INPUT_HINT_TEXT;
	},
	
	bind: function () {
		this.element.observe('focus', this.onFocusHandler.bind(this))
					.observe('blur', this.onBlurHandler.bind(this));
	},
	
	onFocusHandler: function() {
		if (this.isEmpty()) {
			this.element.addClassName(this.INPUT_ACTIVE_CLASS)
						.value = '';
		}
	},
	
	onBlurHandler: function() {
		if (this.isEmpty()) {
			this.element.removeClassName(this.INPUT_ACTIVE_CLASS)
						.value = this.INPUT_HINT_TEXT;
		}
	},
	
	initState: function () {
		if (!this.isEmpty()) {
			this.element.addClassName(this.INPUT_ACTIVE_CLASS);
		} else {
			this.element.value = this.INPUT_HINT_TEXT;
		}
		
		if(this.element.value != this.INPUT_HINT_TEXT) {
			this.element.addClassName(this.INPUT_ACTIVE_CLASS);
		}
		
	},
	
	initHints : function () {
		this.hints.push('Vul een titel, auteur of trefwoord in');
		this.hints.push('Vul een online titel, emailnieuwsbrief of trefwoord in');
		this.hints.push('Vul een titel of trefwoord in');
		this.hints.push('Vul een titel, auteur, isbn of trefwoord in');
		this.hints.push('Vul een opleiding, evenement of trefwoord in');
		this.hints.push('Vul een titel of trefwoord in');
		this.hints.push('Vul een titel of trefwoord in');
	},
	
	setHint : function (hintValue) {
		if (hintValue <= 6 && hintValue >= 0){
			hintValue = this.hints[hintValue];
		}
		if (this.isEmpty()){
			this.element.value = hintValue;
		}
		this.INPUT_HINT_TEXT = hintValue;
	}
});

/**
 * Kluwer.portlets.SearchFilter
 */
Kluwer.portlets.SearchFilter = Class.create({
	button: null,
	activeContainer: null,
	
	initialize: function (aClass, aActiveContainer) {
		$$('.' + aClass + '-expand').each(function (button) {
			var container = button.next('.tohide');
			var title = button.next('.title');
			new Kluwer.animations.ExpandCollapseEnimation(
				container, 
				button,
				title,
				function (button) { return button.hasClassName('minus')?'expanded':'collapsed'; },
				{container: 'hidden', button: 'minus', title: 'active'}
			);
		});

		this.button = new Kluwer.animations.Button('searchFilterButton', updateFiltersMindingEducationFilter.bind(window, window.location.href, 'searchFiltersList', 'searchFiltersListCategory'));
		this.button.setEnabled(false);
		
		this.activeContainer = $(aActiveContainer);

		$$("[name='educationFilter']").each(function (button) {
			button.observe('click', this.itemEducationClick.bind(this));
		}.bind(this));

		$$('.searchFiltersListItem').each(function (button) {
			button.observe('click', this.itemClick.bind(this));
		}.bind(this));
		
		$$('.searchFiltersListCategoryItem').each(function (button) {
			button.observe('click', this.itemCategoryClick.bind(this));
		}.bind(this));
		
		this.updateCategoryActiveItems();
		this.updateActiveItems();
	},
	
	itemClick: function () {
		this.button.setEnabled(true);
		this.updateActiveItems();
	},

	itemEducationClick: function () {
		this.button.setEnabled(true);
	},

	itemCategoryClick: function () {
		this.button.setEnabled(true);
		this.updateCategoryActiveItems();
	},
	
	updateActiveItems: function () {
		var counter = $$('h3#filterResults');
		if (counter){ 
			var items = $$('.searchFiltersListItem');
			var active = items.findAll(function(item) { return $F(item); }).size();
			this.activeContainer.update('(' + active + '/' + items.size() + ')');
			try{
				counter[0].innerHTML = '(' + active + '/' + items.size() + ')';
			}catch(err){};
		}
	},
	// This function updates the category results titles.
	// The counter has 2 values, either 1 - update results titles for whole category
	// available for 3 categories - Boeken, Software, Online
	// and 4 - update each subcategory of Opleiding category
	updateCategoryActiveItems: function () {
		var counter;
		updatePuntenSelect();
		if (navigator.userAgent.indexOf("MSIE") > -1) {
			counter = document.getElementsByName("categoryFilterResults");
		} else {
			counter = $$('h3#categoryFilterResults');
		}
		if (counter.length == 1) { 
			try{
				var items = $$('.searchFiltersListCategoryItem');
				var active = items.findAll(function(item) { return $F(item); }).size();
				counter[0].innerHTML = '(' + active + '/' + items.size() + ')';
			}catch(err){};
		} else {
			try{
				if (navigator.userAgent.indexOf("MSIE") > -1) {
					var items = document.getElementsByTagName("ul");
					var contor = 0;
					for (var i=0;i<items.length;i++) {
						if ((items[i].style.display != 'none') && (items[i].name == "searchFiltersListCategory")) {
							var inputElements = items[i].getElementsByTagName("input");
							var indexActive = 0;
							var indexTotal = 0;
							for (var jIndex=0;jIndex<inputElements.length;jIndex++){
								if (inputElements[jIndex].type == 'checkbox') {
									if (inputElements[jIndex].checked) {
										indexActive++;
									}
									indexTotal++;
								}
							}
							counter[contor].innerHTML = '(' + indexActive + '/' + indexTotal + ')';
							contor++;
						}
					}
				} else {
					var items = document.getElementsByName("searchFiltersListCategory");
					var contor = 0;
					for (var i=0;i<items.length;i++) {
						if (items[i].style.display != 'none') {
							var inputElements = items[i].getElementsByTagName("input");
							var indexActive = 0;
							var indexTotal = 0;
							for (var jIndex=0;jIndex<inputElements.length;jIndex++){
								if (inputElements[jIndex].type == 'checkbox') {
									if (inputElements[jIndex].checked) {
										indexActive++;
									}
									indexTotal++;
								}
							}
							counter[contor].innerHTML = '(' + indexActive + '/' + indexTotal + ')';
							contor++;
						}
					}					
				}
			}catch(err){};
		}	
	}
	
});

function trySubmit(form,domainList){
	submitSearch(domainList);
	return false;
} 

function updateFiltersMindingEducationFilter(url, filtersListId, categoryFilterListId) {
	var eduFilterVal = "";
    var eduFilterRadiobuttons = getElementsByName_iefix('input','educationFilter');
	if(eduFilterRadiobuttons!=null)
		for(var i = 0; i< eduFilterRadiobuttons.length; i++ ) 
			if(eduFilterRadiobuttons[i].checked) 
				if(eduFilterRadiobuttons[i].value=="True") eduFilterVal = "!";
    var newUrl = createUpdateFiltersUrl(url, eduFilterVal+createFiltersStrParam(filtersListId, categoryFilterListId));
	setTimeout(function()
    {
    window.location = newUrl;
    }, 0);
	
}

// This function sets the selected element for the select for PEPunten
// SubCategory, according to checkboxes state when page is loaded.
// Checkboxes state is set according to pageState filters state. 
function updatePuntenSelect() {
	var pePuntenDiv = document.getElementById("PEPuntenDiv");
	if (pePuntenDiv != null) {
		var pePuntenSelect = document.getElementById("PEPuntenSelect");
		var inputElements = pePuntenDiv.getElementsByTagName("input");
		var i=0;
		var contorCheckboxes=0;
		for (i=0;i<inputElements.length;i++){
			if (inputElements[i].type == "checkbox" ){
				if (inputElements[i].checked == true) {
					break;
				}
				contorCheckboxes++;
			}
		}
		var nrChecked = 0;
		for (i=0;i<inputElements.length;i++){
			if (inputElements[i].type == "checkbox" ){
				if (inputElements[i].checked == true) {
					nrChecked++;
				}
			}
		}
		if (nrChecked > 1) {
			for (i=0;i<inputElements.length;i++){
				if (inputElements[i].type == "checkbox" ){
					inputElements[i].checked = false;
				}
			}
			for (i=0;i<inputElements.length;i++){
				if (inputElements[i].type == "checkbox" ){
					inputElements[i].checked = true;
					break;
				}
			}
			pePuntenSelect.options[0].selected = true;
		} else {
			pePuntenSelect.options[contorCheckboxes].selected = true;
		}
	}
}

// This function is called on the onChange event of the PEPunten select.
// The checkboxes are updated according to the selected element of the select.
// It also calls the button's setEnable method and the event for updating
// the number of results titles
function updatePuntenCheckBoxes(menu, obj) {
	var pePuntenDiv = document.getElementById("PEPuntenDiv");
	var inputElements = pePuntenDiv.getElementsByTagName("input");
	var i=0;
	var contorCheckboxes=0;
	for (i=0;i<inputElements.length;i++){
		if (inputElements[i].type == "checkbox" ){
			inputElements[i].checked = false;
			if (menu.options[contorCheckboxes].selected){
				inputElements[i].checked = true;
			}
			contorCheckboxes++;
		}
	}
	obj.button.setEnabled(true);
	obj.updateCategoryActiveItems();
}

// KOMUS-109

function preRubrieken(rubrieken) {
	var groupId;
	groupId = rubrieken.id;
	groupId = groupId.substr(1);
	groupId = 'g'+groupId;
	var dLength = document.getElementById(groupId).value;	
	removePreRubriekens("searchformactive");
	var maingroup = rubrieken.parentNode;
	if(dLength == 2) {
		maingroup.parentNode.className="searchformactive2";
	} else if(dLength == 3) {
		maingroup.parentNode.className="searchformactive3";
	} else if(dLength == 4) {	
		maingroup.parentNode.className="searchformactive4";
	} else if(dLength == 5) {
		maingroup.parentNode.className="searchformactive5";
	} else if(dLength == 6) {
		maingroup.parentNode.className="searchformactive6";
	} 
}
function removePreRubriekens(theClass) {
    var allHTMLTags=document.getElementsByTagName("*");
    for (i=0; i<allHTMLTags.length; i++) {
    	if(typeof(allHTMLTags[i]) != 'undefined' ) {
	     if (allHTMLTags[i].className==theClass+2) {
	         allHTMLTags[i].className="inactive";
	      }
	      else if (allHTMLTags[i].className==theClass+3) {
	         allHTMLTags[i].className="inactive";
	      }
	      else if (allHTMLTags[i].className==theClass+4) {
	         allHTMLTags[i].className="inactive";
	      }
	      else if (allHTMLTags[i].className==theClass+5) {
	         allHTMLTags[i].className="inactive";
	      }
	      else if (allHTMLTags[i].className==theClass+6) {
	         allHTMLTags[i].className="inactive";
	      }
	     }
    }
 }
 function GetBodyWidth(){
	  var x = 0;
	  if (self.innerHeight) {		  
			  x = self.innerWidth-17.5;
	  }
	  else if (document.documentElement && document.documentElement.clientHeight){
			  x = document.documentElement.clientWidth;			  
	  }
	  else if (document.body){
			  x = document.body.clientWidth;			 
	  }
	  return x;
}
function GetWidth(id){
	  var x = 0;
	  if(!document.getElementById(id)) return x;
	  x = document.getElementById(id).offsetWidth;
	  return x;
}

function setPosition(id, positionX){
	if(!document.getElementById(id)) return false;
	var object = document.getElementById(id);
	var widths=0;
	if(positionX != ''){
		widths = positionX;
	}
	else {
		widths =Math.round( (GetBodyWidth() - object.offsetWidth)/2);	
	}
	object.style.left = widths + 'px';	
}

function setBadgePosition () {
 var left = (GetBodyWidth()  - GetWidth('logo')) / 2 + 30;
 if(left < 30) left = 30;
 setPosition('badgeHome', left);
}
function setBadgeImagePosition () {
	if(document.getElementById('bageImage') != null) {
		 var left = (GetBodyWidth()  - GetWidth('logo')) / 2 + 643;
		 if(left < 648) left = 648;
		 setPosition(document.getElementById('bageImage').parentNode.id, left);
	}
}

function setsbContainerWidth () {
	width = GetBodyWidth();
	if(width < 870){
		width = 870;
	}
	document.getElementById('sbContainer').style.width = width + 'px';	
}

function addListener(element, type, expression, bubbling){
   var  bubbling = bubbling || false;
   if(window.addEventListener) { // Standard
	  element.addEventListener(type, expression, bubbling);
	  return true;
   } else if(window.attachEvent) { // IE
	  element.attachEvent('on' + type, expression);
	  return true;
   } else return false;
}

function getByTagAndClassName(container, tagName, className){
   return getByClassName(container.getElementsByTagName(tagName), className);
}

function getByClassName(elements, className){
   for( var x = 0; x < elements.length; x++ ) {
       if ( (className ==null && elements[x].className == '') || (elements[x].className == className) ) {
           return elements[x];
       }
   }
}